Skip to content

Commit

Permalink
Add mutating and validating webhook for CloneSet (#209)
Browse files Browse the repository at this point in the history
Signed-off-by: Siyu Wang <[email protected]>
  • Loading branch information
FillZpp authored and Fei-Guo committed Jan 7, 2020
1 parent 52a177b commit aed6793
Show file tree
Hide file tree
Showing 15 changed files with 967 additions and 3 deletions.
3 changes: 3 additions & 0 deletions pkg/apis/apps/v1alpha1/cloneset_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ const (
// CloneSetInstanceID is a unique id for Pods and PVCs.
// Each pod and the pvcs it owns have the same instance-id.
CloneSetInstanceID = "apps.kruise.io/cloneset-instance-id"

// DefaultCloneSetMaxUnavailable is the default value of maxUnavailable for CloneSet update strategy.
DefaultCloneSetMaxUnavailable = "10%"
)

// CloneSetSpec defines the desired state of CloneSet
Expand Down
2 changes: 1 addition & 1 deletion pkg/apis/apps/v1alpha1/defaults.go
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ func SetDefaults_CloneSet(obj *CloneSet) {
*obj.Spec.UpdateStrategy.Partition = 0
}
if obj.Spec.UpdateStrategy.MaxUnavailable == nil {
maxUnavailable := intstr.FromInt(1)
maxUnavailable := intstr.FromString(DefaultCloneSetMaxUnavailable)
obj.Spec.UpdateStrategy.MaxUnavailable = &maxUnavailable
}
}
2 changes: 1 addition & 1 deletion pkg/controller/cloneset/update/cloneset_update.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ func calculateUpdateCount(strategy appsv1alpha1.CloneSetUpdateStrategy, totalRep
partition = int(*strategy.Partition)
}
maxUnavailable, _ := intstrutil.GetValueFromIntOrPercent(
intstrutil.ValueOrDefault(strategy.MaxUnavailable, intstrutil.FromString("10%")), totalReplicas, true)
intstrutil.ValueOrDefault(strategy.MaxUnavailable, intstrutil.FromString(appsv1alpha1.DefaultCloneSetMaxUnavailable)), totalReplicas, true)

