-
Notifications
You must be signed in to change notification settings - Fork 50
/
pgclustercontroller.go
1092 lines (926 loc) · 38.5 KB
/
pgclustercontroller.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 pgcluster
/*
Copyright 2017 - 2021 Crunchy Data Solutions, Inc.
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.
*/
import (
"context"
"encoding/json"
"fmt"
"reflect"
"strconv"
"strings"
"github.com/percona/percona-postgresql-operator/internal/config"
"github.com/percona/percona-postgresql-operator/internal/kubeapi"
"github.com/percona/percona-postgresql-operator/internal/operator"
backrestoperator "github.com/percona/percona-postgresql-operator/internal/operator/backrest"
clusteroperator "github.com/percona/percona-postgresql-operator/internal/operator/cluster"
"github.com/percona/percona-postgresql-operator/internal/operator/pvc"
"github.com/percona/percona-postgresql-operator/internal/util"
crv1 "github.com/percona/percona-postgresql-operator/pkg/apis/crunchydata.com/v1"
informers "github.com/percona/percona-postgresql-operator/pkg/generated/informers/externalversions/crunchydata.com/v1"
log "github.com/sirupsen/logrus"
appsv1 "k8s.io/api/apps/v1"
kerrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/util/workqueue"
)
// Controller holds the connections for the controller
type Controller struct {
Client *kubeapi.Client
Queue workqueue.RateLimitingInterface
Informer informers.PgclusterInformer
PgclusterWorkerCount int
}
// onAdd is called when a pgcluster is added
func (c *Controller) onAdd(obj interface{}) {
key, err := cache.MetaNamespaceKeyFunc(obj)
if err == nil {
log.Debugf("cluster putting key in queue %s", key)
c.Queue.Add(key)
}
}
// RunWorker is a long-running function that will continually call the
// processNextWorkItem function in order to read and process a message on the
// workqueue.
func (c *Controller) RunWorker(stopCh <-chan struct{}, doneCh chan<- struct{}) {
go c.waitForShutdown(stopCh)
for c.processNextItem() {
}
log.Debug("pgcluster Contoller: worker queue has been shutdown, writing to the done channel")
doneCh <- struct{}{}
}
// waitForShutdown waits for a message on the stop channel and then shuts down the work queue
func (c *Controller) waitForShutdown(stopCh <-chan struct{}) {
<-stopCh
c.Queue.ShutDown()
log.Debug("pgcluster Contoller: received stop signal, worker queue told to shutdown")
}
func (c *Controller) processNextItem() bool {
ctx := context.TODO()
// Wait until there is a new item in the working queue
key, quit := c.Queue.Get()
if quit {
return false
}
log.Debugf("working on %s", key.(string))
keyParts := strings.Split(key.(string), "/")
keyNamespace := keyParts[0]
keyResourceName := keyParts[1]
log.Debugf("cluster add queue got key ns=[%s] resource=[%s]", keyNamespace, keyResourceName)
// Tell the queue that we are done with processing this key. This unblocks the key for other workers
// This allows safe parallel processing because two pods with the same key are never processed in
// parallel.
defer c.Queue.Done(key)
// get the pgcluster
cluster, err := c.Client.CrunchydataV1().Pgclusters(keyNamespace).Get(ctx, keyResourceName, metav1.GetOptions{})
if err != nil {
log.Debugf("cluster add - pgcluster not found, this is invalid")
c.Queue.Forget(key) // NB(cbandy): This should probably be a retry.
return true
}
log.Debugf("[pgcluster Controller] ns %s onAdd %s", cluster.ObjectMeta.Namespace, cluster.ObjectMeta.SelfLink)
if cluster.Spec.Status == crv1.CompletedStatus ||
cluster.Status.State == crv1.PgclusterStateBootstrapping ||
cluster.Status.State == crv1.PgclusterStateInitialized {
log.Debugf("pgcluster Contoller: onAdd event received for cluster %s but "+
"will not process because it either has a 'completed' status or is currently in an "+
"'initialized' or 'bootstrapping' state", cluster.GetName())
return true
}
// If bootstrapping from an existing data source then attempt to create the pgBackRest repository.
// If a repo already exists (e.g. because it is associated with a currently running cluster) then
// proceed with bootstrapping.
// Also, if the "upgrading" annotation is present on the pgcluster, assume the cluster has
// already been bootstrapped and is being recreated as part of the upgrade process. More
// specifically, ignore the data source and proceed with adding cluster deployments.
_, upgrading := cluster.Annotations[config.ANNOTATION_UPGRADE_IN_PROGRESS]
if cluster.Spec.PGDataSource.RestoreFrom != "" && !upgrading {
repoCreated, err := clusteroperator.AddBootstrapRepo(c.Client, cluster)
if err != nil {
log.Error(err)
c.Queue.AddRateLimited(key)
return true
}
// if no errors and no repo was created, then we know that the repo is for a currently running
// cluster and we can therefore proceed with bootstrapping.
if !repoCreated {
if err := clusteroperator.AddClusterBootstrap(c.Client, cluster); err != nil {
log.Error(err)
c.Queue.AddRateLimited(key)
return true
}
}
c.Queue.Forget(key)
return true
}
patch, err := json.Marshal(map[string]interface{}{
"status": crv1.PgclusterStatus{
State: crv1.PgclusterStateProcessed,
Message: "Successfully processed Pgcluster by controller",
},
})
if err == nil {
_, err = c.Client.CrunchydataV1().Pgclusters(keyNamespace).
Patch(ctx, cluster.Name, types.MergePatchType, patch, metav1.PatchOptions{})
}
if err != nil {
log.Errorf("ERROR updating pgcluster status on add: %s", err.Error())
c.Queue.Forget(key) // NB(cbandy): This should probably be a retry.
return true
}
log.Debugf("pgcluster added: %s", cluster.ObjectMeta.Name)
// AddClusterBase creates all deployments for the cluster (in addition to various other supporting
// resources such as services, configMaps, secrets, etc.), but leaves them scaled to 0. This
// ensures all deployments exist as needed to properly orchestrate initialization of the
// cluster, e.g. we need to ensure the primary DB deployment resource has been created before
// bringing the repo deployment online, since that in turn will bring the primary DB online.
clusteroperator.AddClusterBase(c.Client, cluster, cluster.ObjectMeta.Namespace)
c.Queue.Forget(key)
return true
}
// onUpdate is called when a pgcluster is updated
func (c *Controller) onUpdate(oldObj, newObj interface{}) {
oldcluster := oldObj.(*crv1.Pgcluster)
newcluster := newObj.(*crv1.Pgcluster)
// initialize a slice that may contain functions that need to be executed
// as part of a rolling update
rollingUpdateFuncs := [](func(kubeapi.Interface, *crv1.Pgcluster, *appsv1.Deployment) error){}
// set "rescale" to true if we are adding a rolling update function that
// requires the Deployment to be scaled down in order for it to work
rescale := false
log.Debugf("pgcluster onUpdate for cluster %s (namespace %s)", newcluster.ObjectMeta.Namespace,
newcluster.ObjectMeta.Name)
// if the status of the pgcluster shows that it has been bootstrapped, then proceed with
// creating the cluster (i.e. the cluster deployment, services, etc.)
if newcluster.Spec.Status != crv1.CompletedStatus &&
newcluster.Status.State == crv1.PgclusterStateBootstrapped {
clusteroperator.AddClusterBase(c.Client, newcluster, newcluster.GetNamespace())
return
}
// if the 'shutdown' parameter in the pgcluster update shows that the cluster should be either
// shutdown or started but its current status does not properly reflect that it is, then
// proceed with the logic needed to either shutdown or start the cluster
//
// we do need to check if the status has info in it. There have been cases
// where the entire status has been removed that could be external to the
// operator itself. In the case of checking that the state is in a shutdown
// phase, we also want to check if the status is completely empty. If it is,
// we will proceed with the shutdown.
if newcluster.Spec.Shutdown && newcluster.Status.State != crv1.PgclusterStateShutdown {
if err := clusteroperator.ShutdownCluster(c.Client, *newcluster); err != nil {
log.Error(err)
}
} else if !newcluster.Spec.Shutdown &&
(newcluster.Status.State == crv1.PgclusterStateShutdown || newcluster.Status.State == "") {
if err := clusteroperator.StartupCluster(c.Client, *newcluster); err != nil {
log.Error(err)
}
}
// check to see if autofail setting has been changed. If set to "true", it
// will be disabled, otherwise it will be enabled. Simple.
if oldcluster.Spec.DisableAutofail != newcluster.Spec.DisableAutofail {
// take the inverse, as this func checks for autofail being enabled
// if we can't toggle autofailover, log the error but continue on
if err := util.ToggleAutoFailover(c.Client, !newcluster.Spec.DisableAutofail,
newcluster.Name, newcluster.Namespace); err != nil {
log.Error(err)
}
}
// handle standby being enabled and disabled for the cluster
if oldcluster.Spec.Standby && !newcluster.Spec.Standby {
if err := clusteroperator.DisableStandby(c.Client, *newcluster); err != nil {
log.Error(err)
return
}
} else if !oldcluster.Spec.Standby && newcluster.Spec.Standby {
if err := clusteroperator.EnableStandby(c.Client, *newcluster); err != nil {
log.Error(err)
return
}
}
// if the service type has changed, update the service type. Log an error if
// it fails, but continue on
if oldcluster.Spec.ServiceType != newcluster.Spec.ServiceType {
updateServices(c.Client, newcluster)
}
//TODO add check for replicas
if oldcluster.Spec.PGImage != newcluster.Spec.PGImage {
err := clusteroperator.UpdatePGImage(c.Client, newcluster)
if err != nil {
log.Error("Can't update pg image", err)
}
}
// see if we are adding / removing the metrics collection sidecar
if oldcluster.Spec.Exporter != newcluster.Spec.Exporter {
var err error
// determine if the sidecar is being enabled/disabled and take the precursor
// actions before the deployment template is modified
if newcluster.Spec.Exporter {
err = clusteroperator.AddExporter(c.Client, c.Client.Config, newcluster)
} else {
err = clusteroperator.RemoveExporter(c.Client, c.Client.Config, newcluster)
}
if err == nil {
rollingUpdateFuncs = append(rollingUpdateFuncs, clusteroperator.UpdateExporterSidecar)
} else {
log.Errorf("could not update metrics collection sidecar: %q", err.Error())
}
}
if oldcluster.Spec.PgAdminImage != newcluster.Spec.PgAdminImage {
err := clusteroperator.UpdatePGAdminImage(c.Client, newcluster)
if err != nil {
log.Errorf("failed to update pgadmin image", err)
}
}
// see if we are adding / removing the pgBadger sidecar
if oldcluster.Spec.PGBadger != newcluster.Spec.PGBadger || oldcluster.Spec.PGBadgerImage != newcluster.Spec.PGBadgerImage ||
oldcluster.Spec.PGBadgerPort != newcluster.Spec.PGBadgerPort {
var err error
// determine if the sidecar is being enabled/disabled and take the precursor
// actions before the deployment template is modified
if newcluster.Spec.PGBadger {
err = clusteroperator.AddPGBadger(c.Client, c.Client.Config, newcluster)
} else {
err = clusteroperator.RemovePGBadger(c.Client, c.Client.Config, newcluster)
}
if err == nil {
rollingUpdateFuncs = append(rollingUpdateFuncs, clusteroperator.UpdatePGBadgerSidecar)
} else {
log.Errorf("could not update pgbadger sidecar: %q", err.Error())
}
}
// see if any of the resource values have changed for the database or exporter container,
// if so, update them
if !reflect.DeepEqual(oldcluster.Spec.Resources, newcluster.Spec.Resources) ||
!reflect.DeepEqual(oldcluster.Spec.Limits, newcluster.Spec.Limits) ||
!reflect.DeepEqual(oldcluster.Spec.ExporterResources, newcluster.Spec.ExporterResources) ||
!reflect.DeepEqual(oldcluster.Spec.ExporterLimits, newcluster.Spec.ExporterLimits) {
rollingUpdateFuncs = append(rollingUpdateFuncs, clusteroperator.UpdateResources)
}
// see if any of the pgBackRest repository resource values have changed, and
// if so, update them
if !reflect.DeepEqual(oldcluster.Spec.BackrestResources, newcluster.Spec.BackrestResources) ||
!reflect.DeepEqual(oldcluster.Spec.BackrestLimits, newcluster.Spec.BackrestLimits) {
if err := backrestoperator.UpdateResources(c.Client, newcluster); err != nil {
log.Error(err)
return
}
}
if oldcluster.Spec.BackrestRepoImage != newcluster.Spec.BackrestRepoImage {
err := backrestoperator.UpdateBackrestRepoImage(c.Client, newcluster)
if err != nil {
log.Error("Failed to update backrest repo image", err)
}
}
// see if the pgBackRest PVC size value changed.
if oldcluster.Spec.BackrestStorage.Size != newcluster.Spec.BackrestStorage.Size {
// validate that this resize can occur
if err := util.ValidatePVCResize(oldcluster.Spec.BackrestStorage.Size, newcluster.Spec.BackrestStorage.Size); err != nil {
log.Error(err)
} else {
if err := backrestoperator.ResizePVC(c.Client, newcluster); err != nil {
log.Error(err)
}
}
}
// see if the pgAdmin PVC size valued changed.
if oldcluster.Spec.PGAdminStorage.Size != newcluster.Spec.PGAdminStorage.Size {
// validate that this resize can occur
if err := util.ValidatePVCResize(oldcluster.Spec.PGAdminStorage.Size, newcluster.Spec.PGAdminStorage.Size); err != nil {
log.Error(err)
} else {
if err := clusteroperator.ResizePGAdminPVC(c.Client, newcluster); err != nil {
log.Error(err)
}
}
}
// see if any of the pgBouncer values have changed, and if so, update the
// pgBouncer deployment
if !reflect.DeepEqual(oldcluster.Spec.PgBouncer, newcluster.Spec.PgBouncer) {
if err := updatePgBouncer(c, oldcluster, newcluster); err != nil {
log.Error(err)
return
}
}
// if we are not in a standby state, check to see if the tablespaces have
// differed, and if so, add the additional volumes to the primary and replicas
if !reflect.DeepEqual(oldcluster.Spec.TablespaceMounts, newcluster.Spec.TablespaceMounts) {
if err := updateTablespaces(c, oldcluster, newcluster); err != nil {
log.Error(err)
return
}
rollingUpdateFuncs = append(rollingUpdateFuncs, clusteroperator.UpdateTablespaces)
}
// check to see if any of the annotations have been modified, in particular,
// the non-system annotations
if !reflect.DeepEqual(oldcluster.Spec.Annotations, newcluster.Spec.Annotations) {
if changed, err := updateAnnotations(c, oldcluster, newcluster); err != nil {
log.Error(err)
return
} else if changed {
// append the PostgreSQL specific functions as part of a rolling update
rollingUpdateFuncs = append(rollingUpdateFuncs, clusteroperator.UpdateAnnotations)
}
}
// check to see if any of the custom labels have been modified
if !reflect.DeepEqual(util.GetCustomLabels(oldcluster), util.GetCustomLabels(newcluster)) {
// update the custom labels on all of the managed objects at are not the
// Postgres cluster deployments
if err := updateLabels(c, oldcluster, newcluster); err != nil {
log.Error(err)
return
}
// append the PostgreSQL specific functions as part of a rolling update
rollingUpdateFuncs = append(rollingUpdateFuncs, clusteroperator.UpdateLabels)
}
// check to see if any tolerations have been modified
if !reflect.DeepEqual(oldcluster.Spec.Tolerations, newcluster.Spec.Tolerations) {
rollingUpdateFuncs = append(rollingUpdateFuncs, clusteroperator.UpdateTolerations)
}
// check to see if there are any modifications to TLS
if !reflect.DeepEqual(oldcluster.Spec.TLS, newcluster.Spec.TLS) ||
oldcluster.Spec.TLSOnly != newcluster.Spec.TLSOnly {
rollingUpdateFuncs = append(rollingUpdateFuncs, clusteroperator.UpdateTLS)
// if need be, toggle the TLS settings
if !reflect.DeepEqual(oldcluster.Spec.TLS, newcluster.Spec.TLS) {
if err := clusteroperator.ToggleTLS(c.Client, newcluster); err != nil {
log.Error(err)
return
}
}
}
// check to see if the S3 bucket name has changed. If it has, this requires
// both updating the Postgres + pgBackRest Deployments AND reruning the stanza
// create Job
if oldcluster.Spec.BackrestS3Bucket != newcluster.Spec.BackrestS3Bucket {
// first, update the pgBackRest repository
if err := updateBackrestS3(c, newcluster); err != nil {
log.Errorf("not updating pgBackrest S3 settings: %s", err.Error())
} else {
// if that is successful, add updating the pgBackRest S3 settings to the
// rolling update changes
rollingUpdateFuncs = append(rollingUpdateFuncs, clusteroperator.UpdateBackrestS3)
}
}
// check to see if the size of the primary PVC has changed
if oldcluster.Spec.PrimaryStorage.Size != newcluster.Spec.PrimaryStorage.Size {
// validate that this resize can occur
if err := util.ValidatePVCResize(oldcluster.Spec.PrimaryStorage.Size, newcluster.Spec.PrimaryStorage.Size); err != nil {
log.Error(err)
} else {
rescale = true
rollingUpdateFuncs = append(rollingUpdateFuncs, clusteroperator.ResizeClusterPVC)
}
}
// check to see if the size of the WAL PVC has changed
if oldcluster.Spec.WALStorage.Size != newcluster.Spec.WALStorage.Size {
// validate that this resize can occur
if err := util.ValidatePVCResize(oldcluster.Spec.WALStorage.Size, newcluster.Spec.WALStorage.Size); err != nil {
log.Error(err)
} else {
rescale = true
rollingUpdateFuncs = append(rollingUpdateFuncs, clusteroperator.ResizeWALPVC)
}
}
// if there is no need to perform a rolling update, exit here
if len(rollingUpdateFuncs) == 0 {
return
}
// otherwise, create an anonymous function that executes each of the rolling
// update functions as part of the rolling update
if err := clusteroperator.RollingUpdate(c.Client, c.Client.Config, newcluster, rescale,
func(clientset kubeapi.Interface, cluster *crv1.Pgcluster, deployment *appsv1.Deployment) error {
for _, fn := range rollingUpdateFuncs {
if err := fn(clientset, cluster, deployment); err != nil {
return err
}
}
return nil
}); err != nil {
log.Error(err)
return
}
// one follow-up post rolling update: if the S3 bucket changed, issue a
// "create stanza" job
if oldcluster.Spec.BackrestS3Bucket != newcluster.Spec.BackrestS3Bucket {
backrestoperator.StanzaCreate(newcluster.Namespace, newcluster.Name, c.Client)
}
}
// onDelete is called when a pgcluster is deleted
func (c *Controller) onDelete(obj interface{}) {
ctx := context.TODO()
cluster := obj.(*crv1.Pgcluster)
log.Debugf("pgcluster onDelete for cluster %s (namespace %s)", cluster.Name, cluster.Namespace)
// guard: if an upgrade is in progress, do not do any of the rest
if _, ok := cluster.ObjectMeta.GetAnnotations()[config.ANNOTATION_UPGRADE_IN_PROGRESS]; ok {
log.Debug("upgrade in progress, not proceeding with additional cleanups")
return
}
// guard: see if the "rmdata Job" is running.
options := metav1.ListOptions{
LabelSelector: fields.AndSelectors(
fields.OneTermEqualSelector(config.LABEL_PG_CLUSTER, cluster.Name),
fields.OneTermEqualSelector(config.LABEL_RMDATA, config.LABEL_TRUE),
).String(),
}
jobs, err := c.Client.BatchV1().Jobs(cluster.Namespace).List(ctx, options)
if err != nil {
log.Error(err)
return
}
// iterate through the list of Jobs and see if any are currently active or
// succeeded.
// a succeeded Job could be a remnaint of an old Job for the cluser of a
// same name, in which case, we can continue with deleting the cluster
for _, job := range jobs.Items {
// we will return for one of two reasons:
// 1. if the Job is currently active
// 2. if the Job is not active but never has completed and is below the
// backoff limit -- this could be evidence that the Job is retrying
if job.Status.Active > 0 {
return
} else if job.Status.Succeeded < 1 && job.Status.Failed < *job.Spec.BackoffLimit {
return
}
}
// we need to create a special pgtask that will create the Job (I know). So
// let's attempt to do that here. First, clear out any other pgtask with this
// existing name. If it errors because it's not found, we're OK
taskName := cluster.Name + "-rmdata"
if err := c.Client.CrunchydataV1().Pgtasks(cluster.Namespace).Delete(
ctx, taskName, metav1.DeleteOptions{}); err != nil && !kerrors.IsNotFound(err) {
log.Error(err)
return
}
// determine if the data directory or backups should be kept
kbValue, keepBackupsExsist := isAnnotationExists(cluster, config.ANNOTATION_CLUSTER_KEEP_BACKUPS)
keepBackups := false
if keepBackupsExsist {
keepBackupsValue, err := strconv.ParseBool(kbValue)
if err != nil {
log.Error("parse kepp-backups value to bool")
return
}
keepBackups = keepBackupsValue
}
value, keepDataExist := isAnnotationExists(cluster, config.ANNOTATION_CLUSTER_KEEP_DATA)
keepData := false
if keepDataExist {
keepDataValue, err := strconv.ParseBool(value)
if err != nil {
log.Error("parse kepp-data value to bool")
return
}
keepData = keepDataValue
}
// create the deletion job. this will delete any data and backups for this
// cluster
if err := util.CreateRMDataTask(c.Client, cluster, "", !keepBackups, !keepData, false, false); err != nil {
log.Error(err)
}
}
// isAnnotationExists cheks if annotation exists or not
func isAnnotationExists(cluster *crv1.Pgcluster, key string) (value string, isAnnotation bool) {
value, isAnnotation = cluster.Spec.Annotations.Backrest[key]
if isAnnotation {
return
}
value, isAnnotation = cluster.Spec.Annotations.Postgres[key]
if isAnnotation {
return
}
value, isAnnotation = cluster.Spec.Annotations.Global[key]
return
}
// AddPGClusterEventHandler adds the pgcluster event handler to the pgcluster informer
func (c *Controller) AddPGClusterEventHandler() {
c.Informer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: c.onAdd,
UpdateFunc: c.onUpdate,
DeleteFunc: c.onDelete,
})
log.Debugf("pgcluster Controller: added event handler to informer")
}
// updateAnnotations updates any custom annitations that may be on the managed
// deployments, which includes:
//
// - globally applied annotations
// - pgBackRest instance specific annotations
// - pgBouncer instance specific annotations
//
// The Postgres specific annotations need to be handled by the caller function,
// due to the fact they need to be applied in a rolling update manner that can
// be controlled. We indicate this to the calling function by returning "true"
func updateAnnotations(c *Controller, oldCluster *crv1.Pgcluster, newCluster *crv1.Pgcluster) (bool, error) {
// so we have a two-tier problem we need to solve:
// 1. Which of the deployment types are being modified (or in the case of
// global, all of them)?
// 2. Which annotations are being added/modified/removed? Kubernetes actually
// has a convenient function for updating the annotations, so we do no
// need to do too much works
annotationsPostgres := map[string]string{}
annotationsBackrest := map[string]string{}
annotationsPgBouncer := map[string]string{}
// check the individual deployment groups. If the annotations differ in either the specific group or
// in the global group, set them in their respective map
if !reflect.DeepEqual(oldCluster.Spec.Annotations.Postgres, newCluster.Spec.Annotations.Postgres) ||
!reflect.DeepEqual(oldCluster.Spec.Annotations.Global, newCluster.Spec.Annotations.Global) {
// store the global annotations first
for k, v := range newCluster.Spec.Annotations.Global {
annotationsPostgres[k] = v
}
// then store the postgres specific annotations
for k, v := range newCluster.Spec.Annotations.Postgres {
annotationsPostgres[k] = v
}
}
if !reflect.DeepEqual(oldCluster.Spec.Annotations.Backrest, newCluster.Spec.Annotations.Backrest) ||
!reflect.DeepEqual(oldCluster.Spec.Annotations.Global, newCluster.Spec.Annotations.Global) {
// store the global annotations first
for k, v := range newCluster.Spec.Annotations.Global {
annotationsBackrest[k] = v
}
// then store the pgbackrest specific annotations
for k, v := range newCluster.Spec.Annotations.Backrest {
annotationsBackrest[k] = v
}
}
if !reflect.DeepEqual(oldCluster.Spec.Annotations.PgBouncer, newCluster.Spec.Annotations.PgBouncer) ||
!reflect.DeepEqual(oldCluster.Spec.Annotations.Global, newCluster.Spec.Annotations.Global) {
// store the global annotations first
for k, v := range newCluster.Spec.Annotations.Global {
annotationsPgBouncer[k] = v
}
// then store the pgbouncer specific annotations
for k, v := range newCluster.Spec.Annotations.PgBouncer {
annotationsPgBouncer[k] = v
}
}
// so if there are changes, we can apply them to the various deployments,
// but only do so if we have to
if len(annotationsBackrest) != 0 {
if err := backrestoperator.UpdateAnnotations(c.Client, newCluster, annotationsBackrest); err != nil {
return false, err
}
}
if len(annotationsPgBouncer) != 0 {
if err := clusteroperator.UpdatePgBouncerAnnotations(c.Client, newCluster, annotationsPgBouncer); err != nil && !kerrors.IsNotFound(err) {
return false, err
}
}
return len(annotationsPostgres) != 0, nil
}
// updateBackrestS3 makes updates to the pgBackRest repo Deployment if any of
// the S3 specific settings have changed. Presently, this is just the S3 bucket
// name
func updateBackrestS3(c *Controller, cluster *crv1.Pgcluster) error {
ctx := context.TODO()
// get the pgBackRest deployment
backrestDeploymentName := fmt.Sprintf(util.BackrestRepoDeploymentName, cluster.Name)
backrestDeployment, err := c.Client.AppsV1().Deployments(cluster.Namespace).Get(ctx,
backrestDeploymentName, metav1.GetOptions{})
if err != nil {
return err
}
// update the environmental variable(s) in the container that is aptly(?)
// named database
for i, container := range backrestDeployment.Spec.Template.Spec.Containers {
if container.Name != "database" {
continue
}
for j, envVar := range backrestDeployment.Spec.Template.Spec.Containers[i].Env {
if envVar.Name == "PGBACKREST_REPO1_S3_BUCKET" {
backrestDeployment.Spec.Template.Spec.Containers[i].Env[j].Value = cluster.Spec.BackrestS3Bucket
}
}
}
if _, err := c.Client.AppsV1().Deployments(cluster.Namespace).Update(ctx,
backrestDeployment, metav1.UpdateOptions{}); err != nil {
return err
}
// update the annotation on the pgBackRest Secret too
secretName := fmt.Sprintf(util.BackrestRepoSecretName, cluster.Name)
patch, _ := kubeapi.NewMergePatch().Add("metadata", "annotations")(map[string]string{
config.ANNOTATION_S3_BUCKET: cluster.Spec.BackrestS3Bucket,
}).Bytes()
if _, err := c.Client.CoreV1().Secrets(cluster.Namespace).Patch(ctx,
secretName, types.MergePatchType, patch, metav1.PatchOptions{}); err != nil {
return err
}
return nil
}
// updateLabels updates the custom labels on all of the managed objects *except*
// the Postgres instances themselves, i.e. the deployment templates
func updateLabels(c *Controller, oldCluster *crv1.Pgcluster, newCluster *crv1.Pgcluster) error {
// we need to figure out which labels need to be removed from the list
labelsToRemove := make([]string, 0)
labels := util.GetCustomLabels(newCluster)
for old := range util.GetCustomLabels(oldCluster) {
if _, ok := labels[old]; !ok {
labelsToRemove = append(labelsToRemove, old)
}
}
// go through each object group and update the labels.
if err := updateLabelsForDeployments(c, newCluster, labels, labelsToRemove); err != nil {
return err
}
if err := updateLabelsForPVCs(c, newCluster, labels, labelsToRemove); err != nil {
return err
}
if err := updateLabelsForConfigMaps(c, newCluster, labels, labelsToRemove); err != nil {
return err
}
if err := updateLabelsForSecrets(c, newCluster, labels, labelsToRemove); err != nil {
return err
}
return updateLabelsForServices(c, newCluster, labels, labelsToRemove)
}
// updateLabelsForConfigMaps updates the custom labels for ConfigMaps
func updateLabelsForConfigMaps(c *Controller, cluster *crv1.Pgcluster, labels map[string]string, labelsToRemove []string) error {
ctx := context.TODO()
options := metav1.ListOptions{
LabelSelector: fields.AndSelectors(
fields.OneTermEqualSelector(config.LABEL_PG_CLUSTER, cluster.Name),
fields.OneTermEqualSelector(config.LABEL_VENDOR, config.LABEL_CRUNCHY),
).String(),
}
items, err := c.Client.CoreV1().ConfigMaps(cluster.Namespace).List(ctx, options)
if err != nil {
return err
}
for i := range items.Items {
item := &items.Items[i]
for j := range labelsToRemove {
delete(item.ObjectMeta.Labels, labelsToRemove[j])
}
for k, v := range labels {
item.ObjectMeta.Labels[k] = v
}
if _, err := c.Client.CoreV1().ConfigMaps(cluster.Namespace).Update(ctx,
item, metav1.UpdateOptions{}); err != nil {
return err
}
}
return nil
}
// updateLabelsForDeployments updates the custom labels for Deployments, except
// for the **templates** on the Postgres instances
func updateLabelsForDeployments(c *Controller, cluster *crv1.Pgcluster, labels map[string]string, labelsToRemove []string) error {
ctx := context.TODO()
options := metav1.ListOptions{
LabelSelector: fields.AndSelectors(
fields.OneTermEqualSelector(config.LABEL_PG_CLUSTER, cluster.Name),
fields.OneTermEqualSelector(config.LABEL_VENDOR, config.LABEL_CRUNCHY),
).String(),
}
// create the contents of the merge patch for updating the labels on the
// Deployments. We're going to create two merge patches: one for just Postgres
// instances, and one for every other instance. We're not updating the
// template for the Postgres Deployments as that will trigger a restart
mergePatchDeployments := kubeapi.NewMergePatch()
mergePatchPostgresDeployments := kubeapi.NewMergePatch()
// first set the patch for labels that need to be removed.
for i := range labelsToRemove {
mergePatchDeployments.Remove("metadata", "labels", labelsToRemove[i])
mergePatchDeployments.Remove("spec", "template", "metadata", "labels", labelsToRemove[i])
mergePatchPostgresDeployments.Remove("metadata", "labels", labelsToRemove[i])
}
// now, set the patch for labels that need to be added/updated
for k, v := range labels {
mergePatchDeployments.Add("metadata", "labels", k)(v)
mergePatchDeployments.Add("spec", "template", "metadata", "labels", k)(v)
mergePatchPostgresDeployments.Add("metadata", "labels", k)(v)
}
// generate the bytes for the two patches
patchDeployments, err := mergePatchDeployments.Bytes()
if err != nil {
return err
}
patchPostgresDeployments, err := mergePatchPostgresDeployments.Bytes()
if err != nil {
return err
}
items, err := c.Client.AppsV1().Deployments(cluster.Namespace).List(ctx, options)
if err != nil {
return err
}
for i := range items.Items {
item := &items.Items[i]
patch := patchDeployments
if _, isPostgresInstance := item.ObjectMeta.Labels[config.LABEL_PG_DATABASE]; isPostgresInstance {
patch = patchPostgresDeployments
}
// and patch!
if _, err := c.Client.AppsV1().Deployments(cluster.Namespace).Patch(ctx,
item.Name, types.MergePatchType, patch, metav1.PatchOptions{}); err != nil {
return err
}
}
return nil
}
// updateLabelsForPVCs updates the custom labels for PVCs
func updateLabelsForPVCs(c *Controller, cluster *crv1.Pgcluster, labels map[string]string, labelsToRemove []string) error {
ctx := context.TODO()
options := metav1.ListOptions{
LabelSelector: fields.AndSelectors(
fields.OneTermEqualSelector(config.LABEL_PG_CLUSTER, cluster.Name),
fields.OneTermEqualSelector(config.LABEL_VENDOR, config.LABEL_CRUNCHY),
).String(),
}
items, err := c.Client.CoreV1().PersistentVolumeClaims(cluster.Namespace).List(ctx, options)
if err != nil {
return err
}
for i := range items.Items {
item := &items.Items[i]
for j := range labelsToRemove {
delete(item.ObjectMeta.Labels, labelsToRemove[j])
}
for k, v := range labels {
item.ObjectMeta.Labels[k] = v
}
if _, err := c.Client.CoreV1().PersistentVolumeClaims(cluster.Namespace).Update(ctx,
item, metav1.UpdateOptions{}); err != nil {
return err
}
}
return nil
}
// updateLabelsForSecrets updates the custom labels for Secrets
func updateLabelsForSecrets(c *Controller, cluster *crv1.Pgcluster, labels map[string]string, labelsToRemove []string) error {
ctx := context.TODO()
options := metav1.ListOptions{
LabelSelector: fields.AndSelectors(
fields.OneTermEqualSelector(config.LABEL_PG_CLUSTER, cluster.Name),
fields.OneTermEqualSelector(config.LABEL_VENDOR, config.LABEL_CRUNCHY),
).String(),
}
items, err := c.Client.CoreV1().Secrets(cluster.Namespace).List(ctx, options)
if err != nil {
return err
}
for i := range items.Items {
item := &items.Items[i]
for j := range labelsToRemove {
delete(item.ObjectMeta.Labels, labelsToRemove[j])
}
for k, v := range labels {
item.ObjectMeta.Labels[k] = v
}
if _, err := c.Client.CoreV1().Secrets(cluster.Namespace).Update(ctx,
item, metav1.UpdateOptions{}); err != nil {
return err
}
}
return nil
}
// updateLabelsForServices updates the custom labels for Services
func updateLabelsForServices(c *Controller, cluster *crv1.Pgcluster, labels map[string]string, labelsToRemove []string) error {
ctx := context.TODO()
options := metav1.ListOptions{
LabelSelector: fields.AndSelectors(
fields.OneTermEqualSelector(config.LABEL_PG_CLUSTER, cluster.Name),
fields.OneTermEqualSelector(config.LABEL_VENDOR, config.LABEL_CRUNCHY),
).String(),
}
items, err := c.Client.CoreV1().Services(cluster.Namespace).List(ctx, options)
if err != nil {
return err
}
for i := range items.Items {
item := &items.Items[i]
for j := range labelsToRemove {
delete(item.ObjectMeta.Labels, labelsToRemove[j])
}
for k, v := range labels {
item.ObjectMeta.Labels[k] = v
}
if _, err := c.Client.CoreV1().Services(cluster.Namespace).Update(ctx,
item, metav1.UpdateOptions{}); err != nil {
return err
}
}
return nil
}
// updatePgBouncer updates the pgBouncer Deployment to reflect any changes that
// may be made, which include:
// - enabling a pgBouncer Deployment :)
// - disabling a pgBouncer Deployment :(
// - any changes to the resizing, etc.
func updatePgBouncer(c *Controller, oldCluster *crv1.Pgcluster, newCluster *crv1.Pgcluster) error {
log.Debugf("update pgbouncer for cluster %s", newCluster.Name)
// first, handle the easy ones, i.e. determine if we are enabling or disabling
if oldCluster.Spec.PgBouncer.Enabled() != newCluster.Spec.PgBouncer.Enabled() {
log.Debugf("pgbouncer enabled: %t", newCluster.Spec.PgBouncer.Enabled())
// if this is being enabled, it's a simple step where we can return here
if newCluster.Spec.PgBouncer.Enabled() {
return clusteroperator.AddPgbouncer(c.Client, c.Client.Config, newCluster)
}
// if we're not enabled, we're disabled
return clusteroperator.DeletePgbouncer(c.Client, c.Client.Config, newCluster)
}
// otherwise, this is an update
return clusteroperator.UpdatePgbouncer(c.Client, c.Client.Config, oldCluster, newCluster)
}
// updateServices handles any updates to the Service objects. Given how legacy
// replica services are handled (really, replica service singular), the update
// around replica services is a bit grotty, but it is what it is.
//
// If there are errors on the updates, this logs them but will continue on
// unless otherwise noted.
func updateServices(clientset kubeapi.Interface, cluster *crv1.Pgcluster) {
ctx := context.TODO()
// handle the primary instance
if err := clusteroperator.UpdateClusterService(clientset, cluster); err != nil {
log.Error(err)
}