Skip to content

Commit a63e0de

Browse files
author
Mengqi Yu
committed
split the exmaple file into multiple files
1 parent 883c5a7 commit a63e0de

File tree

4 files changed

+222
-135
lines changed

4 files changed

+222
-135
lines changed

example/controller.go

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
/*
2+
Copyright 2018 The Kubernetes Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package main
18+
19+
import (
20+
"context"
21+
22+
"github.com/go-logr/logr"
23+
24+
appsv1 "k8s.io/api/apps/v1"
25+
"k8s.io/apimachinery/pkg/api/errors"
26+
"sigs.k8s.io/controller-runtime/pkg/client"
27+
"sigs.k8s.io/controller-runtime/pkg/reconcile"
28+
)
29+
30+
// reconcileReplicaSet reconciles ReplicaSets
31+
type reconcileReplicaSet struct {
32+
// client can be used to retrieve objects from the APIServer.
33+
client client.Client
34+
log logr.Logger
35+
}
36+
37+
// Implement reconcile.Reconciler so the controller can reconcile objects
38+
var _ reconcile.Reconciler = &reconcileReplicaSet{}
39+
40+
func (r *reconcileReplicaSet) Reconcile(request reconcile.Request) (reconcile.Result, error) {
41+
// set up a convinient log object so we don't have to type request over and over again
42+
log := r.log.WithValues("request", request)
43+
44+
// Fetch the ReplicaSet from the cache
45+
rs := &appsv1.ReplicaSet{}
46+
err := r.client.Get(context.TODO(), request.NamespacedName, rs)
47+
if errors.IsNotFound(err) {
48+
log.Error(nil, "Could not find ReplicaSet")
49+
return reconcile.Result{}, nil
50+
}
51+
52+
if err != nil {
53+
log.Error(err, "Could not fetch ReplicaSet")
54+
return reconcile.Result{}, err
55+
}
56+
57+
// Print the ReplicaSet
58+
log.Info("Reconciling ReplicaSet", "container name", rs.Spec.Template.Spec.Containers[0].Name)
59+
60+
// Set the label if it is missing
61+
if rs.Labels == nil {
62+
rs.Labels = map[string]string{}
63+
}
64+
if rs.Labels["hello"] == "world" {
65+
return reconcile.Result{}, nil
66+
}
67+
68+
// Update the ReplicaSet
69+
rs.Labels["hello"] = "world"
70+
err = r.client.Update(context.TODO(), rs)
71+
if err != nil {
72+
log.Error(err, "Could not write ReplicaSet")
73+
return reconcile.Result{}, err
74+
}
75+
76+
return reconcile.Result{}, nil
77+
}

example/main.go

Lines changed: 7 additions & 135 deletions
Original file line numberDiff line numberDiff line change
@@ -17,31 +17,22 @@ limitations under the License.
1717
package main
1818

1919
import (
20-
"context"
2120
"flag"
22-
"fmt"
23-
"net/http"
2421
"os"
2522

26-
"github.com/go-logr/logr"
27-
2823
admissionregistrationv1beta1 "k8s.io/api/admissionregistration/v1beta1"
2924
appsv1 "k8s.io/api/apps/v1"
3025
corev1 "k8s.io/api/core/v1"
31-
"k8s.io/apimachinery/pkg/api/errors"
3226
apitypes "k8s.io/apimachinery/pkg/types"
3327
_ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
34-
"sigs.k8s.io/controller-runtime/pkg/client"
3528
"sigs.k8s.io/controller-runtime/pkg/client/config"
3629
"sigs.k8s.io/controller-runtime/pkg/controller"
3730
"sigs.k8s.io/controller-runtime/pkg/handler"
3831
"sigs.k8s.io/controller-runtime/pkg/manager"
39-
"sigs.k8s.io/controller-runtime/pkg/reconcile"
4032
logf "sigs.k8s.io/controller-runtime/pkg/runtime/log"
4133
"sigs.k8s.io/controller-runtime/pkg/runtime/signals"
4234
"sigs.k8s.io/controller-runtime/pkg/source"
4335
"sigs.k8s.io/controller-runtime/pkg/webhook"
44-
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
4536
"sigs.k8s.io/controller-runtime/pkg/webhook/admission/builder"
4637
"sigs.k8s.io/controller-runtime/pkg/webhook/types"
4738
)
@@ -112,21 +103,21 @@ func main() {
112103
as, err := webhook.NewServer("foo-admission-server", mgr, webhook.ServerOptions{
113104
Port: 443,
114105
CertDir: "/tmp/cert",
115-
Client: mgr.GetClient(),
116-
KVMap: map[string]interface{}{"foo": "bar"},
106+
//Client: mgr.GetClient(),
107+
KVMap: map[string]interface{}{"foo": "bar"},
117108
BootstrapOptions: &webhook.BootstrapOptions{
118109
Secret: &apitypes.NamespacedName{
119110
Namespace: "default",
120111
Name: "foo-admission-server-secret",
121112
},
122113

123-
Service: &apitypes.NamespacedName{
114+
Service: &webhook.Service{
124115
Namespace: "default",
125116
Name: "foo-admission-server-service",
126-
},
127-
// Labels should select the pods that runs this webhook server.
128-
Labels: map[string]string{
129-
"app": "foo-admission-server",
117+
// Selectors should select the pods that runs this webhook server.
118+
Selectors: map[string]string{
119+
"app": "foo-admission-server",
120+
},
130121
},
131122
},
132123
})
@@ -145,122 +136,3 @@ func main() {
145136
os.Exit(1)
146137
}
147138
}
148-
149-
// reconcileReplicaSet reconciles ReplicaSets
150-
type reconcileReplicaSet struct {
151-
// client can be used to retrieve objects from the APIServer.
152-
client client.Client
153-
log logr.Logger
154-
}
155-
156-
// Implement reconcile.Reconciler so the controller can reconcile objects
157-
var _ reconcile.Reconciler = &reconcileReplicaSet{}
158-
159-
func (r *reconcileReplicaSet) Reconcile(request reconcile.Request) (reconcile.Result, error) {
160-
// set up a convinient log object so we don't have to type request over and over again
161-
log := r.log.WithValues("request", request)
162-
163-
// Fetch the ReplicaSet from the cache
164-
rs := &appsv1.ReplicaSet{}
165-
err := r.client.Get(context.TODO(), request.NamespacedName, rs)
166-
if errors.IsNotFound(err) {
167-
log.Error(nil, "Could not find ReplicaSet")
168-
return reconcile.Result{}, nil
169-
}
170-
171-
if err != nil {
172-
log.Error(err, "Could not fetch ReplicaSet")
173-
return reconcile.Result{}, err
174-
}
175-
176-
// Print the ReplicaSet
177-
log.Info("Reconciling ReplicaSet", "container name", rs.Spec.Template.Spec.Containers[0].Name)
178-
179-
// Set the label if it is missing
180-
if rs.Labels == nil {
181-
rs.Labels = map[string]string{}
182-
}
183-
if rs.Labels["hello"] == "world" {
184-
return reconcile.Result{}, nil
185-
}
186-
187-
// Update the ReplicaSet
188-
rs.Labels["hello"] = "world"
189-
err = r.client.Update(context.TODO(), rs)
190-
if err != nil {
191-
log.Error(err, "Could not write ReplicaSet")
192-
return reconcile.Result{}, err
193-
}
194-
195-
return reconcile.Result{}, nil
196-
}
197-
198-
// podAnnotator annotates Pods
199-
type podAnnotator struct {
200-
client client.Client
201-
decoder admission.Decoder
202-
}
203-
204-
// Implement admission.Handler so the controller can handle admission request.
205-
var _ admission.Handler = &podAnnotator{}
206-
207-
// podAnnotator adds an annotation to every incoming pods.
208-
func (a *podAnnotator) Handle(_ context.Context, req admission.Request) admission.Response {
209-
pod := &corev1.Pod{}
210-
211-
err := a.decoder.Decode(req, pod)
212-
if err != nil {
213-
return admission.ErrorResponse(http.StatusBadRequest, err)
214-
}
215-
copy := pod.DeepCopy()
216-
217-
err = mutatePodsFn(copy)
218-
if err != nil {
219-
return admission.ErrorResponse(http.StatusInternalServerError, err)
220-
}
221-
return admission.PatchResponse(pod, copy)
222-
}
223-
224-
// mutatePodsFn add an annotation to the given pod
225-
func mutatePodsFn(pod *corev1.Pod) error {
226-
anno := pod.GetAnnotations()
227-
anno["example-mutating-admission-webhhok"] = "foo"
228-
pod.SetAnnotations(anno)
229-
return nil
230-
}
231-
232-
// podValidator validates Pods
233-
type podValidator struct {
234-
client client.Client
235-
decoder admission.Decoder
236-
}
237-
238-
// Implement admission.Handler so the controller can handle admission request.
239-
var _ admission.Handler = &podValidator{}
240-
241-
// podValidator admits a pod iff a specific annotation exists.
242-
func (v *podValidator) Handle(_ context.Context, req admission.Request) admission.Response {
243-
pod := &corev1.Pod{}
244-
245-
err := v.decoder.Decode(req, pod)
246-
if err != nil {
247-
return admission.ErrorResponse(http.StatusBadRequest, err)
248-
}
249-
250-
allowed, reason, err := validatePodsFn(pod)
251-
if err != nil {
252-
return admission.ErrorResponse(http.StatusInternalServerError, err)
253-
}
254-
return admission.ValidationResponse(allowed, reason)
255-
}
256-
257-
func validatePodsFn(pod *corev1.Pod) (bool, string, error) {
258-
anno := pod.GetAnnotations()
259-
key := "example-mutating-admission-webhhok"
260-
_, found := anno[key]
261-
if found {
262-
return found, "", nil
263-
} else {
264-
return found, fmt.Sprintf("failed to find annotation with key: %v", key), nil
265-
}
266-
}

example/mutatingwebhook.go

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/*
2+
Copyright 2018 The Kubernetes Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package main
18+
19+
import (
20+
"context"
21+
"fmt"
22+
"net/http"
23+
24+
corev1 "k8s.io/api/core/v1"
25+
"sigs.k8s.io/controller-runtime/pkg/client"
26+
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
27+
)
28+
29+
// podAnnotator annotates Pods
30+
type podAnnotator struct {
31+
client client.Client
32+
decoder admission.Decoder
33+
}
34+
35+
// Implement admission.Handler so the controller can handle admission request.
36+
var _ admission.Handler = &podAnnotator{}
37+
38+
// podAnnotator adds an annotation to every incoming pods.
39+
func (a *podAnnotator) Handle(ctx context.Context, req admission.Request) admission.Response {
40+
pod := &corev1.Pod{}
41+
42+
err := a.decoder.Decode(req, pod)
43+
if err != nil {
44+
return admission.ErrorResponse(http.StatusBadRequest, err)
45+
}
46+
copy := pod.DeepCopy()
47+
48+
err = mutatePodsFn(ctx, copy)
49+
if err != nil {
50+
return admission.ErrorResponse(http.StatusInternalServerError, err)
51+
}
52+
return admission.PatchResponse(pod, copy)
53+
}
54+
55+
// mutatePodsFn add an annotation to the given pod
56+
func mutatePodsFn(ctx context.Context, pod *corev1.Pod) error {
57+
v, ok := ctx.Value(admission.StringKey("foo")).(string)
58+
if !ok {
59+
return fmt.Errorf("the value associated with %v is expected to be a string", "foo")
60+
}
61+
anno := pod.GetAnnotations()
62+
anno["example-mutating-admission-webhook"] = v
63+
pod.SetAnnotations(anno)
64+
return nil
65+
}

0 commit comments

Comments
 (0)