/
virtualmachinesetresourcepolicy_validator.go
180 lines (139 loc) · 6.82 KB
/
virtualmachinesetresourcepolicy_validator.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
// Copyright (c) 2019-2021 VMware, Inc. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package validation
import (
"net/http"
"reflect"
"k8s.io/apimachinery/pkg/api/resource"
"k8s.io/apimachinery/pkg/api/validation"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/validation/field"
"sigs.k8s.io/controller-runtime/pkg/client"
ctrlmgr "sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/webhook"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
"github.com/pkg/errors"
vmopv1 "github.com/vmware-tanzu/vm-operator/api/v1alpha2"
"github.com/vmware-tanzu/vm-operator/pkg/builder"
"github.com/vmware-tanzu/vm-operator/pkg/context"
"github.com/vmware-tanzu/vm-operator/webhooks/common"
)
const (
webHookName = "default"
)
// +kubebuilder:webhook:verbs=create;update,path=/default-validate-vmoperator-vmware-com-v1alpha2-virtualmachinesetresourcepolicy,mutating=false,failurePolicy=fail,groups=vmoperator.vmware.com,resources=virtualmachinesetresourcepolicies,versions=v1alpha2,name=default.validating.virtualmachinesetresourcepolicy.v1alpha2.vmoperator.vmware.com,sideEffects=None,admissionReviewVersions=v1;v1beta1
// +kubebuilder:rbac:groups=vmoperator.vmware.com,resources=virtualmachinesetresourcepolicies,verbs=get;list
// +kubebuilder:rbac:groups=vmoperator.vmware.com,resources=virtualmachinesetresourcepolicies/status,verbs=get
// AddToManager adds the webhook to the provided manager.
func AddToManager(ctx *context.ControllerManagerContext, mgr ctrlmgr.Manager) error {
hook, err := builder.NewValidatingWebhook(ctx, mgr, webHookName, NewValidator(mgr.GetClient()))
if err != nil {
return errors.Wrapf(err, "failed to create VirtualMachineSetResourcePolicy validation webhook")
}
mgr.GetWebhookServer().Register(hook.Path, hook)
return nil
}
// NewValidator returns the package's Validator.
func NewValidator(_ client.Client) builder.Validator {
return validator{
converter: runtime.DefaultUnstructuredConverter,
}
}
type validator struct {
converter runtime.UnstructuredConverter
}
func (v validator) For() schema.GroupVersionKind {
return vmopv1.SchemeGroupVersion.WithKind(reflect.TypeOf(vmopv1.VirtualMachineSetResourcePolicy{}).Name())
}
func (v validator) ValidateCreate(ctx *context.WebhookRequestContext) admission.Response {
vmRP, err := v.vmRPFromUnstructured(ctx.Obj)
if err != nil {
return webhook.Errored(http.StatusBadRequest, err)
}
var fieldErrs field.ErrorList
fieldErrs = append(fieldErrs, v.validateSpec(ctx, vmRP)...)
validationErrs := make([]string, 0, len(fieldErrs))
for _, fieldErr := range fieldErrs {
validationErrs = append(validationErrs, fieldErr.Error())
}
return common.BuildValidationResponse(ctx, nil, validationErrs, nil)
}
func (v validator) ValidateDelete(*context.WebhookRequestContext) admission.Response {
return admission.Allowed("")
}
func (v validator) ValidateUpdate(ctx *context.WebhookRequestContext) admission.Response {
vmRP, err := v.vmRPFromUnstructured(ctx.Obj)
if err != nil {
return webhook.Errored(http.StatusBadRequest, err)
}
oldVMRP, err := v.vmRPFromUnstructured(ctx.OldObj)
if err != nil {
return webhook.Errored(http.StatusBadRequest, err)
}
var fieldErrs field.ErrorList
fieldErrs = append(fieldErrs, v.validateAllowedChanges(ctx, vmRP, oldVMRP)...)
validationErrs := make([]string, 0, len(fieldErrs))
for _, fieldErr := range fieldErrs {
validationErrs = append(validationErrs, fieldErr.Error())
}
return common.BuildValidationResponse(ctx, nil, validationErrs, nil)
}
func (v validator) validateSpec(ctx *context.WebhookRequestContext, vmRP *vmopv1.VirtualMachineSetResourcePolicy) field.ErrorList {
var fieldErrs field.ErrorList
specPath := field.NewPath("spec")
fieldErrs = append(fieldErrs, v.validateResourcePool(ctx, specPath.Child("resourcepool"), vmRP.Spec.ResourcePool)...)
fieldErrs = append(fieldErrs, v.validateFolder(ctx, specPath.Child("folder"), vmRP.Spec.Folder)...)
fieldErrs = append(fieldErrs, v.validateClusterModules(ctx, specPath.Child("clustermodules"), vmRP.Spec.ClusterModuleGroups)...)
return fieldErrs
}
func (v validator) validateResourcePool(ctx *context.WebhookRequestContext, fldPath *field.Path, rp vmopv1.ResourcePoolSpec) field.ErrorList {
var fieldErrs field.ErrorList
reservation, limits := rp.Reservations, rp.Limits
reservationsPath := fldPath.Child("reservations")
fieldErrs = append(fieldErrs, validateReservationAndLimit(reservationsPath.Child("cpu"), reservation.Cpu, limits.Cpu)...)
fieldErrs = append(fieldErrs, validateReservationAndLimit(reservationsPath.Child("memory"), reservation.Memory, limits.Memory)...)
return fieldErrs
}
func (v validator) validateFolder(ctx *context.WebhookRequestContext, specPath *field.Path, folder string) field.ErrorList {
var fieldErrs field.ErrorList
return fieldErrs
}
func (v validator) validateClusterModules(ctx *context.WebhookRequestContext, fldPath *field.Path, clusterModuleGroups []string) field.ErrorList {
var fieldErrs field.ErrorList
groupNames := map[string]struct{}{}
for i, name := range clusterModuleGroups {
if _, ok := groupNames[name]; ok {
fieldErrs = append(fieldErrs, field.Duplicate(fldPath.Index(i).Child("clusterModuleGroups"), name))
continue
}
groupNames[name] = struct{}{}
}
return fieldErrs
}
// validateAllowedChanges returns true only if immutable fields have not been modified.
func (v validator) validateAllowedChanges(ctx *context.WebhookRequestContext, vmRP, oldVMRP *vmopv1.VirtualMachineSetResourcePolicy) field.ErrorList {
var allErrs field.ErrorList
specPath := field.NewPath("spec")
// Validate all fields under spec which are not allowed to change.
allErrs = append(allErrs, validation.ValidateImmutableField(vmRP.Spec.ResourcePool, oldVMRP.Spec.ResourcePool, specPath.Child("resourcepool"))...)
allErrs = append(allErrs, validation.ValidateImmutableField(vmRP.Spec.Folder, oldVMRP.Spec.Folder, specPath.Child("folder"))...)
allErrs = append(allErrs, validation.ValidateImmutableField(vmRP.Spec.ClusterModuleGroups, oldVMRP.Spec.ClusterModuleGroups, specPath.Child("clustermodules"))...)
return allErrs
}
// vmRPFromUnstructured returns the VirtualMachineSetResourcePolicy from the unstructured object.
func (v validator) vmRPFromUnstructured(obj runtime.Unstructured) (*vmopv1.VirtualMachineSetResourcePolicy, error) {
vmRP := &vmopv1.VirtualMachineSetResourcePolicy{}
if err := v.converter.FromUnstructured(obj.UnstructuredContent(), vmRP); err != nil {
return nil, err
}
return vmRP, nil
}
func validateReservationAndLimit(reservationPath *field.Path, reservation, limit resource.Quantity) field.ErrorList {
if reservation.IsZero() || limit.IsZero() || reservation.Value() <= limit.Value() {
return nil
}
return field.ErrorList{
field.Invalid(reservationPath, reservation.String(), "reservation value cannot exceed the limit value"),
}
}