Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

application: init webhook #359

Merged
merged 3 commits into from
Aug 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 8 additions & 0 deletions cmd/fleet-manager/application/application.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (

"kurator.dev/kurator/cmd/fleet-manager/options"
"kurator.dev/kurator/pkg/fleet-manager"
"kurator.dev/kurator/pkg/webhooks"
)

var log = ctrl.Log.WithName("application")
Expand All @@ -37,5 +38,12 @@ func InitControllers(ctx context.Context, opts *options.Options, mgr ctrl.Manage
return err
}

if err := (&webhooks.ApplicationWebhook{
Client: mgr.GetClient(),
}).SetupWebhookWithManager(mgr); err != nil {
log.Error(err, "unable to create Application webhook", "Webhook", "Application")
return err
}

return nil
}
2 changes: 2 additions & 0 deletions cmd/fleet-manager/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,8 @@ func run(ctx context.Context, opts *options.Options) error {
LeaderElectionResourceLock: resourcelock.LeasesResourceLock,
LeaderElectionID: "kurator-fleet-manager-leader-elect",
LeaderElectionNamespace: opts.LeaderElectionNamespace,
Port: opts.WebhookPort,
CertDir: opts.WebhookCertDir,
EventBroadcaster: broadcaster,
})
if err != nil {
Expand Down
15 changes: 15 additions & 0 deletions cmd/fleet-manager/options/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ type Options struct {
LeaderElectionNamespace string
ProfilerAddress string
Concurrency int
WebhookPort int
WebhookCertDir string
}

func (opt *Options) AddFlags(fs *pflag.FlagSet) {
Expand Down Expand Up @@ -71,4 +73,17 @@ func (opt *Options) AddFlags(fs *pflag.FlagSet) {
"",
"Path to the directory containing the Fleet manifests, built-in manifests will be used if not specified",
)

fs.IntVar(
&opt.WebhookPort,
"webhook-port",
9443,
"Webhook Server port.",
)

fs.StringVar(
&opt.WebhookCertDir,
"webhook-cert-dir",
"/tmp/k8s-webhook-server/serving-certs/",
"Webhook cert dir, only used when webhook-port is specified.")
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ metadata:
spec:
dnsNames:
- kurator-webhook-service.{{ .Release.Namespace }}.svc
- kurator-webhook-service-fleet.{{ .Release.Namespace }}.svc
- kurator-webhook-service.{{ .Release.Namespace }}.svc.cluster.local
issuerRef:
kind: Issuer
Expand Down
15 changes: 15 additions & 0 deletions manifests/charts/fleet-manager/templates/deployment.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,28 @@ spec:
- args:
- --leader-elect
- --v={{ .Values.logging.level }}
- --webhook-port={{ .Values.webhook.port }}
- --webhook-cert-dir={{ .Values.webhook.certMountPath }}
image: {{ .Values.image.hub }}/fleet-manager:{{ .Values.image.tag }}
imagePullPolicy: {{ .Values.image.pullPolicy }}
name: manager
ports:
- containerPort: {{ .Values.webhook.port }}
name: webhook-server
protocol: TCP
volumeMounts:
- mountPath: {{ .Values.webhook.certMountPath }}
name: cert
readOnly: true
serviceAccountName: kurator-fleet-manager
terminationGracePeriodSeconds: 10
tolerations:
- effect: NoSchedule
key: node-role.kubernetes.io/master
- effect: NoSchedule
key: node-role.kubernetes.io/control-plane
volumes:
- name: cert
secret:
defaultMode: 420
secretName: kurator-webhook-service-cert
11 changes: 11 additions & 0 deletions manifests/charts/fleet-manager/templates/service.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
apiVersion: v1
kind: Service
metadata:
name: kurator-webhook-service-fleet
namespace: {{ .Release.Namespace }}
spec:
ports:
- port: 443
targetPort: webhook-server
selector:
app.kubernetes.io/name: kurator-fleet-manager
30 changes: 30 additions & 0 deletions manifests/charts/fleet-manager/templates/webhooks.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingWebhookConfiguration
metadata:
annotations:
cert-manager.io/inject-ca-from: {{ .Release.Namespace }}/kurator-serving-cert
creationTimestamp: null
name: fleet-manager-validating-webhook-configuration
webhooks:
- admissionReviewVersions:
- v1
- v1beta1
clientConfig:
service:
name: kurator-webhook-service-fleet
namespace: {{ .Release.Namespace }}
path: /validate-apps-kurator-dev-v1alpha1-application # do not change this
failurePolicy: Fail
matchPolicy: Equivalent
name: validation.application.apps.kurator.dev
rules:
- apiGroups:
- apps.kurator.dev
apiVersions:
- v1alpha1
operations:
- CREATE
- UPDATE
resources:
- applications
sideEffects: None
4 changes: 4 additions & 0 deletions manifests/charts/fleet-manager/values.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,7 @@ image:

logging:
level: 0

webhook:
port: 9443
certMountPath: /tmp/k8s-webhook-server/serving-certs
128 changes: 128 additions & 0 deletions pkg/webhooks/application_webhook.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
/*
Copyright Kurator 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 webhooks

import (
"context"
"fmt"

apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/validation/field"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/webhook"

"kurator.dev/kurator/pkg/apis/apps/v1alpha1"
)

var _ webhook.CustomValidator = &ApplicationWebhook{}

type ApplicationWebhook struct {
Client client.Reader
}

func (wh *ApplicationWebhook) SetupWebhookWithManager(mgr ctrl.Manager) error {
return ctrl.NewWebhookManagedBy(mgr).
For(&v1alpha1.Application{}).
WithValidator(wh).
Complete()
}

func (wh *ApplicationWebhook) ValidateCreate(_ context.Context, obj runtime.Object) error {
in, ok := obj.(*v1alpha1.Application)
if !ok {
return apierrors.NewBadRequest(fmt.Sprintf("expected a Application but got a %T", obj))
}

return wh.validate(in)
}

func (wh *ApplicationWebhook) validate(in *v1alpha1.Application) error {
var allErrs field.ErrorList

allErrs = append(allErrs, validateFleet(in)...)

if len(allErrs) > 0 {
return apierrors.NewInvalid(v1alpha1.SchemeGroupVersion.WithKind("Application").GroupKind(), in.Name, allErrs)
}

return nil
}

// validateFleet validates the fleet in the application with the following rules:
// 1 if defaultFleet is set, make sure all policy fleet(if set) is same as the defaultFleet
// 2 if defaultFleet is not set, every individual policies must be set and must be same as the first policy fleet
func validateFleet(in *v1alpha1.Application) field.ErrorList {
var allErrs field.ErrorList

defaultFleet := ""
if in.Spec.Destination != nil {
defaultFleet = in.Spec.Destination.Fleet
}

// if defaultFleet is set, make sure all policy fleet(if set) is same as the defaultFleet
if defaultFleet != "" {
for i, policy := range in.Spec.SyncPolicies {
if policy.Destination != nil && policy.Destination.Fleet != "" && defaultFleet != policy.Destination.Fleet {
allErrs = append(allErrs, field.Invalid(field.NewPath("spec", "syncPolicies").Index(i).Child("destination", "fleet"), policy.Destination.Fleet, fmt.Sprintf("must be same as application.spec.destination.fleet:%v, because fleet must be consistent throughout the application", defaultFleet)))
}
}
}

// if defaultFleet is not set, every individual policies must be set and must be same as the first policy fleet
if defaultFleet == "" {
var (
firstPolicyFleet string
isFirst = true
)
for i, policy := range in.Spec.SyncPolicies {
// if individual policy fleet is not set, return err
if policy.Destination == nil || policy.Destination.Fleet == "" {
allErrs = append(allErrs, field.Required(field.NewPath("spec", "syncPolicies").Index(i).Child("destination", "fleet"), "must be set when application.spec.destination.fleet is not set"))
return allErrs
}
if isFirst {
firstPolicyFleet = policy.Destination.Fleet
isFirst = false
}
if !isFirst && firstPolicyFleet != policy.Destination.Fleet {
allErrs = append(allErrs, field.Invalid(field.NewPath("spec", "syncPolicies").Index(i).Child("destination", "fleet"), policy.Destination.Fleet, fmt.Sprintf("must be same as firstPolicyFleet:%v, because fleet must be consistent throughout the application", firstPolicyFleet)))
}
}
}

return allErrs
}

func (wh *ApplicationWebhook) ValidateUpdate(_ context.Context, oldObj, newObj runtime.Object) error {
_, ok := oldObj.(*v1alpha1.Application)
if !ok {
return apierrors.NewBadRequest(fmt.Sprintf("expected a Application but got a %T", oldObj))
}

newApplication, ok := newObj.(*v1alpha1.Application)
if !ok {
return apierrors.NewBadRequest(fmt.Sprintf("expected a Application but got a %T", newObj))
}

return wh.validate(newApplication)
}

func (wh *ApplicationWebhook) ValidateDelete(_ context.Context, obj runtime.Object) error {
return nil
}
101 changes: 101 additions & 0 deletions pkg/webhooks/application_webhook_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
/*
Copyright Kurator 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 webhooks

import (
"io/fs"
"os"
"path"
"path/filepath"
"testing"

. "github.com/onsi/gomega"
"github.com/stretchr/testify/assert"
"sigs.k8s.io/yaml"

"kurator.dev/kurator/pkg/apis/apps/v1alpha1"
)

func TestValidApplicationValidation(t *testing.T) {
// read configuration from examples directory to test valid application configuration
r := path.Join("../../examples", "application")
caseNames := make([]string, 0)
err := filepath.WalkDir(r, func(path string, d fs.DirEntry, err error) error {
if d.IsDir() {
return nil
}

caseNames = append(caseNames, path)

return nil
})
assert.NoError(t, err)

wh := &ApplicationWebhook{}
for _, tt := range caseNames {
t.Run(tt, func(t *testing.T) {
g := NewWithT(t)
c, err := readApplication(tt)
g.Expect(err).NotTo(HaveOccurred())

err = wh.validate(c)
g.Expect(err).NotTo(HaveOccurred())
})
}
}

func TestInvalidApplicationValidation(t *testing.T) {
r := path.Join("testdata", "application")
caseNames := make([]string, 0)
err := filepath.WalkDir(r, func(path string, d fs.DirEntry, err error) error {
if d.IsDir() {
return nil
}

caseNames = append(caseNames, path)

return nil
})
assert.NoError(t, err)

wh := &ApplicationWebhook{}
for _, tt := range caseNames {
t.Run(tt, func(t *testing.T) {
g := NewWithT(t)
c, err := readApplication(tt)
g.Expect(err).NotTo(HaveOccurred())

err = wh.validate(c)
g.Expect(err).To(HaveOccurred())
t.Logf("%v", err)
})
}
}

func readApplication(filename string) (*v1alpha1.Application, error) {
b, err := os.ReadFile(filename)
if err != nil {
return nil, err
}

c := &v1alpha1.Application{}
if err := yaml.Unmarshal(b, c); err != nil {
return nil, err
}

return c, nil
}