/
subnet_webhook.go
335 lines (280 loc) · 10.7 KB
/
subnet_webhook.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
// SPDX-FileCopyrightText: 2024 SAP SE or an SAP affiliate company and IronCore contributors
// SPDX-License-Identifier: Apache-2.0
package v1alpha1
import (
"context"
"fmt"
"reflect"
"strings"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
"github.com/pkg/errors"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/validation/field"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
logf "sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/webhook"
_ "sigs.k8s.io/controller-runtime/pkg/webhook/admission"
)
const (
CFinishedChildSubnetToSubnetIndexKey = "finishedChildSubnetToSubnet"
CFinishedChildIPToSubnetIndexKey = "finishedChildIPToSubnet"
)
// log is for logging in this package.
var subnetlog = logf.Log.WithName("subnet-resource")
var subnetWebhookClient client.Client
func (in *Subnet) SetupWebhookWithManager(mgr ctrl.Manager) error {
createChildSubnetIndexValue := func(object client.Object) []string {
subnet, ok := object.(*Subnet)
if !ok {
return nil
}
state := subnet.Status.State
parentSubnet := subnet.Spec.ParentSubnet.Name
if parentSubnet == "" {
return nil
}
if state != CFinishedSubnetState {
return nil
}
return []string{parentSubnet}
}
createChildIPIndexValue := func(object client.Object) []string {
ip, ok := object.(*IP)
if !ok {
return nil
}
state := ip.Status.State
parentSubnet := ip.Spec.Subnet.Name
if state != CFinishedIPState {
return nil
}
return []string{parentSubnet}
}
if err := mgr.GetFieldIndexer().IndexField(
context.Background(), &Subnet{}, CFinishedChildSubnetToSubnetIndexKey, createChildSubnetIndexValue); err != nil {
return err
}
if err := mgr.GetFieldIndexer().IndexField(
context.Background(), &IP{}, CFinishedChildIPToSubnetIndexKey, createChildIPIndexValue); err != nil {
return err
}
subnetWebhookClient = mgr.GetClient()
return ctrl.NewWebhookManagedBy(mgr).
For(in).
Complete()
}
// +kubebuilder:webhook:path=/validate-ipam-metal-ironcore-dev-v1alpha1-subnet,mutating=false,failurePolicy=fail,sideEffects=None,groups=ipam.metal.ironcore.dev,resources=subnets,verbs=create;update;delete,versions=v1alpha1,name=vsubnet.kb.io,admissionReviewVersions={v1,v1beta1}
var _ webhook.Validator = &Subnet{}
// ValidateCreate implements webhook.Validator so a webhook will be registered for the type
func (in *Subnet) ValidateCreate() (admission.Warnings, error) {
subnetlog.Info("validate create", "name", in.Name)
var allErrs field.ErrorList
var warnings admission.Warnings
rulesCount := in.countCIDRReservationRules()
rulesPaths := []string{"spec.cidr", "spec.capacity", "spec.hostIdentifierBits"}
minQuantity := resource.NewQuantity(1, resource.DecimalSI)
maxQuantity, err := resource.ParseQuantity("340282366920938463463374607431768211456")
if err != nil {
return warnings, apierrors.NewInternalError(err)
}
if rulesCount == 0 || rulesCount > 1 {
errMsg := fmt.Sprintf("value should be set for the one of the following fields: %s", strings.Join(rulesPaths, ", "))
for _, path := range rulesPaths {
allErrs = append(allErrs, field.Invalid(field.NewPath(path), in.Spec.CIDR, errMsg))
}
}
if in.Spec.Consumer != nil {
if _, err := schema.ParseGroupVersion(in.Spec.Consumer.APIVersion); err != nil {
allErrs = append(allErrs, field.Invalid(field.NewPath("spec.consumer.apiVersion"), in.Spec.Consumer, err.Error()))
}
}
if in.Spec.ParentSubnet.Name == "" &&
in.Spec.CIDR == nil {
allErrs = append(allErrs, field.Invalid(field.NewPath("spec.cidr"), in.Spec.CIDR, "cidr should be set explicitly if a top level subnet (without parent subnet) is created"))
}
if in.Spec.Capacity != nil && maxQuantity.Cmp(*in.Spec.Capacity) < 0 &&
minQuantity.Cmp(*in.Spec.Capacity) > 0 {
allErrs = append(allErrs, field.Invalid(field.NewPath("spec.capacity"), in.Spec.CIDR, "if set, capacity value should be between 1 and 2^128"))
}
if !in.uniqueRegionSet() {
allErrs = append(allErrs, field.Invalid(field.NewPath("spec.regions"), in.Spec.Regions, "region values should be unique"))
}
for i, region := range in.Spec.Regions {
if !in.uniqueAZSet(region.AvailabilityZones) {
allErrs = append(allErrs, field.Invalid(field.NewPath(fmt.Sprintf("spec.regions[%d].availabilityZones", i)), region.AvailabilityZones, "availability zone values should be unique"))
}
}
if len(allErrs) > 0 {
gvk := in.GroupVersionKind()
gk := schema.GroupKind{
Group: gvk.Group,
Kind: gvk.Kind,
}
return warnings, apierrors.NewInvalid(gk, in.Name, allErrs)
}
return warnings, nil
}
// ValidateUpdate implements webhook.Validator so a webhook will be registered for the type
func (in *Subnet) ValidateUpdate(old runtime.Object) (admission.Warnings, error) {
subnetlog.Info("validate update", "name", in.Name)
var warnings admission.Warnings
oldSubnet, ok := old.(*Subnet)
if !ok {
return warnings, errors.New("cannot cast previous object version to Subnet CR type")
}
var allErrs field.ErrorList
if !(oldSubnet.Spec.CIDR == nil && in.Spec.CIDR == nil) {
if oldSubnet.Spec.CIDR == nil || in.Spec.CIDR == nil ||
!oldSubnet.Spec.CIDR.Equal(in.Spec.CIDR) {
allErrs = append(allErrs,
field.Invalid(
field.NewPath("spec.cidr"), in.Spec.CIDR, "CIDR change is disallowed"))
}
}
if !(oldSubnet.Spec.PrefixBits == nil && in.Spec.PrefixBits == nil) {
if oldSubnet.Spec.PrefixBits == nil || in.Spec.PrefixBits == nil ||
*oldSubnet.Spec.PrefixBits != *in.Spec.PrefixBits {
allErrs = append(allErrs, field.Invalid(field.NewPath("spec.hostIdentifierBits"), in.Spec.PrefixBits, "Host identifier bits change is disallowed"))
}
}
if !(oldSubnet.Spec.Capacity == nil && in.Spec.Capacity == nil) {
if oldSubnet.Spec.Capacity == nil || in.Spec.Capacity == nil ||
!oldSubnet.Spec.Capacity.Equal(*in.Spec.Capacity) {
allErrs = append(allErrs, field.Invalid(field.NewPath("spec.capacity"), in.Spec.Capacity, "Capacity change is disallowed"))
}
}
if oldSubnet.Spec.ParentSubnet.Name != in.Spec.ParentSubnet.Name {
allErrs = append(allErrs, field.Invalid(field.NewPath("spec.parentSubnet.name"), in.Spec.CIDR, "Parent Subnet change is disallowed"))
}
if oldSubnet.Spec.Network.Name != in.Spec.Network.Name {
allErrs = append(allErrs, field.Invalid(field.NewPath("spec.network.name"), in.Spec.CIDR, "Network change is disallowed"))
}
if !reflect.DeepEqual(oldSubnet.Spec.Regions, in.Spec.Regions) {
allErrs = append(allErrs, field.Invalid(field.NewPath("spec.regions"), in.Spec.CIDR, "Regions change is disallowed"))
}
if len(allErrs) > 0 {
return warnings, apierrors.NewInvalid(
schema.GroupKind{
Group: SchemeGroupVersion.Group,
Kind: "Subnet",
}, in.Name, allErrs)
}
return warnings, nil
}
// ValidateDelete implements webhook.Validator so a webhook will be registered for the type
func (in *Subnet) ValidateDelete() (admission.Warnings, error) {
subnetlog.Info("validate delete", "name", in.Name)
var allErrs field.ErrorList
var warnings admission.Warnings
if in.Spec.Consumer != nil {
unstruct := &unstructured.Unstructured{}
gv, err := schema.ParseGroupVersion(in.Spec.Consumer.APIVersion)
if err != nil {
message := fmt.Sprintf(
"unable to parse APIVersion of consumer resource, therefore allowing to delete Subnet."+
" name: %s, api version: %s", in.Name, in.Spec.Consumer.APIVersion)
subnetlog.Error(
err, message)
return append(warnings, message), nil
}
gvk := gv.WithKind(in.Spec.Consumer.Kind)
unstruct.SetGroupVersionKind(gvk)
namespacedName := types.NamespacedName{
Namespace: in.Namespace,
Name: in.Spec.Consumer.Name,
}
ctx := context.Background()
err = subnetWebhookClient.Get(ctx, namespacedName, unstruct)
if !apierrors.IsNotFound(err) {
consumerUnstruct := unstruct.Object
deletionTimestamp, _, err := unstructured.NestedString(consumerUnstruct, "metadata", "deletionTimestamp")
switch {
case err != nil:
allErrs = append(allErrs, field.Invalid(field.NewPath("spec.consumer"), in.Spec.Consumer, err.Error()))
case deletionTimestamp == "":
allErrs = append(allErrs, field.Invalid(field.NewPath("spec.consumer"), in.Spec.Consumer, "Consumer is not deleted"))
}
}
}
childSubnetsMatchingFields := client.MatchingFields{
CFinishedChildSubnetToSubnetIndexKey: in.Name,
}
subnets := &SubnetList{}
if err := subnetWebhookClient.List(context.Background(), subnets, client.InNamespace(in.Namespace), childSubnetsMatchingFields, client.Limit(1)); err != nil {
wrappedErr := errors.Wrap(err, "unable to get connected child subnets")
subnetlog.Error(wrappedErr,
"", "name", types.NamespacedName{Namespace: in.Namespace, Name: in.Name})
return append(warnings, wrappedErr.Error()), wrappedErr
}
if len(subnets.Items) > 0 {
allErrs = append(allErrs, field.InternalError(
field.NewPath("metadata.name"),
errors.New("Subnet is still in use by another subnets")))
}
childIPsMatchingFields := client.MatchingFields{
CFinishedChildIPToSubnetIndexKey: in.Name,
}
ips := &IPList{}
if err := subnetWebhookClient.List(context.Background(), ips, client.InNamespace(in.Namespace), childIPsMatchingFields, client.Limit(1)); err != nil {
wrappedErr := errors.Wrap(err, "unable to get connected child ips")
subnetlog.Error(wrappedErr, "", "name", types.NamespacedName{Namespace: in.Namespace, Name: in.Name})
return append(warnings, wrappedErr.Error()), wrappedErr
}
if len(ips.Items) > 0 {
allErrs = append(allErrs, field.InternalError(field.NewPath("metadata.name"), errors.New("Subnet is still in use by IPs")))
}
if len(allErrs) > 0 {
return warnings, apierrors.NewInvalid(
schema.GroupKind{
Group: SchemeGroupVersion.Group,
Kind: "Subnet",
}, in.Name, allErrs)
}
return warnings, nil
}
func (in *Subnet) countCIDRReservationRules() int {
count := 0
if in.Spec.CIDR != nil {
count += 1
}
if in.Spec.Capacity != nil {
count += 1
}
if in.Spec.PrefixBits != nil {
count += 1
}
return count
}
func (in *Subnet) uniqueRegionSet() bool {
regionset := make(StringSet)
for _, item := range in.Spec.Regions {
if err := regionset.Put(item.Name); err != nil {
return false
}
}
return true
}
func (in *Subnet) uniqueAZSet(azs []string) bool {
azset := make(StringSet)
for _, item := range azs {
if err := azset.Put(item); err != nil {
return false
}
}
return true
}
type StringSet map[string]struct{}
func (s StringSet) Put(item string) error {
_, ok := s[item]
if ok {
return errors.Errorf("set already has value %s", item)
}
s[item] = struct{}{}
return nil
}