...
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 podhttpchaoslog = logf.Log.WithName("rawpodhttp-resource")
29
30
31
32
33 type PodHttpChaosHandler interface {
34 Apply(context.Context, *PodHttpChaos) (int32, error)
35 }
36
37 var podHttpChaosHandler PodHttpChaosHandler
38
39
40 func RegisterPodHttpHandler(newHandler PodHttpChaosHandler) {
41 podHttpChaosHandler = newHandler
42 }
43
44
45 func (in *PodHttpChaos) SetupWebhookWithManager(mgr ctrl.Manager) error {
46 mgr.GetWebhookServer().
47 Register("/mutate-chaos-mesh-org-v1alpha1-podhttpchaos", &webhook.Admission{Handler: &PodHttpChaosWebhookRunner{}})
48 return nil
49 }
50
51
52
53
54
55
56 type PodHttpChaosWebhookRunner struct {
57 decoder *admission.Decoder
58 }
59
60
61 func (r *PodHttpChaosWebhookRunner) Handle(ctx context.Context, req admission.Request) admission.Response {
62 chaos := &PodHttpChaos{}
63 err := r.decoder.Decode(req, chaos)
64 if err != nil {
65 return admission.Errored(http.StatusBadRequest, err)
66 }
67
68 if podHttpChaosHandler != nil {
69 statusCode, err := podHttpChaosHandler.Apply(ctx, chaos)
70 if err != nil {
71 return admission.Errored(statusCode, err)
72 }
73 }
74
75
76 marshaledPodHttpChaos, err := json.Marshal(chaos)
77 if err != nil {
78 return admission.Errored(http.StatusInternalServerError, err)
79 }
80
81 return admission.PatchResponseFromRaw(req.Object.Raw, marshaledPodHttpChaos)
82 }
83
84
85 func (r *PodHttpChaosWebhookRunner) InjectDecoder(d *admission.Decoder) error {
86 r.decoder = d
87 return nil
88 }
89