/
webhook.go
230 lines (197 loc) · 7.06 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
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
package main
import (
"encoding/json"
log "github.com/sirupsen/logrus"
"io/ioutil"
"k8s.io/api/admission/v1beta1"
"net/http"
"sigs.k8s.io/yaml"
"strings"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/serializer"
)
var (
runtimeScheme = runtime.NewScheme()
deserializer = serializer.NewCodecFactory(runtimeScheme).UniversalDeserializer()
defaulter = runtime.ObjectDefaulter(runtimeScheme)
)
var (
exporterAnnotationsKey = "inject-exporters"
exporterUpdatedAnnotationsKey = "inject-exporter-updated"
)
func loadConfig (fileSuffix, sidecarCfgDirectoryPath string) (corev1.Container, error){
log.Infoln("Checkin sidecar configuration file located here: ", sidecarCfgDirectoryPath)
data, err := ioutil.ReadFile(sidecarCfgDirectoryPath + "/config_" + fileSuffix + ".yaml")
if err != nil {
log.Error("Cannot read sidecar configuration file or file not found! ", err)
return corev1.Container{}, err
}
var config corev1.Container
if err := yaml.Unmarshal(data, &config); err != nil {
log.Error("Cannot unmarshal sidecar configuration JSON file..", err)
return corev1.Container{}, err
}
return config, nil
}
func updateAnnotations() MutatingPatch{
return MutatingPatch{
Op: "add",
Path: "/metadata/annotations",
Value: map[string]string{
"injected-by-sidecar": "true",
},
}
}
func addSidecarContainerExporter(target []corev1.Container, sidecarConfiguration []corev1.Container) []MutatingPatch{
var patches []MutatingPatch
first := len(target) == 0
var value interface{}
for _, add := range sidecarConfiguration {
value = add
path := "/spec/containers"
if first {
first = false
value = []corev1.Container{add}
} else {
path = path + "/-"
}
patches = append(patches, MutatingPatch{
Op: "add",
Path: path,
Value: value,
})
}
return patches
}
func (whs *WebhookServer) checkMutateAndGetConfig(labels map[string]string) ([]corev1.Container, bool) {
log.Infof("Checking configuration for handling mutate correctly....")
if value, ok := labels[exporterAnnotationsKey]; ok {
exporterLists := strings.Split(value, ",")
var exporterConfigurationList []corev1.Container
for _, value := range exporterLists {
sanitaizedValues := strings.Replace(strings.Replace(value, "-", "", -1), "_", "", -1)
sanitaizedValues = strings.Replace(sanitaizedValues, ".", "", -1)
configLoaded, err := loadConfig(sanitaizedValues, whs.Parameters.SidecarConfigurationDirectory)
if err != nil {
log.Errorf("Error during load of config %v: ", value, err)
return nil, false
}
exporterConfigurationList = append(exporterConfigurationList, configLoaded)
}
log.Infof("Exporter configuration list are.... %v", exporterConfigurationList)
return exporterConfigurationList, true
}
return nil, false
}
func (whs *WebhookServer) createPatch(pod *corev1.Pod) ([]byte, v1beta1.PatchType, error) {
var patches []MutatingPatch
patchType := v1beta1.PatchTypeJSONPatch
log.Infof("Add Sidecar configuration...")
patches = append(patches, addSidecarContainerExporter(pod.Spec.Containers, whs.Parameters.SidecarConfiguration)...)
log.Infof("Add annotations...")
patches = append(patches, updateAnnotations())
patchBytes, err := json.Marshal(patches)
if err != nil {
log.Errorf("Error during marshal of patch response")
return nil, patchType, err
}
return patchBytes, patchType, nil
}
func (whs *WebhookServer) mutate(review *v1beta1.AdmissionReview) *v1beta1.AdmissionResponse {
log.Infof("Mutating the admissionReview.....")
var pod corev1.Pod
if err := json.Unmarshal(review.Request.Object.Raw, &pod); err != nil {
return &v1beta1.AdmissionResponse{
Allowed: false,
Result: &metav1.Status{
TypeMeta: metav1.TypeMeta{},
ListMeta: metav1.ListMeta{},
Message: err.Error(),
},
}
}
log.Infof("Pod Spec object is... %v", pod.Spec)
config, err := whs.checkMutateAndGetConfig(pod.GetLabels())
if !err {
log.Infof("No need to mutate Pod %v", pod.Name)
return &v1beta1.AdmissionResponse{
Allowed: true,
}
}
//Now is time to PATCH
whs.Parameters.SidecarConfiguration = config
patchBytes, JSONPatchType, errorPatch := whs.createPatch(&pod)
log.Infof("Sending patch request... %v", patchBytes)
if errorPatch != nil {
return &v1beta1.AdmissionResponse{
Allowed: false,
Result: &metav1.Status{
TypeMeta: metav1.TypeMeta{},
ListMeta: metav1.ListMeta{},
Message: errorPatch.Error(),
},
}
}
return &v1beta1.AdmissionResponse{
UID: review.Request.UID,
Allowed: true,
Patch: patchBytes,
PatchType: &JSONPatchType,
}
}
func (whs *WebhookServer) healthHandler (writer http.ResponseWriter, request *http.Request) {
writer.Header().Set("Content-Type", "application-json")
writer.WriteHeader(http.StatusOK)
jsonReturnData := make(map[string]string)
jsonReturnData["status"] = "ALIVE"
if err := json.NewEncoder(writer).Encode(jsonReturnData); err != nil {
http.Error(writer, "Error on health check", http.StatusInternalServerError)
}
}
func (whs *WebhookServer) mutateHandler(writer http.ResponseWriter, request *http.Request) {
if request.Body == nil || request.Header.Get("Content-type") != "application/json" {
log.Error("Error perfoming the request....")
http.Error(writer, "Error perfoming the request, body empty or wrong header content-type...", http.StatusInternalServerError)
return
}
data, err := ioutil.ReadAll(request.Body)
if err != nil || len(data) == 0 {
log.Error("Error reading the body or body is empty!!")
http.Error(writer, "Error reading the body or body is empty!!", http.StatusInternalServerError)
}
log.Infof("Request body is %v", data)
log.Infoln("Successfully get the request....")
admissionReview := v1beta1.AdmissionReview{}
admissionReviewResponse := v1beta1.AdmissionReview{}
_, _, err = deserializer.Decode(data, nil, &admissionReview)
if err != nil {
log.Error("Cannot decode object admission review....", err)
http.Error(writer, "cannot decode object...", http.StatusInternalServerError)
} else {
log.Infof("Deserialized admission review > %v", admissionReview)
log.Infof("Deserialize object....")
if strings.Contains(strings.ToLower(admissionReview.Request.RequestResource.Resource), "pod") {
log.Infof("Going to call mutation....")
admissionReviewResponse.Response = whs.mutate(&admissionReview)
admissionReviewResponse.Response.UID = admissionReview.Request.UID
} else {
log.Infof("Return basic response...")
admissionReviewResponse.Response = &v1beta1.AdmissionResponse{
UID: admissionReview.Request.UID,
Allowed: true,
}
}
}
resp, err := json.Marshal(admissionReviewResponse)
if err != nil {
log.Errorf("Cannot marshalize the response of admissionReview.... %v", err)
http.Error(writer, "Cannot marshalize the object", http.StatusInternalServerError)
}
log.Infof("Writing response.... %v", admissionReviewResponse.Response)
if _, err := writer.Write(resp); err != nil {
log.Errorf("Cannot write the response %v", err)
http.Error(writer, "Cannot Write the response", http.StatusInternalServerError)
}
}