Skip to content

Merging Admissionwebhook branch into master #127

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

Closed
wants to merge 13 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
290 changes: 258 additions & 32 deletions Gopkg.lock

Large diffs are not rendered by default.

77 changes: 77 additions & 0 deletions example/controller.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/*
Copyright 2018 The Kubernetes 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 main

import (
"context"

"github.com/go-logr/logr"

appsv1 "k8s.io/api/apps/v1"
"k8s.io/apimachinery/pkg/api/errors"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
)

// reconcileReplicaSet reconciles ReplicaSets
type reconcileReplicaSet struct {
// client can be used to retrieve objects from the APIServer.
client client.Client
log logr.Logger
}

// Implement reconcile.Reconciler so the controller can reconcile objects
var _ reconcile.Reconciler = &reconcileReplicaSet{}

func (r *reconcileReplicaSet) Reconcile(request reconcile.Request) (reconcile.Result, error) {
// set up a convinient log object so we don't have to type request over and over again
log := r.log.WithValues("request", request)

// Fetch the ReplicaSet from the cache
rs := &appsv1.ReplicaSet{}
err := r.client.Get(context.TODO(), request.NamespacedName, rs)
if errors.IsNotFound(err) {
log.Error(nil, "Could not find ReplicaSet")
return reconcile.Result{}, nil
}

if err != nil {
log.Error(err, "Could not fetch ReplicaSet")
return reconcile.Result{}, err
}

// Print the ReplicaSet
log.Info("Reconciling ReplicaSet", "container name", rs.Spec.Template.Spec.Containers[0].Name)

// Set the label if it is missing
if rs.Labels == nil {
rs.Labels = map[string]string{}
}
if rs.Labels["hello"] == "world" {
return reconcile.Result{}, nil
}

// Update the ReplicaSet
rs.Labels["hello"] = "world"
err = r.client.Update(context.TODO(), rs)
if err != nil {
log.Error(err, "Could not write ReplicaSet")
return reconcile.Result{}, err
}

return reconcile.Result{}, nil
}
107 changes: 57 additions & 50 deletions example/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,29 +17,27 @@ limitations under the License.
package main

import (
"context"
"flag"
"os"

"github.com/go-logr/logr"
admissionregistrationv1beta1 "k8s.io/api/admissionregistration/v1beta1"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
apitypes "k8s.io/apimachinery/pkg/types"
_ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/config"
"sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
logf "sigs.k8s.io/controller-runtime/pkg/runtime/log"
"sigs.k8s.io/controller-runtime/pkg/runtime/signals"
"sigs.k8s.io/controller-runtime/pkg/source"
"sigs.k8s.io/controller-runtime/pkg/webhook"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission/builder"
"sigs.k8s.io/controller-runtime/pkg/webhook/types"
)

var (
log = logf.Log.WithName("example-controller")
)
var log = logf.Log.WithName("example-controller")

func main() {
flag.Parse()
Expand Down Expand Up @@ -75,56 +73,65 @@ func main() {
os.Exit(1)
}

if err := mgr.Start(signals.SetupSignalHandler()); err != nil {
entryLog.Error(err, "unable to run manager")
// Setup webhooks
mutatingWebhook, err := builder.NewWebhookBuilder().
Name("mutating.k8s.io").
Type(types.WebhookTypeMutating).
Path("/mutating-pods").
Operations(admissionregistrationv1beta1.Create, admissionregistrationv1beta1.Update).
WithManager(mgr).
ForType(&corev1.Pod{}).
Build(&podAnnotator{client: mgr.GetClient(), decoder: mgr.GetAdmissionDecoder()})
if err != nil {
entryLog.Error(err, "unable to setup mutating webhook")
os.Exit(1)
}
}

// reconcileReplicaSet reconciles ReplicaSets
type reconcileReplicaSet struct {
client client.Client
log logr.Logger
}

// Implement reconcile.Reconciler so the controller can reconcile objects
var _ reconcile.Reconciler = &reconcileReplicaSet{}

func (r *reconcileReplicaSet) Reconcile(request reconcile.Request) (reconcile.Result, error) {
// set up a convinient log object so we don't have to type request over and over again
log := r.log.WithValues("request", request)

// Fetch the ReplicaSet from the cache
rs := &appsv1.ReplicaSet{}
err := r.client.Get(context.TODO(), request.NamespacedName, rs)
if errors.IsNotFound(err) {
log.Error(nil, "Could not find ReplicaSet")
return reconcile.Result{}, nil
}

validatingWebhook, err := builder.NewWebhookBuilder().
Name("validating.k8s.io").
Type(types.WebhookTypeValidating).
Path("/validating-pods").
Operations(admissionregistrationv1beta1.Create, admissionregistrationv1beta1.Update).
WithManager(mgr).
ForType(&corev1.Pod{}).
Build(&podValidator{client: mgr.GetClient(), decoder: mgr.GetAdmissionDecoder()})
if err != nil {
log.Error(err, "Could not fetch ReplicaSet")
return reconcile.Result{}, err
entryLog.Error(err, "unable to setup validating webhook")
os.Exit(1)
}

// Print the ReplicaSet
log.Info("Reconciling ReplicaSet", "container name", rs.Spec.Template.Spec.Containers[0].Name)

// Set the label if it is missing
if rs.Labels == nil {
rs.Labels = map[string]string{}
}
if rs.Labels["hello"] == "world" {
return reconcile.Result{}, nil
as, err := webhook.NewServer("foo-admission-server", mgr, webhook.ServerOptions{
Port: 443,
CertDir: "/tmp/cert",
KVMap: map[string]interface{}{"foo": "bar"},
BootstrapOptions: &webhook.BootstrapOptions{
Secret: &apitypes.NamespacedName{
Namespace: "default",
Name: "foo-admission-server-secret",
},

Service: &webhook.Service{
Namespace: "default",
Name: "foo-admission-server-service",
// Selectors should select the pods that runs this webhook server.
Selectors: map[string]string{
"app": "foo-admission-server",
},
},
},
})
if err != nil {
entryLog.Error(err, "unable to create a new webhook server")
os.Exit(1)
}

// Update the ReplicaSet
rs.Labels["hello"] = "world"
err = r.client.Update(context.TODO(), rs)
err = as.Register(mutatingWebhook, validatingWebhook)
if err != nil {
log.Error(err, "Could not write ReplicaSet")
return reconcile.Result{}, err
entryLog.Error(err, "unable to register webhooks in the admission server")
os.Exit(1)
}

return reconcile.Result{}, nil
if err := mgr.Start(signals.SetupSignalHandler()); err != nil {
entryLog.Error(err, "unable to run manager")
os.Exit(1)
}
}
65 changes: 65 additions & 0 deletions example/mutatingwebhook.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/*
Copyright 2018 The Kubernetes 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 main

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

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

// podAnnotator annotates Pods
type podAnnotator struct {
client client.Client
decoder admission.Decoder
}

// Implement admission.Handler so the controller can handle admission request.
var _ admission.Handler = &podAnnotator{}

// podAnnotator adds an annotation to every incoming pods.
func (a *podAnnotator) Handle(ctx context.Context, req admission.Request) admission.Response {
pod := &corev1.Pod{}

err := a.decoder.Decode(req, pod)
if err != nil {
return admission.ErrorResponse(http.StatusBadRequest, err)
}
copy := pod.DeepCopy()

err = mutatePodsFn(ctx, copy)
if err != nil {
return admission.ErrorResponse(http.StatusInternalServerError, err)
}
return admission.PatchResponse(pod, copy)
}

// mutatePodsFn add an annotation to the given pod
func mutatePodsFn(ctx context.Context, pod *corev1.Pod) error {
v, ok := ctx.Value(admission.StringKey("foo")).(string)
if !ok {
return fmt.Errorf("the value associated with %v is expected to be a string", "foo")
}
anno := pod.GetAnnotations()
anno["example-mutating-admission-webhook"] = v
pod.SetAnnotations(anno)
return nil
}
73 changes: 73 additions & 0 deletions example/validatingwebhook.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/*
Copyright 2018 The Kubernetes 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 main

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

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

// podValidator validates Pods
type podValidator struct {
client client.Client
decoder admission.Decoder
}

// Implement admission.Handler so the controller can handle admission request.
var _ admission.Handler = &podValidator{}

// podValidator admits a pod iff a specific annotation exists.
func (v *podValidator) Handle(ctx context.Context, req admission.Request) admission.Response {
pod := &corev1.Pod{}

err := v.decoder.Decode(req, pod)
if err != nil {
return admission.ErrorResponse(http.StatusBadRequest, err)
}

allowed, reason, err := validatePodsFn(ctx, pod)
if err != nil {
return admission.ErrorResponse(http.StatusInternalServerError, err)
}
return admission.ValidationResponse(allowed, reason)
}

func validatePodsFn(ctx context.Context, pod *corev1.Pod) (bool, string, error) {
v, ok := ctx.Value(admission.StringKey("foo")).(string)
if !ok {
return false, "",
fmt.Errorf("the value associated with key %q is expected to be a string", v)
}
annotations := pod.GetAnnotations()
key := "example-mutating-admission-webhook"
anno, found := annotations[key]
switch {
case !found:
return found, fmt.Sprintf("failed to find annotation with key: %q", key), nil
case found && anno == v:
return found, "", nil
case found && anno != v:
return false,
fmt.Sprintf("the value associate with key %q is expected to be %q, but got %q", "foo", v, anno), nil
}
return false, "", nil
}
4 changes: 2 additions & 2 deletions hack/verify.sh
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,13 @@ header_text "running gometalinter.v2"
gometalinter.v2 --disable-all \
--deadline 5m \
--enable=misspell \
--enable=structcheck \
--enable=golint \
--enable=deadcode \
--enable=goimports \
--enable=errcheck \
--enable=varcheck \
--enable=goconst \
--enable=gas \
--enable=gosec \
--enable=unparam \
--enable=ineffassign \
--enable=nakedret \
Expand All @@ -53,5 +52,6 @@ gometalinter.v2 --disable-all \
--skip=atomic \
./pkg/...
# TODO: Enable these as we fix them to make them pass
# --enable=structcheck \
# --enable=maligned \
# --enable=safesql \
Loading