-
Notifications
You must be signed in to change notification settings - Fork 124
/
admission.go
203 lines (173 loc) · 6.21 KB
/
admission.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
/*
Copyright 2019 The Machine Controller Authors.
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 admission
import (
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"reflect"
"time"
"github.com/Masterminds/semver/v3"
"gomodules.xyz/jsonpatch/v2"
machinecontroller "github.com/kubermatic/machine-controller/pkg/controller/machine"
"github.com/kubermatic/machine-controller/pkg/node"
userdatamanager "github.com/kubermatic/machine-controller/pkg/userdata/manager"
admissionv1 "k8s.io/api/admission/v1"
apiequality "k8s.io/apimachinery/pkg/api/equality"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/klog"
ctrlruntimeclient "sigs.k8s.io/controller-runtime/pkg/client"
)
type admissionData struct {
client ctrlruntimeclient.Client
workerClient ctrlruntimeclient.Client
userDataManager *userdatamanager.Manager
nodeSettings machinecontroller.NodeSettings
useOSM bool
namespace string
constraints *semver.Constraints
}
var jsonPatch = admissionv1.PatchTypeJSONPatch
type Builder struct {
ListenAddress string
Client ctrlruntimeclient.Client
WorkerClient ctrlruntimeclient.Client
UserdataManager *userdatamanager.Manager
NodeFlags *node.Flags
UseOSM bool
Namespace string
VersionConstraints *semver.Constraints
}
func (build Builder) Build() (*http.Server, error) {
mux := http.NewServeMux()
ad := &admissionData{
client: build.Client,
workerClient: build.WorkerClient,
userDataManager: build.UserdataManager,
useOSM: build.UseOSM,
namespace: build.Namespace,
constraints: build.VersionConstraints,
}
if err := build.NodeFlags.UpdateNodeSettings(&ad.nodeSettings); err != nil {
return nil, fmt.Errorf("error updating nodeSettings, %w", err)
}
mux.HandleFunc("/machinedeployments", handleFuncFactory(ad.mutateMachineDeployments))
mux.HandleFunc("/machines", handleFuncFactory(ad.mutateMachines))
mux.HandleFunc("/healthz", healthZHandler)
return &http.Server{
Addr: build.ListenAddress,
Handler: http.TimeoutHandler(mux, 25*time.Second, "timeout"),
}, nil
}
func healthZHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}
func newJSONPatch(original, current runtime.Object) ([]jsonpatch.JsonPatchOperation, error) {
originalGVK := original.GetObjectKind().GroupVersionKind()
currentGVK := current.GetObjectKind().GroupVersionKind()
if !reflect.DeepEqual(originalGVK, currentGVK) {
return nil, fmt.Errorf("GroupVersionKind %#v is expected to match %#v", originalGVK, currentGVK)
}
ori, err := json.Marshal(original)
if err != nil {
return nil, err
}
klog.V(6).Infof("jsonpatch: Marshaled original: %s", string(ori))
cur, err := json.Marshal(current)
if err != nil {
return nil, err
}
klog.V(6).Infof("jsonpatch: Marshaled target: %s", string(cur))
return jsonpatch.CreatePatch(ori, cur)
}
func createAdmissionResponse(original, mutated runtime.Object) (*admissionv1.AdmissionResponse, error) {
response := &admissionv1.AdmissionResponse{}
response.Allowed = true
if !apiequality.Semantic.DeepEqual(original, mutated) {
patchOpts, err := newJSONPatch(original, mutated)
if err != nil {
return nil, fmt.Errorf("failed to create json patch: %w", err)
}
patchRaw, err := json.Marshal(patchOpts)
if err != nil {
return nil, fmt.Errorf("failed to marshal json patch: %w", err)
}
klog.V(3).Infof("Produced jsonpatch: %s", string(patchRaw))
response.Patch = patchRaw
response.PatchType = &jsonPatch
}
return response, nil
}
type mutator func(context.Context, admissionv1.AdmissionRequest) (*admissionv1.AdmissionResponse, error)
func handleFuncFactory(mutate mutator) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
review, err := readReview(r)
if err != nil {
klog.Warningf("invalid admission review: %v", err)
// proper AdmissionReview responses require metadata that is not available
// in broken requests, so we return a basic failure response
w.WriteHeader(http.StatusBadRequest)
if _, err := w.Write([]byte(fmt.Sprintf("invalid request: %v", err))); err != nil {
klog.Errorf("failed to write badRequest: %v", err)
}
return
}
// run the mutation logic
response, err := mutate(r.Context(), *review.Request)
if err != nil {
response = &admissionv1.AdmissionResponse{}
response.Result = &metav1.Status{Message: err.Error()}
}
response.UID = review.Request.UID
resp, err := json.Marshal(&admissionv1.AdmissionReview{
TypeMeta: metav1.TypeMeta{
APIVersion: admissionv1.SchemeGroupVersion.String(),
Kind: "AdmissionReview",
},
Response: response,
})
if err != nil {
klog.Errorf("failed to marshal admissionResponse: %v", err)
return
}
if _, err := w.Write(resp); err != nil {
klog.Errorf("failed to write admissionResponse: %v", err)
}
}
}
func readReview(r *http.Request) (*admissionv1.AdmissionReview, error) {
var body []byte
if r.Body == nil {
return nil, fmt.Errorf("request has no body")
}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, fmt.Errorf("error reading data from request body: %w", err)
}
// verify the content type is accurate
if contentType := r.Header.Get("Content-Type"); contentType != "application/json" {
return nil, fmt.Errorf("header Content-Type was %s, expected application/json", contentType)
}
admissionReview := &admissionv1.AdmissionReview{}
if err := json.Unmarshal(body, admissionReview); err != nil {
return nil, fmt.Errorf("failed to unmarshal request into admissionReview: %w", err)
}
if admissionReview.Request == nil {
return nil, errors.New("invalid admission review: no request defined")
}
return admissionReview, nil
}