-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathutil.go
More file actions
782 lines (672 loc) · 22.2 KB
/
util.go
File metadata and controls
782 lines (672 loc) · 22.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
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
package cluster
import (
"bytes"
"context"
"encoding/gob"
"encoding/json"
"fmt"
"net/http"
"reflect"
"sort"
"strings"
"time"
appsv1 "k8s.io/api/apps/v1"
v1 "k8s.io/api/core/v1"
policyv1 "k8s.io/api/policy/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
acidzalando "github.com/cybertec-postgresql/cybertec-pg-operator/pkg/apis/cpo.opensource.cybertec.at"
cpov1 "github.com/cybertec-postgresql/cybertec-pg-operator/pkg/apis/cpo.opensource.cybertec.at/v1"
"github.com/cybertec-postgresql/cybertec-pg-operator/pkg/spec"
"github.com/cybertec-postgresql/cybertec-pg-operator/pkg/util"
"github.com/cybertec-postgresql/cybertec-pg-operator/pkg/util/constants"
"github.com/cybertec-postgresql/cybertec-pg-operator/pkg/util/k8sutil"
"github.com/cybertec-postgresql/cybertec-pg-operator/pkg/util/nicediff"
"github.com/cybertec-postgresql/cybertec-pg-operator/pkg/util/retryutil"
"github.com/sirupsen/logrus"
)
// OAuthTokenGetter provides the method for fetching OAuth tokens
type OAuthTokenGetter interface {
getOAuthToken() (string, error)
}
// SecretOauthTokenGetter enables fetching OAuth tokens by reading Kubernetes secrets
type SecretOauthTokenGetter struct {
kubeClient *k8sutil.KubernetesClient
OAuthTokenSecretName spec.NamespacedName
}
type PodType string
const (
TYPE_POSTGRESQL = PodType("postgresql")
TYPE_REPOSITORY = PodType("repo-host")
TYPE_BACKUP_JOB = PodType("backup-job")
TYPE_LOGICAL_BACKUP = PodType("logical-backup")
TYPE_POOLER = PodType("pooler")
)
func newSecretOauthTokenGetter(kubeClient *k8sutil.KubernetesClient,
OAuthTokenSecretName spec.NamespacedName) *SecretOauthTokenGetter {
return &SecretOauthTokenGetter{kubeClient, OAuthTokenSecretName}
}
func (g *SecretOauthTokenGetter) getOAuthToken() (string, error) {
//TODO: we can move this function to the Controller in case it will be needed there. As for now we use it only in the Cluster
// Temporary getting postgresql-operator secret from the NamespaceDefault
credentialsSecret, err := g.kubeClient.
Secrets(g.OAuthTokenSecretName.Namespace).
Get(context.TODO(), g.OAuthTokenSecretName.Name, metav1.GetOptions{})
if err != nil {
return "", fmt.Errorf("could not get credentials secret: %v", err)
}
data := credentialsSecret.Data
if string(data["read-only-token-type"]) != "Bearer" {
return "", fmt.Errorf("wrong token type: %v", data["read-only-token-type"])
}
return string(data["read-only-token-secret"]), nil
}
func isValidUsername(username string) bool {
return userRegexp.MatchString(username)
}
func (c *Cluster) isProtectedUsername(username string) bool {
for _, protected := range c.OpConfig.ProtectedRoles {
if username == protected {
return true
}
}
return false
}
func (c *Cluster) isSystemUsername(username string) bool {
// is there a pooler system user defined
for _, systemUser := range c.systemUsers {
if username == systemUser.Name {
return true
}
}
return false
}
func isValidFlag(flag string) bool {
for _, validFlag := range []string{constants.RoleFlagSuperuser, constants.RoleFlagLogin, constants.RoleFlagCreateDB,
constants.RoleFlagInherit, constants.RoleFlagReplication, constants.RoleFlagByPassRLS,
constants.RoleFlagCreateRole} {
if flag == validFlag || flag == "NO"+validFlag {
return true
}
}
return false
}
func invertFlag(flag string) string {
if flag[:2] == "NO" {
return flag[2:]
}
return "NO" + flag
}
func normalizeUserFlags(userFlags []string) ([]string, error) {
uniqueFlags := make(map[string]bool)
addLogin := true
for _, flag := range userFlags {
if !alphaNumericRegexp.MatchString(flag) {
return nil, fmt.Errorf("user flag %q is not alphanumeric", flag)
}
flag = strings.ToUpper(flag)
if _, ok := uniqueFlags[flag]; !ok {
if !isValidFlag(flag) {
return nil, fmt.Errorf("user flag %q is not valid", flag)
}
invFlag := invertFlag(flag)
if uniqueFlags[invFlag] {
return nil, fmt.Errorf("conflicting user flags: %q and %q", flag, invFlag)
}
uniqueFlags[flag] = true
}
}
flags := []string{}
for k := range uniqueFlags {
if k == constants.RoleFlagNoLogin || k == constants.RoleFlagLogin {
addLogin = false
if k == constants.RoleFlagNoLogin {
// we don't add NOLOGIN to the list of flags to be consistent with what we get
// from the readPgUsersFromDatabase in SyncUsers
continue
}
}
flags = append(flags, k)
}
if addLogin {
flags = append(flags, constants.RoleFlagLogin)
}
sort.Strings(flags)
return flags, nil
}
// specPatch produces a JSON of the Kubernetes object specification passed (typically service or
// statefulset) to use it in a MergePatch.
func specPatch(spec interface{}) ([]byte, error) {
return json.Marshal(struct {
Spec interface{} `json:"spec"`
}{spec})
}
func dataPatch(data interface{}) ([]byte, error) {
return json.Marshal(struct {
Data interface{} `json:"data"`
}{data})
}
// metaAnnotationsPatch produces a JSON of the object metadata that has only the annotation
// field in order to use it in a MergePatch. Note that we don't patch the complete metadata, since
// it contains the current revision of the object that could be outdated at the time we patch.
func metaAnnotationsPatch(annotations map[string]string) ([]byte, error) {
var meta metav1.ObjectMeta
meta.Annotations = annotations
return json.Marshal(struct {
ObjMeta interface{} `json:"metadata"`
}{&meta})
}
func (c *Cluster) logPDBChanges(old, new *policyv1.PodDisruptionBudget, isUpdate bool, reason string) {
if isUpdate {
c.logger.Infof("pod disruption budget %q has been changed", util.NameFromMeta(old.ObjectMeta))
} else {
c.logger.Infof("pod disruption budget %q is not in the desired state and needs to be updated",
util.NameFromMeta(old.ObjectMeta),
)
}
logNiceDiff(c.logger, old.Spec, new.Spec)
}
func logNiceDiff(log *logrus.Entry, old, new interface{}) {
o, erro := json.MarshalIndent(old, "", " ")
n, errn := json.MarshalIndent(new, "", " ")
if erro != nil || errn != nil {
panic("could not marshal API objects, should not happen")
}
nice := nicediff.Diff(string(o), string(n), true)
for _, s := range strings.Split(nice, "\n") {
// " is not needed in the value to understand
log.Debugf(strings.ReplaceAll(s, "\"", ""))
}
}
func (c *Cluster) logStatefulSetChanges(old, new *appsv1.StatefulSet, isUpdate bool, reasons []string) {
if isUpdate {
c.logger.Infof("statefulset %s has been changed", util.NameFromMeta(old.ObjectMeta))
} else {
c.logger.Infof("statefulset %s is not in the desired state and needs to be updated",
util.NameFromMeta(old.ObjectMeta),
)
}
logNiceDiff(c.logger, old.Spec, new.Spec)
if !reflect.DeepEqual(old.Annotations, new.Annotations) {
c.logger.Debugf("metadata.annotation are different")
logNiceDiff(c.logger, old.Annotations, new.Annotations)
}
if len(reasons) > 0 {
for _, reason := range reasons {
c.logger.Infof("reason: %s", reason)
}
}
}
func (c *Cluster) logServiceChanges(role PostgresRole, old, new *v1.Service, isUpdate bool, reason string) {
if isUpdate {
c.logger.Infof("%s service %s has been changed",
role, util.NameFromMeta(old.ObjectMeta),
)
} else {
c.logger.Infof("%s service %s is not in the desired state and needs to be updated",
role, util.NameFromMeta(old.ObjectMeta),
)
}
logNiceDiff(c.logger, old.Spec, new.Spec)
if reason != "" {
c.logger.Infof("reason: %s", reason)
}
}
func getPostgresContainer(podSpec *v1.PodSpec) (pgContainer v1.Container) {
for _, container := range podSpec.Containers {
if container.Name == constants.PostgresContainerName {
pgContainer = container
}
}
// if no postgres container was found, take the first one in the podSpec
if reflect.DeepEqual(pgContainer, v1.Container{}) && len(podSpec.Containers) > 0 {
pgContainer = podSpec.Containers[0]
}
return pgContainer
}
func (c *Cluster) getTeamMembers(teamID string) ([]string, error) {
if teamID == "" {
msg := "no teamId specified"
if c.OpConfig.EnableTeamIdClusternamePrefix {
return nil, fmt.Errorf(msg)
}
c.logger.Warnf(msg)
return nil, nil
}
members := []string{}
if c.OpConfig.EnablePostgresTeamCRD && c.Config.PgTeamMap != nil {
c.logger.Debugf("fetching possible additional team members for team %q", teamID)
additionalMembers := []string{}
for team, membership := range *c.Config.PgTeamMap {
if team == teamID {
additionalMembers = membership.AdditionalMembers
c.logger.Debugf("found %d additional members for team %q", len(additionalMembers), teamID)
}
}
members = append(members, additionalMembers...)
}
if !c.OpConfig.EnableTeamsAPI {
c.logger.Debugf("team API is disabled")
return members, nil
}
token, err := c.oauthTokenGetter.getOAuthToken()
if err != nil {
return nil, fmt.Errorf("could not get oauth token to authenticate to team service API: %v", err)
}
teamInfo, statusCode, err := c.teamsAPIClient.TeamInfo(teamID, token)
if err != nil {
if statusCode == http.StatusNotFound {
c.logger.Warningf("could not get team info for team %q: %v", teamID, err)
} else {
return nil, fmt.Errorf("could not get team info for team %q: %v", teamID, err)
}
} else {
for _, member := range teamInfo.Members {
if !(util.SliceContains(members, member)) {
members = append(members, member)
}
}
}
return members, nil
}
// Returns annotations to be passed to child objects
func (c *Cluster) annotationsSet(annotations map[string]string) map[string]string {
if annotations == nil {
annotations = make(map[string]string)
}
pgCRDAnnotations := c.ObjectMeta.Annotations
// allow to inherit certain labels from the 'postgres' object
for k, v := range pgCRDAnnotations {
for _, match := range c.OpConfig.InheritedAnnotations {
if k == match {
annotations[k] = v
}
}
}
if len(annotations) > 0 {
return annotations
}
return nil
}
func (c *Cluster) waitForPodLabel(podEvents chan PodEvent, stopCh chan struct{}, role *PostgresRole) (*v1.Pod, error) {
timeout := time.After(c.OpConfig.PodLabelWaitTimeout)
for {
select {
case podEvent := <-podEvents:
podRole := PostgresRole(podEvent.CurPod.Labels[c.OpConfig.PodRoleLabel])
if role == nil {
if podRole == Master || podRole == Replica {
return podEvent.CurPod, nil
}
} else if *role == podRole {
return podEvent.CurPod, nil
}
case <-timeout:
return nil, fmt.Errorf("pod label wait timeout")
case <-stopCh:
return nil, fmt.Errorf("pod label wait cancelled")
}
}
}
func (c *Cluster) waitForPodMasterLabel(podName spec.NamespacedName) error {
stopCh := make(chan struct{})
ch := c.registerPodSubscriber(podName)
defer c.unregisterPodSubscriber(podName)
defer close(stopCh)
role := Master
_, err := c.waitForPodLabel(ch, stopCh, &role)
if err != nil {
return err
}
return nil
}
func (c *Cluster) waitForPodDeletion(podEvents chan PodEvent) error {
timeout := time.After(c.OpConfig.PodDeletionWaitTimeout)
for {
select {
case podEvent := <-podEvents:
if podEvent.EventType == PodEventDelete {
return nil
}
case <-timeout:
return fmt.Errorf("pod deletion wait timeout")
}
}
}
func (c *Cluster) waitStatefulsetReady() error {
return retryutil.Retry(c.OpConfig.ResourceCheckInterval, c.OpConfig.ResourceCheckTimeout,
func() (bool, error) {
listOptions := metav1.ListOptions{
LabelSelector: c.labelsSetWithType(false, TYPE_POSTGRESQL).String(),
}
ss, err := c.KubeClient.StatefulSets(c.Namespace).List(context.TODO(), listOptions)
if err != nil {
return false, err
}
if len(ss.Items) != 1 {
return false, fmt.Errorf("statefulset is not found")
}
return *ss.Items[0].Spec.Replicas == ss.Items[0].Status.Replicas, nil
})
}
func (c *Cluster) _waitPodLabelsReady(anyReplica bool) error {
var (
podsNumber int
)
ls := c.labelsSetWithType(false, TYPE_POSTGRESQL)
namespace := c.Namespace
listOptions := metav1.ListOptions{
LabelSelector: ls.String(),
}
masterListOption := metav1.ListOptions{
LabelSelector: labels.Merge(ls, labels.Set{
c.OpConfig.PodRoleLabel: string(Master),
}).String(),
}
replicaListOption := metav1.ListOptions{
LabelSelector: labels.Merge(ls, labels.Set{
c.OpConfig.PodRoleLabel: string(Replica),
}).String(),
}
podsNumber = 1
if !anyReplica {
pods, err := c.KubeClient.Pods(namespace).List(context.TODO(), listOptions)
if err != nil {
return err
}
podsNumber = len(pods.Items)
c.logger.Debugf("Waiting for %d pods to become ready", podsNumber)
} else {
c.logger.Debugf("Waiting for any replica pod to become ready")
}
err := retryutil.Retry(c.OpConfig.ResourceCheckInterval, c.OpConfig.ResourceCheckTimeout,
func() (bool, error) {
masterCount := 0
if !anyReplica {
masterPods, err2 := c.KubeClient.Pods(namespace).List(context.TODO(), masterListOption)
if err2 != nil {
return false, err2
}
if len(masterPods.Items) > 1 {
return false, fmt.Errorf("too many masters (%d pods with the master label found)",
len(masterPods.Items))
}
masterCount = len(masterPods.Items)
}
replicaPods, err2 := c.KubeClient.Pods(namespace).List(context.TODO(), replicaListOption)
if err2 != nil {
return false, err2
}
replicaCount := len(replicaPods.Items)
if anyReplica && replicaCount > 0 {
c.logger.Debugf("Found %d running replica pods", replicaCount)
return true, nil
}
return masterCount+replicaCount >= podsNumber, nil
})
return err
}
func (c *Cluster) waitForAnyReplicaLabelReady() error {
return c._waitPodLabelsReady(true)
}
func (c *Cluster) waitForAllPodsLabelReady() error {
return c._waitPodLabelsReady(false)
}
func (c *Cluster) waitStatefulsetPodsReady() error {
c.setProcessName("waiting for the pods of the statefulset")
// TODO: wait for the first Pod only
if err := c.waitStatefulsetReady(); err != nil {
return fmt.Errorf("stateful set error: %v", err)
}
// TODO: wait only for master
if err := c.waitForAllPodsLabelReady(); err != nil {
return fmt.Errorf("pod labels error: %v", err)
}
return nil
}
func (c *Cluster) waitForPrimaryLoadBalancerIp() error {
return retryutil.Retry(c.OpConfig.ResourceCheckInterval, c.OpConfig.ResourceCheckTimeout,
func() (bool, error) {
name := c.serviceName(Master)
svc, err := c.KubeClient.Services(c.Namespace).Get(context.TODO(), name, metav1.GetOptions{})
if err != nil {
return false, err
}
if svc == nil {
return false, fmt.Errorf("primary loadbalancer service is not found")
}
return len(svc.Status.LoadBalancer.Ingress) > 0, nil
})
return nil
}
func (c *Cluster) getPrimaryLoadBalancerIp() (string, error) {
name := c.serviceName(Master)
svc, err := c.KubeClient.Services(c.Namespace).Get(context.TODO(), name, metav1.GetOptions{})
if err != nil {
return "", err
}
if svc == nil {
return "", fmt.Errorf("primary loadbalancer service is not found")
}
if len(svc.Status.LoadBalancer.Ingress) == 0 {
return "", fmt.Errorf("IP is not assigned")
}
ingress := svc.Status.LoadBalancer.Ingress[0]
return util.Coalesce(ingress.Hostname, ingress.IP), nil
}
// Returns labels used to create or list k8s objects such as pods
// For backward compatibility, shouldAddExtraLabels must be false
// when listing k8s objects. See operator PR #252
func (c *Cluster) labelsSet(shouldAddExtraLabels bool) labels.Set {
return c.labelsSetWithType(shouldAddExtraLabels, "")
}
func (c *Cluster) labelsSetWithType(shouldAddExtraLabels bool, typeLabel PodType) labels.Set {
lbls := make(map[string]string)
for k, v := range c.OpConfig.ClusterLabels {
lbls[k] = v
}
lbls[c.OpConfig.ClusterNameLabel] = c.Name
if typeLabel != "" {
lbls["member.cpo.opensource.cybertec.at/type"] = string(typeLabel)
}
if shouldAddExtraLabels {
// enables filtering resources owned by a team
lbls["team"] = c.Postgresql.Spec.TeamID
// allow to inherit certain labels from the 'postgres' object
if spec, err := c.GetSpec(); err == nil {
for k, v := range spec.ObjectMeta.Labels {
for _, match := range c.OpConfig.InheritedLabels {
if k == match {
lbls[k] = v
}
}
}
} else {
c.logger.Warningf("could not get the list of InheritedLabels for cluster %q: %v", c.Name, err)
}
}
return labels.Set(lbls)
}
func (c *Cluster) labelsSelector(typeLabel PodType) *metav1.LabelSelector {
return &metav1.LabelSelector{
MatchLabels: c.labelsSetWithType(false, typeLabel),
MatchExpressions: nil,
}
}
func (c *Cluster) roleLabelsSelector(role PostgresRole) *metav1.LabelSelector {
lbls := c.labelsSetWithType(false, TYPE_POSTGRESQL)
lbls[c.OpConfig.PodRoleLabel] = string(role)
return &metav1.LabelSelector{
MatchLabels: c.labelsSetWithType(false, TYPE_POSTGRESQL),
MatchExpressions: nil,
}
}
func (c *Cluster) roleLabelsSet(shouldAddExtraLabels bool, role PostgresRole) labels.Set {
// Role labels set is only matching database pods
var lbls labels.Set
// Ignore PodRoleLabel for Role ClusterPods
if role != ClusterPods {
lbls = c.labelsSet(shouldAddExtraLabels) //c.labelsSetWithType(shouldAddExtraLabels, TYPE_POSTGRESQL)
lbls[c.OpConfig.PodRoleLabel] = string(role)
} else {
lbls = c.labelsSetWithType(shouldAddExtraLabels, "")
}
return lbls
}
func (c *Cluster) dnsName(role PostgresRole) string {
var dnsString, oldDnsString string
if role == Master {
dnsString = c.masterDNSName(c.Name)
} else {
dnsString = c.replicaDNSName(c.Name)
}
// if cluster name starts with teamID we might need to provide backwards compatibility
clusterNameWithoutTeamPrefix, _ := cpov1.ExtractClusterName(c.Name, c.Spec.TeamID)
if clusterNameWithoutTeamPrefix != "" {
if role == Master {
oldDnsString = c.oldMasterDNSName(clusterNameWithoutTeamPrefix)
} else {
oldDnsString = c.oldReplicaDNSName(clusterNameWithoutTeamPrefix)
}
dnsString = fmt.Sprintf("%s,%s", dnsString, oldDnsString)
}
return dnsString
}
func (c *Cluster) masterDNSName(clusterName string) string {
return strings.ToLower(c.OpConfig.MasterDNSNameFormat.Format(
"cluster", clusterName,
"namespace", c.Namespace,
"team", c.teamName(),
"hostedzone", c.OpConfig.DbHostedZone))
}
func (c *Cluster) replicaDNSName(clusterName string) string {
return strings.ToLower(c.OpConfig.ReplicaDNSNameFormat.Format(
"cluster", clusterName,
"namespace", c.Namespace,
"team", c.teamName(),
"hostedzone", c.OpConfig.DbHostedZone))
}
func (c *Cluster) oldMasterDNSName(clusterName string) string {
return strings.ToLower(c.OpConfig.MasterLegacyDNSNameFormat.Format(
"cluster", clusterName,
"team", c.teamName(),
"hostedzone", c.OpConfig.DbHostedZone))
}
func (c *Cluster) oldReplicaDNSName(clusterName string) string {
return strings.ToLower(c.OpConfig.ReplicaLegacyDNSNameFormat.Format(
"cluster", clusterName,
"team", c.teamName(),
"hostedzone", c.OpConfig.DbHostedZone))
}
func (c *Cluster) credentialSecretName(username string) string {
return c.credentialSecretNameForCluster(username, c.Name)
}
func (c *Cluster) credentialSecretNameForCluster(username string, clusterName string) string {
// secret must consist of lower case alphanumeric characters, '-' or '.',
// and must start and end with an alphanumeric character
return c.OpConfig.SecretNameTemplate.Format(
"username", strings.Replace(username, "_", "-", -1),
"cluster", clusterName,
"tprkind", cpov1.PostgresCRDResourceKind,
"tprgroup", acidzalando.GroupName)
}
func cloneSpec(from *cpov1.Postgresql) (*cpov1.Postgresql, error) {
var (
buf bytes.Buffer
result *cpov1.Postgresql
err error
)
enc := gob.NewEncoder(&buf)
if err = enc.Encode(*from); err != nil {
return nil, fmt.Errorf("could not encode the spec: %v", err)
}
dec := gob.NewDecoder(&buf)
if err = dec.Decode(&result); err != nil {
return nil, fmt.Errorf("could not decode the spec: %v", err)
}
return result, nil
}
func (c *Cluster) setSpec(newSpec *cpov1.Postgresql) {
c.specMu.Lock()
c.Postgresql = *newSpec
c.specMu.Unlock()
}
// GetSpec returns a copy of the operator-side spec of a Postgres cluster in a thread-safe manner
func (c *Cluster) GetSpec() (*cpov1.Postgresql, error) {
c.specMu.RLock()
defer c.specMu.RUnlock()
return cloneSpec(&c.Postgresql)
}
func (c *Cluster) patroniUsesKubernetes() bool {
return c.OpConfig.EtcdHost == ""
}
func (c *Cluster) patroniKubernetesUseConfigMaps() bool {
if !c.patroniUsesKubernetes() {
return false
}
// otherwise, follow the operator configuration
return c.OpConfig.KubernetesUseConfigMaps
}
// Earlier arguments take priority
func mergeContainers(containers ...[]v1.Container) ([]v1.Container, []string) {
containerNameTaken := map[string]bool{}
result := make([]v1.Container, 0)
conflicts := make([]string, 0)
for _, containerArray := range containers {
for _, container := range containerArray {
if _, taken := containerNameTaken[container.Name]; taken {
conflicts = append(conflicts, container.Name)
} else {
containerNameTaken[container.Name] = true
result = append(result, container)
}
}
}
return result, conflicts
}
func trimCronjobName(name string) string {
maxLength := 52
if len(name) > maxLength {
name = name[0:maxLength]
name = strings.TrimRight(name, "-")
}
return name
}
func parseResourceRequirements(resourcesRequirement v1.ResourceRequirements) (cpov1.Resources, error) {
var resources cpov1.Resources
resourcesJSON, err := json.Marshal(resourcesRequirement)
if err != nil {
return cpov1.Resources{}, fmt.Errorf("could not marshal K8s resources requirements")
}
if err = json.Unmarshal(resourcesJSON, &resources); err != nil {
return cpov1.Resources{}, fmt.Errorf("could not unmarshal K8s resources requirements into cpov1.Resources struct")
}
return resources, nil
}
func (c *Cluster) multisiteEnabled() bool {
var enable *bool
if c.Spec.Multisite != nil {
enable = util.CoalesceBool(c.Spec.Multisite.Enable, c.OpConfig.Multisite.Enable)
} else {
enable = c.OpConfig.Multisite.Enable
}
return enable != nil && *enable
}
func isInMaintenanceWindow(specMaintenanceWindows []cpov1.MaintenanceWindow) bool {
if len(specMaintenanceWindows) == 0 {
return true
}
now := time.Now()
currentDay := now.Weekday()
currentTime := now.Format("15:04")
for _, window := range specMaintenanceWindows {
startTime := window.StartTime.Format("15:04")
endTime := window.EndTime.Format("15:04")
if window.Everyday || window.Weekday == currentDay {
if currentTime >= startTime && currentTime <= endTime {
return true
}
}
}
return false
}