-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathadmission_controller.go
196 lines (166 loc) · 6.64 KB
/
admission_controller.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
/*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
admission "k8s.io/api/admission/v1beta1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/serializer"
)
const (
jsonContentType = `application/json`
)
var (
universalDeserializer = serializer.NewCodecFactory(runtime.NewScheme()).UniversalDeserializer()
)
// patchOperation is an operation of a JSON patch, see https://tools.ietf.org/html/rfc6902 .
type patchOperation struct {
Op string `json:"op"`
Path string `json:"path"`
Value interface{} `json:"value,omitempty"`
}
// admitFunc is a callback for admission controller logic. Given an AdmissionRequest, it returns the sequence of patch
// operations to be applied in case of success, or the error that will be shown when the operation is rejected.
type admitFunc func(*admission.AdmissionRequest) ([]patchOperation, error)
// isKubeNamespace checks if the given namespace is a Kubernetes-owned namespace.
func isKubeNamespace(ns string) bool {
return ns == metav1.NamespacePublic || ns == metav1.NamespaceSystem
}
// JSON pretty print
func prettyJSON(data []byte) ([]byte, error) {
var out bytes.Buffer
err := json.Indent(&out, data, "", " ")
if err == nil {
return out.Bytes(), err
}
return data, nil
}
// doServeAdmitFunc parses the HTTP request for an admission controller webhook, and -- in case of a well-formed
// request -- delegates the admission control logic to the given admitFunc. The response body is then returned as raw
// bytes.
func doServeAdmitFunc(w http.ResponseWriter, r *http.Request, admit admitFunc) ([]byte, error) {
// Step 1: Request validation. Only handle POST requests with a body and json content type.
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return nil, fmt.Errorf("invalid method %s, only POST requests are allowed", r.Method)
}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return nil, fmt.Errorf("could not read request body: %v", err)
}
// log request
if config.VerboseLogs {
out, err := prettyJSON(body)
if err != nil {
log.Fatal(err)
}
log.Printf("request: %s\n", out)
}
if contentType := r.Header.Get("Content-Type"); contentType != jsonContentType {
w.WriteHeader(http.StatusBadRequest)
return nil, fmt.Errorf("unsupported content type %s, only %s is supported", contentType, jsonContentType)
}
// Step 2: Parse the AdmissionReview request.
var admissionReviewReq admission.AdmissionReview
if _, _, err := universalDeserializer.Decode(body, nil, &admissionReviewReq); err != nil {
w.WriteHeader(http.StatusBadRequest)
return nil, fmt.Errorf("could not deserialize request: %v", err)
} else if admissionReviewReq.Request == nil {
w.WriteHeader(http.StatusBadRequest)
return nil, errors.New("malformed admission review: request is nil")
}
// Step 3: Construct the AdmissionReview response.
admissionReviewResponse := admission.AdmissionReview{
// Since the admission webhook now supports multiple API versions, we need
// to explicitly include the API version in the response.
// This API version needs to match the version from the request exactly, otherwise
// the API server will be unable to process the response.
// Note: a v1beta1 AdmissionReview is JSON-compatible with the v1 version, that's why
// we do not need to differentiate during unmarshaling or in the actual logic.
TypeMeta: admissionReviewReq.TypeMeta,
Response: &admission.AdmissionResponse{
UID: admissionReviewReq.Request.UID,
},
}
var patchOps []patchOperation
// Apply the admit function only for non-Kubernetes namespaces. For objects in Kubernetes namespaces, return
// an empty set of patch operations.
if !isKubeNamespace(admissionReviewReq.Request.Namespace) {
patchOps, err = admit(admissionReviewReq.Request)
}
if err != nil {
// If the handler returned an error, incorporate the error message into the response and deny the object
// creation.
admissionReviewResponse.Response.Allowed = false
admissionReviewResponse.Response.Result = &metav1.Status{
Message: err.Error(),
}
} else {
// Otherwise, encode the patch operations to JSON and return a positive response.
patchBytes, err := json.Marshal(patchOps)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return nil, fmt.Errorf("could not marshal JSON patch: %v", err)
}
admissionReviewResponse.Response.Allowed = true
admissionReviewResponse.Response.Patch = patchBytes
// Announce that we are returning a JSON patch (note: this is the only
// patch type currently supported, but we have to explicitly announce
// it nonetheless).
admissionReviewResponse.Response.PatchType = new(admission.PatchType)
*admissionReviewResponse.Response.PatchType = admission.PatchTypeJSONPatch
}
// log response
if config.VerboseLogs {
out, err := json.MarshalIndent(&admissionReviewResponse, "", " ")
if err != nil {
log.Fatal(err)
}
log.Printf("response: %s\n", string(out))
}
// Return the AdmissionReview with a response as JSON.
responseBytes, err := json.Marshal(&admissionReviewResponse)
if err != nil {
return nil, fmt.Errorf("marshaling response: %v", err)
}
return responseBytes, nil
}
// serveAdmitFunc is a wrapper around doServeAdmitFunc that adds error handling and logging.
func serveAdmitFunc(w http.ResponseWriter, r *http.Request, admit admitFunc) {
log.Print("handling webhook request ...")
var writeErr error
if responseBytes, err := doServeAdmitFunc(w, r, admit); err != nil {
log.Printf("error handling webhook request: %v", err)
w.WriteHeader(http.StatusInternalServerError)
_, writeErr = w.Write([]byte(err.Error()))
} else {
log.Printf("webhook request handled successfully")
_, writeErr = w.Write(responseBytes)
}
if writeErr != nil {
log.Printf("could not write response: %v", writeErr)
}
}
// admitFuncHandler takes an admitFunc and wraps it into a http.Handler by means of calling serveAdmitFunc.
func admitFuncHandler(admit admitFunc) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
serveAdmitFunc(w, r, admit)
})
}