/
aerospikecluster_validating_webhook.go
2275 lines (1873 loc) · 61.1 KB
/
aerospikecluster_validating_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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2024.
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 (
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"os"
"path/filepath"
"reflect"
"regexp"
"strings"
validate "github.com/asaskevich/govalidator"
"github.com/go-logr/logr"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/utils/ptr"
logf "sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/webhook"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
internalerrors "github.com/aerospike/aerospike-kubernetes-operator/errors"
lib "github.com/aerospike/aerospike-management-lib"
"github.com/aerospike/aerospike-management-lib/asconfig"
)
var networkConnectionTypes = []string{"service", "heartbeat", "fabric"}
var versionRegex = regexp.MustCompile(`(\d+(\.\d+)+)`)
//nolint:lll // for readability
// +kubebuilder:webhook:path=/validate-asdb-aerospike-com-v1-aerospikecluster,mutating=false,failurePolicy=fail,sideEffects=None,groups=asdb.aerospike.com,resources=aerospikeclusters,verbs=create;update,versions=v1,name=vaerospikecluster.kb.io,admissionReviewVersions={v1}
var _ webhook.Validator = &AerospikeCluster{}
// ValidateCreate implements webhook.Validator so a webhook will be registered for the type
func (c *AerospikeCluster) ValidateCreate() (admission.Warnings, error) {
aslog := logf.Log.WithName(ClusterNamespacedName(c))
aslog.Info("Validate create")
return nil, c.validate(aslog)
}
// ValidateDelete implements webhook.Validator so a webhook will be registered for the type
func (c *AerospikeCluster) ValidateDelete() (admission.Warnings, error) {
aslog := logf.Log.WithName(ClusterNamespacedName(c))
aslog.Info("Validate delete")
return nil, nil
}
// ValidateUpdate validate update
func (c *AerospikeCluster) ValidateUpdate(oldObj runtime.Object) (admission.Warnings, error) {
aslog := logf.Log.WithName(ClusterNamespacedName(c))
aslog.Info("Validate update")
old := oldObj.(*AerospikeCluster)
if err := c.validate(aslog); err != nil {
return nil, err
}
outgoingVersion, err := GetImageVersion(old.Spec.Image)
if err != nil {
return nil, err
}
incomingVersion, err := GetImageVersion(c.Spec.Image)
if err != nil {
return nil, err
}
if err := asconfig.IsValidUpgrade(
outgoingVersion, incomingVersion,
); err != nil {
return nil, fmt.Errorf("failed to start upgrade: %v", err)
}
// Volume storage update is not allowed but cascadeDelete policy is allowed
if err := old.Spec.Storage.validateStorageSpecChange(&c.Spec.Storage); err != nil {
return nil, fmt.Errorf("storage config cannot be updated: %v", err)
}
// MultiPodPerHost cannot be updated
if !ptr.Equal(c.Spec.PodSpec.MultiPodPerHost, old.Spec.PodSpec.MultiPodPerHost) {
return nil, fmt.Errorf("cannot update MultiPodPerHost setting")
}
if err := validateNetworkPolicyUpdate(
&old.Spec.AerospikeNetworkPolicy, &c.Spec.AerospikeNetworkPolicy,
); err != nil {
return nil, err
}
// Validate AerospikeConfig update
if err := validateAerospikeConfigUpdate(
aslog, incomingVersion, outgoingVersion,
c.Spec.AerospikeConfig, old.Spec.AerospikeConfig,
c.Status.AerospikeConfig, c.Status.Pods,
); err != nil {
return nil, err
}
// Validate RackConfig update
return nil, c.validateRackUpdate(aslog, old)
}
func (c *AerospikeCluster) validate(aslog logr.Logger) error {
aslog.V(1).Info("Validate AerospikeCluster spec", "obj.Spec", c.Spec)
// Validate obj name
if c.Name == "" {
return fmt.Errorf("aerospikeCluster name cannot be empty")
}
if strings.Contains(c.Name, " ") {
// Few parsing logic depend on this
return fmt.Errorf("aerospikeCluster name cannot have spaces")
}
// Validate obj namespace
if c.Namespace == "" {
return fmt.Errorf("aerospikeCluster namespace name cannot be empty")
}
if strings.Contains(c.Namespace, " ") {
// Few parsing logic depend on this
return fmt.Errorf("aerospikeCluster name cannot have spaces")
}
// Validate image type. Only enterprise image allowed for now
if !isEnterprise(c.Spec.Image) {
return fmt.Errorf("CommunityEdition Cluster not supported")
}
// Validate size
if c.Spec.Size == 0 {
return fmt.Errorf("invalid cluster size 0")
}
// Validate MaxUnavailable for PodDisruptionBudget
if err := c.validateMaxUnavailable(); err != nil {
return err
}
// Validate Image version
version, err := GetImageVersion(c.Spec.Image)
if err != nil {
return err
}
val, err := lib.CompareVersions(version, baseVersion)
if err != nil {
return fmt.Errorf("failed to check image version: %v", err)
}
if val < 0 {
return fmt.Errorf(
"image version %s not supported. Base version %s", version,
baseVersion,
)
}
err = validateClusterSize(aslog, version, int(c.Spec.Size))
if err != nil {
return err
}
// Storage should be validated before validating aerospikeConfig and fileStorage
if err := validateStorage(&c.Spec.Storage, &c.Spec.PodSpec); err != nil {
return err
}
for idx := range c.Spec.RackConfig.Racks {
rack := &c.Spec.RackConfig.Racks[idx]
// Storage should be validated before validating aerospikeConfig and fileStorage
if err := validateStorage(&rack.Storage, &c.Spec.PodSpec); err != nil {
return err
}
// Validate if passed aerospikeConfig
if err := validateAerospikeConfigSchema(
aslog, version, rack.AerospikeConfig,
); err != nil {
return fmt.Errorf("aerospikeConfig not valid: %v", err)
}
// Validate common aerospike config
if err := c.validateAerospikeConfig(
&rack.AerospikeConfig, &rack.Storage, int(c.Spec.Size),
); err != nil {
return err
}
if err := validateRequiredFileStorageForMetadata(
rack.AerospikeConfig, &rack.Storage, c.Spec.ValidationPolicy, version,
); err != nil {
return err
}
if err := validateRequiredFileStorageForFeatureConf(
rack.AerospikeConfig, &rack.Storage,
); err != nil {
return err
}
}
// Validate resource and limit
if err := c.validatePodSpecResourceAndLimits(aslog); err != nil {
return err
}
// Validate access control
if err := c.validateAccessControl(aslog); err != nil {
return err
}
// Validate rackConfig
if err := c.validateRackConfig(aslog); err != nil {
return err
}
if err := validateClientCertSpec(
c.Spec.OperatorClientCertSpec, c.Spec.AerospikeConfig,
); err != nil {
return err
}
if err := c.validateNetworkPolicy(c.Namespace); err != nil {
return err
}
// Validate Sidecars
if err := c.validatePodSpec(); err != nil {
return err
}
return c.validateSCNamespaces()
}
func (c *AerospikeCluster) validateSCNamespaces() error {
scNamespaceSet := sets.NewString()
for idx := range c.Spec.RackConfig.Racks {
rack := &c.Spec.RackConfig.Racks[idx]
tmpSCNamespaceSet := sets.NewString()
nsList := rack.AerospikeConfig.Value["namespaces"].([]interface{})
for _, nsConfInterface := range nsList {
nsConf := nsConfInterface.(map[string]interface{})
isEnabled := IsNSSCEnabled(nsConf)
if isEnabled {
tmpSCNamespaceSet.Insert(nsConf["name"].(string))
if isInMemoryNamespace(nsConf) {
return fmt.Errorf("in-memory SC namespace is not supported, namespace %v", nsConf["name"])
}
}
}
if idx == 0 {
scNamespaceSet = tmpSCNamespaceSet
continue
}
if !scNamespaceSet.Equal(tmpSCNamespaceSet) {
return fmt.Errorf("SC namespaces list is different for different racks. All racks should have same SC namespaces")
}
}
return nil
}
func (c *AerospikeOperatorClientCertSpec) validate() error {
if (c.SecretCertSource == nil) == (c.CertPathInOperator == nil) {
return fmt.Errorf(
"either `secretCertSource` or `certPathInOperator` must be set in `operatorClientCertSpec` but not"+
" both: %+v",
c,
)
}
if c.SecretCertSource != nil {
if (c.SecretCertSource.ClientCertFilename == "") != (c.SecretCertSource.ClientKeyFilename == "") {
return fmt.Errorf(
"both `clientCertFilename` and `clientKeyFilename` should be either set or not set in"+
" `secretCertSource`: %+v",
c.SecretCertSource,
)
}
if (c.SecretCertSource.CaCertsFilename != "") && (c.SecretCertSource.CaCertsSource != nil) {
return fmt.Errorf(
"both `caCertsFilename` or `caCertsSource` cannot be set in `secretCertSource`: %+v",
c.SecretCertSource,
)
}
}
if c.CertPathInOperator != nil &&
(c.CertPathInOperator.ClientCertPath == "") != (c.CertPathInOperator.ClientKeyPath == "") {
return fmt.Errorf(
"both `clientCertPath` and `clientKeyPath` should be either set or not set in `certPathInOperator"+
"`: %+v",
c.CertPathInOperator,
)
}
if !c.IsClientCertConfigured() {
return fmt.Errorf("operator client cert is not configured")
}
return nil
}
func validateClientCertSpec(
clientCertSpec *AerospikeOperatorClientCertSpec,
configSpec *AerospikeConfigSpec,
) error {
networkConf, networkConfExist := configSpec.Value[confKeyNetwork]
if !networkConfExist {
return nil
}
serviceConf, serviceConfExists := networkConf.(map[string]interface{})[confKeyNetworkService]
if !serviceConfExists {
return nil
}
tlsAuthenticateClientConfig, ok := serviceConf.(map[string]interface{})["tls-authenticate-client"]
if !ok {
return nil
}
switch {
case reflect.DeepEqual("false", tlsAuthenticateClientConfig):
return nil
case reflect.DeepEqual("any", tlsAuthenticateClientConfig):
if clientCertSpec == nil {
return fmt.Errorf("operator client cert is not specified")
}
if err := clientCertSpec.validate(); err != nil {
return err
}
return nil
default:
if clientCertSpec == nil {
return fmt.Errorf("operator client cert is not specified")
}
if clientCertSpec.TLSClientName == "" {
return fmt.Errorf("operator TLSClientName is not specified")
}
if err := clientCertSpec.validate(); err != nil {
return err
}
}
return nil
}
func (c *AerospikeOperatorClientCertSpec) IsClientCertConfigured() bool {
return (c.SecretCertSource != nil && c.SecretCertSource.ClientCertFilename != "") ||
(c.CertPathInOperator != nil && c.CertPathInOperator.ClientCertPath != "")
}
func (c *AerospikeCluster) validateRackUpdate(
aslog logr.Logger, old *AerospikeCluster,
) error {
if reflect.DeepEqual(c.Spec.RackConfig, old.Spec.RackConfig) {
return nil
}
outgoingVersion, err := GetImageVersion(old.Spec.Image)
if err != nil {
return err
}
incomingVersion, err := GetImageVersion(c.Spec.Image)
if err != nil {
return err
}
// Old racks cannot be updated
// Also need to exclude a default rack with default rack ID. No need to check here,
// user should not provide or update default rackID
// Also when user add new rackIDs old default will be removed by reconciler.
for rackIdx := range old.Spec.RackConfig.Racks {
oldRack := old.Spec.RackConfig.Racks[rackIdx]
for specIdx := range c.Spec.RackConfig.Racks {
newRack := c.Spec.RackConfig.Racks[specIdx]
if oldRack.ID == newRack.ID {
if oldRack.NodeName != newRack.NodeName ||
oldRack.RackLabel != newRack.RackLabel ||
oldRack.Region != newRack.Region ||
oldRack.Zone != newRack.Zone {
return fmt.Errorf(
"old RackConfig (NodeName, RackLabel, Region, Zone) cannot be updated. Old rack %v, new rack %v",
oldRack, newRack,
)
}
if len(oldRack.AerospikeConfig.Value) != 0 || len(newRack.AerospikeConfig.Value) != 0 {
var rackStatusConfig *AerospikeConfigSpec
for statusIdx := range c.Status.RackConfig.Racks {
statusRack := c.Status.RackConfig.Racks[statusIdx]
if statusRack.ID == newRack.ID {
rackStatusConfig = &statusRack.AerospikeConfig
break
}
}
// Validate aerospikeConfig update
if err := validateAerospikeConfigUpdate(
aslog, incomingVersion, outgoingVersion,
&newRack.AerospikeConfig, &oldRack.AerospikeConfig,
rackStatusConfig, c.Status.Pods,
); err != nil {
return fmt.Errorf(
"invalid update in Rack(ID: %d) aerospikeConfig: %v",
oldRack.ID, err,
)
}
}
if len(oldRack.Storage.Volumes) != 0 || len(newRack.Storage.Volumes) != 0 {
// Storage might have changed
oldStorage := oldRack.Storage
newStorage := newRack.Storage
// Volume storage update is not allowed but cascadeDelete policy is allowed
if err := oldStorage.validateStorageSpecChange(&newStorage); err != nil {
return fmt.Errorf(
"rack storage config cannot be updated: %v", err,
)
}
}
break
}
}
}
return nil
}
// TODO: FIX
func (c *AerospikeCluster) validateAccessControl(_ logr.Logger) error {
_, err := IsAerospikeAccessControlValid(&c.Spec)
return err
}
func (c *AerospikeCluster) validatePodSpecResourceAndLimits(_ logr.Logger) error {
checkResourcesLimits := false
if err := c.validateResourceAndLimits(
c.Spec.PodSpec.AerospikeContainerSpec.Resources, false,
); err != nil {
return err
}
for idx := range c.Spec.RackConfig.Racks {
rack := &c.Spec.RackConfig.Racks[idx]
if rack.Storage.CleanupThreads != AerospikeVolumeSingleCleanupThread {
checkResourcesLimits = true
break
}
}
if checkResourcesLimits && c.Spec.PodSpec.AerospikeInitContainerSpec == nil {
return fmt.Errorf(
"init container spec should have resources.Limits set if CleanupThreads is more than 1",
)
}
if c.Spec.PodSpec.AerospikeInitContainerSpec != nil {
return c.validateResourceAndLimits(c.Spec.PodSpec.AerospikeInitContainerSpec.Resources, checkResourcesLimits)
}
return nil
}
func (c *AerospikeCluster) validateResourceAndLimits(
resources *v1.ResourceRequirements, checkResourcesLimits bool,
) error {
if checkResourcesLimits {
if resources == nil || resources.Limits == nil {
return fmt.Errorf(
"resources.Limits for init container cannot be empty if CleanupThreads is being set more than 1",
)
}
} else if resources == nil {
return nil
}
if resources.Limits != nil && resources.Requests != nil &&
((resources.Limits.Cpu().Cmp(*resources.Requests.Cpu()) < 0) ||
(resources.Limits.Memory().Cmp(*resources.Requests.Memory()) < 0)) {
return fmt.Errorf(
"resources.Limits cannot be less than resource.Requests. Resources %v",
resources,
)
}
return nil
}
func (c *AerospikeCluster) validateRackConfig(_ logr.Logger) error {
// Validate namespace names
// TODO: Add more validation for namespace name
for _, nsName := range c.Spec.RackConfig.Namespaces {
if strings.Contains(nsName, " ") {
return fmt.Errorf(
"namespace name `%s` cannot have spaces, Namespaces %v", nsName,
c.Spec.RackConfig.Namespaces,
)
}
}
rackMap := map[int]bool{}
migrateFillDelaySet := sets.Set[int]{}
for idx := range c.Spec.RackConfig.Racks {
rack := &c.Spec.RackConfig.Racks[idx]
// Check for duplicate
if _, ok := rackMap[rack.ID]; ok {
return fmt.Errorf(
"duplicate rackID %d not allowed, racks %v", rack.ID,
c.Spec.RackConfig.Racks,
)
}
rackMap[rack.ID] = true
// Check out of range rackID
// Check for defaultRackID is in mutate (user can not use defaultRackID).
// Allow DefaultRackID
if rack.ID > MaxRackID {
return fmt.Errorf(
"invalid rackID. RackID range (%d, %d)", MinRackID, MaxRackID,
)
}
if rack.InputAerospikeConfig != nil {
_, inputRackNetwork := rack.InputAerospikeConfig.Value["network"]
_, inputRackSecurity := rack.InputAerospikeConfig.Value["security"]
if inputRackNetwork || inputRackSecurity {
// Aerospike K8s Operator doesn't support different network configurations for different racks.
// I.e.
// - the same heartbeat port (taken from current node) is used for all peers regardless to racks.
// - a single target port is used in headless service and LB.
// - we need to refactor how connection is created to AS to take into account rack's network config.
// So, just reject rack specific network connections for now.
return fmt.Errorf(
"you can't specify network or security configuration for rack %d ("+
"network and security should be the same for all racks)",
rack.ID,
)
}
}
migrateFillDelay, err := GetMigrateFillDelay(&rack.AerospikeConfig)
if err != nil {
return err
}
migrateFillDelaySet.Insert(migrateFillDelay)
}
// If len of migrateFillDelaySet is more than 1, it means that different migrate-fill-delay is set across racks
if migrateFillDelaySet.Len() > 1 {
return fmt.Errorf("migrate-fill-delay value should be same across all racks")
}
// Validate batch upgrade/restart param
if err := c.validateBatchSize(c.Spec.RackConfig.RollingUpdateBatchSize,
"spec.rackConfig.rollingUpdateBatchSize"); err != nil {
return err
}
// Validate batch scaleDown param
if err := c.validateBatchSize(c.Spec.RackConfig.ScaleDownBatchSize,
"spec.rackConfig.scaleDownBatchSize"); err != nil {
return err
}
// Validate MaxIgnorablePods param
if c.Spec.RackConfig.MaxIgnorablePods != nil {
if err := validateIntOrStringField(c.Spec.RackConfig.MaxIgnorablePods,
"spec.rackConfig.maxIgnorablePods"); err != nil {
return err
}
}
// TODO: should not use batch if racks are less than replication-factor
return nil
}
type nsConf struct {
noOfRacksForNamespaces int
replicationFactor int
}
func getNsConfForNamespaces(rackConfig RackConfig) map[string]nsConf {
nsConfs := map[string]nsConf{}
for idx := range rackConfig.Racks {
rack := &rackConfig.Racks[idx]
nsList := rack.AerospikeConfig.Value["namespaces"].([]interface{})
for _, nsInterface := range nsList {
nsName := nsInterface.(map[string]interface{})["name"].(string)
var noOfRacksForNamespaces int
if _, ok := nsConfs[nsName]; !ok {
noOfRacksForNamespaces = 1
} else {
noOfRacksForNamespaces = nsConfs[nsName].noOfRacksForNamespaces + 1
}
rf, _ := getNamespaceReplicationFactor(nsInterface.(map[string]interface{}))
nsConfs[nsName] = nsConf{
noOfRacksForNamespaces: noOfRacksForNamespaces,
replicationFactor: rf,
}
}
}
return nsConfs
}
// ******************************************************************************
// Helper
// ******************************************************************************
// TODO: This should be version specific and part of management lib.
// max cluster size for pre-5.0 cluster
const maxEnterpriseClusterSzLt5_0 = 128
// max cluster size for 5.0+ cluster
const maxEnterpriseClusterSzGt5_0 = 256
const versionForSzCheck = "5.0.0"
func validateClusterSize(_ logr.Logger, version string, sz int) error {
val, err := lib.CompareVersions(version, versionForSzCheck)
if err != nil {
return fmt.Errorf(
"failed to validate cluster size limit from version: %v", err,
)
}
if val < 0 && sz > maxEnterpriseClusterSzLt5_0 {
return fmt.Errorf(
"cluster size cannot be more than %d", maxEnterpriseClusterSzLt5_0,
)
}
if val > 0 && sz > maxEnterpriseClusterSzGt5_0 {
return fmt.Errorf(
"cluster size cannot be more than %d", maxEnterpriseClusterSzGt5_0,
)
}
return nil
}
func (c *AerospikeCluster) validateAerospikeConfig(
configSpec *AerospikeConfigSpec, storage *AerospikeStorageSpec, clSize int,
) error {
config := configSpec.Value
if config == nil {
return fmt.Errorf("aerospikeConfig cannot be empty")
}
// service conf
serviceConf, ok := config["service"].(map[string]interface{})
if !ok {
return fmt.Errorf(
"aerospikeConfig.service not a valid map %v", config["service"],
)
}
if _, ok = serviceConf["cluster-name"]; !ok {
return fmt.Errorf("aerospikeCluster name not found in config. Looks like object is not mutated by webhook")
}
// network conf
networkConf, ok := config["network"].(map[string]interface{})
if !ok {
return fmt.Errorf(
"aerospikeConfig.network not a valid map %v", config["network"],
)
}
if err := c.validateNetworkConfig(networkConf); err != nil {
return err
}
// namespace conf
nsListInterface, ok := config["namespaces"]
if !ok {
return fmt.Errorf(
"aerospikeConfig.namespace not a present. aerospikeConfig %v",
config,
)
} else if nsListInterface == nil {
return fmt.Errorf("aerospikeConfig.namespace cannot be nil")
}
if nsList, ok1 := nsListInterface.([]interface{}); !ok1 {
return fmt.Errorf(
"aerospikeConfig.namespace not valid namespace list %v",
nsListInterface,
)
} else if err := validateNamespaceConfig(
nsList, storage, clSize,
); err != nil {
return err
}
// logging conf
// config["logging"] is added in mutating webhook
loggingConfList, ok := config["logging"].([]interface{})
if !ok {
return fmt.Errorf(
"aerospikeConfig.logging not a valid list %v", config["logging"],
)
}
return validateLoggingConf(loggingConfList)
}
func validateLoggingConf(loggingConfList []interface{}) error {
syslogParams := []string{"facility", "path", "tag"}
for idx := range loggingConfList {
logConf, ok := loggingConfList[idx].(map[string]interface{})
if !ok {
return fmt.Errorf(
"aerospikeConfig.logging not a list of valid map %v", logConf,
)
}
if logConf["name"] != "syslog" {
for _, param := range syslogParams {
if _, ok := logConf[param]; ok {
return fmt.Errorf("can use %s only with `syslog` in aerospikeConfig.logging %v", param, logConf)
}
}
}
}
return nil
}
func (c *AerospikeCluster) validateNetworkConfig(networkConf map[string]interface{}) error {
serviceConf, serviceExist := networkConf["service"]
if !serviceExist {
return fmt.Errorf("network.service section not found in config")
}
tlsNames := sets.Set[string]{}
// network.tls conf
if _, ok := networkConf["tls"]; ok {
tlsConfList := networkConf["tls"].([]interface{})
for _, tlsConfInt := range tlsConfList {
tlsConf := tlsConfInt.(map[string]interface{})
if tlsName, ok := tlsConf["name"]; ok {
tlsNames.Insert(tlsName.(string))
}
if _, ok := tlsConf["ca-path"]; ok {
if _, ok1 := tlsConf["ca-file"]; ok1 {
return fmt.Errorf(
"both `ca-path` and `ca-file` cannot be set in `tls`. tlsConf %v",
tlsConf,
)
}
}
}
}
if err := validateTLSClientNames(
serviceConf.(map[string]interface{}), c.Spec.OperatorClientCertSpec,
); err != nil {
return err
}
for _, connectionType := range networkConnectionTypes {
if err := validateNetworkConnection(
networkConf, tlsNames, connectionType,
); err != nil {
return err
}
}
return nil
}
// ValidateTLSAuthenticateClient validate the tls-authenticate-client field in the service configuration.
func ValidateTLSAuthenticateClient(serviceConf map[string]interface{}) (
[]string, error,
) {
config, ok := serviceConf["tls-authenticate-client"]
if !ok {
return []string{}, nil
}
switch value := config.(type) {
case string:
if value == "any" || value == "false" {
return []string{}, nil
}
return nil, fmt.Errorf(
"tls-authenticate-client contains invalid value: %s", value,
)
case bool:
if !value {
return []string{}, nil
}
return nil, fmt.Errorf(
"tls-authenticate-client contains invalid value: %t", value,
)
case []interface{}:
dnsNames := make([]string, len(value))
for i := 0; i < len(value); i++ {
dnsName, ok := value[i].(string)
if !ok {
return nil, fmt.Errorf(
"tls-authenticate-client contains invalid type value: %v",
value,
)
}
if !validate.IsDNSName(dnsName) {
return nil, fmt.Errorf(
"tls-authenticate-client contains invalid dns-name: %v",
dnsName,
)
}
dnsNames[i] = dnsName
}
return dnsNames, nil
}
return nil, fmt.Errorf(
"tls-authenticate-client contains invalid type value: %v", config,
)
}
func validateTLSClientNames(
serviceConf map[string]interface{},
clientCertSpec *AerospikeOperatorClientCertSpec,
) error {
dnsnames, err := ValidateTLSAuthenticateClient(serviceConf)
if err != nil {
return err
}
if len(dnsnames) == 0 {
return nil
}
localCertNames, err := readNamesFromLocalCertificate(clientCertSpec)
if err != nil {
return err
}
if !containsAnyName(dnsnames, localCertNames) && len(localCertNames) > 0 {
return fmt.Errorf(
"tls-authenticate-client (%+v) doesn't contain name from Operator's certificate (%+v), "+
"configure OperatorClientCertSpec.TLSClientName properly",
dnsnames, localCertNames,
)
}
return nil
}
func containsAnyName(
clientNames []string, namesToFind map[string]struct{},
) bool {
for _, clientName := range clientNames {
if _, exists := namesToFind[clientName]; exists {
return true
}
}
return false
}
func readNamesFromLocalCertificate(clientCertSpec *AerospikeOperatorClientCertSpec) (
map[string]struct{}, error,
) {
result := make(map[string]struct{})
if clientCertSpec == nil || clientCertSpec.CertPathInOperator == nil ||
clientCertSpec.CertPathInOperator.ClientCertPath == "" {
return result, nil
}
r, err := os.ReadFile(clientCertSpec.CertPathInOperator.ClientCertPath)
if err != nil {
return result, err
}
block, _ := pem.Decode(r)
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return result, err
}
if len(cert.Subject.CommonName) > 0 {
result[cert.Subject.CommonName] = struct{}{}
}
for _, dns := range cert.DNSNames {
result[dns] = struct{}{}
}
return result, nil
}
func validateNetworkConnection(
networkConf map[string]interface{}, tlsNames sets.Set[string],
connectionType string,
) error {
if connectionConfig, exists := networkConf[connectionType]; exists {
connectionConfigMap := connectionConfig.(map[string]interface{})
if tlsName, ok := connectionConfigMap[confKeyTLSName]; ok {
if _, tlsPortExist := connectionConfigMap["tls-port"]; !tlsPortExist {
return fmt.Errorf(
"you can't specify tls-name for network.%s without specifying tls-port",
connectionType,
)
}
if !tlsNames.Has(tlsName.(string)) {
return fmt.Errorf("tls-name '%s' is not configured", tlsName)
}
} else {
for param := range connectionConfigMap {
if strings.HasPrefix(param, "tls-") {
return fmt.Errorf(
"you can't specify %s for network.%s without specifying tls-name",
param, connectionType,
)
}
}
}
}
return nil
}
//nolint:gocyclo // for readability
func validateNamespaceConfig(
nsConfInterfaceList []interface{}, storage *AerospikeStorageSpec,
clSize int,
) error {
if len(nsConfInterfaceList) == 0 {
return fmt.Errorf("aerospikeConfig.namespace list cannot be empty")
}
// Get list of all devices used in namespace. match it with namespace device list