Skip to content

Commit 8810470

Browse files
authored
Merge pull request #328 from mengqiy/simplifywhif
⚠️ Simplify the webhook interface
2 parents 1dafd94 + ae02690 commit 8810470

22 files changed

+723
-20
lines changed

Gopkg.lock

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
File renamed without changes.
File renamed without changes.

example/mutatingwebhook.go renamed to examples/builtins/mutatingwebhook.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ func (a *podAnnotator) Handle(ctx context.Context, req admission.Request) admiss
5151
return admission.Errored(http.StatusInternalServerError, err)
5252
}
5353

54-
return admission.PatchResponseFromRaw(req.AdmissionRequest.Object.Raw, marshaledPod)
54+
return admission.PatchResponseFromRaw(req.Object.Raw, marshaledPod)
5555
}
5656

5757
// podAnnotator implements inject.Client.
@@ -63,7 +63,7 @@ func (a *podAnnotator) InjectClient(c client.Client) error {
6363
return nil
6464
}
6565

66-
// podAnnotator implements inject.Decoder.
66+
// podAnnotator implements admission.DecoderInjector.
6767
// A decoder will be automatically injected.
6868

6969
// InjectDecoder injects the decoder.

example/validatingwebhook.go renamed to examples/builtins/validatingwebhook.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ func (v *podValidator) InjectClient(c client.Client) error {
6262
return nil
6363
}
6464

65-
// podValidator implements inject.Decoder.
65+
// podValidator implements admission.DecoderInjector.
6666
// A decoder will be automatically injected.
6767

6868
// InjectDecoder injects the decoder.

