-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopenstackbaremetalset_webhook.go
More file actions
205 lines (174 loc) · 6.99 KB
/
Copy pathopenstackbaremetalset_webhook.go
File metadata and controls
205 lines (174 loc) · 6.99 KB
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
/*
Copyright 2023.
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.
*/
// Generated by:
//
// operator-sdk create webhook --group baremetal --version v1beta1 --kind OpenStackBaremetalSet --programmatic-validation
//
package v1beta1
import (
"context"
"fmt"
"github.com/go-playground/validator/v10"
metal3v1 "github.com/metal3-io/baremetal-operator/apis/metal3.io/v1alpha1"
"github.com/openstack-k8s-operators/lib-common/modules/common/labels"
"k8s.io/apimachinery/pkg/api/equality"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/validation/field"
goClient "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"
)
// Client needed for API calls (manager's client, set by first SetupWebhookWithManager() call
// to any particular webhook)
var webhookClient goClient.Client
// SetupWebhookClient sets the webhook client for API webhook functions.
// This allows internal webhooks to initialize the client before calling validation/default functions.
func SetupWebhookClient(client goClient.Client) {
webhookClient = client
}
// log is for logging in this package.
var openstackbaremetalsetlog = logf.Log.WithName("openstackbaremetalset-resource")
var _ webhook.Validator = &OpenStackBaremetalSet{}
// ValidateCreate implements webhook.Validator so a webhook will be registered for the type
func (r *OpenStackBaremetalSet) ValidateCreate() (admission.Warnings, error) {
openstackbaremetalsetlog.Info("validate create", "name", r.Name)
var errors field.ErrorList
// Check if OpenStackBaremetalSet name matches RFC1123 for use in labels
validate := validator.New()
if err := validate.Var(r.Name, "hostname_rfc1123"); err != nil {
openstackbaremetalsetlog.Error(err, "Error validating OpenStackBaremetalSet name, name must follow RFC1123")
errors = append(errors, field.Invalid(
field.NewPath("Name"),
r.Name,
fmt.Sprintf("Error validating OpenStackBaremetalSet name %s, name must follow RFC1123", r.Name)))
return nil, apierrors.NewInvalid(
schema.GroupKind{Group: "baremetal.openstack.org", Kind: "OpenStackBaremetalSet"},
r.Name,
errors)
}
// Validate userData and networkData secrets namespace
err := r.ValidateCloudInitSecrets()
if err != nil {
return nil, err
}
//
// Validate that there are enough available BMHs for the initial requested count
//
baremetalHostsList, err := GetBaremetalHosts(
context.TODO(),
webhookClient,
r.Spec.BmhNamespace,
r.Spec.BmhLabelSelector,
)
if err != nil {
return nil, err
}
if _, err := VerifyBaremetalSetScaleUp(openstackbaremetalsetlog, r, baremetalHostsList, &metal3v1.BareMetalHostList{}); err != nil {
return nil, err
}
return nil, nil
}
// ValidateCloudInitSecrets checks if userData and networkData secrets are in the same namespace as bmh
func (r *OpenStackBaremetalSet) ValidateCloudInitSecrets() error {
var secretsWithIssue []string
for _, host := range r.Spec.BaremetalHosts {
if host.NetworkData != nil && host.NetworkData.Namespace != r.Spec.BmhNamespace {
secretsWithIssue = append(secretsWithIssue, host.NetworkData.Name)
}
if host.UserData != nil && host.UserData.Namespace != r.Spec.BmhNamespace {
secretsWithIssue = append(secretsWithIssue, host.UserData.Name)
}
}
if len(secretsWithIssue) > 0 {
return fmt.Errorf("userData and networkData secrets %v should exist in the bmh namespace %s",
secretsWithIssue, r.Spec.BmhNamespace)
}
return nil
}
// Validate implements OpenStackBaremetalSetTemplateSpec validation
func (spec OpenStackBaremetalSetTemplateSpec) ValidateTemplate(oldCount int, oldSpec OpenStackBaremetalSetTemplateSpec) error {
if oldCount > 0 &&
(!equality.Semantic.DeepEqual(spec.BmhLabelSelector, oldSpec.BmhLabelSelector) ||
!equality.Semantic.DeepEqual(spec.HardwareReqs, oldSpec.HardwareReqs)) {
return fmt.Errorf("cannot change \"bmhLabelSelector\" nor \"hardwareReqs\" when previous count of \"baremetalHosts\" > 0")
}
return nil
}
// ValidateUpdate implements webhook.Validator so a webhook will be registered for the type
func (r *OpenStackBaremetalSet) ValidateUpdate(old runtime.Object) (admission.Warnings, error) {
openstackbaremetalsetlog.Info("validate update", "name", r.Name)
var ok bool
var oldInstance *OpenStackBaremetalSet
if oldInstance, ok = old.(*OpenStackBaremetalSet); !ok {
return nil, fmt.Errorf("runtime object is not an OpenStackBaremetalSet")
}
if err := r.Spec.ValidateTemplate(len(oldInstance.Spec.BaremetalHosts),
oldInstance.Spec.OpenStackBaremetalSetTemplateSpec); err != nil {
return nil, err
}
//
// Force BmhLabelSelector and HardwareReqs to remain the same unless the *old* count of spec.BaremetalHosts was 0.
// We do this to maintain consistency across the gathered list of BMHs during reconcile.
//
oldCount := len(oldInstance.Spec.BaremetalHosts)
newCount := len(r.Spec.BaremetalHosts)
if newCount != oldCount {
//
// Don't allow count changes if instance.Status.BaremetalHosts contains any
// bmhRefs that are missing from Metal3 BMHs. We need to force the user to
// restore the old BMHs before allowing the OSBMS controller to perform any
// operations for scaling up or down.
//
// TODO: Create a specific context here instead of passing TODO()?
if err := VerifyAndSyncBaremetalStatusBmhRefs(context.TODO(), webhookClient, r); err != nil {
return nil, err
}
//
// Validate that there are enough available BMHs for a potential scale-up
//
if newCount > oldCount {
// Every BMH available that matches our (optional) labels
baremetalHostsList, err := GetBaremetalHosts(
context.TODO(),
webhookClient,
r.Spec.BmhNamespace,
r.Spec.BmhLabelSelector,
)
if err != nil {
return nil, err
}
// All BMHs were are *already* using
existingBaremetalHosts, err := GetBaremetalHosts(
context.TODO(),
webhookClient,
r.Spec.BmhNamespace,
labels.GetLabels(r, labels.GetGroupLabel(ServiceName), map[string]string{}),
)
if err != nil {
return nil, err
}
if _, err := VerifyBaremetalSetScaleUp(openstackbaremetalsetlog, r, baremetalHostsList, existingBaremetalHosts); err != nil {
return nil, err
}
}
}
return nil, nil
}
// ValidateDelete implements webhook.Validator so a webhook will be registered for the type
func (r *OpenStackBaremetalSet) ValidateDelete() (admission.Warnings, error) {
openstackbaremetalsetlog.Info("validate delete", "name", r.Name)
return nil, nil
}