-
Notifications
You must be signed in to change notification settings - Fork 11
/
mutations.go
246 lines (213 loc) · 7.51 KB
/
mutations.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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
package main
import (
"fmt"
"strings"
admissionv1 "k8s.io/api/admission/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
var (
podResource = metav1.GroupVersionResource{Version: "v1", Resource: "pods"}
volumeClaimResource = metav1.GroupVersionResource{Version: "v1", Resource: "persistentvolumeclaims"}
)
// applyMutations implements the logic of our admission controller webhook.
func (wh *mutationWH) applyMutations(req *admissionv1.AdmissionRequest) ([]patchOperation, error) {
// This handler should only get called on Pod or Pvc objects as per the MutatingWebhookConfiguration in the YAML file.
// However, if (for whatever reason) this gets invoked on an object of a different kind, issue a log message but
// let the object request pass through otherwise.
if req.Resource == podResource {
// Parse the Pod object.
raw := req.Object.Raw
pod := corev1.Pod{}
if _, _, err := universalDeserializer.Decode(raw, nil, &pod); err != nil {
return nil, fmt.Errorf("could not deserialize pod object: %v", err)
}
return wh.applyMutationOnPod(pod)
} else if req.Resource == volumeClaimResource {
// Parse the Pvc object.
raw := req.Object.Raw
pvc := corev1.PersistentVolumeClaim{}
if _, _, err := universalDeserializer.Decode(raw, nil, &pvc); err != nil {
return nil, fmt.Errorf("could not deserialize pvc object: %v", err)
}
return wh.applyMutationOnPvc(pvc)
}
log.Printf("Got an unexpected resource %s, don't know what to do with...", req.Resource)
return nil, nil
}
// applyMutationOnPod gets the deserialized pod spec and returns the patch operations
// to apply, if any, or an error if something went wrong.
func (wh *mutationWH) applyMutationOnPod(pod corev1.Pod) ([]patchOperation, error) {
var patches []patchOperation
if wh.registry != "" {
if pod.Spec.InitContainers != nil {
for i, c := range pod.Spec.InitContainers {
log.Tracef("/spec/initContainers/%d/image = %s", i, c.Image)
if !containsAnyRegistry(c.Image, append(wh.ignoredRegistries, wh.registry)) {
patches = append(patches, patchOperation{
Op: "replace",
Path: fmt.Sprintf("/spec/initContainers/%d/image", i),
Value: replaceRegistryIfSet(c.Image, wh.registry),
})
}
}
}
if pod.Spec.Containers != nil {
for i, c := range pod.Spec.Containers {
log.Tracef("/spec/containers/%d/image = %s", i, c.Image)
if !containsAnyRegistry(c.Image, append(wh.ignoredRegistries, wh.registry)) {
patches = append(patches, patchOperation{
Op: "replace",
Path: fmt.Sprintf("/spec/containers/%d/image", i),
Value: replaceRegistryIfSet(c.Image, wh.registry),
})
}
}
}
}
if wh.forceImagePullPolicy {
if pod.Spec.InitContainers != nil {
for i, c := range pod.Spec.InitContainers {
log.Tracef("/spec/initContainers/%d/imagePullPolicy = %s", i, c.ImagePullPolicy)
op := "replace"
// still take the case when ImagePullPolicy is empty, but this case should not happen.
// Policy defaults to Always if tag is latest, IfNotPresent otherwise.
if c.ImagePullPolicy == "" {
op = "add"
}
if wh.imagePullPolicyToForce != c.ImagePullPolicy {
patches = append(patches, patchOperation{
Op: op,
Path: fmt.Sprintf("/spec/initContainers/%d/imagePullPolicy", i),
Value: wh.imagePullPolicyToForce,
})
}
}
}
if pod.Spec.Containers != nil {
for i, c := range pod.Spec.Containers {
log.Tracef("/spec/containers/%d/imagePullPolicy = %s", i, c.ImagePullPolicy)
if c.ImagePullPolicy != wh.imagePullPolicyToForce {
op := "replace"
if c.ImagePullPolicy == "" {
op = "add"
}
patches = append(patches, patchOperation{
Op: op,
Path: fmt.Sprintf("/spec/containers/%d/imagePullPolicy", i),
Value: wh.imagePullPolicyToForce,
})
}
}
}
}
if wh.imagePullSecret != "" {
// if there are no existing pull secrets, append or replace is the same operation.
if pod.Spec.ImagePullSecrets == nil {
patches = append(patches, patchOperation{
Op: "add",
Path: "/spec/imagePullSecrets",
Value: []map[string]string{{"name": wh.imagePullSecret}},
})
} else {
if wh.appendImagePullSecret {
// in the append branch,
// in case of existing secrets in the pod, we check if the secret does not exist and we append it to the list
imagePullSecretsAlreadyExist := false
for _, i := range pod.Spec.ImagePullSecrets {
if i.Name == wh.imagePullSecret {
imagePullSecretsAlreadyExist = true
break
}
}
if !imagePullSecretsAlreadyExist {
patches = append(patches, patchOperation{
Op: "add",
Path: fmt.Sprintf("/spec/imagePullSecrets/%d", len(pod.Spec.ImagePullSecrets)),
Value: []map[string]string{{"name": wh.imagePullSecret}},
})
}
} else {
// in the replace branch,
// if the secret is not the one to set, we replace the existing secret(s)
if !(len(pod.Spec.ImagePullSecrets) == 1 && pod.Spec.ImagePullSecrets[0].Name == wh.imagePullSecret) {
patches = append(patches, patchOperation{
Op: "replace",
Path: "/spec/imagePullSecrets",
Value: []map[string]string{{"name": wh.imagePullSecret}},
})
}
}
}
}
log.Debugf("Patch applied: %v", patches)
return patches, nil
}
// replaceRegistryIfSet assumes the image format is a.b[:port]/c/d:e
// if a.b is present, it is replaced by the registry given as argument.
func replaceRegistryIfSet(image string, registry string) string {
imageParts := strings.Split(image, "/")
if len(imageParts) == 1 {
// case imagename or imagename:version, where version can contains .
imageParts = append([]string{registry}, imageParts...)
} else {
// case something/imagename:version, assessing the something part.
if strings.Contains(imageParts[0], ".") {
imageParts[0] = registry
} else {
imageParts = append([]string{registry}, imageParts...)
}
}
return strings.Join(imageParts, "/")
}
// applyMutationOnPvc gets the deserialized pvc spec and returns the patch operations
// to apply, if any, or an error if something went wrong.
func (wh *mutationWH) applyMutationOnPvc(pvc corev1.PersistentVolumeClaim) ([]patchOperation, error) {
var patches []patchOperation
if wh.defaultStorageClass != "" {
if pvc.Spec.StorageClassName != nil {
if *pvc.Spec.StorageClassName != wh.defaultStorageClass {
patches = append(patches, patchOperation{
Op: "replace",
Path: "/spec/storageClassName",
Value: wh.defaultStorageClass,
})
}
} else {
patches = append(patches, patchOperation{
Op: "add",
Path: "/spec/storageClassName",
Value: wh.defaultStorageClass,
})
}
}
log.Debugf("Patch applied: %v", patches)
return patches, nil
}
// containsRegistry returns true if the image "contains",
// i.e. start with the registry prefix.
// A tailing / is added during the comparison to ensure
// the registry is not only a prefix of the image.
func containsRegistry(image string, registry string) bool {
return strings.HasPrefix(image, registry+"/")
}
func containsAnyRegistry(image string, registries []string) bool {
for _, s := range registries {
if containsRegistry(image, s) {
return true
}
}
return false
}
func isPullPolicyValid(policy string) (bool, corev1.PullPolicy) {
switch policy {
case string(corev1.PullAlways):
return true, corev1.PullAlways
case string(corev1.PullIfNotPresent):
return true, corev1.PullIfNotPresent
case string(corev1.PullNever):
return true, corev1.PullNever
default:
return false, corev1.PullAlways
}
}