forked from Altinity/clickhouse-operator
/
normalizer.go
1483 lines (1269 loc) · 48.6 KB
/
normalizer.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 2019 Altinity Ltd and/or its affiliates. All rights reserved.
//
// 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 model
import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"sort"
"strings"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
kube "k8s.io/client-go/kubernetes"
"github.com/google/uuid"
"k8s.io/api/core/v1"
log "github.com/altinity/clickhouse-operator/pkg/announcer"
chiV1 "github.com/altinity/clickhouse-operator/pkg/apis/clickhouse.altinity.com/v1"
"github.com/altinity/clickhouse-operator/pkg/chop"
"github.com/altinity/clickhouse-operator/pkg/util"
)
// Normalizer specifies structures normalizer
type Normalizer struct {
kubeClient kube.Interface
chi *chiV1.ClickHouseInstallation
// Whether should insert default cluster if no cluster specified
withDefaultCluster bool
}
// NewNormalizer creates new normalizer
func NewNormalizer(kubeClient kube.Interface) *Normalizer {
return &Normalizer{
kubeClient: kubeClient,
}
}
// CreateTemplatedCHI produces ready-to-use CHI object
func (n *Normalizer) CreateTemplatedCHI(chi *chiV1.ClickHouseInstallation) (*chiV1.ClickHouseInstallation, error) {
if chi == nil {
// No CHI specified - meaning we are building 'empty' CHI with no clusters inside
chi = new(chiV1.ClickHouseInstallation)
n.withDefaultCluster = false
} else {
// Insert default cluster in case no clusters specified in this CHI
n.withDefaultCluster = true
}
// What base should be used to create CHI
if chop.Config().Template.CHI.Runtime.Template == nil {
// No template specified - start with clear page
n.chi = new(chiV1.ClickHouseInstallation)
} else {
// Template specified - start with template
n.chi = chop.Config().Template.CHI.Runtime.Template.DeepCopy()
}
// At this moment n.chi is either empty CHI or a system-wide template
// We need to apply templates
// Apply CHOP-specified templates
// TODO
// Apply CHI-specified templates
var useTemplates []chiV1.ChiUseTemplate
// 1. Get list of auto templates to be applied
if autoTemplates := chop.Config().GetAutoTemplates(); len(autoTemplates) > 0 {
log.V(2).M(chi).F().Info("Found auto-templates num: %d", len(autoTemplates))
for _, template := range autoTemplates {
log.V(3).M(chi).F().Info("Adding auto-template to merge list: %s/%s ", template.Name, template.Namespace)
useTemplates = append(useTemplates, chiV1.ChiUseTemplate{
Name: template.Name,
Namespace: template.Namespace,
UseType: useTypeMerge,
})
}
}
// 2. Append templates, explicitly requested in CHI to the list of templates to be applied
if len(chi.Spec.UseTemplates) > 0 {
useTemplates = append(useTemplates, chi.Spec.UseTemplates...)
}
// UseTemplates must contain reasonable data, thus has to be normalized
if len(useTemplates) > 0 {
n.normalizeUseTemplates(useTemplates)
}
// Apply templates (auto and explicitly requested)
for i := range useTemplates {
useTemplate := &useTemplates[i]
if template := chop.Config().FindTemplate(useTemplate, chi.Namespace); template == nil {
log.V(1).M(chi).F().Warning("UNABLE to find template %s/%s referenced in useTemplates. Skip it.", useTemplate.Namespace, useTemplate.Name)
} else {
// Apply template
(&n.chi.Spec).MergeFrom(&template.Spec, chiV1.MergeTypeOverrideByNonEmptyValues)
n.chi.Labels = util.MergeStringMapsOverwrite(
n.chi.Labels,
util.CopyMapFilter(
template.Labels,
chop.Config().Label.Include,
chop.Config().Label.Exclude,
),
)
n.chi.Annotations = util.MergeStringMapsOverwrite(
n.chi.Annotations, util.CopyMapFilter(
template.Annotations,
chop.Config().Annotation.Include,
append(chop.Config().Annotation.Exclude, util.ListSkippedAnnotations()...),
),
)
log.V(2).M(chi).F().Info("Merge template %s/%s referenced in useTemplates", useTemplate.Namespace, useTemplate.Name)
}
}
// After all templates applied, place provided CHI on top of the whole stack
n.chi.MergeFrom(chi, chiV1.MergeTypeOverrideByNonEmptyValues)
return n.normalize()
}
// normalize normalizes whole CHI.
// Returns normalized CHI
func (n *Normalizer) normalize() (*chiV1.ClickHouseInstallation, error) {
// Walk over ChiSpec datatype fields
n.chi.Spec.TaskID = n.normalizeTaskID(n.chi.Spec.TaskID)
n.chi.Spec.UseTemplates = n.normalizeUseTemplates(n.chi.Spec.UseTemplates)
n.chi.Spec.Stop = n.normalizeStop(n.chi.Spec.Stop)
n.chi.Spec.Restart = n.normalizeRestart(n.chi.Spec.Restart)
n.chi.Spec.Troubleshoot = n.normalizeTroubleshoot(n.chi.Spec.Troubleshoot)
n.chi.Spec.NamespaceDomainPattern = n.normalizeNamespaceDomainPattern(n.chi.Spec.NamespaceDomainPattern)
n.chi.Spec.Templating = n.normalizeTemplating(n.chi.Spec.Templating)
n.chi.Spec.Reconciling = n.normalizeReconciling(n.chi.Spec.Reconciling)
n.chi.Spec.Defaults = n.normalizeDefaults(n.chi.Spec.Defaults)
n.chi.Spec.Configuration = n.normalizeConfiguration(n.chi.Spec.Configuration)
n.chi.Spec.Templates = n.normalizeTemplates(n.chi.Spec.Templates)
// UseTemplates already done
n.finalizeCHI()
n.fillStatus()
return n.chi, nil
}
// finalizeCHI performs some finalization tasks, which should be done after CHI is normalized
func (n *Normalizer) finalizeCHI() {
n.chi.FillSelfCalculatedAddressInfo()
n.chi.FillCHIPointer()
n.chi.WalkHosts(func(host *chiV1.ChiHost) error {
hostTemplate := n.getHostTemplate(host)
hostApplyHostTemplate(host, hostTemplate)
return nil
})
n.fillCHIAddressInfo()
n.chi.WalkHosts(func(host *chiV1.ChiHost) error {
return n.calcFingerprints(host)
})
}
// fillCHIAddressInfo
func (n *Normalizer) fillCHIAddressInfo() {
n.chi.WalkHostsFullPath(0, 0, func(
chi *chiV1.ClickHouseInstallation,
chiScopeIndex int,
chiScopeCycleSize int,
chiScopeCycleIndex int,
chiScopeCycleOffset int,
clusterScopeIndex int,
clusterScopeCycleSize int,
clusterScopeCycleIndex int,
clusterScopeCycleOffset int,
clusterIndex int,
cluster *chiV1.ChiCluster,
shardIndex int,
shard *chiV1.ChiShard,
replicaIndex int,
replica *chiV1.ChiReplica,
host *chiV1.ChiHost,
) error {
host.Address.StatefulSet = CreateStatefulSetName(host)
return nil
})
}
// getHostTemplate gets Host Template to be used to normalize Host
func (n *Normalizer) getHostTemplate(host *chiV1.ChiHost) *chiV1.ChiHostTemplate {
statefulSetName := CreateStatefulSetName(host)
// Which host template would be used - either explicitly defined in or a default one
hostTemplate, ok := host.GetHostTemplate()
if ok {
// Host references known HostTemplate
log.V(2).M(host).F().Info("StatefulSet %s uses custom hostTemplate %s", statefulSetName, hostTemplate.Name)
return hostTemplate
}
// Host references UNKNOWN HostTemplate, will use default one
// However, with default template there is a nuance - hostNetwork requires different default host template
// Check hostNetwork case at first
podTemplate, ok := host.GetPodTemplate()
if ok {
if podTemplate.Spec.HostNetwork {
// HostNetwork
hostTemplate = newDefaultHostTemplateForHostNetwork(statefulSetName)
}
}
// In case hostTemplate still is not assigned - use default one
if hostTemplate == nil {
hostTemplate = newDefaultHostTemplate(statefulSetName)
}
log.V(3).M(host).F().Info("StatefulSet %s use default hostTemplate", statefulSetName)
return hostTemplate
}
// hostApplyHostTemplate
func hostApplyHostTemplate(host *chiV1.ChiHost, template *chiV1.ChiHostTemplate) {
if host.Name == "" {
host.Name = template.Spec.Name
}
for _, portDistribution := range template.PortDistribution {
switch portDistribution.Type {
case chiV1.PortDistributionUnspecified:
if host.TCPPort == chPortNumberMustBeAssignedLater {
host.TCPPort = template.Spec.TCPPort
}
if host.HTTPPort == chPortNumberMustBeAssignedLater {
host.HTTPPort = template.Spec.HTTPPort
}
if host.InterserverHTTPPort == chPortNumberMustBeAssignedLater {
host.InterserverHTTPPort = template.Spec.InterserverHTTPPort
}
case chiV1.PortDistributionClusterScopeIndex:
if host.TCPPort == chPortNumberMustBeAssignedLater {
base := chDefaultTCPPortNumber
if template.Spec.TCPPort != chPortNumberMustBeAssignedLater {
base = template.Spec.TCPPort
}
host.TCPPort = base + int32(host.Address.ClusterScopeIndex)
}
if host.HTTPPort == chPortNumberMustBeAssignedLater {
base := chDefaultHTTPPortNumber
if template.Spec.HTTPPort != chPortNumberMustBeAssignedLater {
base = template.Spec.HTTPPort
}
host.HTTPPort = base + int32(host.Address.ClusterScopeIndex)
}
if host.InterserverHTTPPort == chPortNumberMustBeAssignedLater {
base := chDefaultInterserverHTTPPortNumber
if template.Spec.InterserverHTTPPort != chPortNumberMustBeAssignedLater {
base = template.Spec.InterserverHTTPPort
}
host.InterserverHTTPPort = base + int32(host.Address.ClusterScopeIndex)
}
}
}
hostApplyPortsFromSettings(host)
host.InheritTemplatesFrom(nil, nil, template)
}
// hostApplyPortsFromSettings
func hostApplyPortsFromSettings(host *chiV1.ChiHost) {
// Use host personal settings at first
ensurePortValuesFromSettings(host, host.GetSettings(), false)
// Fallback to common settings
ensurePortValuesFromSettings(host, host.GetCHI().Spec.Configuration.Settings, true)
}
// ensurePortValuesFromSettings fetches port spec from settings, if any provided
func ensurePortValuesFromSettings(host *chiV1.ChiHost, settings *chiV1.Settings, finalize bool) {
fallbackTCPPortNumber := chPortNumberMustBeAssignedLater
fallbackHTTPPortNumber := chPortNumberMustBeAssignedLater
fallbackInterserverHTTPPortNumber := chPortNumberMustBeAssignedLater
if finalize {
fallbackTCPPortNumber = chDefaultTCPPortNumber
fallbackHTTPPortNumber = chDefaultHTTPPortNumber
fallbackInterserverHTTPPortNumber = chDefaultInterserverHTTPPortNumber
}
ensurePortValue(&host.TCPPort, settings.GetTCPPort(), fallbackTCPPortNumber)
ensurePortValue(&host.HTTPPort, settings.GetHTTPPort(), fallbackHTTPPortNumber)
ensurePortValue(&host.InterserverHTTPPort, settings.GetInterserverHTTPPort(), fallbackInterserverHTTPPortNumber)
}
// ensurePortValue
func ensurePortValue(port *int32, value, _default int32) {
// Port may already be explicitly specified in podTemplate or by portDistribution
if *port != chPortNumberMustBeAssignedLater {
// Port has a value already
return
}
// Port has no value, let's use value from settings
if value != chPortNumberMustBeAssignedLater {
// Settings has a value, use it
*port = value
return
}
// Port has no explicit value, settings has no value, fallback to default value
*port = _default
}
// fillStatus fills .status section of a CHI with values based on current CHI
func (n *Normalizer) fillStatus() {
endpoint := CreateCHIServiceFQDN(n.chi)
pods := make([]string, 0)
fqdns := make([]string, 0)
n.chi.WalkHosts(func(host *chiV1.ChiHost) error {
pods = append(pods, CreatePodName(host))
fqdns = append(fqdns, CreateFQDN(host))
return nil
})
// Spam normalized config in high-verbose modes only
normalized := false
if v, err := chop.Config().GetLogLevel(); (err == nil) && (v >= 1) {
normalized = true
}
n.chi.FillStatus(endpoint, pods, fqdns, normalized)
}
// normalizeTaskID normalizes .spec.taskID
func (n *Normalizer) normalizeTaskID(taskID *string) *string {
if taskID != nil {
if len(*taskID) > 0 {
return taskID
}
}
id := uuid.New().String()
return &id
}
// normalizeStop normalizes .spec.stop
func (n *Normalizer) normalizeStop(stop string) string {
if util.IsStringBool(stop) {
// It is bool, use as it is
return stop
}
// In case it is unknown value - just use set it to false
return util.StringBoolFalseLowercase
}
// normalizeRestart normalizes .spec.restart
func (n *Normalizer) normalizeRestart(restart string) string {
switch strings.ToLower(restart) {
case strings.ToLower(chiV1.RestartAll):
return chiV1.RestartAll
case strings.ToLower(chiV1.RestartRollingUpdate):
return chiV1.RestartRollingUpdate
}
// In case it is unknown value - just use empty
return ""
}
// normalizeTroubleshoot normalizes .spec.stop
func (n *Normalizer) normalizeTroubleshoot(troubleshoot string) string {
if util.IsStringBool(troubleshoot) {
// It is bool, use as it is
return troubleshoot
}
// In case it is unknown value - just use set it to false
return util.StringBoolFalseLowercase
}
// normalizeNamespaceDomainPattern normalizes .spec.namespaceDomainPattern
func (n *Normalizer) normalizeNamespaceDomainPattern(namespaceDomainPattern string) string {
if strings.Count(namespaceDomainPattern, "%s") > 1 {
return ""
}
return namespaceDomainPattern
}
// normalizeDefaults normalizes .spec.defaults
func (n *Normalizer) normalizeDefaults(defaults *chiV1.ChiDefaults) *chiV1.ChiDefaults {
if defaults == nil {
defaults = chiV1.NewChiDefaults()
}
// Set defaults for CHI object properties
defaults.ReplicasUseFQDN = util.CastStringBoolToStringTrueFalse(defaults.ReplicasUseFQDN, false)
// Ensure field
if defaults.DistributedDDL == nil {
//defaults.DistributedDDL = chiV1.NewChiDistributedDDL()
}
// Ensure field
if defaults.Templates == nil {
//defaults.Templates = chiV1.NewChiTemplateNames()
}
defaults.Templates.HandleDeprecatedFields()
return defaults
}
// normalizeConfiguration normalizes .spec.configuration
func (n *Normalizer) normalizeConfiguration(conf *chiV1.Configuration) *chiV1.Configuration {
if conf == nil {
conf = chiV1.NewConfiguration()
}
conf.Zookeeper = n.normalizeConfigurationZookeeper(conf.Zookeeper)
conf.Users = n.normalizeConfigurationUsers(conf.Users)
conf.Profiles = n.normalizeConfigurationProfiles(conf.Profiles)
conf.Quotas = n.normalizeConfigurationQuotas(conf.Quotas)
conf.Settings = n.normalizeConfigurationSettings(conf.Settings)
conf.Files = n.normalizeConfigurationFiles(conf.Files)
conf.Clusters = n.normalizeClusters(conf.Clusters)
return conf
}
// normalizeTemplates normalizes .spec.templates
func (n *Normalizer) normalizeTemplates(templates *chiV1.ChiTemplates) *chiV1.ChiTemplates {
if templates == nil {
//templates = chiV1.NewChiTemplates()
return nil
}
for i := range templates.HostTemplates {
hostTemplate := &templates.HostTemplates[i]
n.normalizeHostTemplate(hostTemplate)
}
for i := range templates.PodTemplates {
podTemplate := &templates.PodTemplates[i]
n.normalizePodTemplate(podTemplate)
}
for i := range templates.VolumeClaimTemplates {
vcTemplate := &templates.VolumeClaimTemplates[i]
n.normalizeVolumeClaimTemplate(vcTemplate)
}
for i := range templates.ServiceTemplates {
serviceTemplate := &templates.ServiceTemplates[i]
n.normalizeServiceTemplate(serviceTemplate)
}
return templates
}
// normalizeTemplating normalizes .spec.templating
func (n *Normalizer) normalizeTemplating(templating *chiV1.ChiTemplating) *chiV1.ChiTemplating {
if templating == nil {
templating = chiV1.NewChiTemplating()
}
switch strings.ToLower(templating.GetPolicy()) {
case
chiV1.TemplatingPolicyManual,
chiV1.TemplatingPolicyAuto:
templating.SetPolicy(strings.ToLower(templating.GetPolicy()))
default:
templating.SetPolicy(strings.ToLower(chiV1.TemplatingPolicyManual))
}
return templating
}
// normalizeReconciling normalizes .spec.reconciling
func (n *Normalizer) normalizeReconciling(reconciling *chiV1.ChiReconciling) *chiV1.ChiReconciling {
if reconciling == nil {
reconciling = chiV1.NewChiReconciling().SetDefaults()
}
switch strings.ToLower(reconciling.GetPolicy()) {
case
chiV1.ReconcilingPolicyWait,
chiV1.ReconcilingPolicyNoWait:
reconciling.SetPolicy(strings.ToLower(reconciling.GetPolicy()))
default:
reconciling.SetPolicy(strings.ToLower(chiV1.ReconcilingPolicyUnspecified))
}
reconciling.Cleanup = n.normalizeReconcilingCleanup(reconciling.Cleanup)
return reconciling
}
func (n *Normalizer) normalizeReconcilingCleanup(cleanup *chiV1.ChiCleanup) *chiV1.ChiCleanup {
if cleanup == nil {
cleanup = chiV1.NewChiCleanup()
}
if cleanup.UnknownObjects == nil {
cleanup.UnknownObjects = cleanup.DefaultUnknownObjects()
}
n.normalizeCleanup(&cleanup.UnknownObjects.StatefulSet, chiV1.ObjectsCleanupDelete)
n.normalizeCleanup(&cleanup.UnknownObjects.PVC, chiV1.ObjectsCleanupDelete)
n.normalizeCleanup(&cleanup.UnknownObjects.ConfigMap, chiV1.ObjectsCleanupDelete)
n.normalizeCleanup(&cleanup.UnknownObjects.Service, chiV1.ObjectsCleanupDelete)
if cleanup.ReconcileFailedObjects == nil {
cleanup.ReconcileFailedObjects = cleanup.DefaultReconcileFailedObjects()
}
n.normalizeCleanup(&cleanup.ReconcileFailedObjects.StatefulSet, chiV1.ObjectsCleanupRetain)
n.normalizeCleanup(&cleanup.ReconcileFailedObjects.PVC, chiV1.ObjectsCleanupRetain)
n.normalizeCleanup(&cleanup.ReconcileFailedObjects.ConfigMap, chiV1.ObjectsCleanupRetain)
n.normalizeCleanup(&cleanup.ReconcileFailedObjects.Service, chiV1.ObjectsCleanupRetain)
return cleanup
}
func (n *Normalizer) normalizeCleanup(str *string, value string) {
switch *str {
case
chiV1.ObjectsCleanupRetain,
chiV1.ObjectsCleanupDelete:
default:
*str = value
}
}
// normalizeHostTemplate normalizes .spec.templates.hostTemplates
func (n *Normalizer) normalizeHostTemplate(template *chiV1.ChiHostTemplate) {
// Name
// PortDistribution
if template.PortDistribution == nil {
// In case no PortDistribution provided - setup default one
template.PortDistribution = []chiV1.ChiPortDistribution{
{Type: chiV1.PortDistributionUnspecified},
}
}
// Normalize PortDistribution
for i := range template.PortDistribution {
portDistribution := &template.PortDistribution[i]
switch portDistribution.Type {
case
chiV1.PortDistributionUnspecified,
chiV1.PortDistributionClusterScopeIndex:
// distribution is known
default:
// distribution is not known
portDistribution.Type = chiV1.PortDistributionUnspecified
}
}
// Spec
n.normalizeHostTemplateSpec(&template.Spec)
// Introduce HostTemplate into Index
n.chi.Spec.Templates.EnsureHostTemplatesIndex().Set(template.Name, template)
}
// normalizePodTemplate normalizes .spec.templates.podTemplates
func (n *Normalizer) normalizePodTemplate(template *chiV1.ChiPodTemplate) {
// Name
// Zone
if len(template.Zone.Values) == 0 {
// In case no values specified - no key is reasonable
template.Zone.Key = ""
} else if template.Zone.Key == "" {
// We have values specified, but no key
// Use default zone key in this case
template.Zone.Key = "failure-domain.beta.kubernetes.io/zone"
} else {
// We have both key and value(s) specified explicitly
}
// PodDistribution
for i := range template.PodDistribution {
if additionalPoDistributions := n.normalizePodDistribution(&template.PodDistribution[i]); additionalPoDistributions != nil {
template.PodDistribution = append(template.PodDistribution, additionalPoDistributions...)
}
}
// Spec
template.Spec.Affinity = mergeAffinity(template.Spec.Affinity, newAffinity(template))
// In case we have hostNetwork specified, we need to have ClusterFirstWithHostNet DNS policy, because of
// https://kubernetes.io/docs/concepts/services-networking/dns-pod-service/#pod-s-dns-policy
// which tells: For Pods running with hostNetwork, you should explicitly set its DNS policy “ClusterFirstWithHostNet”.
if template.Spec.HostNetwork {
template.Spec.DNSPolicy = v1.DNSClusterFirstWithHostNet
}
// Introduce PodTemplate into Index
n.chi.Spec.Templates.EnsurePodTemplatesIndex().Set(template.Name, template)
}
const defaultTopologyKey = "kubernetes.io/hostname"
func (n *Normalizer) normalizePodDistribution(podDistribution *chiV1.ChiPodDistribution) []chiV1.ChiPodDistribution {
if podDistribution.TopologyKey == "" {
podDistribution.TopologyKey = defaultTopologyKey
}
switch podDistribution.Type {
case
chiV1.PodDistributionUnspecified,
// AntiAffinity section
chiV1.PodDistributionClickHouseAntiAffinity,
chiV1.PodDistributionShardAntiAffinity,
chiV1.PodDistributionReplicaAntiAffinity:
// PodDistribution is known
if podDistribution.Scope == "" {
podDistribution.Scope = chiV1.PodDistributionScopeCluster
}
return nil
case
chiV1.PodDistributionAnotherNamespaceAntiAffinity,
chiV1.PodDistributionAnotherClickHouseInstallationAntiAffinity,
chiV1.PodDistributionAnotherClusterAntiAffinity:
// PodDistribution is known
return nil
case
chiV1.PodDistributionMaxNumberPerNode:
// PodDistribution is known
if podDistribution.Number < 0 {
podDistribution.Number = 0
}
return nil
case
// Affinity section
chiV1.PodDistributionNamespaceAffinity,
chiV1.PodDistributionClickHouseInstallationAffinity,
chiV1.PodDistributionClusterAffinity,
chiV1.PodDistributionShardAffinity,
chiV1.PodDistributionReplicaAffinity,
chiV1.PodDistributionPreviousTailAffinity:
// PodDistribution is known
return nil
case chiV1.PodDistributionCircularReplication:
// PodDistribution is known
// PodDistributionCircularReplication is a shortcut to simplify complex set of other distributions
// All shortcuts have to be expanded
if podDistribution.Scope == "" {
podDistribution.Scope = chiV1.PodDistributionScopeCluster
}
// TODO need to support multi-cluster
cluster := n.chi.Spec.Configuration.Clusters[0]
// Expand shortcut
return []chiV1.ChiPodDistribution{
{
Type: chiV1.PodDistributionShardAntiAffinity,
Scope: podDistribution.Scope,
},
{
Type: chiV1.PodDistributionReplicaAntiAffinity,
Scope: podDistribution.Scope,
},
{
Type: chiV1.PodDistributionMaxNumberPerNode,
Scope: podDistribution.Scope,
Number: cluster.Layout.ReplicasCount,
},
{
Type: chiV1.PodDistributionPreviousTailAffinity,
},
{
Type: chiV1.PodDistributionNamespaceAffinity,
},
{
Type: chiV1.PodDistributionClickHouseInstallationAffinity,
},
{
Type: chiV1.PodDistributionClusterAffinity,
},
}
}
// PodDistribution is not known
podDistribution.Type = chiV1.PodDistributionUnspecified
return nil
}
// normalizeVolumeClaimTemplate normalizes .spec.templates.volumeClaimTemplates
func (n *Normalizer) normalizeVolumeClaimTemplate(template *chiV1.ChiVolumeClaimTemplate) {
// Check name
// Check PVCReclaimPolicy
if !template.PVCReclaimPolicy.IsValid() {
template.PVCReclaimPolicy = chiV1.PVCReclaimPolicyDelete
}
// Check Spec
// Introduce VolumeClaimTemplate into Index
n.chi.Spec.Templates.EnsureVolumeClaimTemplatesIndex().Set(template.Name, template)
}
// normalizeServiceTemplate normalizes .spec.templates.serviceTemplates
func (n *Normalizer) normalizeServiceTemplate(template *chiV1.ChiServiceTemplate) {
// Check name
// Check GenerateName
// Check ObjectMeta
// Check Spec
// Introduce ServiceClaimTemplate into Index
n.chi.Spec.Templates.EnsureServiceTemplatesIndex().Set(template.Name, template)
}
// normalizeUseTemplates normalizes .spec.useTemplates
func (n *Normalizer) normalizeUseTemplates(useTemplates []chiV1.ChiUseTemplate) []chiV1.ChiUseTemplate {
for i := range useTemplates {
useTemplate := &useTemplates[i]
n.normalizeUseTemplate(useTemplate)
}
return useTemplates
}
// normalizeUseTemplate normalizes ChiUseTemplate
func (n *Normalizer) normalizeUseTemplate(useTemplate *chiV1.ChiUseTemplate) {
// Check Name
if useTemplate.Name == "" {
// This is strange
}
// Check Namespace
if useTemplate.Namespace == "" {
// So far do nothing with empty namespace
}
// Ensure UseType
switch useTemplate.UseType {
case useTypeMerge:
// Known use type, all is fine, do nothing
default:
// Unknown - use default value
useTemplate.UseType = useTypeMerge
}
}
// normalizeClusters normalizes clusters
func (n *Normalizer) normalizeClusters(clusters []*chiV1.ChiCluster) []*chiV1.ChiCluster {
// We need to have at least one cluster available
clusters = n.ensureClusters(clusters)
// Normalize all clusters
for i := range clusters {
clusters[i] = n.normalizeCluster(clusters[i])
}
return clusters
}
// newDefaultCluster
func (n *Normalizer) newDefaultCluster() *chiV1.ChiCluster {
return &chiV1.ChiCluster{
Name: "cluster",
}
}
// ensureClusters
func (n *Normalizer) ensureClusters(clusters []*chiV1.ChiCluster) []*chiV1.ChiCluster {
if len(clusters) > 0 {
return clusters
}
if n.withDefaultCluster {
return []*chiV1.ChiCluster{n.newDefaultCluster()}
}
return []*chiV1.ChiCluster{}
}
// calcFingerprints calculates fingerprints for ClickHouse configuration data
func (n *Normalizer) calcFingerprints(host *chiV1.ChiHost) error {
zk := host.GetZookeeper()
host.Config.ZookeeperFingerprint = util.Fingerprint(zk)
global := n.chi.Spec.Configuration.Settings.AsSortedSliceOfStrings()
local := host.Settings.AsSortedSliceOfStrings()
host.Config.SettingsFingerprint = util.Fingerprint(
fmt.Sprintf("%s%s",
util.Fingerprint(global),
util.Fingerprint(local),
),
)
host.Config.FilesFingerprint = util.Fingerprint(
fmt.Sprintf("%s%s",
util.Fingerprint(
n.chi.Spec.Configuration.Files.Filter(
nil,
[]chiV1.SettingsSection{chiV1.SectionUsers},
true,
).AsSortedSliceOfStrings(),
),
util.Fingerprint(
host.Files.Filter(
nil,
[]chiV1.SettingsSection{chiV1.SectionUsers},
true,
).AsSortedSliceOfStrings(),
),
),
)
return nil
}
// normalizeConfigurationZookeeper normalizes .spec.configuration.zookeeper
func (n *Normalizer) normalizeConfigurationZookeeper(zk *chiV1.ChiZookeeperConfig) *chiV1.ChiZookeeperConfig {
if zk == nil {
return nil
}
// In case no ZK port specified - assign default
for i := range zk.Nodes {
// Convenience wrapper
node := &zk.Nodes[i]
if node.Port == 0 {
node.Port = zkDefaultPort
}
}
// In case no ZK root specified - assign '/clickhouse/{namespace}/{chi name}'
//if zk.Root == "" {
// zk.Root = fmt.Sprintf(zkDefaultRootTemplate, n.chi.Namespace, n.chi.Name)
//}
return zk
}
// substWithSecretField substitute users settings field with value from k8s secret
func (n *Normalizer) substWithSecretField(users *chiV1.Settings, username string, userSettingsField, userSettingsK8SSecretField string) bool {
// Has to have source field specified
if !users.Has(username + "/" + userSettingsK8SSecretField) {
return false
}
// Anyway remove source field, it should not be included into final ClickHouse config,
// because these source fields are synthetic ones (clickhouse does not know them).
defer users.Delete(username + "/" + userSettingsK8SSecretField)
secretFieldValue, err := n.fetchSecretFieldValue(users, username, userSettingsK8SSecretField)
if err != nil {
return false
}
users.Set(username+"/"+userSettingsField, chiV1.NewSettingScalar(secretFieldValue))
return true
}
// substWithSecretEnvField substitute users settings field with value from k8s secret stored in ENV var
func (n *Normalizer) substWithSecretEnvField(users *chiV1.Settings, username string, userSettingsField, userSettingsK8SSecretField string) bool {
// Fetch secret name and key within secret
_, secretName, key, err := parseSecretFieldAddress(users, username, userSettingsK8SSecretField)
if err != nil {
return false
}
// Subst plaintext field with secret field
if !n.substWithSecretField(users, username, userSettingsField, userSettingsK8SSecretField) {
return false
}
// ENV VAR name and value
envVarName := username + "_" + userSettingsField
for _, envVar := range n.chi.Attributes.ExchangeEnv {
if envVar.Name == envVarName {
// Such a variable already exists
return false
}
}
envVar := corev1.EnvVar{
Name: envVarName,
ValueFrom: &corev1.EnvVarSource{
SecretKeyRef: &v1.SecretKeySelector{
LocalObjectReference: v1.LocalObjectReference{
Name: secretName,
},
Key: key,
},
},
}
n.chi.Attributes.ExchangeEnv = append(n.chi.Attributes.ExchangeEnv, envVar)
// Replace setting with empty value and reference to ENV VAR
users.Set(username+"/"+userSettingsField, chiV1.NewSettingScalar("").SetAttribute("from_env", envVarName))
return true
}
var (
// ErrSecretFieldNotFound specifies error when secret key is not found
ErrSecretFieldNotFound = fmt.Errorf("not found")
)
// parseSecretFieldAddress parses address into namespace, name, key triple
func parseSecretFieldAddress(users *chiV1.Settings, username, userSettingsK8SSecretField string) (string, string, string, error) {
secretFieldAddress := users.Get(username + "/" + userSettingsK8SSecretField).String()
// Extract secret's namespace and name and then field name within the secret,
// by splitting namespace/name/field (aka key) triple. Namespace can be omitted in the settings
var namespace, name, key string
switch tags := strings.Split(secretFieldAddress, "/"); len(tags) {
case 2:
// Assume namespace is omitted
namespace = chop.Config().Runtime.Namespace
name = tags[0]
key = tags[1]
case 3:
// All components are in place
namespace = tags[0]
name = tags[1]
key = tags[2]
default:
// Skip incorrect entry
log.V(1).Warning("unable to parse secret field address: %s", secretFieldAddress)
return "", "", "", ErrSecretFieldNotFound
}
// Sanity check
if (namespace == "") || (name == "") || (key == "") {
log.V(1).M(namespace, name).F().Warning("incorrect secret field address: %s", secretFieldAddress)
return "", "", "", ErrSecretFieldNotFound
}
return namespace, name, key, nil
}
// fetchSecretFieldValue fetches the value of the specified field in the specified secret
func (n *Normalizer) fetchSecretFieldValue(users *chiV1.Settings, username, userSettingsK8SSecretField string) (string, error) {
// Fetch address of the field
namespace, name, key, err := parseSecretFieldAddress(users, username, userSettingsK8SSecretField)
if err != nil {
return "", err
}
secret, err := n.kubeClient.CoreV1().Secrets(namespace).Get(context.TODO(), name, metav1.GetOptions{})
if err != nil {
log.V(1).M(namespace, name).F().Info("unable to read secret %v", err)
return "", ErrSecretFieldNotFound
}
// Find the field within the secret
for k, value := range secret.Data {
if key == k {
return string(value), nil
}
}
log.V(1).M(namespace, name).F().Info("unable to locate in specified address (namespace/name/key triple) from: %s/%s", username, userSettingsK8SSecretField)
return "", ErrSecretFieldNotFound
}
// normalizeUsersList extracts usernames from provided 'users' settings
func (n *Normalizer) normalizeUsersList(users *chiV1.Settings, extra ...string) (usernames []string) {
// Extract username from path
usernameMap := make(map[string]bool)
users.Walk(func(path string, _ *chiV1.Setting) {
// Split username/action into username and all the rest. Ex. 'admin/password', 'admin/networks/ip'
tags := strings.Split(path, "/")
// Basic sanity check - need to have at least "username/something" pair
if len(tags) < 2 {
// Skip incorrect entry
return
}
username := tags[0]
usernameMap[username] = true
})
// Add extra users
for _, username := range extra {
usernameMap[username] = true
}
// Make sorted list of unique usernames
for username := range usernameMap {
usernames = append(usernames, username)
}
sort.Strings(usernames)
return usernames
}
const defaultUsername = "default"
// normalizeConfigurationUsers normalizes .spec.configuration.users
func (n *Normalizer) normalizeConfigurationUsers(users *chiV1.Settings) *chiV1.Settings {
// Ensure and normalize user settings