-
Notifications
You must be signed in to change notification settings - Fork 91
/
app.go
489 lines (450 loc) · 13.2 KB
/
app.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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
// Copyright 2019 Hewlett Packard Enterprise Development LP
// 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 validator
import (
"encoding/json"
"fmt"
"strconv"
"strings"
kdv1 "github.com/bluek8s/kubedirector/pkg/apis/kubedirector/v1beta1"
"github.com/bluek8s/kubedirector/pkg/catalog"
"github.com/bluek8s/kubedirector/pkg/shared"
"k8s.io/api/admission/v1beta1"
"k8s.io/apimachinery/pkg/api/equality"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
type appPatchSpec struct {
Op string `json:"op"`
Path string `json:"path"`
Value appPatchValue `json:"value,omitempty"`
}
type appPatchValue struct {
packageURLValue *packageURL
stringValue *string
stringSliceValue *[]string
}
type packageURL struct {
URL string `json:"packageURL"`
}
func (obj appPatchValue) MarshalJSON() ([]byte, error) {
if obj.packageURLValue != nil {
return json.Marshal(obj.packageURLValue)
}
if obj.stringValue != nil {
return json.Marshal(obj.stringValue)
}
return json.Marshal(obj.stringSliceValue)
}
// validateUniqueness checks the lists of roles and service IDs for duplicates.
// Any generated error messages will be added to the input list and returned.
func validateUniqueness(
allRoleIDs []string,
allServiceIDs []string,
valErrors []string,
) []string {
if !shared.ListIsUnique(allRoleIDs) {
valErrors = append(valErrors, nonUniqueRoleID)
}
if !shared.ListIsUnique(allServiceIDs) {
valErrors = append(valErrors, nonUniqueServiceID)
}
return valErrors
}
// validateRefUniqueness checks the lists of role references for duplicates.
// Any generated error messages will be added to the input list and returned.
func validateRefUniqueness(
appCR *kdv1.KubeDirectorApp,
valErrors []string,
) []string {
if !shared.ListIsUnique(appCR.Spec.Config.SelectedRoles) {
valErrors = append(valErrors, nonUniqueSelectedRole)
}
roleSeen := make(map[string]bool)
for _, roleService := range appCR.Spec.Config.RoleServices {
if _, ok := roleSeen[roleService.RoleID]; ok {
valErrors = append(valErrors, nonUniqueServiceRole)
break
}
roleSeen[roleService.RoleID] = true
}
return valErrors
}
// validateServiceRoles checks serviceIDs and roleID from roleServices
// in the config section, to ensure that they refer to legal/existing service
// and role definitions. Any generated error messages will be added to the
// input list and returned.
func validateServiceRoles(
appCR *kdv1.KubeDirectorApp,
allRoleIDs []string,
allServiceIDs []string,
valErrors []string,
) []string {
for _, nodeRole := range appCR.Spec.Config.RoleServices {
if !shared.StringInList(nodeRole.RoleID, allRoleIDs) {
invalidMsg := fmt.Sprintf(
invalidNodeRoleID,
nodeRole.RoleID,
strings.Join(allRoleIDs, ","),
)
valErrors = append(valErrors, invalidMsg)
}
for _, serviceID := range nodeRole.ServiceIDs {
if !shared.StringInList(serviceID, allServiceIDs) {
invalidMsg := fmt.Sprintf(
invalidServiceID,
serviceID,
strings.Join(allServiceIDs, ","),
)
valErrors = append(valErrors, invalidMsg)
}
}
}
return valErrors
}
// validateSelectedRoles checks the selectedRoles array to make sure it
// only contains valid role IDs. Any generated error messages will be added to
// the input list and returned.
func validateSelectedRoles(
appCR *kdv1.KubeDirectorApp,
allRoleIDs []string,
valErrors []string,
) []string {
for _, role := range appCR.Spec.Config.SelectedRoles {
if catalog.GetRoleFromID(appCR, role) == nil {
invalidMsg := fmt.Sprintf(
invalidSelectedRoleID,
role,
strings.Join(allRoleIDs, ","),
)
valErrors = append(valErrors, invalidMsg)
}
}
return valErrors
}
// validateRoles checks each role for property constraints not expressible
// in the schema. If any overrideable properties are unspecified, the corresponding
// global values are used. This will add an PATCH spec for mutation the app CR.
// The role in appCR will be correspondingly updated so that it can later be
// used to check whether the resulting CR differs from the current stored appCR.
func validateRoles(
appCR *kdv1.KubeDirectorApp,
patches []appPatchSpec,
valErrors []string,
) ([]appPatchSpec, []string) {
// Any global defaults will be removed from the CR. Remember their values
// though for use in populating the role definitions.
var globalImageRepoTag *string
var globalSetupPackageURL *string
var globalPersistDirs *[]string
var globalEventList *[]string
if appCR.Spec.DefaultImageRepoTag == nil {
globalImageRepoTag = nil
} else {
tagCopy := *appCR.Spec.DefaultImageRepoTag
globalImageRepoTag = &tagCopy
appCR.Spec.DefaultImageRepoTag = nil
patches = append(
patches,
appPatchSpec{
Op: "remove",
Path: "/spec/defaultImageRepoTag",
},
)
}
if !appCR.Spec.DefaultSetupPackage.IsSet {
globalSetupPackageURL = nil
} else {
if appCR.Spec.DefaultSetupPackage.IsNull {
globalSetupPackageURL = nil
} else {
urlCopy := appCR.Spec.DefaultSetupPackage.PackageURL.PackageURL
globalSetupPackageURL = &urlCopy
}
appCR.Spec.DefaultSetupPackage = kdv1.SetupPackage{}
patches = append(
patches,
appPatchSpec{
Op: "remove",
Path: "/spec/defaultConfigPackage",
},
)
}
if appCR.Spec.DefaultPersistDirs == nil {
globalPersistDirs = nil
} else {
dirsCopy := make([]string, len(*appCR.Spec.DefaultPersistDirs))
copy(dirsCopy, *appCR.Spec.DefaultPersistDirs)
globalPersistDirs = &dirsCopy
appCR.Spec.DefaultPersistDirs = nil
patches = append(
patches,
appPatchSpec{
Op: "remove",
Path: "/spec/defaultPersistDirs",
},
)
}
if appCR.Spec.DefaultEventList == nil {
globalEventList = nil
} else {
eventsCopy := make([]string, len(*appCR.Spec.DefaultEventList))
copy(eventsCopy, *appCR.Spec.DefaultEventList)
globalEventList = &eventsCopy
appCR.Spec.DefaultEventList = nil
patches = append(
patches,
appPatchSpec{
Op: "remove",
Path: "/spec/defaultEventList",
},
)
}
// OK let's do the roles.
numRoles := len(appCR.Spec.NodeRoles)
for index := 0; index < numRoles; index++ {
role := &(appCR.Spec.NodeRoles[index])
if role.SetupPackage.IsSet == false {
// Nothing specified so, inherit the global specification
if globalSetupPackageURL == nil {
role.SetupPackage.IsSet = true
role.SetupPackage.IsNull = true
patches = append(
patches,
appPatchSpec{
Op: "add",
Path: "/spec/roles/" + strconv.Itoa(index) + "/configPackage",
Value: appPatchValue{
stringValue: nil,
},
},
)
} else {
role.SetupPackage.IsSet = true
role.SetupPackage.IsNull = false
role.SetupPackage.PackageURL = kdv1.SetupPackageURL{
PackageURL: *globalSetupPackageURL,
}
patches = append(
patches,
appPatchSpec{
Op: "add",
Path: "/spec/roles/" + strconv.Itoa(index) + "/configPackage",
Value: appPatchValue{
packageURLValue: &packageURL{URL: *globalSetupPackageURL},
},
},
)
}
}
if role.ContainerSpec != nil {
if role.ContainerSpec.Tty {
if !role.ContainerSpec.Stdin {
valErrors = append(
valErrors,
fmt.Sprintf(
ttyWithoutStdin,
role.ID,
),
)
}
}
}
if role.ImageRepoTag == nil {
// We allow roles to have different container images but unlike the
// setup package there cannot be a role with no image.
if globalImageRepoTag == nil {
valErrors = append(
valErrors,
fmt.Sprintf(
noDefaultImage,
role.ID,
),
)
continue
}
// No special image specified so inherit from global.
role.ImageRepoTag = globalImageRepoTag
patches = append(
patches,
appPatchSpec{
Op: "add",
Path: "/spec/roles/" + strconv.Itoa(index) + "/imageRepoTag",
Value: appPatchValue{
stringValue: globalImageRepoTag,
},
},
)
}
if role.PersistDirs == nil {
if globalPersistDirs != nil {
role.PersistDirs = globalPersistDirs
patches = append(
patches,
appPatchSpec{
Op: "add",
Path: "/spec/roles/" + strconv.Itoa(index) + "/persistDirs",
Value: appPatchValue{
stringSliceValue: globalPersistDirs,
},
},
)
}
}
if role.EventList == nil {
if globalEventList != nil {
role.EventList = globalEventList
patches = append(
patches,
appPatchSpec{
Op: "add",
Path: "/spec/roles/" + strconv.Itoa(index) + "/eventList",
Value: appPatchValue{
stringSliceValue: globalEventList,
},
},
)
}
}
}
return patches, valErrors
}
// validateServices checks each service for property constraints not
// expressible in the schema. Currently this just means checking that the
// service endpoint must specify url_schema if isDashboard is true. Any
// generated error messages will be added to the input list and returned.
func validateServices(
appCR *kdv1.KubeDirectorApp,
valErrors []string,
) []string {
for _, service := range appCR.Spec.Services {
if service.Endpoint.IsDashboard {
if service.Endpoint.URLScheme == "" {
invalidMsg := fmt.Sprintf(
noURLScheme,
service.ID,
)
valErrors = append(valErrors, invalidMsg)
}
}
}
return valErrors
}
// admitAppCR is the top-level app validation function, which invokes
// the top-specific validation subroutines and composes the admission
// response.
func admitAppCR(
ar *v1beta1.AdmissionReview,
) *v1beta1.AdmissionResponse {
var valErrors []string
var patches []appPatchSpec
var admitResponse = v1beta1.AdmissionResponse{
Allowed: false,
}
// Reject a delete if the app CR is currently in use.
if ar.Request.Operation == v1beta1.Delete {
references := shared.ClustersUsingApp(
ar.Request.Namespace,
ar.Request.Name,
)
if len(references) != 0 {
referencesStr := strings.Join(references, ", ")
appInUseMsg := fmt.Sprintf(
appInUse,
referencesStr,
)
admitResponse.Result = &metav1.Status{
Message: "\n" + appInUseMsg,
}
return &admitResponse
}
}
// For a delete operation, we're done now.
if ar.Request.Operation == v1beta1.Delete {
admitResponse.Allowed = true
return &admitResponse
}
// Deserialize the object.
raw := ar.Request.Object.Raw
appCR := kdv1.KubeDirectorApp{}
if jsonErr := json.Unmarshal(raw, &appCR); jsonErr != nil {
admitResponse.Result = &metav1.Status{
Message: "\n" + jsonErr.Error(),
}
return &admitResponse
}
// Now do validation for create/update.
allRoleIDs := catalog.GetAllRoleIDs(&appCR)
allServiceIDs := catalog.GetAllServiceIDs(&appCR)
valErrors = validateUniqueness(allRoleIDs, allServiceIDs, valErrors)
valErrors = validateRefUniqueness(&appCR, valErrors)
valErrors = validateServiceRoles(&appCR, allRoleIDs, allServiceIDs, valErrors)
valErrors = validateSelectedRoles(&appCR, allRoleIDs, valErrors)
patches, valErrors = validateRoles(&appCR, patches, valErrors)
valErrors = validateServices(&appCR, valErrors)
if len(valErrors) == 0 {
if len(patches) != 0 {
patchResult, patchErr := json.Marshal(patches)
if patchErr == nil {
admitResponse.Patch = patchResult
patchType := v1beta1.PatchTypeJSONPatch
admitResponse.PatchType = &patchType
} else {
valErrors = append(valErrors, failedToPatch)
}
}
}
// Reject an update if the app CR is currently in use AND this update is
// changing the spec. Note that we don't do this at the beginning of the
// handler because we want to get defaults populated before comparing.
if ar.Request.Operation == v1beta1.Update {
references := shared.ClustersUsingApp(
ar.Request.Namespace,
ar.Request.Name,
)
if len(references) != 0 {
prevAppCR := kdv1.KubeDirectorApp{}
prevRaw := ar.Request.OldObject.Raw
if prevJSONErr := json.Unmarshal(prevRaw, &prevAppCR); prevJSONErr != nil {
admitResponse.Result = &metav1.Status{
Message: "\n" + prevJSONErr.Error(),
}
return &admitResponse
}
// Before doing the comparison, make sure we ignore differences
// in the global default setup package. Global defaults should
// NOT be set at this point in either object, and if they are then
// they have no functional effect on kdclusters, but there was a
// bug in KD pre-0.5 that could leave defaultConfigPackage set
// to null. See the commit comments in the PR that closes issue
// #319 for more details.
prevAppCR.Spec.DefaultSetupPackage = appCR.Spec.DefaultSetupPackage
if !equality.Semantic.DeepEqual(appCR.Spec, prevAppCR.Spec) {
referencesStr := strings.Join(references, ", ")
appInUseMsg := fmt.Sprintf(
appInUse,
referencesStr,
)
admitResponse.Result = &metav1.Status{
Message: "\n" + appInUseMsg,
}
return &admitResponse
}
}
}
if len(valErrors) == 0 {
admitResponse.Allowed = true
} else {
admitResponse.Result = &metav1.Status{
Message: "\n" + strings.Join(valErrors, "\n"),
}
}
return &admitResponse
}