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