Skip to content

Commit

Permalink
Update webhook example
Browse files Browse the repository at this point in the history
  • Loading branch information
iawia002 committed Aug 30, 2023
1 parent 776a8ec commit ec2e904
Show file tree
Hide file tree
Showing 39 changed files with 126 additions and 70 deletions.
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,6 @@ type Foo struct {
Status FooStatus `json:"status,omitempty"`
}

// +kubebuilder:webhook:path=/mutate-foo-example-io-v1alpha1-foo,mutating=true,failurePolicy=fail,sideEffects=None,groups=foo.example.io,resources=foos,verbs=create;update,versions=v1alpha1,name=foo.example.io,admissionReviewVersions=v1
// +kubebuilder:webhook:path=/validate-foo-example-io-v1alpha1-foo,mutating=false,failurePolicy=fail,sideEffects=None,groups=foo.example.io,resources=foos,verbs=create;update,versions=v1alpha1,name=foo.example.io,admissionReviewVersions=v1

// +kubebuilder:webhook:path=/mutate-v1-pod,mutating=true,failurePolicy=fail,sideEffects=None,groups="",resources=pods,verbs=create;update,versions=v1,name=mpod.kb.io,admissionReviewVersions=v1

// +kubebuilder:validation:Enum=A;B

// FooType ...
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ import (
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
)

// +kubebuilder:webhook:path=/mutate-foo-example-io-v1alpha1-foo,mutating=true,failurePolicy=fail,sideEffects=None,groups=foo.example.io,resources=foos,verbs=create;update,versions=v1alpha1,name=foo.example.io,admissionReviewVersions=v1
// +kubebuilder:webhook:path=/validate-foo-example-io-v1alpha1-foo,mutating=false,failurePolicy=fail,sideEffects=None,groups=foo.example.io,resources=foos,verbs=create;update,versions=v1alpha1,name=foo.example.io,admissionReviewVersions=v1