examples/crd/main.go

Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
/*
2+
Copyright 2019 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+
"math/rand"
22+
"os"
23+
"time"
24+
25+
corev1 "k8s.io/api/core/v1"
26+
apierrors "k8s.io/apimachinery/pkg/api/errors"
27+
"k8s.io/apimachinery/pkg/runtime"
28+
_ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
29+
ctrl "sigs.k8s.io/controller-runtime"
30+
api "sigs.k8s.io/controller-runtime/examples/crd/pkg"
31+
"sigs.k8s.io/controller-runtime/pkg/client"
32+
"sigs.k8s.io/controller-runtime/pkg/log/zap"
33+
)
34+
35+
var (
36+
setupLog = ctrl.Log.WithName("setup")
37+
recLog = ctrl.Log.WithName("reconciler")
38+
)
39+
40+
type reconciler struct {
41+
client.Client
42+
scheme *runtime.Scheme
43+
}
44+
45+
func (r *reconciler) Reconcile(req ctrl.Request) (ctrl.Result, error) {
46+
log := recLog.WithValues("chaospod", req.NamespacedName)
47+
log.V(1).Info("reconciling chaos pod")
48+
ctx := context.Background()
49+
50+
var chaospod api.ChaosPod
51+
if err := r.Get(ctx, req.NamespacedName, &chaospod); err != nil {
52+
log.Error(err, "unable to get chaosctl")
53+
return ctrl.Result{}, err
54+
}
55+
56+
var pod corev1.Pod
57+
podFound := true
58+
if err := r.Get(ctx, req.NamespacedName, &pod); err != nil {
59+
if !apierrors.IsNotFound(err) {
60+
log.Error(err, "unable to get pod")
61+
return ctrl.Result{}, err
62+
}
63+
podFound = false
64+
}
65+
66+
if podFound {
67+
shouldStop := chaospod.Spec.NextStop.Time.Before(time.Now())
68+
if !shouldStop {
69+
return ctrl.Result{RequeueAfter: chaospod.Spec.NextStop.Sub(time.Now()) + 1*time.Second}, nil
70+
}
71+
72+
if err := r.Delete(ctx, &pod); err != nil {
73+
log.Error(err, "unable to delete pod")
74+
return ctrl.Result{}, err
75+
}
76+
77+
return ctrl.Result{Requeue: true}, nil
78+
}
79+
80+
templ := chaospod.Spec.Template.DeepCopy()
81+
pod.ObjectMeta = templ.ObjectMeta
82+
pod.Name = req.Name
83+
pod.Namespace = req.Namespace
84+
pod.Spec = templ.Spec
85+
86+
if err := ctrl.SetControllerReference(&chaospod, &pod, r.scheme); err != nil {
87+
log.Error(err, "unable to set pod's owner reference")
88+
return ctrl.Result{}, err
89+
}
90+
91+
if err := r.Create(ctx, &pod); err != nil {
92+
log.Error(err, "unable to create pod")
93+
return ctrl.Result{}, err
94+
}
95+
96+
chaospod.Spec.NextStop.Time = time.Now().Add(time.Duration(10*(rand.Int63n(2)+1)) * time.Second)
97+
chaospod.Status.LastRun = pod.CreationTimestamp
98+
if err := r.Update(ctx, &chaospod); err != nil {
99+
log.Error(err, "unable to update chaosctl status")
100+
return ctrl.Result{}, err
101+
}
102+
return ctrl.Result{}, nil
103+
}
104+
105+
func main() {
106+
ctrl.SetLogger(zap.Logger(true))
107+
108+
mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{})
109+
if err != nil {
110+
setupLog.Error(err, "unable to start manager")
111+
os.Exit(1)
112+
}
113+
114+
// in a real controller, we'd create a new scheme for this
115+
err = api.AddToScheme(mgr.GetScheme())
116+
if err != nil {
117+
setupLog.Error(err, "unable to add scheme")
118+
os.Exit(1)
119+
}
120+
121+
err = ctrl.NewControllerManagedBy(mgr).
122+
For(&api.ChaosPod{}).
123+
Owns(&corev1.Pod{}).
124+
Complete(&reconciler{
125+
Client: mgr.GetClient(),
126+
scheme: mgr.GetScheme(),
127+
})
128+
129+
if err != nil {
130+
setupLog.Error(err, "unable to create controller")
131+
os.Exit(1)
132+
}
133+
134+
setupLog.Info("starting manager")
135+
if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil {
136+
setupLog.Error(err, "problem running manager")
137+
os.Exit(1)
138+
}
139+
}

examples/crd/pkg/doc.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
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 pkg
18+
19+
import (
20+
logf "sigs.k8s.io/controller-runtime/pkg/runtime/log"
21+
)
22+
23+
var log = logf.Log.WithName("chaospod-resource")

examples/crd/pkg/resource.go

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
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 pkg
18+
19+
import (
20+
"fmt"
21+
"time"
22+
23+
corev1 "k8s.io/api/core/v1"
24+
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
25+
"k8s.io/apimachinery/pkg/runtime"
26+
"k8s.io/apimachinery/pkg/runtime/schema"
27+
"sigs.k8s.io/controller-runtime/pkg/scheme"
28+
"sigs.k8s.io/controller-runtime/pkg/webhook"
29+
)
30+
31+
// ChaosPodSpec defines the desired state of ChaosPod
32+
type ChaosPodSpec struct {
33+
Template corev1.PodTemplateSpec `json:"template"`
34+
// +optional
35+
NextStop metav1.Time `json:"nextStop,omitempty"`
36+
}
37+
38+
// ChaosPodStatus defines the observed state of ChaosPod.
39+
// It should always be reconstructable from the state of the cluster and/or outside world.
40+
type ChaosPodStatus struct {
41+
LastRun metav1.Time `json:"lastRun,omitempty"`
42+
}
43+
44+
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
45+
46+
// ChaosPod is the Schema for the randomjobs API
47+
// +kubebuilder:printcolumn:name="next stop",type="string",JSONPath=".spec.nextStop",format="date"
48+
// +kubebuilder:printcolumn:name="last run",type="string",JSONPath=".status.lastRun",format="date"
49+
// +k8s:openapi-gen=true
50+
type ChaosPod struct {
51+
metav1.TypeMeta `json:",inline"`
52+
metav1.ObjectMeta `json:"metadata,omitempty"`
53+
54+
Spec ChaosPodSpec `json:"spec,omitempty"`
55+
Status ChaosPodStatus `json:"status,omitempty"`
56+
}
57+
58+
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
59+
60+
// ChaosPodList contains a list of ChaosPod
61+
type ChaosPodList struct {
62+
metav1.TypeMeta `json:",inline"`
63+
metav1.ListMeta `json:"metadata,omitempty"`
64+
Items []ChaosPod `json:"items"`
65+
}
66+
67+
// ValidateCreate implements webhookutil.validator so a webhook will be registered for the type
68+
func (c *ChaosPod) ValidateCreate() error {
69+
log.Info("validate create", "name", c.Name)
70+
71+
if c.Spec.NextStop.Before(&metav1.Time{Time: time.Now()}) {
72+
return fmt.Errorf(".spec.nextStop must be later than current time")
73+
}
74+
return nil
75+
}
76+
77+
// ValidateUpdate implements webhookutil.validator so a webhook will be registered for the type
78+
func (c *ChaosPod) ValidateUpdate(old runtime.Object) error {
79+
log.Info("validate update", "name", c.Name)
80+
81+
if c.Spec.NextStop.Before(&metav1.Time{Time: time.Now()}) {
82+
return fmt.Errorf(".spec.nextStop must be later than current time")
83+
}
84+
85+
oldC, ok := old.(*ChaosPod)
86+
if !ok {
87+
return fmt.Errorf("expect old object to be a %T instead of %T", oldC, old)
88+
}
89+
if c.Spec.NextStop.After(oldC.Spec.NextStop.Add(time.Hour)) {
90+
return fmt.Errorf("it is not allowed to delay.spec.nextStop for more than 1 hour")
91+
}
92+
return nil
93+
}
94+
95+
var _ webhook.Defaulter = &ChaosPod{}
96+
97+
// Default implements webhookutil.defaulter so a webhook will be registered for the type
98+
func (c *ChaosPod) Default() {
99+
log.Info("default", "name", c.Name)
100+
101+
if c.Spec.NextStop.Before(&metav1.Time{Time: time.Now()}) {
102+
c.Spec.NextStop = metav1.Time{Time: time.Now().Add(time.Minute)}
103+
}
104+
}
105+
106+
func init() {
107+
SchemeBuilder.Register(&ChaosPod{}, &ChaosPodList{})
108+
}
109+
110+
var (
111+
// SchemeGroupVersion is group version used to register these objects
112+
SchemeGroupVersion = schema.GroupVersion{Group: "chaosapps.metamagical.io", Version: "v1"}
113+
114+
// SchemeBuilder is used to add go types to the GroupVersionKind scheme
115+
SchemeBuilder = &scheme.Builder{GroupVersion: SchemeGroupVersion}
116+
117+
// AddToScheme is required by pkg/client/...
118+
AddToScheme = SchemeBuilder.AddToScheme
119+
)

0 commit comments

Comments
 (0)