return integer.IntMax(integer.IntMin(
notUpdatedCount-partition,
Expand Down
2 changes: 1 addition & 1 deletion pkg/util/inplaceupdate/inplace_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ import (
"sigs.k8s.io/controller-runtime/pkg/client"
)

var inPlaceUpdatePatchRexp = regexp.MustCompile("/spec/containers/([0-9]+)/image")
var inPlaceUpdatePatchRexp = regexp.MustCompile("^/spec/containers/([0-9]+)/image$")

// Interface for managing pods in-place update.
type Interface interface {
Expand Down
14 changes: 14 additions & 0 deletions pkg/util/tools.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,17 @@ func SlowStartBatch(count int, initialBatchSize int, fn func(index int) error) (
}
return successes, nil
}

// CheckDuplicate finds if there are duplicated items in a list.
func CheckDuplicate(list []string) []string {
tmpMap := make(map[string]struct{})
var dupList []string
for _, name := range list {
if _, ok := tmpMap[name]; ok {
dupList = append(dupList, name)
} else {
tmpMap[name] = struct{}{}
}
}
return dupList
}
53 changes: 53 additions & 0 deletions pkg/webhook/default_server/add_mutating_cloneset.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/*
Copyright 2019 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 defaultserver

import (
"fmt"

appsv1alpha1 "github.com/openkruise/kruise/pkg/apis/apps/v1alpha1"
"github.com/openkruise/kruise/pkg/util/gate"
"github.com/openkruise/kruise/pkg/webhook/default_server/cloneset/mutating"
)

func init() {
if !gate.ResourceEnabled(&appsv1alpha1.CloneSet{}) {
return
}
for k, v := range mutating.Builders {
_, found := builderMap[k]
if found {
log.V(1).Info(fmt.Sprintf(
"conflicting webhook builder names in builder map: %v", k))
}
builderMap[k] = v
}
for k, v := range mutating.HandlerMap {
_, found := HandlerMap[k]
if found {
log.V(1).Info(fmt.Sprintf(
"conflicting webhook builder names in handler map: %v", k))
}
_, found = builderMap[k]
if !found {
log.V(1).Info(fmt.Sprintf(
"can't find webhook builder name %q in builder map", k))
continue
}
HandlerMap[k] = v
}
}
53 changes: 53 additions & 0 deletions pkg/webhook/default_server/add_validating_cloneset.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/*
Copyright 2019 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 defaultserver

import (
"fmt"

appsv1alpha1 "github.com/openkruise/kruise/pkg/apis/apps/v1alpha1"
"github.com/openkruise/kruise/pkg/util/gate"
"github.com/openkruise/kruise/pkg/webhook/default_server/cloneset/validating"
)

func init() {
if !gate.ResourceEnabled(&appsv1alpha1.CloneSet{}) {
return
}
for k, v := range validating.Builders {
_, found := builderMap[k]
if found {
log.V(1).Info(fmt.Sprintf(
"conflicting webhook builder names in builder map: %v", k))
}
builderMap[k] = v
}
for k, v := range validating.HandlerMap {
_, found := HandlerMap[k]
if found {
log.V(1).Info(fmt.Sprintf(
"conflicting webhook builder names in handler map: %v", k))
}
_, found = builderMap[k]
if !found {
log.V(1).Info(fmt.Sprintf(
"can't find webhook builder name %q in builder map", k))
continue
}
HandlerMap[k] = v
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
/*
Copyright 2019 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 mutating

import (
"context"
"encoding/json"
"net/http"

"github.com/openkruise/kruise/pkg/util"
patchutil "github.com/openkruise/kruise/pkg/util/patch"
"k8s.io/klog"

appsv1alpha1 "github.com/openkruise/kruise/pkg/apis/apps/v1alpha1"
"sigs.k8s.io/controller-runtime/pkg/runtime/inject"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission/types"
)

func init() {
webhookName := "mutating-create-update-cloneset"
if HandlerMap[webhookName] == nil {
HandlerMap[webhookName] = []admission.Handler{}
}
HandlerMap[webhookName] = append(HandlerMap[webhookName], &CloneSetCreateUpdateHandler{})
}

// CloneSetCreateUpdateHandler handles CloneSet
type CloneSetCreateUpdateHandler struct {
// To use the client, you need to do the following:
// - uncomment it
// - import sigs.k8s.io/controller-runtime/pkg/client
// - uncomment the InjectClient method at the bottom of this file.
// Client client.Client

// Decoder decodes objects
Decoder types.Decoder
}

var _ admission.Handler = &CloneSetCreateUpdateHandler{}

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

err := h.Decoder.Decode(req, obj)
if err != nil {
return admission.ErrorResponse(http.StatusBadRequest, err)
}

appsv1alpha1.SetDefaults_CloneSet(obj)

marshaled, err := json.Marshal(obj)
if err != nil {
return admission.ErrorResponse(http.StatusInternalServerError, err)
}
resp := patchutil.ResponseFromRaw(req.AdmissionRequest.Object.Raw, marshaled)
if len(resp.Patches) > 0 {
klog.V(5).Infof("Admit CloneSet %s/%s patches: %v", obj.Namespace, obj.Name, util.DumpJSON(resp.Patches))
}
return resp
}

//var _ inject.Client = &CloneSetCreateUpdateHandler{}
//
//// InjectClient injects the client into the CloneSetCreateUpdateHandler
//func (h *CloneSetCreateUpdateHandler) InjectClient(c client.Client) error {
// h.Client = c
// return nil
//}

var _ inject.Decoder = &CloneSetCreateUpdateHandler{}

// InjectDecoder injects the decoder into the CloneSetCreateUpdateHandler
func (h *CloneSetCreateUpdateHandler) InjectDecoder(d types.Decoder) error {
h.Decoder = d
return nil
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
Copyright 2019 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 mutating

import (
appsv1alpha1 "github.com/openkruise/kruise/pkg/apis/apps/v1alpha1"
admissionregistrationv1beta1 "k8s.io/api/admissionregistration/v1beta1"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission/builder"
)

func init() {
builderName := "mutating-create-update-cloneset"
Builders[builderName] = builder.
NewWebhookBuilder().
Name(builderName+".kruise.io").
Path("/"+builderName).
Mutating().
Operations(admissionregistrationv1beta1.Create, admissionregistrationv1beta1.Update).
FailurePolicy(admissionregistrationv1beta1.Fail).
ForType(&appsv1alpha1.CloneSet{})
}
29 changes: 29 additions & 0 deletions pkg/webhook/default_server/cloneset/mutating/webhooks.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*
Copyright 2019 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 mutating

import (
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission/builder"
)

var (
// Builders contain admission webhook builders
Builders = map[string]*builder.WebhookBuilder{}
// HandlerMap contains admission webhook handlers
HandlerMap = map[string][]admission.Handler{}
)
Loading

0 comments on commit aed6793

Please sign in to comment.