Skip to content

Commit

Permalink
fix: validate update AdvancedDaemonSet (#1505)
Browse files Browse the repository at this point in the history
* fix: validate update AdvancedDaemonSet

Signed-off-by: hantmac <[email protected]>

refactor it

fix

fix

Signed-off-by: hantmac <[email protected]>

* fix ut

Signed-off-by: hantmac <[email protected]>

---------

Signed-off-by: hantmac <[email protected]>
  • Loading branch information
hantmac committed Mar 8, 2024
1 parent c7e1daa commit 209d476
Show file tree
Hide file tree
Showing 4 changed files with 351 additions and 162 deletions.
104 changes: 104 additions & 0 deletions pkg/webhook/daemonset/validating/daemonset_create_update_handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
/*
Copyright 2020 The Kruise Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package validating

import (
"context"
"net/http"

admissionv1 "k8s.io/api/admission/v1"
apiequality "k8s.io/apimachinery/pkg/api/equality"
genericvalidation "k8s.io/apimachinery/pkg/api/validation"
"k8s.io/apimachinery/pkg/util/validation/field"
"k8s.io/klog/v2"
apivalidation "k8s.io/kubernetes/pkg/apis/core/validation"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"

appsv1alpha1 "github.com/openkruise/kruise/apis/apps/v1alpha1"
)

// ValidateDaemonSetName can be used to check whether the given daemon set name is valid.
// Prefix indicates this name will be used as part of generation, in which case
// trailing dashes are allowed.
var ValidateDaemonSetName = genericvalidation.NameIsDNSSubdomain

// DaemonSetCreateUpdateHandler handles DaemonSet
type DaemonSetCreateUpdateHandler struct {
// Decoder decodes objects
Decoder *admission.Decoder
}

func (h *DaemonSetCreateUpdateHandler) validateDaemonSetUpdate(ds, oldDs *appsv1alpha1.DaemonSet) field.ErrorList {
allErrs := apivalidation.ValidateObjectMetaUpdate(&ds.ObjectMeta, &oldDs.ObjectMeta, field.NewPath("metadata"))
daemonset := ds.DeepCopy()
daemonset.Spec.Template = oldDs.Spec.Template
daemonset.Spec.UpdateStrategy = oldDs.Spec.UpdateStrategy
daemonset.Spec.Lifecycle = oldDs.Spec.Lifecycle
daemonset.Spec.BurstReplicas = oldDs.Spec.BurstReplicas
daemonset.Spec.MinReadySeconds = oldDs.Spec.MinReadySeconds
daemonset.Spec.RevisionHistoryLimit = oldDs.Spec.RevisionHistoryLimit

if !apiequality.Semantic.DeepEqual(daemonset.Spec, oldDs.Spec) {
allErrs = append(allErrs, field.Forbidden(field.NewPath("spec"), "updates to daemonset spec for fields other than 'BurstReplicas', 'template', 'lifecycle', 'updateStrategy', 'minReadySeconds', and 'revisionHistoryLimit' are forbidden"))
}
allErrs = append(allErrs, validateDaemonSetSpec(&ds.Spec, field.NewPath("spec"))...)
return allErrs
}

var _ admission.Handler = &DaemonSetCreateUpdateHandler{}

// Handle handles admission requests.
func (h *DaemonSetCreateUpdateHandler) Handle(ctx context.Context, req admission.Request) admission.Response {
obj := &appsv1alpha1.DaemonSet{}
oldObj := &appsv1alpha1.DaemonSet{}
switch req.AdmissionRequest.Operation {
case admissionv1.Create:
err := h.Decoder.Decode(req, obj)
if err != nil {
return admission.Errored(http.StatusBadRequest, err)
}
allowed, reason, err := validatingDaemonSetFn(ctx, obj)
if err != nil {
klog.Warningf("ds %s/%s action %v fail:%s", obj.Namespace, obj.Name, req.AdmissionRequest.Operation, err.Error())
return admission.Errored(http.StatusInternalServerError, err)
}
return admission.ValidationResponse(allowed, reason)

case admissionv1.Update:
err := h.Decoder.Decode(req, obj)
if err != nil {
return admission.Errored(http.StatusBadRequest, err)
}
if err := h.Decoder.DecodeRaw(req.AdmissionRequest.OldObject, oldObj); err != nil {
return admission.Errored(http.StatusBadRequest, err)
}

if allErrs := h.validateDaemonSetUpdate(obj, oldObj); len(allErrs) > 0 {
return admission.Errored(http.StatusUnprocessableEntity, allErrs.ToAggregate())
}
}

return admission.ValidationResponse(true, "")
}

var _ admission.DecoderInjector = &DaemonSetCreateUpdateHandler{}

// InjectDecoder injects the decoder into the DaemonSetCreateUpdateHandler
func (h *DaemonSetCreateUpdateHandler) InjectDecoder(d *admission.Decoder) error {
h.Decoder = d
return nil
}
102 changes: 0 additions & 102 deletions pkg/webhook/daemonset/validating/daemonset_validating_handler_test.go

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,30 +1,10 @@
/*
Copyright 2020 The Kruise Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package validating

import (
"context"
"fmt"
"net/http"
"strconv"

appsv1alpha1 "github.com/openkruise/kruise/apis/apps/v1alpha1"
webhookutil "github.com/openkruise/kruise/pkg/webhook/util"
"github.com/openkruise/kruise/pkg/webhook/util/convertor"
corev1 "k8s.io/api/core/v1"
genericvalidation "k8s.io/apimachinery/pkg/api/validation"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
Expand All @@ -33,24 +13,15 @@ import (
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/apimachinery/pkg/util/validation"
"k8s.io/apimachinery/pkg/util/validation/field"
"k8s.io/klog/v2"
appsvalidation "k8s.io/kubernetes/pkg/apis/apps/validation"
corevalidation "k8s.io/kubernetes/pkg/apis/core/validation"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
)

// ValidateDaemonSetName can be used to check whether the given daemon set name is valid.
// Prefix indicates this name will be used as part of generation, in which case
// trailing dashes are allowed.
var ValidateDaemonSetName = genericvalidation.NameIsDNSSubdomain

// DaemonSetCreateUpdateHandler handles DaemonSet
type DaemonSetCreateUpdateHandler struct {
// Decoder decodes objects
Decoder *admission.Decoder
}
appsv1alpha1 "github.com/openkruise/kruise/apis/apps/v1alpha1"
webhookutil "github.com/openkruise/kruise/pkg/webhook/util"
"github.com/openkruise/kruise/pkg/webhook/util/convertor"
)

func (h *DaemonSetCreateUpdateHandler) validatingDaemonSetFn(ctx context.Context, obj *appsv1alpha1.DaemonSet) (bool, string, error) {
func validatingDaemonSetFn(ctx context.Context, obj *appsv1alpha1.DaemonSet) (bool, string, error) {
allErrs := validateDaemonSet(obj)
if len(allErrs) != 0 {
return false, "", allErrs.ToAggregate()
Expand Down Expand Up @@ -195,29 +166,3 @@ func getPercentValue(intOrStringValue intstr.IntOrString) (int, bool) {
value, _ := strconv.Atoi(intOrStringValue.StrVal[:len(intOrStringValue.StrVal)-1])
return value, true
}

var _ admission.Handler = &DaemonSetCreateUpdateHandler{}

// Handle handles admission requests.
func (h *DaemonSetCreateUpdateHandler) Handle(ctx context.Context, req admission.Request) admission.Response {
obj := &appsv1alpha1.DaemonSet{}

err := h.Decoder.Decode(req, obj)
if err != nil {
return admission.Errored(http.StatusBadRequest, err)
}
allowed, reason, err := h.validatingDaemonSetFn(ctx, obj)
if err != nil {
klog.Warningf("ds %s/%s action %v fail:%s", obj.Namespace, obj.Name, req.AdmissionRequest.Operation, err.Error())
return admission.Errored(http.StatusInternalServerError, err)
}
return admission.ValidationResponse(allowed, reason)
}

var _ admission.DecoderInjector = &DaemonSetCreateUpdateHandler{}

// InjectDecoder injects the decoder into the DaemonSetCreateUpdateHandler
func (h *DaemonSetCreateUpdateHandler) InjectDecoder(d *admission.Decoder) error {
h.Decoder = d
return nil
}
Loading

0 comments on commit 209d476

Please sign in to comment.