k8s.io/apiserver@v0.31.1/pkg/admission/chain.go (about)

     1  /*
     2  Copyright 2014 The Kubernetes 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 admission
    18  
    19  import "context"
    20  
    21  // chainAdmissionHandler is an instance of admission.NamedHandler that performs admission control using
    22  // a chain of admission handlers
    23  type chainAdmissionHandler []Interface
    24  
    25  // NewChainHandler creates a new chain handler from an array of handlers. Used for testing.
    26  func NewChainHandler(handlers ...Interface) chainAdmissionHandler {
    27  	return chainAdmissionHandler(handlers)
    28  }
    29  
    30  // Admit performs an admission control check using a chain of handlers, and returns immediately on first error
    31  func (admissionHandler chainAdmissionHandler) Admit(ctx context.Context, a Attributes, o ObjectInterfaces) error {
    32  	for _, handler := range admissionHandler {
    33  		if !handler.Handles(a.GetOperation()) {
    34  			continue
    35  		}
    36  		if mutator, ok := handler.(MutationInterface); ok {
    37  			err := mutator.Admit(ctx, a, o)
    38  			if err != nil {
    39  				return err
    40  			}
    41  		}
    42  	}
    43  	return nil
    44  }
    45  
    46  // Validate performs an admission control check using a chain of handlers, and returns immediately on first error
    47  func (admissionHandler chainAdmissionHandler) Validate(ctx context.Context, a Attributes, o ObjectInterfaces) error {
    48  	for _, handler := range admissionHandler {
    49  		if !handler.Handles(a.GetOperation()) {
    50  			continue
    51  		}
    52  		if validator, ok := handler.(ValidationInterface); ok {
    53  			err := validator.Validate(ctx, a, o)
    54  			if err != nil {
    55  				return err
    56  			}
    57  		}
    58  	}
    59  	return nil
    60  }
    61  
    62  // Handles will return true if any of the handlers handles the given operation
    63  func (admissionHandler chainAdmissionHandler) Handles(operation Operation) bool {
    64  	for _, handler := range admissionHandler {
    65  		if handler.Handles(operation) {
    66  			return true
    67  		}
    68  	}
    69  	return false
    70  }