...

Source file src/k8s.io/kubernetes/test/images/agnhost/webhook/addlabel.go

Documentation: k8s.io/kubernetes/test/images/agnhost/webhook

     1  /*
     2  Copyright 2018 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 webhook
    18  
    19  import (
    20  	"encoding/json"
    21  
    22  	"k8s.io/api/admission/v1"
    23  	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    24  	"k8s.io/klog/v2"
    25  )
    26  
    27  const (
    28  	addFirstLabelPatch string = `[
    29           { "op": "add", "path": "/metadata/labels", "value": {"added-label": "yes"}}
    30       ]`
    31  	addAdditionalLabelPatch string = `[
    32           { "op": "add", "path": "/metadata/labels/added-label", "value": "yes" }
    33       ]`
    34  	updateLabelPatch string = `[
    35           { "op": "replace", "path": "/metadata/labels/added-label", "value": "yes" }
    36       ]`
    37  )
    38  
    39  // Add a label {"added-label": "yes"} to the object
    40  func addLabel(ar v1.AdmissionReview) *v1.AdmissionResponse {
    41  	klog.V(2).Info("calling add-label")
    42  	obj := struct {
    43  		metav1.ObjectMeta `json:"metadata,omitempty"`
    44  	}{}
    45  	raw := ar.Request.Object.Raw
    46  	err := json.Unmarshal(raw, &obj)
    47  	if err != nil {
    48  		klog.Error(err)
    49  		return toV1AdmissionResponse(err)
    50  	}
    51  
    52  	reviewResponse := v1.AdmissionResponse{}
    53  	reviewResponse.Allowed = true
    54  
    55  	pt := v1.PatchTypeJSONPatch
    56  	labelValue, hasLabel := obj.ObjectMeta.Labels["added-label"]
    57  	switch {
    58  	case len(obj.ObjectMeta.Labels) == 0:
    59  		reviewResponse.Patch = []byte(addFirstLabelPatch)
    60  		reviewResponse.PatchType = &pt
    61  	case !hasLabel:
    62  		reviewResponse.Patch = []byte(addAdditionalLabelPatch)
    63  		reviewResponse.PatchType = &pt
    64  	case labelValue != "yes":
    65  		reviewResponse.Patch = []byte(updateLabelPatch)
    66  		reviewResponse.PatchType = &pt
    67  	default:
    68  		// already set
    69  	}
    70  	return &reviewResponse
    71  }
    72  

View as plain text