// SetupWebhookWithManager ...
func (r *Foo) SetupWebhookWithManager(mgr ctrl.Manager) error {
return ctrl.NewWebhookManagedBy(mgr).
Expand Down
6 changes: 4 additions & 2 deletions kubernetes/controller/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import (
metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server"
"sigs.k8s.io/controller-runtime/pkg/webhook"

foov1alpha1 "github.com/iawia002/pandora/kubernetes/apis/example/apis/foo/v1alpha1"
foov1alpha1 "github.com/iawia002/pandora/kubernetes/apis/foo/v1alpha1"
controllerruntime "github.com/iawia002/pandora/kubernetes/controller/controller-runtime"
samplecontroller "github.com/iawia002/pandora/kubernetes/controller/sample-controller"
controllerwebhook "github.com/iawia002/pandora/kubernetes/controller/webhook"
Expand Down Expand Up @@ -110,7 +110,9 @@ func run(config *rest.Config) error {
if err = (&foov1alpha1.Foo{}).SetupWebhookWithManager(mgr); err != nil {
return err
}
mgr.GetWebhookServer().Register("/mutate-v1-pod", &webhook.Admission{Handler: &controllerwebhook.PodAnnotator{Client: mgr.GetClient()}})
if err = controllerwebhook.SetupWebhookWithManager(mgr); err != nil {
return err
}

ctx := signals.SetupSignalHandler()
informer.Start(ctx.Done())
Expand Down
78 changes: 57 additions & 21 deletions kubernetes/controller/webhook/pod.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,38 +2,74 @@ package webhook

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

corev1 "k8s.io/api/core/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
"k8s.io/apimachinery/pkg/runtime"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/builder"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
)

// PodAnnotator ...
type PodAnnotator struct {
Client client.Client
decoder *admission.Decoder
func SetupWebhookWithManager(mgr ctrl.Manager) error {

Check failure on line 14 in kubernetes/controller/webhook/pod.go

View workflow job for this annotation

GitHub Actions / Go 1.21 in ubuntu-latest

exported: exported function SetupWebhookWithManager should have comment or be unexported (revive)
return builder.WebhookManagedBy(mgr).
For(&corev1.Pod{}).
WithDefaulter(&podAnnotator{}).
WithValidator(&podValidator{}).
Complete()
}

// Handle ...
func (a *PodAnnotator) Handle(_ context.Context, req admission.Request) admission.Response {
pod := &corev1.Pod{}
if err := a.decoder.Decode(req, pod); err != nil {
return admission.Errored(http.StatusBadRequest, err)
// +kubebuilder:webhook:path=/mutate--v1-pod,mutating=true,failurePolicy=fail,sideEffects=None,groups="",resources=pods,verbs=create;update,versions=v1,name=mpod.kb.io,admissionReviewVersions=v1

// podAnnotator annotates Pods
type podAnnotator struct{}

// Default ...
func (a *podAnnotator) Default(_ context.Context, obj runtime.Object) error {
pod, ok := obj.(*corev1.Pod)
if !ok {
return fmt.Errorf("expected a Pod but got a %T", obj)
}

if pod.Annotations == nil {
pod.Annotations = map[string]string{}
}
pod.Annotations["example-mutating-admission-webhook"] = "foo"
return nil
}

// +kubebuilder:webhook:path=/validate--v1-pod,mutating=false,failurePolicy=fail,sideEffects=None,groups="",resources=pods,verbs=create;update,versions=v1,name=vpod.kb.io,admissionReviewVersions=v1

// podValidator validates Pods
type podValidator struct{}

// mutate the fields in pod
// validate admits a pod if a specific annotation exists.
func (v *podValidator) validate(_ context.Context, obj runtime.Object) (admission.Warnings, error) {
pod, ok := obj.(*corev1.Pod)
if !ok {
return nil, fmt.Errorf("expected a Pod but got a %T", obj)
}

marshaledPod, err := json.Marshal(pod)
if err != nil {
return admission.Errored(http.StatusInternalServerError, err)
key := "example-mutating-admission-webhook"
anno, found := pod.Annotations[key]
if !found {
return nil, fmt.Errorf("missing annotation %s", key)
}
if anno != "foo" {
return nil, fmt.Errorf("annotation %s did not have value %q", key, "foo")
}
return admission.PatchResponseFromRaw(req.Object.Raw, marshaledPod)

return nil, nil
}

// InjectDecoder ...
func (a *PodAnnotator) InjectDecoder(d *admission.Decoder) error {
a.decoder = d
return nil
func (v *podValidator) ValidateCreate(ctx context.Context, obj runtime.Object) (admission.Warnings, error) {
return v.validate(ctx, obj)
}

func (v *podValidator) ValidateUpdate(ctx context.Context, _, newObj runtime.Object) (admission.Warnings, error) {
return v.validate(ctx, newObj)
}

func (v *podValidator) ValidateDelete(ctx context.Context, obj runtime.Object) (admission.Warnings, error) {
return v.validate(ctx, obj)
}
File renamed without changes.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

File renamed without changes.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ GO111MODULE=on go install k8s.io/code-generator/cmd/openapi-gen
# All API group names in the pkg/apis directory that need code generation
PKGS=(foo/v1alpha1)

CLIENT_PATH=github.com/iawia002/pandora/kubernetes/apis/example
CLIENT_PATH=github.com/iawia002/pandora/kubernetes
CLIENT_APIS=${CLIENT_PATH}/apis

ALL_PKGS=""
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@ set -o pipefail
GO111MODULE=on go install sigs.k8s.io/controller-tools/cmd/controller-gen

echo "Generating Webhook"
controller-gen webhook paths=./apis/... output:dir=./webhook
controller-gen webhook paths="{./apis/..., ./controller/webhook/...}" output:dir=./webhook
Loading

0 comments on commit ec2e904

Please sign in to comment.