-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
cluster.go
445 lines (393 loc) · 17.2 KB
/
cluster.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
/*
Copyright 2021 The Kubernetes 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 webhooks
import (
"context"
"fmt"
"strings"
"github.com/blang/semver"
"github.com/pkg/errors"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/validation/field"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/webhook"
clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1"
"sigs.k8s.io/cluster-api/feature"
"sigs.k8s.io/cluster-api/internal/topology/check"
"sigs.k8s.io/cluster-api/internal/topology/variables"
"sigs.k8s.io/cluster-api/util/version"
)
// SetupWebhookWithManager sets up Cluster webhooks.
func (webhook *Cluster) SetupWebhookWithManager(mgr ctrl.Manager) error {
return ctrl.NewWebhookManagedBy(mgr).
For(&clusterv1.Cluster{}).
WithDefaulter(webhook).
WithValidator(webhook).
Complete()
}
// +kubebuilder:webhook:verbs=create;update;delete,path=/validate-cluster-x-k8s-io-v1beta1-cluster,mutating=false,failurePolicy=fail,matchPolicy=Equivalent,groups=cluster.x-k8s.io,resources=clusters,versions=v1beta1,name=validation.cluster.cluster.x-k8s.io,sideEffects=None,admissionReviewVersions=v1;v1beta1
// +kubebuilder:webhook:verbs=create;update,path=/mutate-cluster-x-k8s-io-v1beta1-cluster,mutating=true,failurePolicy=fail,matchPolicy=Equivalent,groups=cluster.x-k8s.io,resources=clusters,versions=v1beta1,name=default.cluster.cluster.x-k8s.io,sideEffects=None,admissionReviewVersions=v1;v1beta1
// Cluster implements a validating and defaulting webhook for Cluster.
type Cluster struct {
Client client.Reader
}
var _ webhook.CustomDefaulter = &Cluster{}
var _ webhook.CustomValidator = &Cluster{}
// Default satisfies the defaulting webhook interface.
func (webhook *Cluster) Default(ctx context.Context, obj runtime.Object) error {
cluster, ok := obj.(*clusterv1.Cluster)
if !ok {
return apierrors.NewBadRequest(fmt.Sprintf("expected a Cluster but got a %T", obj))
}
if cluster.Spec.InfrastructureRef != nil && cluster.Spec.InfrastructureRef.Namespace == "" {
cluster.Spec.InfrastructureRef.Namespace = cluster.Namespace
}
if cluster.Spec.ControlPlaneRef != nil && cluster.Spec.ControlPlaneRef.Namespace == "" {
cluster.Spec.ControlPlaneRef.Namespace = cluster.Namespace
}
// Additional defaulting if the Cluster uses a managed topology.
if cluster.Spec.Topology != nil {
// Tolerate version strings without a "v" prefix: prepend it if it's not there.
if !strings.HasPrefix(cluster.Spec.Topology.Version, "v") {
cluster.Spec.Topology.Version = "v" + cluster.Spec.Topology.Version
}
clusterClass, err := webhook.getClusterClassForCluster(ctx, cluster)
if err != nil {
// Return early with errors if the ClusterClass can't be retrieved.
return apierrors.NewInternalError(errors.Wrapf(err, "Cluster %s can't be validated. ClusterClass %s can not be retrieved", cluster.Name, cluster.Spec.Topology.Class))
}
// We gather all defaulting errors and return them together.
var allErrs field.ErrorList
defaultedVariables, errs := variables.DefaultClusterVariables(cluster.Spec.Topology.Variables, clusterClass.Spec.Variables,
field.NewPath("spec", "topology", "variables"))
if len(errs) > 0 {
allErrs = append(allErrs, errs...)
} else {
cluster.Spec.Topology.Variables = defaultedVariables
}
if cluster.Spec.Topology.Workers != nil {
for i, md := range cluster.Spec.Topology.Workers.MachineDeployments {
// Continue if there are no variable overrides.
if md.Variables == nil || len(md.Variables.Overrides) == 0 {
continue
}
defaultedVariables, errs := variables.DefaultMachineDeploymentVariables(md.Variables.Overrides, clusterClass.Spec.Variables,
field.NewPath("spec", "topology", "workers", "machineDeployments").Index(i).Child("variables", "overrides"))
if len(errs) > 0 {
allErrs = append(allErrs, errs...)
} else {
md.Variables.Overrides = defaultedVariables
}
}
}
if len(allErrs) > 0 {
return apierrors.NewInvalid(clusterv1.GroupVersion.WithKind("Cluster").GroupKind(), cluster.Name, allErrs)
}
}
return nil
}
// ValidateCreate implements webhook.CustomValidator so a webhook will be registered for the type.
func (webhook *Cluster) ValidateCreate(ctx context.Context, obj runtime.Object) error {
cluster, ok := obj.(*clusterv1.Cluster)
if !ok {
return apierrors.NewBadRequest(fmt.Sprintf("expected a Cluster but got a %T", obj))
}
return webhook.validate(ctx, nil, cluster)
}
// ValidateUpdate implements webhook.CustomValidator so a webhook will be registered for the type.
func (webhook *Cluster) ValidateUpdate(ctx context.Context, oldObj, newObj runtime.Object) error {
newCluster, ok := newObj.(*clusterv1.Cluster)
if !ok {
return apierrors.NewBadRequest(fmt.Sprintf("expected a Cluster but got a %T", newObj))
}
oldCluster, ok := oldObj.(*clusterv1.Cluster)
if !ok {
return apierrors.NewBadRequest(fmt.Sprintf("expected a Cluster but got a %T", oldObj))
}
return webhook.validate(ctx, oldCluster, newCluster)
}
// ValidateDelete implements webhook.CustomValidator so a webhook will be registered for the type.
func (webhook *Cluster) ValidateDelete(_ context.Context, obj runtime.Object) error {
return nil
}
func (webhook *Cluster) validate(ctx context.Context, oldCluster, newCluster *clusterv1.Cluster) error {
var allErrs field.ErrorList
specPath := field.NewPath("spec")
if newCluster.Spec.InfrastructureRef != nil && newCluster.Spec.InfrastructureRef.Namespace != newCluster.Namespace {
allErrs = append(
allErrs,
field.Invalid(
specPath.Child("infrastructureRef", "namespace"),
newCluster.Spec.InfrastructureRef.Namespace,
"must match metadata.namespace",
),
)
}
if newCluster.Spec.ControlPlaneRef != nil && newCluster.Spec.ControlPlaneRef.Namespace != newCluster.Namespace {
allErrs = append(
allErrs,
field.Invalid(
specPath.Child("controlPlaneRef", "namespace"),
newCluster.Spec.ControlPlaneRef.Namespace,
"must match metadata.namespace",
),
)
}
topologyPath := specPath.Child("topology")
// Validate the managed topology, if defined.
if newCluster.Spec.Topology != nil {
allErrs = append(allErrs, webhook.validateTopology(ctx, oldCluster, newCluster, topologyPath)...)
}
// On update.
if oldCluster != nil {
// Error if the update moves the cluster from Managed to Unmanaged i.e. the managed topology is removed on update.
if oldCluster.Spec.Topology != nil && newCluster.Spec.Topology == nil {
allErrs = append(allErrs, field.Forbidden(
topologyPath,
"cannot be removed from an existing Cluster",
))
}
}
if len(allErrs) > 0 {
return apierrors.NewInvalid(clusterv1.GroupVersion.WithKind("Cluster").GroupKind(), newCluster.Name, allErrs)
}
return nil
}
func (webhook *Cluster) validateTopology(ctx context.Context, oldCluster, newCluster *clusterv1.Cluster, fldPath *field.Path) field.ErrorList {
// NOTE: ClusterClass and managed topologies are behind ClusterTopology feature gate flag; the web hook
// must prevent the usage of Cluster.Topology in case the feature flag is disabled.
if !feature.Gates.Enabled(feature.ClusterTopology) {
return field.ErrorList{
field.Forbidden(
fldPath,
"can be set only if the ClusterTopology feature flag is enabled",
),
}
}
var allErrs field.ErrorList
// class should be defined.
if newCluster.Spec.Topology.Class == "" {
allErrs = append(
allErrs,
field.Required(
fldPath.Child("class"),
"class cannot be empty",
),
)
}
// version should be valid.
if !version.KubeSemver.MatchString(newCluster.Spec.Topology.Version) {
allErrs = append(
allErrs,
field.Invalid(
fldPath.Child("version"),
newCluster.Spec.Topology.Version,
"version must be a valid semantic version",
),
)
}
// clusterClass must exist.
clusterClass := &clusterv1.ClusterClass{}
// Check to see if the ClusterClass referenced in the Cluster currently exists.
if err := webhook.Client.Get(ctx, client.ObjectKey{Namespace: newCluster.Namespace, Name: newCluster.Spec.Topology.Class}, clusterClass); err != nil {
allErrs = append(
allErrs, field.Invalid(
fldPath.Child("class"),
newCluster.Name,
fmt.Sprintf("ClusterClass with name %q could not be found", newCluster.Spec.Topology.Class)))
return allErrs
}
allErrs = append(allErrs, check.MachineDeploymentTopologiesAreValidAndDefinedInClusterClass(newCluster, clusterClass)...)
// Check if the variables defined in the ClusterClass are valid.
allErrs = append(allErrs, variables.ValidateClusterVariables(newCluster.Spec.Topology.Variables, clusterClass.Spec.Variables,
fldPath.Child("variables"))...)
// validate the MachineHealthChecks defined in the cluster topology
allErrs = append(allErrs, validateMachineHealthChecks(newCluster, clusterClass)...)
if newCluster.Spec.Topology.Workers != nil {
for i, md := range newCluster.Spec.Topology.Workers.MachineDeployments {
// Continue if there are no variable overrides.
if md.Variables == nil || len(md.Variables.Overrides) == 0 {
continue
}
allErrs = append(allErrs, variables.ValidateMachineDeploymentVariables(md.Variables.Overrides, clusterClass.Spec.Variables,
fldPath.Child("workers", "machineDeployments").Index(i).Child("variables", "overrides"))...)
}
}
if oldCluster != nil { // On update
// Topology or Class can not be added on update unless unsafe cluster topology update annotation is set
if oldCluster.Spec.Topology == nil || oldCluster.Spec.Topology.Class == "" {
if _, ok := newCluster.Annotations[clusterv1.ClusterTopologyUnsafeUpdateClassNameAnnotation]; ok {
return allErrs
}
allErrs = append(
allErrs,
field.Forbidden(
fldPath.Child("class"),
"class cannot be set on an existing Cluster",
),
)
// return early here if there is no class to compare.
return allErrs
}
// Version could only be increased.
inVersion, err := semver.ParseTolerant(newCluster.Spec.Topology.Version)
if err != nil {
allErrs = append(
allErrs,
field.Invalid(
fldPath.Child("version"),
newCluster.Spec.Topology.Version,
"version must be a valid semantic version",
),
)
}
oldVersion, err := semver.ParseTolerant(oldCluster.Spec.Topology.Version)
if err != nil {
// NOTE: this should never happen. Nevertheless, handling this for extra caution.
allErrs = append(
allErrs,
field.Invalid(
fldPath.Child("version"),
oldCluster.Spec.Topology.Version,
fmt.Sprintf("old version %q cannot be compared with %q", oldVersion, inVersion),
),
)
}
if inVersion.NE(semver.Version{}) && oldVersion.NE(semver.Version{}) && version.Compare(inVersion, oldVersion, version.WithBuildTags()) == -1 {
allErrs = append(
allErrs,
field.Invalid(
fldPath.Child("version"),
newCluster.Spec.Topology.Version,
fmt.Sprintf("version cannot be decreased from %q to %q", oldVersion, inVersion),
),
)
}
// A +2 minor version upgrade is not allowed.
ceilVersion := semver.Version{
Major: oldVersion.Major,
Minor: oldVersion.Minor + 2,
Patch: 0,
}
if inVersion.GTE(ceilVersion) {
allErrs = append(
allErrs,
field.Forbidden(
fldPath.Child("version"),
fmt.Sprintf("version cannot be increased from %q to %q", oldVersion, inVersion),
),
)
}
// If the ClusterClass referenced in the Topology has changed compatibility checks are needed.
if oldCluster.Spec.Topology.Class != newCluster.Spec.Topology.Class {
// Check to see if the ClusterClass referenced in the old version of the Cluster exists.
oldClusterClass, err := webhook.getClusterClassForCluster(ctx, oldCluster)
if err != nil {
allErrs = append(
allErrs, field.Forbidden(
fldPath.Child("class"),
fmt.Sprintf("ClusterClass with name %q could not be found, change from class %[1]q to class %q cannot be validated",
oldCluster.Spec.Topology.Class, newCluster.Spec.Topology.Class)))
// Return early with errors if the ClusterClass can't be retrieved.
return allErrs
}
// Check if the new and old ClusterClasses are compatible with one another.
allErrs = append(allErrs, check.ClusterClassesAreCompatible(oldClusterClass, clusterClass)...)
}
}
return allErrs
}
func (webhook *Cluster) getClusterClassForCluster(ctx context.Context, cluster *clusterv1.Cluster) (*clusterv1.ClusterClass, error) {
clusterClass := &clusterv1.ClusterClass{}
// Check to see if the ClusterClass referenced in the old version of the Cluster exists.
if err := webhook.Client.Get(ctx, client.ObjectKey{Namespace: cluster.Namespace, Name: cluster.Spec.Topology.Class}, clusterClass); err != nil {
return nil, err
}
return clusterClass, nil
}
func validateMachineHealthChecks(cluster *clusterv1.Cluster, clusterClass *clusterv1.ClusterClass) field.ErrorList {
var allErrs field.ErrorList
// Validate ControlPlane MachineHealthCheck if defined.
if cluster.Spec.Topology.ControlPlane.MachineHealthCheck != nil && !cluster.Spec.Topology.ControlPlane.MachineHealthCheck.MachineHealthCheckClass.IsZero() {
// Ensure ControlPlane does not define a MachineHealthCheck if the ClusterClass does not define MachineInfrastructure.
if clusterClass.Spec.ControlPlane.MachineInfrastructure == nil {
allErrs = append(allErrs, field.Forbidden(
field.NewPath("spec", "topology", "controlPlane", "machineHealthCheck"),
"can be set only if spec.controlPlane.machineInfrastructure is set in ClusterClass",
))
}
// Ensure ControlPlane MachineHealthCheck defines UnhealthyConditions.
if len(cluster.Spec.Topology.ControlPlane.MachineHealthCheck.MachineHealthCheckClass.UnhealthyConditions) == 0 {
allErrs = append(allErrs, field.Forbidden(
field.NewPath("spec", "topology", "controlPlane", "machineHealthCheck", "unhealthyConditions"),
"must have at least one value",
))
}
}
// If MachineHealthCheck is explicitly enabled then make sure that a MachineHealthCheck definition is
// available either in the Cluster topology or in the ClusterClass.
// (One of these definitions will be used in the controller to create the MachineHealthCheck)
if cluster.Spec.Topology.ControlPlane.MachineHealthCheck != nil &&
cluster.Spec.Topology.ControlPlane.MachineHealthCheck.Enable != nil &&
*cluster.Spec.Topology.ControlPlane.MachineHealthCheck.Enable &&
cluster.Spec.Topology.ControlPlane.MachineHealthCheck.MachineHealthCheckClass.IsZero() &&
clusterClass.Spec.ControlPlane.MachineHealthCheck == nil {
allErrs = append(allErrs, field.Forbidden(
field.NewPath("spec", "topology", "controlPlane", "machineHealthCheck", "enable"),
fmt.Sprintf("cannot be set to %t as MachineHealthCheck definition is not available in the Cluster topology or the ClusterClass", *cluster.Spec.Topology.ControlPlane.MachineHealthCheck.Enable),
))
}
if cluster.Spec.Topology.Workers != nil {
for i, md := range cluster.Spec.Topology.Workers.MachineDeployments {
// If MachineHealthCheck is defined ensure it defines UnhealthyConditions.
if md.MachineHealthCheck != nil && !md.MachineHealthCheck.MachineHealthCheckClass.IsZero() {
if len(md.MachineHealthCheck.MachineHealthCheckClass.UnhealthyConditions) == 0 {
allErrs = append(allErrs, field.Forbidden(
field.NewPath("spec", "topology", "workers", "machineDeployments", "machineHealthCheck").Index(i).Child("unhealthyConditions"),
"must have at least one value",
))
}
}
// If MachineHealthCheck is explicitly enabled then make sure that a MachineHealthCheck definition is
// available either in the Cluster topology or in the ClusterClass.
// (One of these definitions will be used in the controller to create the MachineHealthCheck)
mdClass := machineDeploymentClassOfName(clusterClass, md.Class)
if mdClass != nil { // Note: we skip handling the nil case here as it is already handled in previous validations.
if md.MachineHealthCheck != nil &&
md.MachineHealthCheck.Enable != nil &&
*md.MachineHealthCheck.Enable &&
md.MachineHealthCheck.MachineHealthCheckClass.IsZero() &&
mdClass.MachineHealthCheck == nil {
allErrs = append(allErrs, field.Forbidden(
field.NewPath("spec", "topology", "workers", "machineDeployments", "machineHealthCheck").Index(i).Child("enable"),
fmt.Sprintf("cannot be set to %t as MachineHealthCheck definition is not available in the Cluster topology or the ClusterClass", *md.MachineHealthCheck.Enable),
))
}
}
}
}
return allErrs
}
// machineDeploymentClassOfName find a MachineDeploymentClass of the given name in the provided ClusterClass.
// Returns nill if can not find one.
// TODO: Check if there is already a helper function that can do this.
func machineDeploymentClassOfName(clusterClass *clusterv1.ClusterClass, name string) *clusterv1.MachineDeploymentClass {
for _, mdClass := range clusterClass.Spec.Workers.MachineDeployments {
if mdClass.Class == name {
return &mdClass
}
}
return nil
}