Skip to content

Commit

Permalink
add ephemeraljob validating webhook, add validation&ut
Browse files Browse the repository at this point in the history
Signed-off-by: Abner-1 <Abner199709@gmail.com>
  • Loading branch information
ABNER-1 committed May 21, 2024
1 parent 1bc8d85 commit c77a185
Show file tree
Hide file tree
Showing 8 changed files with 975 additions and 1 deletion.
21 changes: 21 additions & 0 deletions config/webhook/manifests.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -470,6 +470,27 @@ webhooks:
resources:
- daemonsets
sideEffects: None
- admissionReviewVersions:
- v1
- v1beta1
clientConfig:
service:
name: webhook-service
namespace: system
path: /validate-apps-kruise-io-v1alpha1-ephemeraljob
failurePolicy: Fail
name: vephemeraljobs.kb.io
rules:
- apiGroups:
- apps.kruise.io
apiVersions:
- v1alpha1
operations:
- CREATE
- UPDATE
resources:
- ephemeraljobs
sideEffects: None
- admissionReviewVersions:
- v1
- v1beta1
Expand Down
25 changes: 25 additions & 0 deletions pkg/webhook/add_ephemeraljob.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*
Copyright 2021 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 webhook

import (
"github.com/openkruise/kruise/pkg/webhook/ephemeraljob/validating"
)

func init() {
addHandlers(validating.HandlerGetterMap)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/*
Copyright 2021 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"

"k8s.io/apimachinery/pkg/util/validation/field"
"k8s.io/klog/v2"
"k8s.io/kubernetes/pkg/apis/core/validation"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"

appsv1alpha1 "github.com/openkruise/kruise/apis/apps/v1alpha1"
"github.com/openkruise/kruise/pkg/webhook/util/convertor"
)

// EphemeralJobCreateUpdateHandler handles EphemeralJob
type EphemeralJobCreateUpdateHandler struct {
// Decoder decodes objects
Decoder *admission.Decoder
}

var _ admission.Handler = &EphemeralJobCreateUpdateHandler{}

func NewHandler(mgr manager.Manager) admission.Handler {
return &EphemeralJobCreateUpdateHandler{Decoder: admission.NewDecoder(mgr.GetScheme())}

Check warning on line 42 in pkg/webhook/ephemeraljob/validating/ephemeraljob_create_update_handler.go

View check run for this annotation

Codecov / codecov/patch

pkg/webhook/ephemeraljob/validating/ephemeraljob_create_update_handler.go#L41-L42

Added lines #L41 - L42 were not covered by tests
}

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

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

if err := validate(obj); err != nil {
klog.Warningf("Error validate EphemeralJob %s: %v", obj.Name, err)
return admission.Errored(http.StatusBadRequest, err)

Check warning on line 56 in pkg/webhook/ephemeraljob/validating/ephemeraljob_create_update_handler.go

View check run for this annotation

Codecov / codecov/patch

pkg/webhook/ephemeraljob/validating/ephemeraljob_create_update_handler.go#L55-L56

Added lines #L55 - L56 were not covered by tests
}

return admission.ValidationResponse(true, "allowed")
}

func validate(obj *appsv1alpha1.EphemeralJob) error {
ecs, err := convertor.ConvertEphemeralContainer(obj.Spec.Template.EphemeralContainers)
if err != nil {
return err

Check warning on line 65 in pkg/webhook/ephemeraljob/validating/ephemeraljob_create_update_handler.go

View check run for this annotation

Codecov / codecov/patch

pkg/webhook/ephemeraljob/validating/ephemeraljob_create_update_handler.go#L65

Added line #L65 was not covered by tests
}
// don't validate EphemeralContainer TargetContainerName
allErrs := validateEphemeralContainers(ecs, field.NewPath("ephemeralContainers"), validation.PodValidationOptions{})
return allErrs.ToAggregate()
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
package validating

import (
"context"
"fmt"
"net/http"
"reflect"
"testing"

admissionv1 "k8s.io/api/admission/v1"
"k8s.io/apimachinery/pkg/runtime"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"

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

var scheme = runtime.NewScheme()

func init() {
scheme = runtime.NewScheme()
_ = alpha1.AddToScheme(scheme)
}

func getFailedJSON() string {
return `{
"apiVersion": "apps.kruise.io/v1alpha1",
"kind": "EphemeralJob",
"metadata": {
"creationTimestamp": "2024-05-09T08:29:50Z",
"generation": 1,
"name": "ephermeraljob-sample",
"namespace": "test"
},
"spec": {
"parallelism": 1,
"replicas": 1,
"selector": {
"matchLabels": {
"app": "test-2"
}
},
"template": {
"ephemeralContainers": {
"ephemeralContainerCommon": {
"image": "busybox",
"imagePullPolicy": "IfNotPresent",
"name": "debugger",
"securityContext": {
"capabilities": {
"add": [
"SYS_ADMIN",
"NET_ADMIN"
]
}
},
"terminationMessagePolicy": "File"
},
"targetContainerName": "test"
}
},
"ttlSecondsAfterFinished": 1800
}
}`
}

func getOKJSON(targetContainerName string) string {
return fmt.Sprintf(`{
"apiVersion": "apps.kruise.io/v1alpha1",
"kind": "EphemeralJob",
"metadata": {
"name": "ephermeraljob-sample",
"namespace": "test"
},
"spec": {
"parallelism": 1,
"replicas": 1,
"selector": {
"matchLabels": {
"app": "test-2"
}
},
"template": {
"ephemeralContainers": [{
"image": "busybox",
"imagePullPolicy": "IfNotPresent",
"name": "debugger",
"securityContext": {
"capabilities": {
"add": [
"SYS_ADMIN",
"NET_ADMIN"
]
}
},
"terminationMessagePolicy": "File",
"targetContainerName": "%v"
}]
},
"ttlSecondsAfterFinished": 1800
}
}`, targetContainerName)
}

func TestEphemeralJobCreateUpdateHandler_Handle(t *testing.T) {
type args struct {
req admission.Request
}
tests := []struct {
name string
args args
wantOK bool
}{
{
name: "failed case",
wantOK: false,
args: args{
req: admission.Request{
AdmissionRequest: admissionv1.AdmissionRequest{
Operation: admissionv1.Create,
Object: runtime.RawExtension{
Raw: []byte(getFailedJSON()),
},
},
},
},
},
{
name: "ok case with empty targetContainerName",
wantOK: true,
args: args{
req: admission.Request{
AdmissionRequest: admissionv1.AdmissionRequest{
Operation: admissionv1.Create,
Object: runtime.RawExtension{
Raw: []byte(getOKJSON("")),
},
},
},
},
},
{
name: "ok case with targetContainerName",
wantOK: true,
args: args{
req: admission.Request{
AdmissionRequest: admissionv1.AdmissionRequest{
Operation: admissionv1.Create,
Object: runtime.RawExtension{
Raw: []byte(getOKJSON("test")),
},
},
},
},
},
}

d := admission.NewDecoder(scheme)
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
h := &EphemeralJobCreateUpdateHandler{
Decoder: d,
}
if got := h.Handle(context.TODO(), tt.args.req); !reflect.DeepEqual(got.Allowed, tt.wantOK) {
t.Errorf("Handle() = %v, want %v", got.Result.Code == http.StatusOK, tt.wantOK)
} else if !got.Allowed {
t.Log(got.Result.Message)
}
})
}
}
Loading

0 comments on commit c77a185

Please sign in to comment.