/
base_types.go
2301 lines (2108 loc) · 69.3 KB
/
base_types.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
package v1alpha1
import (
"bufio"
"bytes"
"context"
"crypto/sha1"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"os"
"reflect"
"sort"
"strings"
"time"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/operator-framework/operator-sdk/pkg/k8sutil"
"github.com/tungstenfabric/tf-operator/pkg/apis/tf/v1alpha1/templates"
configtemplates "github.com/tungstenfabric/tf-operator/pkg/apis/tf/v1alpha1/templates"
"github.com/tungstenfabric/tf-operator/pkg/certificates"
"github.com/tungstenfabric/tf-operator/pkg/k8s"
)
// NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized.
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
const (
RHEL string = "rhel"
CENTOS string = "centos"
UBUNTU string = "ubuntu"
)
// Container defines name, image and command.
// +k8s:openapi-gen=true
type Container struct {
Name string `json:"name,omitempty"`
Image string `json:"image,omitempty"`
Command []string `json:"command,omitempty"`
}
// ServiceStatus provides information on the current status of the service.
// +k8s:openapi-gen=true
type ServiceStatus struct {
Name *string `json:"name,omitempty"`
Active *bool `json:"active,omitempty"`
Created *bool `json:"created,omitempty"`
}
// PodConfiguration is the common services struct.
// +k8s:openapi-gen=true
type PodConfiguration struct {
// NodeSelector is a selector which must be true for the pod to fit on a node.
// Selector which must match a node's labels for the pod to be scheduled on that node.
// More info: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/.
// +optional
NodeSelector map[string]string `json:"nodeSelector,omitempty" protobuf:"bytes,7,rep,name=nodeSelector"`
// ImagePullSecrets is an optional list of references to secrets in the same namespace to use for pulling any of the images used by this PodSpec.
ImagePullSecrets []string `json:"imagePullSecrets,omitempty"`
// If specified, the pod's tolerations.
// +optional
Tolerations []corev1.Toleration `json:"tolerations,omitempty" protobuf:"bytes,22,opt,name=tolerations"`
// AuthParameters auth parameters
// +optional
AuthParameters AuthParameters `json:"authParameters,omitempty"`
// Kubernetes Cluster Configuration
// +kubebuilder:validation:Enum=info;debug;warning;error;critical;none
// +optional
LogLevel string `json:"logLevel,omitempty"`
// OS family
// +optional
Distribution *string `json:"distribution,omitempty"`
}
type ClusterNodes struct {
AnalyticsNodes string
AnalyticsDBNodes string
AnalyticsAlarmNodes string
AnalyticsSnmpNodes string
ConfigNodes string
ControlNodes string
}
var ZiuKindsNoVrouterCNI = []string{
"Config",
"Analytics",
"AnalyticsAlarm",
"AnalyticsSnmp",
"Redis",
"QueryEngine",
"Cassandra",
"Zookeeper",
"Rabbitmq",
"Control",
"Webui",
}
var ZiuKindsAll = append(ZiuKindsNoVrouterCNI, "Kubemanager")
// Establishes ZIU staging
var ZiuKinds []string
var ZiuRestartTime, _ = time.ParseDuration("20s")
// IntrospectionListenAddress returns listen address for instrospection
func (cc *PodConfiguration) IntrospectionListenAddress(addr string) string {
if IntrospectListenAll {
return "0.0.0.0"
}
return addr
}
func CmpConfigMaps(first, second *corev1.ConfigMap) bool {
if first.Data == nil {
first.Data = map[string]string{}
}
if second.Data == nil {
second.Data = map[string]string{}
}
return reflect.DeepEqual(first.Data, second.Data)
}
func (ss *ServiceStatus) ready() bool {
if ss == nil {
return false
}
if ss.Active == nil {
return false
}
return *ss.Active
}
// ensureSecret creates Secret for a service account
func ensureSecret(serviceAccountName, secretName string,
client client.Client,
scheme *runtime.Scheme,
owner v1.Object) error {
namespace := owner.GetNamespace()
existingSecret := &corev1.Secret{}
err := client.Get(context.TODO(), types.NamespacedName{Name: secretName, Namespace: namespace}, existingSecret)
if err != nil && !k8serrors.IsNotFound(err) {
return err
}
secret := &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: secretName,
Namespace: namespace,
Annotations: map[string]string{
"kubernetes.io/service-account.name": serviceAccountName,
},
},
Type: corev1.SecretType("kubernetes.io/service-account-token"),
}
err = controllerutil.SetControllerReference(owner, secret, scheme)
if err != nil {
return err
}
return client.Create(context.TODO(), secret)
}
// ensureClusterRole creates ClusterRole
func ensureClusterRole(clusterRoleName string,
client client.Client,
scheme *runtime.Scheme,
owner v1.Object) error {
existingClusterRole := &rbacv1.ClusterRole{}
err := client.Get(context.TODO(), types.NamespacedName{Name: clusterRoleName}, existingClusterRole)
if err != nil && !k8serrors.IsNotFound(err) {
return err
}
namespace := owner.GetNamespace()
clusterRole := &rbacv1.ClusterRole{
TypeMeta: metav1.TypeMeta{
APIVersion: "rbac/v1",
Kind: "ClusterRole",
},
ObjectMeta: metav1.ObjectMeta{
Name: clusterRoleName,
Namespace: namespace,
},
Rules: []rbacv1.PolicyRule{{
Verbs: []string{
"*",
},
APIGroups: []string{
"*",
},
Resources: []string{
"*",
},
}},
}
return client.Create(context.TODO(), clusterRole)
}
// ensureClusterRoleBinding creates ClusterRole binding
func ensureClusterRoleBinding(
serviceAccountName, clusterRoleName, clusterRoleBindingName string,
client client.Client,
scheme *runtime.Scheme,
owner v1.Object) error {
namespace := owner.GetNamespace()
existingClusterRoleBinding := &rbacv1.ClusterRoleBinding{}
err := client.Get(context.TODO(), types.NamespacedName{Name: clusterRoleBindingName}, existingClusterRoleBinding)
if err != nil && !k8serrors.IsNotFound(err) {
return err
}
clusterRoleBinding := &rbacv1.ClusterRoleBinding{
TypeMeta: metav1.TypeMeta{
APIVersion: "rbac/v1",
Kind: "ClusterRoleBinding",
},
ObjectMeta: metav1.ObjectMeta{
Name: clusterRoleBindingName,
Namespace: namespace,
},
Subjects: []rbacv1.Subject{{
Kind: "ServiceAccount",
Name: serviceAccountName,
Namespace: namespace,
}},
RoleRef: rbacv1.RoleRef{
APIGroup: "rbac.authorization.k8s.io",
Kind: "ClusterRole",
Name: clusterRoleName,
},
}
return client.Create(context.TODO(), clusterRoleBinding)
}
// ensureServiceAccount creates ServiceAccoung, Secret, ClusterRole and ClusterRoleBinding objects
func ensureServiceAccount(
serviceAccountName string,
clusterRoleName string,
clusterRoleBindingName string,
secretName string,
imagePullSecret []string,
client client.Client,
scheme *runtime.Scheme,
owner v1.Object) error {
if err := ensureSecret(serviceAccountName, secretName, client, scheme, owner); err != nil {
return nil
}
namespace := owner.GetNamespace()
existingServiceAccount := &corev1.ServiceAccount{}
err := client.Get(context.TODO(), types.NamespacedName{Name: serviceAccountName, Namespace: namespace}, existingServiceAccount)
if err != nil && k8serrors.IsNotFound(err) {
serviceAccount := &corev1.ServiceAccount{
TypeMeta: metav1.TypeMeta{
APIVersion: "v1",
Kind: "ServiceAccount",
},
ObjectMeta: metav1.ObjectMeta{
Name: serviceAccountName,
Namespace: namespace,
},
}
serviceAccount.Secrets = append(serviceAccount.Secrets,
corev1.ObjectReference{
Kind: "Secret",
Namespace: namespace,
Name: secretName})
for _, name := range imagePullSecret {
serviceAccount.ImagePullSecrets = append(serviceAccount.ImagePullSecrets,
corev1.LocalObjectReference{Name: name})
}
err = controllerutil.SetControllerReference(owner, serviceAccount, scheme)
if err != nil {
return err
}
if err = client.Create(context.TODO(), serviceAccount); err != nil && !k8serrors.IsAlreadyExists(err) {
return err
}
}
if err := ensureClusterRole(clusterRoleName, client, scheme, owner); err != nil {
return nil
}
if err := ensureClusterRoleBinding(serviceAccountName, clusterRoleName, clusterRoleName, client, scheme, owner); err != nil {
return nil
}
return nil
}
// EnsureServiceAccount prepares the intended podList.
func EnsureServiceAccount(spec *corev1.PodSpec,
instanceType string,
imagePullSecret []string,
client client.Client,
request reconcile.Request,
scheme *runtime.Scheme,
object v1.Object) error {
baseName := request.Name + "-" + instanceType + "-"
serviceAccountName := baseName + "service-account"
err := ensureServiceAccount(
serviceAccountName,
baseName+"role",
baseName+"role-binding",
baseName+"secret",
imagePullSecret,
client, scheme, object)
if err != nil {
log.Error(err, "EnsureServiceAccount failed")
return err
}
spec.ServiceAccountName = serviceAccountName
return nil
}
// +k8s:deepcopy-gen=false
type podAltIPsRetriver func(pod corev1.Pod) []string
// PodAlternativeIPs alternative IPs list for cert alt names subject
// +k8s:deepcopy-gen=false
type PodAlternativeIPs struct {
// Function which operate over pod object
// to retrieve additional IP addresses used
// by this pod.
Retriever podAltIPsRetriver
// ServiceIP through which pod can be reached.
ServiceIP string
}
// Retrieve and add hostname from data subnet
func _addAltHostname(pod corev1.Pod, instanceType string, altNames []string) []string {
if cidr, isSet := pod.Annotations["dataSubnet"]; isSet {
altName, err := GetHostname(&pod, instanceType, cidr)
if err == nil && altName != "" {
for _, name := range altNames {
if name == altName {
return altNames
}
}
altNames = append(altNames, altName)
}
}
return altNames
}
// PodsCertSubjects iterates over passed list of pods and for every pod prepares certificate subject
// which can be later used for generating certificate for given pod.
func PodsCertSubjects(domain string, podList []corev1.Pod, podAltIPs PodAlternativeIPs, clientAuth bool, instanceType string) []certificates.CertificateSubject {
var pods []certificates.CertificateSubject
var osName string
if hn, err := os.Hostname(); err != nil && hn != "" {
osName = hn
}
for _, pod := range podList {
var alternativeIPs []string
if podAltIPs.ServiceIP != "" {
alternativeIPs = append(alternativeIPs, podAltIPs.ServiceIP)
}
if podAltIPs.Retriever != nil {
if altIPs := podAltIPs.Retriever(pod); len(altIPs) > 0 {
for _, v := range altIPs {
if v != pod.Status.PodIP {
alternativeIPs = append(alternativeIPs, v)
}
}
}
}
altNames := []string{
pod.Spec.NodeName,
pod.Annotations["hostname"],
}
if osName != "" {
altNames = append(altNames, osName)
}
if instanceType == "control" || instanceType == "vrouter" {
altNames = _addAltHostname(pod, instanceType, altNames)
}
podInfo := certificates.NewSubject(pod.Name, domain, pod.Spec.NodeName,
pod.Status.PodIP, alternativeIPs, altNames, clientAuth)
pods = append(pods, podInfo)
}
return pods
}
// GetConfigMap creates a config map based on the instance type.
func GetConfigMap(name, ns string, client client.Client) (*corev1.ConfigMap, error) {
configMap := &corev1.ConfigMap{}
err := client.Get(context.TODO(), types.NamespacedName{Name: name, Namespace: ns}, configMap)
return configMap, err
}
func prepConfigData(instanceType string, data map[string]string, configMap *corev1.ConfigMap) {
if configMap.Data == nil {
configMap.Data = make(map[string]string)
}
for k, v := range data {
configMap.Data[k] = v
}
configMap.Data["run-provisioner.sh"] = ProvisionerRunnerData(instanceType + "-provisioner")
configMap.Data["run-nodemanager.sh"] = NodemanagerStartupScript()
}
// CreateConfigMap creates a config map based on the instance type.
func CreateConfigMap(
configMapName string,
client client.Client,
scheme *runtime.Scheme,
request reconcile.Request,
instanceType string,
data map[string]string,
object v1.Object) (*corev1.ConfigMap, error) {
configMap, err := GetConfigMap(configMapName, request.Namespace, client)
if err == nil {
prepConfigData(instanceType, data, configMap)
return configMap, client.Update(context.TODO(), configMap)
}
if !k8serrors.IsNotFound(err) {
return nil, err
}
// TODO: Bug. If config map exists without labels and references, they won't be updated
configMap.SetName(configMapName)
configMap.SetNamespace(request.Namespace)
configMap.SetLabels(map[string]string{"tf_manager": instanceType, instanceType: request.Name})
prepConfigData(instanceType, data, configMap)
if err = controllerutil.SetControllerReference(object, configMap, scheme); err != nil {
return nil, err
}
if err = client.Create(context.TODO(), configMap); err != nil && !k8serrors.IsAlreadyExists(err) {
return nil, err
}
return configMap, nil
}
// CreateSecretEx creates a secret based on the instance type.
func CreateSecretEx(secretName string,
client client.Client,
scheme *runtime.Scheme,
request reconcile.Request,
instanceType string,
data map[string][]byte,
object v1.Object) (*corev1.Secret, error) {
secret := &corev1.Secret{}
err := client.Get(context.TODO(), types.NamespacedName{Name: secretName, Namespace: request.Namespace}, secret)
if err != nil {
if k8serrors.IsNotFound(err) {
secret.SetName(secretName)
secret.SetNamespace(request.Namespace)
secret.SetLabels(map[string]string{"tf_manager": instanceType, instanceType: request.Name})
secret.Data = data
if err = controllerutil.SetControllerReference(object, secret, scheme); err != nil {
return nil, err
}
if err = client.Create(context.TODO(), secret); err != nil && !k8serrors.IsAlreadyExists(err) {
return nil, err
}
}
}
return secret, nil
}
func CreateSecret(secretName string,
client client.Client,
scheme *runtime.Scheme,
request reconcile.Request,
instanceType string,
object v1.Object) (*corev1.Secret, error) {
emptyData := make(map[string][]byte)
return CreateSecretEx(secretName, client, scheme, request, instanceType, emptyData, object)
}
// PrepareSTS prepares the intended podList.
func PrepareSTS(sts *appsv1.StatefulSet,
commonConfiguration *PodConfiguration,
instanceType string,
request reconcile.Request,
scheme *runtime.Scheme,
object v1.Object,
usePralallePodManagementPolicy bool) error {
SetSTSCommonConfiguration(sts, commonConfiguration)
if usePralallePodManagementPolicy {
sts.Spec.PodManagementPolicy = appsv1.PodManagementPolicyType("Parallel")
} else {
sts.Spec.PodManagementPolicy = appsv1.PodManagementPolicyType("OrderedReady")
}
baseName := request.Name + "-" + instanceType
name := baseName + "-statefulset"
sts.SetName(name)
sts.SetNamespace(request.Namespace)
labels := map[string]string{"tf_manager": instanceType, instanceType: request.Name}
sts.SetLabels(labels)
sts.Spec.Selector.MatchLabels = labels
sts.Spec.Template.SetLabels(labels)
if err := controllerutil.SetControllerReference(object, sts, scheme); err != nil {
return err
}
return nil
}
// SetDeploymentCommonConfiguration takes common configuration parameters
// and applies it to the deployment.
func SetDeploymentCommonConfiguration(deployment *appsv1.Deployment,
commonConfiguration *PodConfiguration) *appsv1.Deployment {
var replicas = int32(1)
deployment.Spec.Replicas = &replicas
if len(commonConfiguration.Tolerations) > 0 {
deployment.Spec.Template.Spec.Tolerations = commonConfiguration.Tolerations
}
if len(commonConfiguration.NodeSelector) > 0 {
deployment.Spec.Template.Spec.NodeSelector = commonConfiguration.NodeSelector
}
if len(commonConfiguration.ImagePullSecrets) > 0 {
imagePullSecretList := []corev1.LocalObjectReference{}
for _, imagePullSecretName := range commonConfiguration.ImagePullSecrets {
imagePullSecret := corev1.LocalObjectReference{
Name: imagePullSecretName,
}
imagePullSecretList = append(imagePullSecretList, imagePullSecret)
}
deployment.Spec.Template.Spec.ImagePullSecrets = imagePullSecretList
}
return deployment
}
// SetSTSCommonConfiguration takes common configuration parameters
// and applies it to the pod.
func SetSTSCommonConfiguration(sts *appsv1.StatefulSet,
commonConfiguration *PodConfiguration) {
var replicas = int32(1)
sts.Spec.Replicas = &replicas
if len(commonConfiguration.Tolerations) > 0 {
sts.Spec.Template.Spec.Tolerations = commonConfiguration.Tolerations
}
if len(commonConfiguration.NodeSelector) > 0 {
sts.Spec.Template.Spec.NodeSelector = commonConfiguration.NodeSelector
}
if len(commonConfiguration.ImagePullSecrets) > 0 {
imagePullSecretList := []corev1.LocalObjectReference{}
for _, imagePullSecretName := range commonConfiguration.ImagePullSecrets {
imagePullSecret := corev1.LocalObjectReference{
Name: imagePullSecretName,
}
imagePullSecretList = append(imagePullSecretList, imagePullSecret)
}
sts.Spec.Template.Spec.ImagePullSecrets = imagePullSecretList
}
}
func AddVolumesToPodSpec(spec *corev1.PodSpec, volumeConfigMapMap map[string]string) {
volumeList := spec.Volumes
for configMapName, volumeName := range volumeConfigMapMap {
volume := corev1.Volume{
Name: volumeName,
VolumeSource: corev1.VolumeSource{
ConfigMap: &corev1.ConfigMapVolumeSource{
LocalObjectReference: corev1.LocalObjectReference{
Name: configMapName,
},
},
},
}
volumeList = append(volumeList, volume)
}
spec.Volumes = volumeList
}
func AddHostMountsToPodSpec(spec *corev1.PodSpec, volumeConfigMapMap map[string]string) {
volumeList := spec.Volumes
var hostPathType corev1.HostPathType = corev1.HostPathDirectory
for hostPath, volumeName := range volumeConfigMapMap {
volume := corev1.Volume{
Name: volumeName,
VolumeSource: corev1.VolumeSource{
HostPath: &corev1.HostPathVolumeSource{
Path: hostPath,
Type: &hostPathType,
},
},
}
volumeList = append(volumeList, volume)
}
spec.Volumes = volumeList
}
// AddVolumesToIntendedSTS adds volumes to a deployment.
func AddVolumesToIntendedSTS(sts *appsv1.StatefulSet, volumeConfigMapMap map[string]string) {
AddVolumesToPodSpec(&sts.Spec.Template.Spec, volumeConfigMapMap)
}
// AddVolumesToIntendedDS adds volumes to a deployment.
func AddVolumesToIntendedDS(ds *appsv1.DaemonSet, volumeConfigMapMap map[string]string) {
AddVolumesToPodSpec(&ds.Spec.Template.Spec, volumeConfigMapMap)
}
// AddCAVolumeToIntendedSTS adds volumes to a deployment.
func AddCAVolumeToIntendedSTS(sts *appsv1.StatefulSet) {
if certificates.ClientSignerName != certificates.ExternalSigner {
AddVolumesToIntendedSTS(sts, map[string]string{
certificates.CAConfigMapName: "ca-certs",
})
} else {
AddHostMountsToPodSpec(&sts.Spec.Template.Spec, map[string]string{
certificates.ExternalCAHostPath: "ca-certs",
})
}
}
// AddCAVolumeToIntendedDS adds volumes to a deployment.
func AddCAVolumeToIntendedDS(ds *appsv1.DaemonSet) {
if certificates.ClientSignerName != certificates.ExternalSigner {
AddVolumesToIntendedDS(ds, map[string]string{
certificates.CAConfigMapName: "ca-certs",
})
} else {
AddHostMountsToPodSpec(&ds.Spec.Template.Spec, map[string]string{
certificates.ExternalCAHostPath: "ca-certs",
})
}
}
func AddCertsMounts(name string, container *corev1.Container) {
container.VolumeMounts = append(container.VolumeMounts,
corev1.VolumeMount{
Name: "ca-certs",
MountPath: SignerCAMountPath,
ReadOnly: true,
},
)
container.VolumeMounts = append(container.VolumeMounts,
corev1.VolumeMount{
Name: name + "-secret-certificates",
MountPath: "/etc/certificates",
ReadOnly: true,
},
)
}
func SetLogLevelEnv(logLevel string, container *corev1.Container) {
container.Env = append(container.Env, corev1.EnvVar{Name: "LOG_LEVEL", Value: ConvertLogLevel(logLevel)})
}
func addSecretVolumeToPopSpec(spec *corev1.PodSpec, name string) {
n := name + "-secret-certificates"
if certificates.ClientSignerName != certificates.ExternalSigner {
volume := corev1.Volume{
Name: n,
VolumeSource: corev1.VolumeSource{
Secret: &corev1.SecretVolumeSource{
SecretName: n,
},
},
}
spec.Volumes = append(spec.Volumes, volume)
} else {
AddHostMountsToPodSpec(spec, map[string]string{
certificates.ExternalCertHostPath: n,
})
}
}
// AddSecretVolumesToIntendedSTS adds volumes to a deployment.
func AddSecretVolumesToIntendedSTS(sts *appsv1.StatefulSet, name string) {
addSecretVolumeToPopSpec(&sts.Spec.Template.Spec, name)
}
// AddSecretVolumesToIntendedDS adds volumes to a deployment.
func AddSecretVolumesToIntendedDS(ds *appsv1.DaemonSet, name string) {
addSecretVolumeToPopSpec(&ds.Spec.Template.Spec, name)
}
// QuerySTS queries the STS
func QuerySTS(name string, namespace string, reconcileClient client.Client) (*appsv1.StatefulSet, error) {
sts := &appsv1.StatefulSet{}
err := reconcileClient.Get(context.TODO(), types.NamespacedName{Name: name, Namespace: namespace}, sts)
if err != nil {
return nil, err
}
return sts, nil
}
// CreateServiceSTS creates the service STS, if it is not exists.
func CreateServiceSTS(instance v1.Object,
instanceType string,
sts *appsv1.StatefulSet,
cl client.Client,
) (created bool, err error) {
created, err = false, nil
stsName := instance.GetName() + "-" + instanceType + "-statefulset"
stsNamespace := instance.GetNamespace()
if _, err = QuerySTS(stsName, stsNamespace, cl); err == nil || !k8serrors.IsNotFound(err) {
return
}
var replicas int32
if replicas, err = GetReplicas(cl, sts.Spec.Template.Spec.NodeSelector); err == nil {
sts.Name = stsName
sts.Namespace = stsNamespace
sts.Spec.Replicas = &replicas
if err = cl.Create(context.TODO(), sts); err == nil {
created = true
}
}
return
}
func _contains(name string, containers []corev1.Container) bool {
for _, c := range containers {
if name == c.Name {
return true
}
}
return false
}
func _diff(first, second []corev1.Container) (added []string, deleted []string) {
added = []string{}
deleted = []string{}
for _, c := range first {
if !_contains(c.Name, second) {
deleted = append(deleted, c.Name)
}
}
for _, c := range second {
if !_contains(c.Name, first) {
added = append(added, c.Name)
}
}
return
}
func _containersChanged(first []corev1.Container,
second []corev1.Container,
) (changed bool) {
logger := log.WithName("containerDiff")
for _, container1 := range first {
for _, container2 := range second {
if container1.Name == container2.Name {
if container1.Image != container2.Image {
changed = true
logger.Info("Image changed",
"Container", container1.Name,
"Current Image", container1.Image,
"Intended Image", container2.Image,
)
break
}
sort.SliceStable(
container1.Env,
func(i, j int) bool { return container1.Env[i].Name < container1.Env[j].Name })
sort.SliceStable(
container2.Env,
func(i, j int) bool { return container2.Env[i].Name < container2.Env[j].Name })
if !cmp.Equal(
container1.Env,
container2.Env,
cmpopts.IgnoreFields(corev1.ObjectFieldSelector{}, "APIVersion"),
) {
changed = true
logger.Info("Env changed",
"Container", container1.Name,
"Container Env", container1.Env,
"Intended Env", container2.Env,
)
break
}
}
}
}
return
}
// TODO: Make it more intellectual. Now it's checks only images and envs.
func containersChanged(first *corev1.PodTemplateSpec,
second *corev1.PodTemplateSpec,
) (changed bool) {
changed = false
logger := log.WithName("containersChanged")
// check if same containers
if added, deleted := _diff(first.Spec.Containers, second.Spec.Containers); len(added) != 0 || len(deleted) != 0 {
changed = true
logger.Info("Containers changed",
"Added containers", added,
"Deleted containers", deleted,
)
return
}
// same containers, check images and env variables
if changed = _containersChanged(first.Spec.Containers, second.Spec.Containers); changed {
return
}
changed = _containersChanged(first.Spec.InitContainers, second.Spec.InitContainers)
return
}
// UpdateSafeSTS query existing statefulset and add to it allowed fields.
// Allowed fileds are template, replicas and updateStrategy (k8s restrinction).
// Template will be updated just in case when some container images or container env changed (or use force).
// Nil values to leave fields unchanged.
func UpdateSTS(stsName string,
instanceType string,
namespace string,
template *corev1.PodTemplateSpec,
strategy *appsv1.StatefulSetUpdateStrategy,
force bool,
cl client.Client,
) (updated bool, err error) {
name := stsName + "-" + instanceType + "-statefulset"
updated, err = false, nil
logger := log.WithName("UpdateSTS").WithName(name)
sts, err := QuerySTS(name, namespace, cl)
if sts == nil || err != nil {
logger.Error(err, "Failed to get the stateful set",
"Name", name,
"Namespace", namespace,
)
return
}
changed := false
if force || containersChanged(&sts.Spec.Template, template) {
logger.Info("Some of container images or env changed, or force mode", "force", force)
changed = true
sts.Spec.Template = *template
}
if !changed && !cmp.Equal(sts.Spec.Template.Spec.NodeSelector, template.Spec.NodeSelector) {
sts.Spec.Template.Spec.NodeSelector = template.Spec.NodeSelector
logger.Info("nodeSelector changed")
changed = true
}
replicas, err := GetReplicas(cl, template.Spec.NodeSelector)
if err != nil {
return
}
if replicas != *sts.Spec.Replicas {
if replicas < *sts.Spec.Replicas {
logger.Info("To reduce replicas delete STS manually", "Current", *sts.Spec.Replicas, "Intended", replicas)
} else {
logger.Info("Replicas changed", "Current", *sts.Spec.Replicas, "Intended", replicas)
changed = true
sts.Spec.Replicas = &replicas
}
}
if strategy != nil && !reflect.DeepEqual(strategy, &sts.Spec.UpdateStrategy) {
logger.Info("Update strategy changed")
changed = true
sts.Spec.UpdateStrategy = *strategy
}
if !changed {
return
}
sts.Spec.Template.Labels["change-at"] = time.Now().Format("2006-01-02-15-04-05")
if err = cl.Update(context.TODO(), sts); err != nil {
return
}
if sts.Spec.UpdateStrategy.Type == appsv1.OnDeleteStatefulSetStrategyType {
logger.Info("Update OnDelete strategy")
opts := &client.DeleteAllOfOptions{}
opts.Namespace = namespace
opts.LabelSelector = labelSelector(stsName, instanceType)
pod := &corev1.Pod{}
if err = cl.DeleteAllOf(context.TODO(), pod, opts); err != nil {
return
}
}
logger.Info("Update done")
updated = true
return
}
func RollingUpdateStrategy() *appsv1.StatefulSetUpdateStrategy {
zero := int32(0)
return &appsv1.StatefulSetUpdateStrategy{
Type: appsv1.RollingUpdateStatefulSetStrategyType,
RollingUpdate: &appsv1.RollingUpdateStatefulSetStrategy{
Partition: &zero,
},
}
}
// UpdateServiceSTS safe update for service statefulsets
func UpdateServiceSTS(instance v1.Object,
instanceType string,
sts *appsv1.StatefulSet,
force bool,
clnt client.Client,
) (updated bool, err error) {
stsName := instance.GetName()
stsNamespace := instance.GetNamespace()
stsTemplate := sts.Spec.Template
updated, err = UpdateSTS(stsName, instanceType, stsNamespace, &stsTemplate, &sts.Spec.UpdateStrategy, force, clnt)
return
}
// SetInstanceActive sets the instance to active.
func SetInstanceActive(client client.Client, activeStatus *bool, degradedStatus *bool, sts *appsv1.StatefulSet, request reconcile.Request, object runtime.Object) error {
if err := client.Get(context.TODO(), types.NamespacedName{Name: sts.Name, Namespace: request.Namespace},
sts); err != nil {
return err
}
active := false
if sts.Status.ReadyReplicas == *sts.Spec.Replicas {
active = true
}
degraded := sts.Status.ReadyReplicas < *sts.Spec.Replicas
*activeStatus = active
*degradedStatus = degraded
if err := client.Status().Update(context.TODO(), object); err != nil {
return err
}
return nil
}
func GetPodsHostname(c client.Client, pod *corev1.Pod) (string, error) {
n := corev1.Node{}
if err := c.Get(context.Background(), types.NamespacedName{Name: pod.Spec.NodeName}, &n); err != nil {
return "", err
}
for _, a := range n.Status.Addresses {
if a.Type == corev1.NodeHostName {
// TODO: until moved to latest operator framework FQDN for pod is not available
// so, artificially use FQDN based on host domain
// TODO: commonize things between pods
dnsDomain, err := ClusterDNSDomain(c)
if err != nil || dnsDomain == "" || strings.HasSuffix(a.Address, dnsDomain) {
return a.Address, nil
}
return a.Address + "." + dnsDomain, nil
}
}
return "", errors.New("couldn't get pods hostname")
}
// UpdateAnnotations add hostname to annotation for pod.
func UpdatePodAnnotations(pod *corev1.Pod, client client.Client) (updated bool, err error) {
updated = false
err = nil
annotationMap := pod.GetAnnotations()
if annotationMap == nil {
annotationMap = make(map[string]string)
}
hostname, err := GetPodsHostname(client, pod)
if err != nil {
return
}
hostnameFromAnnotation, ok := annotationMap["hostname"]
if !ok || hostnameFromAnnotation != hostname {
annotationMap["hostname"] = hostname
pod.SetAnnotations(annotationMap)
if err = client.Update(context.TODO(), pod); err != nil {
return
}
updated = true
return
}
return