-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
72 lines (63 loc) · 1.77 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
package main
import (
"gopkg.in/yaml.v2"
"io/ioutil"
"net/http"
"os"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/log/zap"
)
const (
EnvVarConfigFile = "CONFIG_FILE"
DefaultConfigFile = "/tmp/config.yaml"
)
var (
configFile = DefaultConfigFile
mainLogger = ctrl.Log.WithName("pod-mutating-webhook")
)
func init() {
if val, ok := os.LookupEnv(EnvVarConfigFile); ok {
configFile = val
}
}
func main() {
ctrl.SetLogger(zap.New(zap.UseDevMode(false)))
http.HandleFunc("/mutate", handleMutate)
if err := http.ListenAndServeTLS(":8443", "/etc/webhook/certs/tls.crt", "/etc/webhook/certs/tls.key", nil); err != nil {
mainLogger.Error(err, "Failed to start mutating webhook server")
}
}
func handleMutate(w http.ResponseWriter, r *http.Request) {
// load rules
fileContents, err := ioutil.ReadFile(configFile)
if err != nil {
mainLogger.Error(err, "Failed to read image rule config file")
return
}
rules := &(map[string]string{})
if err := yaml.Unmarshal(fileContents, rules); err != nil {
mainLogger.Error(err, "Failed to unmarshall image rules.. skipping mutate")
return
}
// read req body
reqBody, errReading := ioutil.ReadAll(r.Body)
if errReading != nil {
mainLogger.Error(errReading, "Failed to read admission review req body")
return
}
defer r.Body.Close()
// mutate and get resp
mutateImg := MutateContainerImage{logger: mainLogger.WithName("pod-image-mutator")}
resp, errMutating := mutateImg.MutateContainerImages(reqBody, *rules)
if errMutating != nil {
mainLogger.Error(err, "Failed to mutate container image(s)")
return
}
// meaning we have patches to apply
if resp != nil {
// write response back to k8s api
w.WriteHeader(http.StatusOK)
w.Write(resp)
mainLogger.Info("Successfully mutated pod image(s)")
}
}