-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
158 lines (138 loc) · 3.87 KB
/
main.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
package main
import (
"bytes"
"context"
"encoding/json"
"flag"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/klog"
"k8s.io/klog/klogr"
"k8s.io/test-infra-setup/webhook/pkg/kustomize"
"net/http"
"os"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client/config"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
"sigs.k8s.io/yaml"
"strings"
"text/template"
)
var (
scheme = runtime.NewScheme()
setupLog = ctrl.Log.WithName("setup")
log = ctrl.Log.WithName("webhook")
parsedTemplates []*template.Template
)
func main() {
// Setting up logger flags
klog.InitFlags(nil)
var (
metricsAddr string
certDir string
patchesGlob string
)
flag.StringVar(
&metricsAddr,
"metrics-addr",
":8080",
"The address the metric endpoint binds to.",
)
flag.StringVar(
&certDir,
"cert-dir",
"/tmp/k8s-webhook-server/serving-certs",
"The folder were tls.crt and tls.key are stored.",
)
flag.StringVar(
&patchesGlob,
"patches-glob",
"/tmp/patches/*",
"The glob pattern to parse the patches from.",
)
setupLog.Info("Parsing flags")
flag.Parse()
ctrl.SetLogger(klogr.New())
setupLog.Info("Parsing templates")
parsedTemplates = template.Must(template.ParseGlob(patchesGlob)).Templates()
setupLog.Info("Setting up manager")
cfg, err := config.GetConfigWithContext(os.Getenv("KUBECONTEXT"))
if err != nil {
setupLog.Error(err, "unable to get kubeconfig")
os.Exit(1)
}
mgr, err := ctrl.NewManager(cfg, ctrl.Options{
Scheme: scheme,
MetricsBindAddress: metricsAddr,
})
if err != nil {
setupLog.Error(err, "unable to start manager")
os.Exit(1)
}
setupLog.Info("Setting up webhook server")
webhookServer := mgr.GetWebhookServer()
webhookServer.Register("/mutate", &admission.Webhook{
Handler: &mutatingHandler{},
})
webhookServer.CertDir = certDir
webhookServer.Port = 8443
setupLog.Info("Starting manager")
if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil {
setupLog.Error(err, "problem running manager")
os.Exit(1)
}
}
type mutatingHandler struct {
decoder *admission.Decoder
}
var _ admission.DecoderInjector = &mutatingHandler{}
// InjectDecoder injects the decoder into a mutatingHandler.
func (h *mutatingHandler) InjectDecoder(d *admission.Decoder) error {
h.decoder = d
return nil
}
// Handle handles admission requests.
func (h *mutatingHandler) Handle(ctx context.Context, req admission.Request) admission.Response {
// Decode the object in the request and set TypeMeta for kustomize
pod := &v1.Pod{
TypeMeta: metav1.TypeMeta{
APIVersion: "v1",
Kind: "Pod",
},
}
err := h.decoder.Decode(req, pod)
if err != nil {
return admission.Errored(http.StatusBadRequest, err)
}
// Render patches with go template with v1.Pod as data
var patches []string
for _, t := range parsedTemplates {
var p bytes.Buffer
err = t.Execute(&p, pod)
if err != nil {
return admission.Errored(http.StatusBadRequest, err)
}
patches = append(patches, p.String())
}
// Marshal Pod to bytes
objBytes, err := json.Marshal(pod)
if err != nil {
log.Info("debug dump", "pod", string(objBytes))
return admission.Errored(http.StatusBadRequest, err)
}
// Execute kustomize build
newPod, err := kustomize.Build([]string{string(objBytes)}, patches, []kustomize.PatchJSON6902{})
if err != nil {
log.Info("debug dump", "pod", string(objBytes), "patches", strings.Join(patches,"\n"))
return admission.Errored(http.StatusBadRequest, err)
}
// Convert patched Pod from YAML to Json
newPodJson, err := yaml.YAMLToJSON([]byte(newPod))
if err != nil {
log.Info("debug dump", "pod", string(objBytes), "patches", strings.Join(patches,"\n"), "new-pod", newPod)
return admission.Errored(http.StatusBadRequest, err)
}
// Patch current Pod to newPod
return admission.PatchResponseFromRaw(req.Object.Raw, newPodJson)
}