-
Notifications
You must be signed in to change notification settings - Fork 438
/
webhook.go
87 lines (74 loc) · 2.15 KB
/
webhook.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package webhook
import (
"context"
"time"
admissionv1 "k8s.io/api/admission/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/rest"
"k8s.io/klog/v2"
"sigs.k8s.io/controller-runtime/pkg/cache"
"sigs.k8s.io/controller-runtime/pkg/client"
ctrlwebhook "sigs.k8s.io/controller-runtime/pkg/webhook"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
)
var (
createHooks = make(map[metav1.GroupVersionKind]admission.HandlerFunc)
updateHooks = make(map[metav1.GroupVersionKind]admission.HandlerFunc)
)
type ValidatingHook struct {
client client.Client
decoder *admission.Decoder
cache cache.Cache
}
func NewValidatingHook(c cache.Cache) (*ValidatingHook, error) {
cfg, err := rest.InClusterConfig()
if err != nil {
klog.Errorf("use in cluster config failed %v", err)
return nil, err
}
cfg.Timeout = 15 * time.Second
v := &ValidatingHook{
cache: c,
}
// initialize hook handlers mapping
createHooks[deploymentGVK] = v.DeploymentCreateHook
createHooks[statefulSetGVK] = v.StatefulSetCreateHook
createHooks[daemonSetGVK] = v.DaemonSetCreateHook
createHooks[podGVK] = v.PodCreateHook
createHooks[subnetGVK] = v.SubnetCreateHook
updateHooks[subnetGVK] = v.SubnetUpdateHook
return v, nil
}
func (v *ValidatingHook) Handle(ctx context.Context, req admission.Request) (resp admission.Response) {
defer func() {
if resp.AdmissionResponse.Allowed {
klog.V(3).Info("result: allowed")
} else {
klog.V(3).Infof("result: reject, reason: %s", resp.AdmissionResponse.Result.Reason)
}
}()
switch req.Operation {
case admissionv1.Create:
if createHooks[req.Kind] != nil {
klog.Infof("handle create %s %s@%s", req.Kind, req.Name, req.Namespace)
resp = createHooks[req.Kind](ctx, req)
return
}
case admissionv1.Update:
if updateHooks[req.Kind] != nil {
klog.Infof("handle update %s %s@%s", req.Kind, req.Name, req.Namespace)
resp = updateHooks[req.Kind](ctx, req)
return
}
}
resp = ctrlwebhook.Allowed("by pass")
return
}
func (v *ValidatingHook) InjectDecoder(d *admission.Decoder) error {
v.decoder = d
return nil
}
func (v *ValidatingHook) InjectClient(c client.Client) error {
v.client = c
return nil
}