volcano.sh/volcano@v1.9.0/pkg/webhooks/router/admission.go (about)

     1  /*
     2  Copyright 2019 The Volcano Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package router
    18  
    19  import (
    20  	"fmt"
    21  	"net/http"
    22  	"strings"
    23  	"sync"
    24  
    25  	"k8s.io/klog/v2"
    26  
    27  	"volcano.sh/volcano/cmd/webhook-manager/app/options"
    28  )
    29  
    30  type AdmissionHandler func(w http.ResponseWriter, r *http.Request)
    31  
    32  var admissionMap = make(map[string]*AdmissionService)
    33  var admissionMutex sync.Mutex
    34  
    35  func RegisterAdmission(service *AdmissionService) error {
    36  	admissionMutex.Lock()
    37  	defer admissionMutex.Unlock()
    38  
    39  	if _, found := admissionMap[service.Path]; found {
    40  		return fmt.Errorf("duplicated admission service for %s", service.Path)
    41  	}
    42  
    43  	// Also register handler to the service.
    44  	service.Handler = func(w http.ResponseWriter, r *http.Request) {
    45  		Serve(w, r, service.Func)
    46  	}
    47  
    48  	admissionMap[service.Path] = service
    49  
    50  	return nil
    51  }
    52  
    53  func ForEachAdmission(config *options.Config, handler func(*AdmissionService) error) error {
    54  	admissions := strings.Split(strings.TrimSpace(config.EnabledAdmission), ",")
    55  	klog.V(3).Infof("Enabled admissions are: %v, registered map are: %v", admissions, admissionMap)
    56  	for _, admission := range admissions {
    57  		if service, found := admissionMap[admission]; found {
    58  			if err := handler(service); err != nil {
    59  				return err
    60  			}
    61  		}
    62  	}
    63  	return nil
    64  }