-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathattractor_webhook.go
260 lines (226 loc) · 9.89 KB
/
attractor_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
/*
Copyright (c) 2021-2022 Nordix Foundation
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 v1
import (
"context"
"fmt"
"strings"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"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"
)
// log is for logging in this package.
var attractorlog = logf.Log.WithName("attractor-resource")
func (r *Attractor) SetupWebhookWithManager(mgr ctrl.Manager) error {
attractorClient = mgr.GetClient()
return ctrl.NewWebhookManagedBy(mgr).
For(r).
Complete()
}
var attractorClient client.Client
//+kubebuilder:webhook:path=/validate-meridio-nordix-org-v1-attractor,mutating=false,failurePolicy=fail,sideEffects=None,groups=meridio.nordix.org,resources=attractors,verbs=create;update,versions=v1,name=vattractor.kb.io,admissionReviewVersions=v1
var _ webhook.Validator = &Attractor{}
// ValidateCreate implements webhook.Validator so a webhook will be registered for the type
func (r *Attractor) ValidateCreate() error {
attractorlog.Info("validate create", "name", r.Name)
// Get the trench by the label in attractor
selector := client.ObjectKey{
Namespace: r.ObjectMeta.Namespace,
Name: r.ObjectMeta.Labels["trench"],
}
trench := &Trench{}
err := attractorClient.Get(context.TODO(), selector, trench)
if err != nil || trench == nil {
return fmt.Errorf("unable to find the trench in label, %s cannot be created", r.GroupVersionKind().Kind)
}
if r.Spec.Replicas == nil {
r.Spec.Replicas = new(int32)
*r.Spec.Replicas = 1
}
return r.validateAttractor()
}
// ValidateUpdate implements webhook.Validator so a webhook will be registered for the type
func (r *Attractor) ValidateUpdate(old runtime.Object) error {
attractorlog.Info("validate update", "name", r.Name)
err := r.validateUpdate(old)
if err != nil {
return err
}
return r.validateAttractor()
}
// ValidateDelete implements webhook.Validator so a webhook will be registered for the type
func (r *Attractor) ValidateDelete() error {
attractorlog.Info("validate delete", "name", r.Name)
return nil
}
func (r *Attractor) validateAttractor() error {
var allErrs field.ErrorList
if err := r.validateLabels(); err != nil {
allErrs = append(allErrs, field.Invalid(field.NewPath("metadata").Child("labels"), r.ObjectMeta.Labels, err.Error()))
}
switch r.Spec.Interface.Type {
case NSMVlan:
err := validatePrefixAndRange(r.Spec.Interface.PrefixIPv4)
if err != nil {
allErrs = append(allErrs, field.Invalid(field.NewPath("spec").Child("ipv4-prefix"), r.Spec.Interface.PrefixIPv4, err.Error()))
}
err = validatePrefixAndRange(r.Spec.Interface.PrefixIPv6)
if err != nil {
allErrs = append(allErrs, field.Invalid(field.NewPath("spec").Child("ipv6-prefix"), r.Spec.Interface.PrefixIPv6, err.Error()))
}
if r.Spec.Interface.NSMVlan.BaseInterface == "" || r.Spec.Interface.NSMVlan.VlanID == nil {
allErrs = append(allErrs, field.Invalid(field.NewPath("spec").Child("interface").Child("nsm-vlan"),
r.Spec.Interface.NSMVlan, "missing mandatory parameter base-interface/vlan-id"))
}
case NAD:
if r.Spec.Interface.PrefixIPv4 != "" {
allErrs = append(allErrs, field.Forbidden(field.NewPath("spec").Child("ipv4-prefix"), "not supported for type"))
}
if r.Spec.Interface.PrefixIPv6 != "" {
allErrs = append(allErrs, field.Forbidden(field.NewPath("spec").Child("ipv6-prefix"), "not supported for type"))
}
if len(r.Spec.Interface.NetworkAttachments) != 1 {
allErrs = append(allErrs, field.Invalid(field.NewPath("spec").Child("interface").Child("multus-interface"),
r.Spec.Interface.NetworkAttachments, "single Network Attachment item required"))
}
for _, na := range r.Spec.Interface.NetworkAttachments {
if na.Name == "" {
allErrs = append(allErrs, field.Required(field.NewPath("spec").Child("interface").Child("network-attachments").Child("name"),
"missing mandatory Network Attachment parameter name"))
}
if na.Namespace == "" {
allErrs = append(allErrs, field.Required(field.NewPath("spec").Child("interface").Child("network-attachments").Child("namespace"),
"missing mandatory Network Attachment parameter namespace"))
}
}
default:
allErrs = append(allErrs, field.Invalid(field.NewPath("spec").Child("interface").Child("type"), r.Spec.Interface.Type, "not a supported interface"))
}
if len(r.Spec.Composites) > 1 {
allErrs = append(allErrs, field.Invalid(field.NewPath("spec").Child("composites"), r.Spec.Composites, "only one composite per attractor is supported in the current version"))
}
al := &AttractorList{}
sel := labels.Set{"trench": r.ObjectMeta.Labels["trench"]}
err := attractorClient.List(context.TODO(), al, &client.ListOptions{
LabelSelector: sel.AsSelector(),
Namespace: r.ObjectMeta.Namespace,
})
if err != nil {
allErrs = append(allErrs, field.Invalid(field.NewPath("spec").Child("composites"), r.Spec.Composites, "unable to get attractors"))
} else {
vips := map[string]struct{}{}
composites := map[string]struct{}{}
for _, vip := range r.Spec.Vips {
vips[vip] = struct{}{}
}
for _, composite := range r.Spec.Composites {
composites[composite] = struct{}{}
}
for _, attractor := range al.Items {
for _, vip := range attractor.Spec.Vips {
if attractor.ObjectMeta.Name == r.ObjectMeta.Name && attractor.ObjectMeta.Namespace == r.ObjectMeta.Namespace {
continue
}
_, exists := vips[vip]
if exists {
allErrs = append(allErrs, field.Invalid(field.NewPath("spec").Child("vips"), r.Spec.Vips, "a vip cannot be shared between 2 attractors in this version"))
}
}
for _, composite := range attractor.Spec.Composites {
if attractor.ObjectMeta.Name == r.ObjectMeta.Name && attractor.ObjectMeta.Namespace == r.ObjectMeta.Namespace {
continue
}
_, exists := composites[composite]
if exists {
allErrs = append(allErrs, field.Invalid(field.NewPath("spec").Child("composites"), r.Spec.Composites, "a conduit cannot be shared between 2 attractors in this version"))
}
}
}
}
if len(allErrs) == 0 {
return nil
}
return apierrors.NewInvalid(
schema.GroupKind{Group: r.GroupVersionKind().Group, Kind: r.GroupVersionKind().Kind},
r.Name, allErrs)
}
func (r *Attractor) validateLabels() error {
if _, ok := r.ObjectMeta.Labels["trench"]; !ok {
return fmt.Errorf("%s must have a trench label", r.GroupVersionKind().Kind)
}
return nil
}
func (r *Attractor) validateUpdate(old runtime.Object) error {
attrOld, ok := old.(*Attractor)
if !ok {
return apierrors.NewBadRequest(fmt.Sprintf("expected a %s got a %T", r.GroupVersionKind().Kind, attrOld))
}
trenchNew := r.ObjectMeta.Labels["trench"]
trenchOld := attrOld.ObjectMeta.Labels["trench"]
if trenchNew != trenchOld {
return apierrors.NewForbidden(r.GroupResource(),
r.Name, field.Forbidden(field.NewPath("metadata", "labels", "trench"), "update on attractor label trench is forbidden"))
}
if r.Spec.Interface.Type != strings.ToLower(attrOld.Spec.Interface.Type) {
return apierrors.NewForbidden(r.GroupResource(),
r.Name, field.Forbidden(field.NewPath("spec", "interface", "type"), "update on interface type is forbidden"))
}
switch r.Spec.Interface.Type {
case NSMVlan:
if *(r.Spec.Interface.NSMVlan.VlanID) != *(attrOld.Spec.Interface.NSMVlan.VlanID) {
return apierrors.NewForbidden(r.GroupResource(),
r.Name, field.Forbidden(field.NewPath("spec", "interface", "nsm-vlan", "vlan-id"), "update on vlan id is forbidden"))
}
if r.Spec.Interface.NSMVlan.BaseInterface != attrOld.Spec.Interface.NSMVlan.BaseInterface {
return apierrors.NewForbidden(r.GroupResource(),
r.Name, field.Forbidden(field.NewPath("spec", "interface", "nsm-vlan", "base-interface"), "update on base interface is forbidden"))
}
case NAD:
nadsOld := attrOld.Spec.Interface.NetworkAttachments
nadsNew := r.Spec.Interface.NetworkAttachments
if len(nadsNew) != len(nadsOld) {
return apierrors.NewForbidden(r.GroupResource(),
r.Name, field.Forbidden(field.NewPath("spec", "interface", "network-attachments"), "update on network-attachments items forbidden"))
}
for idx, nadNew := range nadsNew {
// order matters
if nadNew.Namespace != nadsOld[idx].Namespace {
return apierrors.NewForbidden(r.GroupResource(),
r.Name, field.Forbidden(field.NewPath("spec", "interface", "network-attachments", "namespace"), "update on namespace forbidden"))
}
if nadNew.Name != nadsOld[idx].Name {
return apierrors.NewForbidden(r.GroupResource(),
r.Name, field.Forbidden(field.NewPath("spec", "interface", "network-attachments", "name"), "update on name forbidden"))
}
if nadNew.InterfaceRequest != nadsOld[idx].InterfaceRequest {
return apierrors.NewForbidden(r.GroupResource(),
r.Name, field.Forbidden(field.NewPath("spec", "interface", "network-attachments", "interface"), "update on interface forbidden"))
}
}
}
if r.Spec.Interface.PrefixIPv4 != attrOld.Spec.Interface.PrefixIPv4 {
return apierrors.NewForbidden(r.GroupResource(),
r.Name, field.Forbidden(field.NewPath("spec", "ipv4-prefix"), "update on prefix is forbidden"))
}
if r.Spec.Interface.PrefixIPv6 != attrOld.Spec.Interface.PrefixIPv6 {
return apierrors.NewForbidden(r.GroupResource(),
r.Name, field.Forbidden(field.NewPath("spec", "ipv6-prefix"), "update on prefix is forbidden"))
}
return nil
}