...

Source file src/github.com/GoogleCloudPlatform/k8s-config-connector/pkg/webhook/generic_defaulter.go

Documentation: github.com/GoogleCloudPlatform/k8s-config-connector/pkg/webhook

     1  // Copyright 2022 Google LLC
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package webhook
    16  
    17  import (
    18  	"context"
    19  	"fmt"
    20  	"net/http"
    21  
    22  	"github.com/GoogleCloudPlatform/k8s-config-connector/pkg/k8s"
    23  
    24  	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
    25  	"k8s.io/klog/v2"
    26  	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
    27  )
    28  
    29  // A generic webhook defaulter that is meant to handle various miscellaneous defaulting.
    30  // The reasons to have a generic defaulter are 1) to avoid the heavyweight boilerplate code
    31  // of registering new webhook handlers and 2) to avoid adding a new entry in the MutatingWebhookConfiguration object with almost all KCC resources listed
    32  // every time we introduce a new feature across the board.
    33  //
    34  // This defaulter should only contain lightweight defaulting logic, for complicated defaulting
    35  // functions, it's recommended to create dedicated webhook handlers.
    36  type genericDefaulter struct {
    37  }
    38  
    39  func NewGenericDefaulter() *genericDefaulter {
    40  	return &genericDefaulter{}
    41  }
    42  
    43  func (a *genericDefaulter) Handle(ctx context.Context, req admission.Request) admission.Response {
    44  	deserializer := codecs.UniversalDeserializer()
    45  	obj := &unstructured.Unstructured{}
    46  	if _, _, err := deserializer.Decode(req.AdmissionRequest.Object.Raw, nil, obj); err != nil {
    47  		klog.Error(err)
    48  		return admission.Errored(http.StatusBadRequest,
    49  			fmt.Errorf("error decoding object: %v", err))
    50  	}
    51  	newObj := obj.DeepCopy()
    52  	if err := k8s.ValidateOrDefaultStateIntoSpecAnnotation(newObj); err != nil {
    53  		return admission.Errored(http.StatusBadRequest, fmt.Errorf("error validating or defaulting '%v' annotation: %v", k8s.StateIntoSpecAnnotation, err))
    54  	}
    55  	return constructPatchResponse(obj, newObj)
    56  }
    57  

View as plain text