-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathstorage_webhook.go
368 lines (299 loc) · 10.8 KB
/
storage_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
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
package v1alpha1
import (
"context"
"fmt"
"math/rand"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"gopkg.in/yaml.v3"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/utils/strings/slices"
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"
"github.com/ydb-platform/ydb-kubernetes-operator/internal/configuration/schema"
. "github.com/ydb-platform/ydb-kubernetes-operator/internal/controllers/constants" //nolint:revive,stylecheck
)
// log is for logging in this package.
var storagelog = logf.Log.WithName("storage-resource")
func (r *Storage) SetupWebhookWithManager(mgr ctrl.Manager) error {
return ctrl.NewWebhookManagedBy(mgr).
For(r).
WithDefaulter(&StorageDefaulter{Client: mgr.GetClient()}).
Complete()
}
func (r *Storage) GetStorageEndpointWithProto() string {
return fmt.Sprintf("%s%s", r.GetStorageProto(), r.GetStorageEndpoint())
}
func (r *Storage) GetStorageProto() string {
proto := GRPCProto
if r.IsStorageEndpointSecure() {
proto = GRPCSProto
}
return proto
}
func (r *Storage) GetStorageEndpoint() string {
endpoint := r.GetGRPCServiceEndpoint()
if r.IsRemoteNodeSetsOnly() {
endpoint = r.GetHostFromConfigEndpoint()
}
return endpoint
}
func (r *Storage) GetGRPCServiceEndpoint() string {
host := fmt.Sprintf(GRPCServiceFQDNFormat, r.Name, r.Namespace)
if r.Spec.Service.GRPC.ExternalHost != "" {
host = r.Spec.Service.GRPC.ExternalHost
}
return fmt.Sprintf("%s:%d", host, GRPCPort)
}
// +k8s:deepcopy-gen=false
type PartialHostsConfig struct {
Hosts []schema.Host `yaml:"hosts,flow"`
}
func (r *Storage) GetHostFromConfigEndpoint() string {
// skip handle error because we already checked in webhook
hostsConfig := PartialHostsConfig{}
_ = yaml.Unmarshal([]byte(r.Spec.Configuration), &hostsConfig)
randNum := rand.Int31n(r.Spec.Nodes) // #nosec G404
host := hostsConfig.Hosts[randNum].Host
return fmt.Sprintf("%s:%d", host, GRPCPort)
}
func (r *Storage) IsStorageEndpointSecure() bool {
if r.Spec.Service.GRPC.TLSConfiguration != nil {
return r.Spec.Service.GRPC.TLSConfiguration.Enabled
}
return false
}
func (r *Storage) IsRemoteNodeSetsOnly() bool {
if len(r.Spec.NodeSets) == 0 {
return false
}
for _, nodeSet := range r.Spec.NodeSets {
if nodeSet.Remote == nil {
return false
}
}
return true
}
// +k8s:deepcopy-gen=false
type PartialDomainsConfig struct {
DomainsConfig struct {
SecurityConfig struct {
EnforceUserTokenRequirement bool `yaml:"enforce_user_token_requirement"`
} `yaml:"security_config"`
} `yaml:"domains_config"`
}
// StorageDefaulter mutates Storages
// +k8s:deepcopy-gen=false
type StorageDefaulter struct {
Client client.Client
}
//+kubebuilder:webhook:path=/mutate-ydb-tech-v1alpha1-storage,mutating=true,failurePolicy=fail,sideEffects=None,groups=ydb.tech,resources=storages,verbs=create;update,versions=v1alpha1,name=mutate-storage.ydb.tech,admissionReviewVersions=v1
// Default implements webhook.Defaulter so a webhook will be registered for the type
func (r *StorageDefaulter) Default(ctx context.Context, obj runtime.Object) error {
storage := obj.(*Storage)
storagelog.Info("default", "name", storage.Name)
if storage.Spec.Image == nil {
storage.Spec.Image = &PodImage{}
}
if storage.Spec.Image.Name == "" {
if storage.Spec.YDBVersion == "" {
storage.Spec.Image.Name = fmt.Sprintf(ImagePathFormat, RegistryPath, DefaultTag)
} else {
storage.Spec.Image.Name = fmt.Sprintf(ImagePathFormat, RegistryPath, storage.Spec.YDBVersion)
}
}
if storage.Spec.Image.PullPolicyName == nil {
policy := corev1.PullIfNotPresent
storage.Spec.Image.PullPolicyName = &policy
}
if storage.Spec.Resources == nil {
storage.Spec.Resources = &corev1.ResourceRequirements{}
}
if storage.Spec.Service == nil {
storage.Spec.Service = &StorageServices{
GRPC: GRPCService{},
Interconnect: InterconnectService{},
Status: StatusService{},
}
}
if storage.Spec.Service.GRPC.TLSConfiguration == nil {
storage.Spec.Service.GRPC.TLSConfiguration = &TLSConfiguration{Enabled: false}
}
if storage.Spec.Service.Interconnect.TLSConfiguration == nil {
storage.Spec.Service.Interconnect.TLSConfiguration = &TLSConfiguration{Enabled: false}
}
if storage.Spec.Monitoring == nil {
storage.Spec.Monitoring = &MonitoringOptions{
Enabled: false,
}
}
if storage.Spec.Domain == "" {
storage.Spec.Domain = DefaultDatabaseDomain
}
configuration, err := BuildConfiguration(storage, nil)
if err != nil {
return err
}
storage.Spec.Configuration = configuration
return nil
}
//+kubebuilder:webhook:path=/validate-ydb-tech-v1alpha1-storage,mutating=true,failurePolicy=fail,sideEffects=None,groups=ydb.tech,resources=storages,verbs=create;update,versions=v1alpha1,name=validate-storage.ydb.tech,admissionReviewVersions=v1
var _ webhook.Validator = &Storage{}
// ValidateCreate implements webhook.Validator so a webhook will be registered for the type
func (r *Storage) ValidateCreate() error {
storagelog.Info("validate create", "name", r.Name)
configuration := make(map[string]interface{})
err := yaml.Unmarshal([]byte(r.Spec.Configuration), &configuration)
if err != nil {
return fmt.Errorf("failed to parse .spec.configuration, error: %w", err)
}
hostsConfig := PartialHostsConfig{}
err = yaml.Unmarshal([]byte(r.Spec.Configuration), &hostsConfig)
if err != nil {
return fmt.Errorf("failed to parse YAML to determine `hosts`, error: %w", err)
}
var nodesNumber int32
if len(hostsConfig.Hosts) == 0 {
nodesNumber = r.Spec.Nodes
} else {
nodesNumber = int32(len(hostsConfig.Hosts))
}
minNodesPerErasure := map[ErasureType]int32{
ErasureMirror3DC: 9,
ErasureBlock42: 8,
None: 1,
}
if nodesNumber < minNodesPerErasure[r.Spec.Erasure] {
return fmt.Errorf("erasure type %v requires at least %v storage nodes", r.Spec.Erasure, minNodesPerErasure[r.Spec.Erasure])
}
yamlConfig := PartialDomainsConfig{}
err = yaml.Unmarshal([]byte(r.Spec.Configuration), &yamlConfig)
if err != nil {
return fmt.Errorf("failed to parse YAML to determine `enforce_user_token_requirement`, error: %w", err)
}
var authEnabled bool
if yamlConfig.DomainsConfig.SecurityConfig.EnforceUserTokenRequirement {
authEnabled = true
}
if (authEnabled && r.Spec.OperatorConnection == nil) || (!authEnabled && r.Spec.OperatorConnection != nil) {
return fmt.Errorf("field 'spec.operatorConnection' does not satisfy with config option `enforce_user_token_requirement: %t`", authEnabled)
}
if r.Spec.NodeSets != nil {
var nodesInSetsCount int32
for _, nodeSetInline := range r.Spec.NodeSets {
nodesInSetsCount += nodeSetInline.Nodes
}
if nodesInSetsCount != r.Spec.Nodes {
return fmt.Errorf("incorrect value nodes: %d, does not satisfy with nodeSets: %d ", r.Spec.Nodes, nodesInSetsCount)
}
}
reservedSecretNames := []string{
"database_encryption",
"datastreams",
}
for _, secret := range r.Spec.Secrets {
if slices.Contains(reservedSecretNames, secret.Name) {
return fmt.Errorf("the secret name %s is reserved, use another one", secret.Name)
}
}
if r.Spec.Volumes != nil {
for _, volume := range r.Spec.Volumes {
if volume.HostPath == nil {
return fmt.Errorf("unsupported volume source, %v. Only hostPath is supported ", volume.VolumeSource)
}
}
}
crdCheckError := checkMonitoringCRD(manager, storagelog, r.Spec.Monitoring != nil)
if crdCheckError != nil {
return crdCheckError
}
return nil
}
func hasUpdatesBesidesFrozen(oldStorage, newStorage *Storage) (bool, string) {
oldStorageCopy := oldStorage.DeepCopy()
newStorageCopy := newStorage.DeepCopy()
// If we set Frozen field to the same value,
// the remaining diff must be empty.
oldStorageCopy.Spec.OperatorSync = false
newStorageCopy.Spec.OperatorSync = false
ignoreNonSpecFields := cmpopts.IgnoreFields(Storage{}, "Status", "ObjectMeta", "TypeMeta")
diff := cmp.Diff(oldStorageCopy, newStorageCopy, ignoreNonSpecFields)
return diff != "", diff
}
// ValidateUpdate implements webhook.Validator so a webhook will be registered for the type
func (r *Storage) ValidateUpdate(old runtime.Object) error {
storagelog.Info("validate update", "name", r.Name)
configuration := make(map[string]interface{})
err := yaml.Unmarshal([]byte(r.Spec.Configuration), &configuration)
if err != nil {
return fmt.Errorf("failed to parse .spec.configuration, error: %w", err)
}
hostsConfig := PartialHostsConfig{}
err = yaml.Unmarshal([]byte(r.Spec.Configuration), &hostsConfig)
if err != nil {
return fmt.Errorf("failed to parse YAML to determine `hosts`, error: %w", err)
}
var nodesNumber int32
if len(hostsConfig.Hosts) == 0 {
nodesNumber = r.Spec.Nodes
} else {
nodesNumber = int32(len(hostsConfig.Hosts))
}
minNodesPerErasure := map[ErasureType]int32{
ErasureMirror3DC: 9,
ErasureBlock42: 8,
None: 1,
}
if nodesNumber < minNodesPerErasure[r.Spec.Erasure] {
return fmt.Errorf("erasure type %v requires at least %v storage nodes", r.Spec.Erasure, minNodesPerErasure[r.Spec.Erasure])
}
if !r.Spec.OperatorSync {
oldStorage := old.(*Storage)
hasIllegalUpdates, diff := hasUpdatesBesidesFrozen(old.(*Storage), r)
if hasIllegalUpdates {
if oldStorage.Spec.OperatorSync {
return fmt.Errorf(
"it is illegal to update spec.OperatorSync and any other "+
"spec fields at the same time. Here is what you else tried to update: %s", diff)
}
return fmt.Errorf(
"it is illegal to update any spec fields when spec.OperatorSync is false. "+
"Here is what you else tried to update: %s", diff)
}
}
yamlConfig := PartialDomainsConfig{}
err = yaml.Unmarshal([]byte(r.Spec.Configuration), &yamlConfig)
if err != nil {
return fmt.Errorf("failed to parse YAML to determine `enforce_user_token_requirement`, error: %w", err)
}
var authEnabled bool
if yamlConfig.DomainsConfig.SecurityConfig.EnforceUserTokenRequirement {
authEnabled = true
}
if (authEnabled && r.Spec.OperatorConnection == nil) || (!authEnabled && r.Spec.OperatorConnection != nil) {
return fmt.Errorf("field 'spec.operatorConnection' does not align with config option `enforce_user_token_requirement: %t`", authEnabled)
}
if r.Spec.NodeSets != nil {
var nodesInSetsCount int32
for _, nodeSetInline := range r.Spec.NodeSets {
nodesInSetsCount += nodeSetInline.Nodes
}
if nodesInSetsCount != r.Spec.Nodes {
return fmt.Errorf("incorrect value nodes: %d, does not satisfy with nodeSets: %d ", r.Spec.Nodes, nodesInSetsCount)
}
}
crdCheckError := checkMonitoringCRD(manager, storagelog, r.Spec.Monitoring != nil)
if crdCheckError != nil {
return crdCheckError
}
return nil
}
func (r *Storage) ValidateDelete() error {
if r.Status.State != StoragePaused {
return fmt.Errorf("storage deletion is only possible from `Paused` state, current state %v", r.Status.State)
}
return nil
}