...
1
2
3
4
5
6
7
8
9
10
11
12
13
14 package v1alpha1
15
16 import (
17 "context"
18 "encoding/json"
19 "net/http"
20
21 ctrl "sigs.k8s.io/controller-runtime"
22 logf "sigs.k8s.io/controller-runtime/pkg/runtime/log"
23 "sigs.k8s.io/controller-runtime/pkg/webhook"
24 "sigs.k8s.io/controller-runtime/pkg/webhook/admission"
25 )
26
27
28 var podiochaoslog = logf.Log.WithName("rawpodio-resource")
29
30
31
32
33 type PodIoChaosHandler interface {
34 Apply(context.Context, *PodIoChaos) error
35 }
36
37 var podIoChaosHandler PodIoChaosHandler
38
39
40 func RegisterPodIoHandler(newHandler PodIoChaosHandler) {
41 podIoChaosHandler = newHandler
42 }
43
44
45 func (in *PodIoChaos) SetupWebhookWithManager(mgr ctrl.Manager) error {
46 mgr.GetWebhookServer().
47 Register("/mutate-chaos-mesh-org-v1alpha1-podiochaos", &webhook.Admission{Handler: &PodIoChaosWebhookRunner{}})
48 return nil
49 }
50
51
52
53
54
55
56 type PodIoChaosWebhookRunner struct {
57 decoder *admission.Decoder
58 }
59
60
61 func (r *PodIoChaosWebhookRunner) Handle(ctx context.Context, req admission.Request) admission.Response {
62 chaos := &PodIoChaos{}
63 err := r.decoder.Decode(req, chaos)
64 if err != nil {
65 return admission.Errored(http.StatusBadRequest, err)
66 }
67
68 if podIoChaosHandler != nil {
69 err = podIoChaosHandler.Apply(ctx, chaos)
70 if err != nil {
71
72 return admission.Errored(http.StatusInternalServerError, err)
73 }
74 }
75
76
77
78 marshaledPodIoChaos, err := json.Marshal(chaos)
79 if err != nil {
80 return admission.Errored(http.StatusInternalServerError, err)
81 }
82 return admission.PatchResponseFromRaw(req.Object.Raw, marshaledPodIoChaos)
83 }
84
85
86 func (r *PodIoChaosWebhookRunner) InjectDecoder(d *admission.Decoder) error {
87 r.decoder = d
88 return nil
89 }
90