/
cloudprofile.go
475 lines (384 loc) · 18.2 KB
/
cloudprofile.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
// Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
//
// 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 validation
import (
"fmt"
"regexp"
"time"
"github.com/gardener/gardener/pkg/apis/core"
"github.com/gardener/gardener/pkg/apis/core/helper"
v1beta1constants "github.com/gardener/gardener/pkg/apis/core/v1beta1/constants"
"github.com/gardener/gardener/pkg/utils"
"github.com/Masterminds/semver"
apivalidation "k8s.io/apimachinery/pkg/api/validation"
metav1validation "k8s.io/apimachinery/pkg/apis/meta/v1/validation"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/validation/field"
"k8s.io/utils/strings/slices"
)
// ValidateCloudProfileCreation validates a CloudProfile object when it is initially created.
func ValidateCloudProfileCreation(cloudProfile *core.CloudProfile) field.ErrorList {
allErrs := field.ErrorList{}
fldPath := field.NewPath("spec")
// check that during creation no version can have an expiration date in the past
fldPathKubernetes := fldPath.Child("kubernetes", "versions")
for index, version := range cloudProfile.Spec.Kubernetes.Versions {
allErrs = append(allErrs, validateVersionExpiration(version, fldPathKubernetes.Index(index))...)
}
fldPathMachineImage := fldPath.Child("machineImages")
for index, image := range cloudProfile.Spec.MachineImages {
fldPathImage := fldPathMachineImage.Index(index)
for index, version := range image.Versions {
fldPathImageVersion := fldPathImage.Child("versions")
allErrs = append(allErrs, validateVersionExpiration(version.ExpirableVersion, fldPathImageVersion.Index(index))...)
}
}
allErrs = append(allErrs, ValidateCloudProfile(cloudProfile)...)
return allErrs
}
// validateVersionExpiration validates that the version has no expiration date in the past
func validateVersionExpiration(version core.ExpirableVersion, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if version.ExpirationDate != nil && version.ExpirationDate.Time.UTC().Before(time.Now().UTC()) {
allErrs = append(allErrs, field.Forbidden(fldPath, fmt.Sprintf("unable to create version %q. Creating a version with expiration date in the past is not allowed", version.Version)))
}
return allErrs
}
// ValidateCloudProfile validates a CloudProfile object.
func ValidateCloudProfile(cloudProfile *core.CloudProfile) field.ErrorList {
allErrs := field.ErrorList{}
allErrs = append(allErrs, apivalidation.ValidateObjectMeta(&cloudProfile.ObjectMeta, false, ValidateName, field.NewPath("metadata"))...)
allErrs = append(allErrs, ValidateCloudProfileSpec(&cloudProfile.Spec, field.NewPath("spec"))...)
return allErrs
}
// ValidateCloudProfileUpdate validates a CloudProfile object before an update.
func ValidateCloudProfileUpdate(newProfile, oldProfile *core.CloudProfile) field.ErrorList {
allErrs := field.ErrorList{}
allErrs = append(allErrs, apivalidation.ValidateObjectMetaUpdate(&newProfile.ObjectMeta, &oldProfile.ObjectMeta, field.NewPath("metadata"))...)
allErrs = append(allErrs, ValidateCloudProfileSpecUpdate(&newProfile.Spec, &oldProfile.Spec, field.NewPath("spec"))...)
allErrs = append(allErrs, ValidateCloudProfile(newProfile)...)
return allErrs
}
// ValidateCloudProfileSpecUpdate validates the spec update of a CloudProfile
func ValidateCloudProfileSpecUpdate(new, old *core.CloudProfileSpec, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
allErrs = append(allErrs, validateCloudProfileVersionsUpdate(new.Kubernetes.Versions, old.Kubernetes.Versions, fldPath.Child("kubernetes", "versions"))...)
for _, oldImage := range old.MachineImages {
for index, newImage := range new.MachineImages {
if oldImage.Name == newImage.Name {
allErrs = append(
allErrs,
validateCloudProfileVersionsUpdate(
helper.ToExpirableVersions(newImage.Versions),
helper.ToExpirableVersions(oldImage.Versions),
fldPath.Child("machineImages").Index(index).Child("versions"),
)...,
)
}
}
}
return allErrs
}
// ValidateCloudProfileAddedVersions validates versions added to the CloudProfile
func ValidateCloudProfileAddedVersions(versions []core.ExpirableVersion, addedVersions map[string]int, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
for _, index := range addedVersions {
version := versions[index]
allErrs = append(allErrs, validateVersionExpiration(version, fldPath.Index(index))...)
}
return allErrs
}
// validateCloudProfileVersionsUpdate validates versions added to the CloudProfile
func validateCloudProfileVersionsUpdate(new, old []core.ExpirableVersion, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
versions := helper.GetAddedVersions(old, new)
allErrs = append(allErrs, ValidateCloudProfileAddedVersions(new, versions, fldPath)...)
return allErrs
}
// ValidateCloudProfileSpec validates the specification of a CloudProfile object.
func ValidateCloudProfileSpec(spec *core.CloudProfileSpec, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if len(spec.Type) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("type"), "must provide a provider type"))
}
allErrs = append(allErrs, validateKubernetesSettings(spec.Kubernetes, fldPath.Child("kubernetes"))...)
allErrs = append(allErrs, validateMachineImages(spec.MachineImages, fldPath.Child("machineImages"))...)
allErrs = append(allErrs, validateMachineTypes(spec.MachineTypes, fldPath.Child("machineTypes"))...)
allErrs = append(allErrs, validateVolumeTypes(spec.VolumeTypes, fldPath.Child("volumeTypes"))...)
allErrs = append(allErrs, validateRegions(spec.Regions, fldPath.Child("regions"))...)
if spec.SeedSelector != nil {
allErrs = append(allErrs, metav1validation.ValidateLabelSelector(&spec.SeedSelector.LabelSelector, fldPath.Child("seedSelector"))...)
}
if spec.CABundle != nil {
_, err := utils.DecodeCertificate([]byte(*(spec.CABundle)))
if err != nil {
allErrs = append(allErrs, field.Invalid(fldPath.Child("caBundle"), *(spec.CABundle), "caBundle is not a valid PEM-encoded certificate"))
}
}
return allErrs
}
func validateKubernetesSettings(kubernetes core.KubernetesSettings, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if len(kubernetes.Versions) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("versions"), "must provide at least one Kubernetes version"))
}
latestKubernetesVersion, _, err := helper.DetermineLatestExpirableVersion(kubernetes.Versions, false)
if err != nil {
allErrs = append(allErrs, field.Invalid(fldPath.Child("versions"), latestKubernetesVersion.Version, "failed to determine the latest kubernetes version from the cloud profile"))
}
if latestKubernetesVersion.ExpirationDate != nil {
allErrs = append(allErrs, field.Invalid(fldPath.Child("versions[]").Child("expirationDate"), latestKubernetesVersion.ExpirationDate, fmt.Sprintf("expiration date of latest kubernetes version ('%s') must not be set", latestKubernetesVersion.Version)))
}
versionsFound := sets.NewString()
r, _ := regexp.Compile(`^([0-9]+\.){2}[0-9]+$`)
for i, version := range kubernetes.Versions {
idxPath := fldPath.Child("versions").Index(i)
if !r.MatchString(version.Version) {
allErrs = append(allErrs, field.Invalid(idxPath, version, fmt.Sprintf("all Kubernetes versions must match the regex %s", r)))
} else if versionsFound.Has(version.Version) {
allErrs = append(allErrs, field.Duplicate(idxPath.Child("version"), version.Version))
} else {
versionsFound.Insert(version.Version)
}
allErrs = append(allErrs, validateExpirableVersion(version, kubernetes.Versions, idxPath)...)
}
return allErrs
}
var supportedVersionClassifications = sets.NewString(string(core.ClassificationPreview), string(core.ClassificationSupported), string(core.ClassificationDeprecated))
func validateExpirableVersion(version core.ExpirableVersion, allVersions []core.ExpirableVersion, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if version.Classification != nil && !supportedVersionClassifications.Has(string(*version.Classification)) {
allErrs = append(allErrs, field.NotSupported(fldPath.Child("classification"), *version.Classification, supportedVersionClassifications.List()))
}
if version.Classification != nil && *version.Classification == core.ClassificationSupported {
currentSemVer, err := semver.NewVersion(version.Version)
if err != nil {
// check is already performed by caller, avoid duplicate error
return allErrs
}
filteredVersions, err := helper.FindVersionsWithSameMajorMinor(helper.FilterVersionsWithClassification(allVersions, core.ClassificationSupported), *currentSemVer)
if err != nil {
// check is already performed by caller, avoid duplicate error
return allErrs
}
// do not allow adding multiple supported versions per minor version
if len(filteredVersions) > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath, fmt.Sprintf("unable to add version %q with classification %q. Only one %q version is allowed per minor version", version.Version, core.ClassificationSupported, core.ClassificationSupported)))
}
}
return allErrs
}
func validateMachineTypes(machineTypes []core.MachineType, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if len(machineTypes) == 0 {
allErrs = append(allErrs, field.Required(fldPath, "must provide at least one machine type"))
}
names := make(map[string]struct{}, len(machineTypes))
for i, machineType := range machineTypes {
idxPath := fldPath.Index(i)
namePath := idxPath.Child("name")
cpuPath := idxPath.Child("cpu")
gpuPath := idxPath.Child("gpu")
memoryPath := idxPath.Child("memory")
archPath := idxPath.Child("architecture")
if len(machineType.Name) == 0 {
allErrs = append(allErrs, field.Required(namePath, "must provide a name"))
}
if _, ok := names[machineType.Name]; ok {
allErrs = append(allErrs, field.Duplicate(namePath, machineType.Name))
break
}
names[machineType.Name] = struct{}{}
allErrs = append(allErrs, ValidateResourceQuantityValue("cpu", machineType.CPU, cpuPath)...)
allErrs = append(allErrs, ValidateResourceQuantityValue("gpu", machineType.GPU, gpuPath)...)
allErrs = append(allErrs, ValidateResourceQuantityValue("memory", machineType.Memory, memoryPath)...)
allErrs = append(allErrs, validateMachineTypeArchitecture(machineType.Architecture, archPath)...)
if machineType.Storage != nil {
allErrs = append(allErrs, validateMachineTypeStorage(*machineType.Storage, idxPath.Child("storage"))...)
}
}
return allErrs
}
func validateMachineTypeStorage(storage core.MachineTypeStorage, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if storage.StorageSize == nil && storage.MinSize == nil {
allErrs = append(allErrs, field.Invalid(fldPath, storage, `must either configure "size" or "minSize"`))
return allErrs
}
if storage.StorageSize != nil && storage.MinSize != nil {
allErrs = append(allErrs, field.Invalid(fldPath, storage, `not allowed to configure both "size" and "minSize"`))
return allErrs
}
if storage.StorageSize != nil {
allErrs = append(allErrs, ValidateResourceQuantityValue("size", *storage.StorageSize, fldPath.Child("size"))...)
}
if storage.MinSize != nil {
allErrs = append(allErrs, ValidateResourceQuantityValue("minSize", *storage.MinSize, fldPath.Child("minSize"))...)
}
return allErrs
}
func validateMachineImages(machineImages []core.MachineImage, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if len(machineImages) == 0 {
allErrs = append(allErrs, field.Required(fldPath, "must provide at least one machine image"))
}
latestMachineImages, err := helper.DetermineLatestMachineImageVersions(machineImages)
if err != nil {
allErrs = append(allErrs, field.Invalid(fldPath, latestMachineImages, err.Error()))
}
duplicateNameVersion := sets.String{}
duplicateName := sets.String{}
for i, image := range machineImages {
idxPath := fldPath.Index(i)
if duplicateName.Has(image.Name) {
allErrs = append(allErrs, field.Duplicate(idxPath, image.Name))
}
duplicateName.Insert(image.Name)
if len(image.Name) == 0 {
allErrs = append(allErrs, field.Required(idxPath.Child("name"), "machine image name must not be empty"))
}
if len(image.Versions) == 0 {
allErrs = append(allErrs, field.Required(idxPath.Child("versions"), fmt.Sprintf("must provide at least one version for the machine image '%s'", image.Name)))
}
for index, machineVersion := range image.Versions {
versionsPath := idxPath.Child("versions").Index(index)
key := fmt.Sprintf("%s-%s", image.Name, machineVersion.Version)
if duplicateNameVersion.Has(key) {
allErrs = append(allErrs, field.Duplicate(versionsPath, key))
}
duplicateNameVersion.Insert(key)
if len(machineVersion.Version) == 0 {
allErrs = append(allErrs, field.Required(versionsPath.Child("version"), machineVersion.Version))
}
_, err := semver.NewVersion(machineVersion.Version)
if err != nil {
allErrs = append(allErrs, field.Invalid(versionsPath.Child("version"), machineVersion.Version, "could not parse version. Use a semantic version. In case there is no semantic version for this image use the extensibility provider (define mapping in the CloudProfile) to map to the actual non semantic version"))
}
allErrs = append(allErrs, validateExpirableVersion(machineVersion.ExpirableVersion, helper.ToExpirableVersions(image.Versions), versionsPath)...)
allErrs = append(allErrs, validateContainerRuntimesInterfaces(machineVersion.CRI, versionsPath.Child("cri"))...)
allErrs = append(allErrs, validateMachineImageVersionArchitecture(machineVersion.Architectures, versionsPath.Child("architecture"))...)
}
}
return allErrs
}
func validateContainerRuntimesInterfaces(cris []core.CRI, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
duplicateCRI := sets.String{}
hasDocker := false
if len(cris) == 0 {
allErrs = append(allErrs, field.Required(fldPath, "must provide at least one supported container runtime"))
return allErrs
}
for i, cri := range cris {
criPath := fldPath.Index(i)
if duplicateCRI.Has(string(cri.Name)) {
allErrs = append(allErrs, field.Duplicate(criPath, cri.Name))
}
duplicateCRI.Insert(string(cri.Name))
if cri.Name == core.CRINameDocker {
hasDocker = true
}
if !availableWorkerCRINames.Has(string(cri.Name)) {
allErrs = append(allErrs, field.NotSupported(criPath, cri, availableWorkerCRINames.List()))
}
allErrs = append(allErrs, validateContainerRuntimes(cri.ContainerRuntimes, criPath.Child("containerRuntimes"))...)
}
if !hasDocker {
allErrs = append(allErrs, field.Invalid(fldPath, cris, "must provide docker as supported container runtime"))
}
return allErrs
}
func validateContainerRuntimes(containerRuntimes []core.ContainerRuntime, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
duplicateCR := sets.String{}
for i, cr := range containerRuntimes {
if duplicateCR.Has(cr.Type) {
allErrs = append(allErrs, field.Duplicate(fldPath.Index(i).Child("type"), cr.Type))
}
duplicateCR.Insert(cr.Type)
}
return allErrs
}
func validateMachineImageVersionArchitecture(archs []string, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
for _, arch := range archs {
if !slices.Contains(v1beta1constants.ValidArchitectures, arch) {
allErrs = append(allErrs, field.NotSupported(fldPath, arch, v1beta1constants.ValidArchitectures))
}
}
return allErrs
}
func validateMachineTypeArchitecture(arch *string, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if !slices.Contains(v1beta1constants.ValidArchitectures, *arch) {
allErrs = append(allErrs, field.NotSupported(fldPath, *arch, v1beta1constants.ValidArchitectures))
}
return allErrs
}
func validateVolumeTypes(volumeTypes []core.VolumeType, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
names := make(map[string]struct{}, len(volumeTypes))
for i, volumeType := range volumeTypes {
idxPath := fldPath.Index(i)
namePath := idxPath.Child("name")
if len(volumeType.Name) == 0 {
allErrs = append(allErrs, field.Required(namePath, "must provide a name"))
}
if _, ok := names[volumeType.Name]; ok {
allErrs = append(allErrs, field.Duplicate(namePath, volumeType.Name))
break
}
names[volumeType.Name] = struct{}{}
if len(volumeType.Class) == 0 {
allErrs = append(allErrs, field.Required(idxPath.Child("class"), "must provide a class"))
}
if volumeType.MinSize != nil {
allErrs = append(allErrs, ValidateResourceQuantityValue("minSize", *volumeType.MinSize, idxPath.Child("minSize"))...)
}
}
return allErrs
}
func validateRegions(regions []core.Region, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if len(regions) == 0 {
allErrs = append(allErrs, field.Required(fldPath, "must provide at least one region"))
}
regionsFound := sets.NewString()
for i, region := range regions {
idxPath := fldPath.Index(i)
namePath := idxPath.Child("name")
zonesPath := idxPath.Child("zones")
labelsPath := idxPath.Child("labels")
if len(region.Name) == 0 {
allErrs = append(allErrs, field.Required(namePath, "must provide a region name"))
} else if regionsFound.Has(region.Name) {
allErrs = append(allErrs, field.Duplicate(namePath, region.Name))
} else {
regionsFound.Insert(region.Name)
}
zonesFound := sets.NewString()
for j, zone := range region.Zones {
namePath := zonesPath.Index(j).Child("name")
if len(zone.Name) == 0 {
allErrs = append(allErrs, field.Required(namePath, "zone name cannot be empty"))
} else if zonesFound.Has(zone.Name) {
allErrs = append(allErrs, field.Duplicate(namePath, zone.Name))
} else {
zonesFound.Insert(zone.Name)
}
}
allErrs = append(allErrs, metav1validation.ValidateLabels(region.Labels, labelsPath)...)
}
return allErrs
}