github.com/Racer159/jackal@v0.32.7-0.20240401174413-0bd2339e4f2e/src/internal/agent/operations/hook.go (about)

     1  // SPDX-License-Identifier: Apache-2.0
     2  // SPDX-FileCopyrightText: 2021-Present The Jackal Authors
     3  
     4  // Package operations provides functions for the mutating webhook.
     5  package operations
     6  
     7  import (
     8  	"fmt"
     9  
    10  	"github.com/Racer159/jackal/src/config/lang"
    11  	"github.com/Racer159/jackal/src/pkg/message"
    12  	admission "k8s.io/api/admission/v1"
    13  )
    14  
    15  // Result contains the result of an admission request.
    16  type Result struct {
    17  	Allowed  bool
    18  	Msg      string
    19  	PatchOps []PatchOperation
    20  }
    21  
    22  // AdmitFunc defines how to process an admission request.
    23  type AdmitFunc func(request *admission.AdmissionRequest) (*Result, error)
    24  
    25  // Hook represents the set of functions for each operation in an admission webhook.
    26  type Hook struct {
    27  	Create  AdmitFunc
    28  	Delete  AdmitFunc
    29  	Update  AdmitFunc
    30  	Connect AdmitFunc
    31  }
    32  
    33  // Execute evaluates the request and try to execute the function for operation specified in the request.
    34  func (h *Hook) Execute(r *admission.AdmissionRequest) (*Result, error) {
    35  	message.Debugf("operations.Execute(*admission.AdmissionRequest) - %#v , %s/%s: %#v", r.Kind, r.Namespace, r.Name, r.Operation)
    36  
    37  	switch r.Operation {
    38  	case admission.Create:
    39  		return wrapperExecution(h.Create, r)
    40  	case admission.Update:
    41  		return wrapperExecution(h.Update, r)
    42  	case admission.Delete:
    43  		return wrapperExecution(h.Delete, r)
    44  	case admission.Connect:
    45  		return wrapperExecution(h.Connect, r)
    46  	}
    47  
    48  	return &Result{Msg: fmt.Sprintf(lang.AgentErrInvalidOp, r.Operation)}, nil
    49  }
    50  
    51  // If the mutatingwebhook calls for an operation with no bound function--go tell on them.
    52  func wrapperExecution(fn AdmitFunc, r *admission.AdmissionRequest) (*Result, error) {
    53  	if fn == nil {
    54  		return nil, fmt.Errorf(lang.AgentErrInvalidOp, r.Operation)
    55  	}
    56  	return fn(r)
    57  }