-
Notifications
You must be signed in to change notification settings - Fork 659
Expand file tree
/
Copy pathinstance.go
More file actions
1566 lines (1366 loc) · 55.2 KB
/
instance.go
File metadata and controls
1566 lines (1366 loc) · 55.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
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2021 - 2026 Crunchy Data Solutions, Inc.
//
// SPDX-License-Identifier: Apache-2.0
package postgrescluster
import (
"context"
"fmt"
"io"
"maps"
"sort"
"strings"
"time"
"github.com/pkg/errors"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
policyv1 "k8s.io/api/policy/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/apimachinery/pkg/util/sets"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"github.com/crunchydata/postgres-operator/internal/collector"
"github.com/crunchydata/postgres-operator/internal/config"
"github.com/crunchydata/postgres-operator/internal/controller/runtime"
"github.com/crunchydata/postgres-operator/internal/feature"
"github.com/crunchydata/postgres-operator/internal/initialize"
"github.com/crunchydata/postgres-operator/internal/logging"
"github.com/crunchydata/postgres-operator/internal/naming"
"github.com/crunchydata/postgres-operator/internal/patroni"
"github.com/crunchydata/postgres-operator/internal/pgbackrest"
"github.com/crunchydata/postgres-operator/internal/pki"
"github.com/crunchydata/postgres-operator/internal/postgres"
"github.com/crunchydata/postgres-operator/internal/tracing"
"github.com/crunchydata/postgres-operator/internal/util"
"github.com/crunchydata/postgres-operator/pkg/apis/postgres-operator.crunchydata.com/v1beta1"
)
// Instance represents a single PostgreSQL instance of a PostgresCluster.
type Instance struct {
Name string
Pods []*corev1.Pod
Runner *appsv1.StatefulSet
Spec *v1beta1.PostgresInstanceSetSpec
}
// IsAvailable is used to choose which instances to redeploy during rolling
// update. It combines information from metadata and status similar to the
// notion of "available" in corev1.Deployment and "healthy" in appsv1.StatefulSet.
func (i Instance) IsAvailable() (available bool, known bool) {
// StatefulSet will have its own notion of Available in the future.
// - https://docs.k8s.io/concepts/workloads/controllers/statefulset/#minimum-ready-seconds
terminating, knownTerminating := i.IsTerminating()
ready, knownReady := i.IsReady()
return ready && !terminating, knownReady && knownTerminating
}
// IsPrimary returns whether or not this instance is the Patroni leader.
func (i Instance) IsPrimary() (primary bool, known bool) {
if len(i.Pods) != 1 {
return false, false
}
return i.Pods[0].Labels[naming.LabelRole] == naming.RolePatroniLeader, true
}
// IsReady returns whether or not this instance is ready to receive PostgreSQL
// connections.
func (i Instance) IsReady() (ready bool, known bool) {
if len(i.Pods) == 1 {
for _, condition := range i.Pods[0].Status.Conditions {
if condition.Type == corev1.PodReady {
return condition.Status == corev1.ConditionTrue, true
}
}
}
return false, false
}
// IsRunning returns whether or not container is running.
func (i Instance) IsRunning(container string) (running bool, known bool) {
if len(i.Pods) == 1 {
for _, status := range i.Pods[0].Status.ContainerStatuses {
if status.Name == container {
return status.State.Running != nil, true
}
}
for _, status := range i.Pods[0].Status.InitContainerStatuses {
if status.Name == container {
return status.State.Running != nil, true
}
}
}
return false, false
}
// IsTerminating returns whether or not this instance is in the process of not
// running.
func (i Instance) IsTerminating() (terminating bool, known bool) {
if len(i.Pods) != 1 {
return false, false
}
// k8s.io/kubernetes/pkg/registry/core/pod.Strategy implements
// k8s.io/apiserver/pkg/registry/rest.RESTGracefulDeleteStrategy so that it
// can set DeletionTimestamp to corev1.PodSpec.TerminationGracePeriodSeconds
// in the future.
// - https://releases.k8s.io/v1.21.0/pkg/registry/core/pod/strategy.go#L135
// - https://releases.k8s.io/v1.21.0/staging/src/k8s.io/apiserver/pkg/registry/rest/delete.go
return i.Pods[0].DeletionTimestamp != nil, true
}
// IsWritable returns whether or not a PostgreSQL connection could write to its
// database.
func (i Instance) IsWritable() (writable, known bool) {
if len(i.Pods) != 1 {
return false, false
}
member := i.Pods[0].Annotations["status"]
role := strings.Index(member, `"role":`)
if role < 0 {
return false, false
}
// TODO(cbandy): Update this to consider when Patroni is paused.
return strings.HasPrefix(member[role:], `"role":"master"`) ||
strings.HasPrefix(member[role:], `"role":"primary"`), true
}
// PodMatchesPodTemplate returns whether or not the Pod for this instance
// matches its specified PodTemplate. When it does not match, the Pod needs to
// be redeployed.
func (i Instance) PodMatchesPodTemplate() (matches bool, known bool) {
if i.Runner == nil || len(i.Pods) != 1 {
return false, false
}
if i.Runner.Status.ObservedGeneration != i.Runner.Generation {
return false, false
}
// When the Status is up-to-date, compare the revision of the Pod to that
// of the PodTemplate.
podRevision := i.Pods[0].Labels[appsv1.StatefulSetRevisionLabel]
return podRevision == i.Runner.Status.UpdateRevision, true
}
// instanceSorter implements sort.Interface for some instance comparison.
type instanceSorter struct {
instances []*Instance
less func(i, j *Instance) bool
}
func (s *instanceSorter) Len() int {
return len(s.instances)
}
func (s *instanceSorter) Less(i, j int) bool {
return s.less(s.instances[i], s.instances[j])
}
func (s *instanceSorter) Swap(i, j int) {
s.instances[i], s.instances[j] = s.instances[j], s.instances[i]
}
// byPriority returns a sort.Interface that sorts instances by how much we want
// each to keep running. The primary instance, when known, is always the highest
// priority. Two instances with otherwise-identical priority are ranked by Name.
func byPriority(instances []*Instance) sort.Interface {
return &instanceSorter{instances: instances, less: func(a, b *Instance) bool {
// The primary instance is the highest priority.
if primary, known := a.IsPrimary(); known && primary {
return false
}
if primary, known := b.IsPrimary(); known && primary {
return true
}
// An available instance is a higher priority than not.
if available, known := a.IsAvailable(); known && available {
return false
}
if available, known := b.IsAvailable(); known && available {
return true
}
return a.Name < b.Name
}}
}
// observedInstances represents all the PostgreSQL instances of a single PostgresCluster.
type observedInstances struct {
byName map[string]*Instance
bySet map[string][]*Instance
forCluster []*Instance
setNames sets.Set[string]
}
// newObservedInstances builds an observedInstances from Kubernetes API objects.
func newObservedInstances(
cluster *v1beta1.PostgresCluster,
runners []appsv1.StatefulSet,
pods []corev1.Pod,
) *observedInstances {
observed := observedInstances{
byName: make(map[string]*Instance),
bySet: make(map[string][]*Instance),
setNames: make(sets.Set[string]),
}
sets := make(map[string]*v1beta1.PostgresInstanceSetSpec)
for i := range cluster.Spec.InstanceSets {
name := cluster.Spec.InstanceSets[i].Name
sets[name] = &cluster.Spec.InstanceSets[i]
observed.setNames.Insert(name)
}
for i := range runners {
ri := runners[i].Name
rs := runners[i].Labels[naming.LabelInstanceSet]
instance := &Instance{
Name: ri,
Runner: &runners[i],
Spec: sets[rs],
}
observed.byName[ri] = instance
observed.bySet[rs] = append(observed.bySet[rs], instance)
observed.forCluster = append(observed.forCluster, instance)
observed.setNames.Insert(rs)
}
for i := range pods {
pi := pods[i].Labels[naming.LabelInstance]
ps := pods[i].Labels[naming.LabelInstanceSet]
instance := observed.byName[pi]
if instance == nil {
instance = &Instance{
Name: pi,
Spec: sets[ps],
}
observed.byName[pi] = instance
observed.bySet[ps] = append(observed.bySet[ps], instance)
observed.forCluster = append(observed.forCluster, instance)
observed.setNames.Insert(ps)
}
instance.Pods = append(instance.Pods, &pods[i])
}
return &observed
}
// writablePod looks at observedInstances and finds an instance that matches
// a few conditions. The instance should be non-terminating, running, and
// writable i.e. the instance with the primary. If such an instance exists, it
// is returned along with the instance pod.
func (observed *observedInstances) writablePod(container string) (*corev1.Pod, *Instance) {
if observed == nil {
return nil, nil
}
for _, instance := range observed.forCluster {
if terminating, known := instance.IsTerminating(); terminating || !known {
continue
}
if writable, known := instance.IsWritable(); !writable || !known {
continue
}
running, known := instance.IsRunning(container)
if running && known && len(instance.Pods) > 0 {
return instance.Pods[0], instance
}
}
return nil, nil
}
// +kubebuilder:rbac:groups="",resources="pods",verbs={list}
// +kubebuilder:rbac:groups="apps",resources="statefulsets",verbs={list}
// observeInstances populates cluster.Status.InstanceSets with observations and
// builds an observedInstances by reading from the Kubernetes API.
func (r *Reconciler) observeInstances(
ctx context.Context, cluster *v1beta1.PostgresCluster,
) (*observedInstances, error) {
pods := &corev1.PodList{}
runners := &appsv1.StatefulSetList{}
autogrow := feature.Enabled(ctx, feature.AutoGrowVolumes)
selector, err := naming.AsSelector(naming.ClusterInstances(cluster.Name))
if err == nil {
err = errors.WithStack(
r.Reader.List(ctx, pods,
client.InNamespace(cluster.Namespace),
client.MatchingLabelsSelector{Selector: selector},
))
}
if err == nil {
err = errors.WithStack(
r.Reader.List(ctx, runners,
client.InNamespace(cluster.Namespace),
client.MatchingLabelsSelector{Selector: selector},
))
}
observed := newObservedInstances(cluster, runners.Items, pods.Items)
// Save desired volume size values in case the status is removed.
// This may happen in cases where the Pod is restarted, the cluster
// is shutdown, etc. Only save values for instances defined in the spec.
previousPGDataDesiredRequests := make(map[string]string)
previousPGWALDesiredRequests := make(map[string]string)
if autogrow {
for _, statusIS := range cluster.Status.InstanceSets {
if statusIS.DesiredPGDataVolume != nil {
maps.Copy(previousPGDataDesiredRequests, statusIS.DesiredPGDataVolume)
}
}
for _, statusIS := range cluster.Status.InstanceSets {
if statusIS.DesiredPGWALVolume != nil {
maps.Copy(previousPGWALDesiredRequests, statusIS.DesiredPGWALVolume)
}
}
}
// Fill out status sorted by set name.
cluster.Status.InstanceSets = cluster.Status.InstanceSets[:0]
for _, name := range sets.List(observed.setNames) {
status := v1beta1.PostgresInstanceSetStatus{Name: name}
status.DesiredPGDataVolume = make(map[string]string)
status.DesiredPGWALVolume = make(map[string]string)
for _, instance := range observed.bySet[name] {
//nolint:gosec // This slice is always small.
status.Replicas += int32(len(instance.Pods))
if ready, known := instance.IsReady(); known && ready {
status.ReadyReplicas++
}
if matches, known := instance.PodMatchesPodTemplate(); known && matches {
status.UpdatedReplicas++
}
if autogrow {
// Store desired pgData and pgWAL volume sizes for each instance Pod.
// The 'suggested-pgdata-pvc-size' and 'suggested-pgwal-pvc-size' annotation
// values are stored in the PostgresCluster status so that 1) they are available
// to the 'reconcilePostgresDataVolume' and 'reconcilePostgresWALVolume' functions
// and 2) so that the values persist after Pod restart and cluster shutdown events.
for _, pod := range instance.Pods {
// don't set an empty status
if pod.Annotations["suggested-pgdata-pvc-size"] != "" {
status.DesiredPGDataVolume[instance.Name] = pod.Annotations["suggested-pgdata-pvc-size"]
}
if pod.Annotations["suggested-pgwal-pvc-size"] != "" {
status.DesiredPGWALVolume[instance.Name] = pod.Annotations["suggested-pgwal-pvc-size"]
}
}
}
}
// If autogrow is enabled, determine the desired volume size for each instance
// now that all the pod annotations have been collected. This final value will be
// checked to ensure that the value from the annotations can be parsed to a valid
// value. Otherwise the previous value, if available, will be used. If a limit is
// not defined for the given volume and an empty string has been returned, nothing
// will be stored in the status. In the event that the value is empty, any existing
// request value will be removed.
if autogrow {
for _, instance := range observed.bySet[name] {
if pgDataRequest := r.storeDesiredRequest(
ctx, cluster, "pgData", name,
status.DesiredPGDataVolume[instance.Name],
previousPGDataDesiredRequests[instance.Name],
); pgDataRequest != "" {
status.DesiredPGDataVolume[instance.Name] = pgDataRequest
} else {
delete(status.DesiredPGDataVolume, instance.Name)
}
if pgWALRequest := r.storeDesiredRequest(
ctx, cluster, "pgWAL", name,
status.DesiredPGWALVolume[instance.Name],
previousPGWALDesiredRequests[instance.Name],
); pgWALRequest != "" {
status.DesiredPGWALVolume[instance.Name] = pgWALRequest
} else {
delete(status.DesiredPGWALVolume, instance.Name)
}
}
}
cluster.Status.InstanceSets = append(cluster.Status.InstanceSets, status)
}
return observed, err
}
// +kubebuilder:rbac:groups="",resources="pods",verbs={list}
// +kubebuilder:rbac:groups="apps",resources="statefulsets",verbs={patch}
// deleteInstances gracefully stops instances of cluster to avoid failovers and
// unclean shutdowns of PostgreSQL. It returns (nil, nil) when finished.
func (r *Reconciler) deleteInstances(
ctx context.Context, cluster *v1beta1.PostgresCluster,
) (*reconcile.Result, error) {
// Find all instance pods to determine which to shutdown and in what order.
pods := &corev1.PodList{}
instances, err := naming.AsSelector(naming.ClusterInstances(cluster.Name))
if err == nil {
err = errors.WithStack(
r.Reader.List(ctx, pods,
client.InNamespace(cluster.Namespace),
client.MatchingLabelsSelector{Selector: instances},
))
}
if err != nil {
return nil, err
}
if len(pods.Items) == 0 {
// There are no instances, so there's nothing to do.
// The caller can do what they like.
return nil, nil
}
// There are some instances, so the caller should at least wait for further
// events.
result := reconcile.Result{}
// stop schedules pod for deletion by scaling its controller to zero.
stop := func(pod *corev1.Pod) error {
instance := &appsv1.StatefulSet{}
instance.SetNamespace(cluster.Namespace)
switch owner := metav1.GetControllerOfNoCopy(pod); {
case owner == nil:
return errors.Errorf("pod %q has no owner", client.ObjectKeyFromObject(pod))
case owner.Kind == "StatefulSet":
instance.SetName(owner.Name)
default:
return errors.Errorf("unexpected kind %q", owner.Kind)
}
// apps/v1.Deployment, apps/v1.ReplicaSet, and apps/v1.StatefulSet all
// have a "spec.replicas" field with the same meaning.
patch := client.RawPatch(client.Merge.Type(), []byte(`{"spec":{"replicas":0}}`))
err := errors.WithStack(r.Writer.Patch(ctx, instance, patch))
// When the pod controller is missing, requeue rather than return an
// error. The garbage collector will stop the pod, and it is not our
// mistake that something else is deleting objects. Use RequeueAfter to
// avoid being rate-limited due to a deluge of delete events.
if err != nil {
result = runtime.RequeueWithoutBackoff(10 * time.Second)
}
return client.IgnoreNotFound(err)
}
if len(pods.Items) == 1 {
// There's one instance; stop it.
return &result, stop(&pods.Items[0])
}
// There are multiple instances; stop the replicas. When none are found,
// requeue to try again.
result.Requeue = true
for i := range pods.Items {
role := pods.Items[i].Labels[naming.LabelRole]
if err == nil && role == naming.RolePatroniReplica {
err = stop(&pods.Items[i])
result.Requeue = false
}
// An instance without a role label is not participating in the Patroni
// cluster. It may be unhealthy or has not yet (re-)joined. Go ahead and
// stop these as well.
if err == nil && len(role) == 0 {
err = stop(&pods.Items[i])
result.Requeue = false
}
}
return &result, err
}
// +kubebuilder:rbac:groups="",resources="configmaps",verbs={delete,list}
// +kubebuilder:rbac:groups="",resources="secrets",verbs={delete,list}
// +kubebuilder:rbac:groups="",resources="persistentvolumeclaims",verbs={delete,list}
// +kubebuilder:rbac:groups="apps",resources="statefulsets",verbs={delete,list}
// deleteInstance will delete all resources related to a single instance
func (r *Reconciler) deleteInstance(
ctx context.Context,
cluster *v1beta1.PostgresCluster,
instanceName string,
) error {
gvks := []runtime.GVK{{
Group: corev1.SchemeGroupVersion.Group,
Version: corev1.SchemeGroupVersion.Version,
Kind: "ConfigMapList",
}, {
Group: corev1.SchemeGroupVersion.Group,
Version: corev1.SchemeGroupVersion.Version,
Kind: "SecretList",
}, {
Group: appsv1.SchemeGroupVersion.Group,
Version: appsv1.SchemeGroupVersion.Version,
Kind: "StatefulSetList",
}, {
Group: corev1.SchemeGroupVersion.Group,
Version: corev1.SchemeGroupVersion.Version,
Kind: "PersistentVolumeClaimList",
}}
selector, err := naming.AsSelector(naming.ClusterInstance(cluster.Name, instanceName))
for _, gvk := range gvks {
if err == nil {
uList := &unstructured.UnstructuredList{}
uList.SetGroupVersionKind(gvk)
err = errors.WithStack(
r.Reader.List(ctx, uList,
client.InNamespace(cluster.GetNamespace()),
client.MatchingLabelsSelector{Selector: selector},
))
for i := range uList.Items {
if err == nil {
err = errors.WithStack(client.IgnoreNotFound(
r.deleteControlled(ctx, cluster, &uList.Items[i])))
}
}
}
}
return err
}
// reconcileInstanceSets reconciles instance sets in the environment to match
// the current spec. This is done by scaling up or down instances where necessary
func (r *Reconciler) reconcileInstanceSets(
ctx context.Context,
cluster *v1beta1.PostgresCluster,
clusterConfigMap *corev1.ConfigMap,
clusterReplicationSecret *corev1.Secret,
rootCA *pki.RootCertificateAuthority,
clusterPodService *corev1.Service,
instanceServiceAccount *corev1.ServiceAccount,
instances *observedInstances,
patroniLeaderService *corev1.Service,
primaryCertificate *corev1.SecretProjection,
clusterVolumes []*corev1.PersistentVolumeClaim,
exporterQueriesConfig, exporterWebConfig *corev1.ConfigMap,
backupsSpecFound bool,
otelConfig *collector.Config,
pgParameters *postgres.ParameterSet,
) error {
// Go through the observed instances and check if a primary has been determined.
// If the cluster is being shutdown and this instance is the primary, store
// the instance name as the startup instance. If the primary can be determined
// from the instance and the cluster is not being shutdown, clear any stored
// startup instance values.
for _, instance := range instances.forCluster {
if primary, known := instance.IsPrimary(); primary && known {
if cluster.Spec.Shutdown != nil && *cluster.Spec.Shutdown {
cluster.Status.StartupInstance = instance.Name
cluster.Status.StartupInstanceSet = instance.Spec.Name
} else {
cluster.Status.StartupInstance = ""
cluster.Status.StartupInstanceSet = ""
}
}
}
// get the number of instance pods from the observedInstance information
var numInstancePods int
for i := range instances.forCluster {
numInstancePods += len(instances.forCluster[i].Pods)
}
// Range over instance sets to scale up and ensure that each set has
// at least the number of replicas defined in the spec. The set can
// have more replicas than defined
for i := range cluster.Spec.InstanceSets {
set := &cluster.Spec.InstanceSets[i]
_, err := r.scaleUpInstances(
ctx, cluster, instances, set,
clusterConfigMap, clusterReplicationSecret,
rootCA, clusterPodService, instanceServiceAccount,
patroniLeaderService, primaryCertificate,
findAvailableInstanceNames(*set, instances, clusterVolumes),
numInstancePods, clusterVolumes, exporterQueriesConfig, exporterWebConfig,
backupsSpecFound, otelConfig, pgParameters,
)
if err == nil {
err = r.reconcileInstanceSetPodDisruptionBudget(ctx, cluster, set)
}
if err != nil {
return err
}
}
// Scaledown is called on the whole cluster in order to consider all
// instances. This is necessary because we have no way to determine
// which instance or instance set contains the primary pod.
err := r.scaleDownInstances(ctx, cluster, instances)
if err != nil {
return err
}
// Cleanup Instance Set resources that are no longer needed
err = r.cleanupPodDisruptionBudgets(ctx, cluster)
if err != nil {
return err
}
// Rollout changes to instances by calling rolloutInstance.
err = r.rolloutInstances(ctx, cluster, instances,
func(ctx context.Context, instance *Instance) error {
return r.rolloutInstance(ctx, cluster, instances, instance)
})
return err
}
// +kubebuilder:rbac:groups="policy",resources="poddisruptionbudgets",verbs={list}
// cleanupPodDisruptionBudgets removes pdbs that do not have an
// associated Instance Set
func (r *Reconciler) cleanupPodDisruptionBudgets(
ctx context.Context,
cluster *v1beta1.PostgresCluster,
) error {
selector, err := naming.AsSelector(naming.ClusterInstanceSets(cluster.Name))
pdbList := &policyv1.PodDisruptionBudgetList{}
if err == nil {
err = r.Reader.List(ctx, pdbList,
client.InNamespace(cluster.Namespace), client.MatchingLabelsSelector{
Selector: selector,
})
}
if err == nil {
setNames := sets.Set[string]{}
for _, set := range cluster.Spec.InstanceSets {
setNames.Insert(set.Name)
}
for i := range pdbList.Items {
pdb := pdbList.Items[i]
if err == nil && !setNames.Has(pdb.Labels[naming.LabelInstanceSet]) {
err = client.IgnoreNotFound(r.deleteControlled(ctx, cluster, &pdb))
}
}
}
return client.IgnoreNotFound(err)
}
// TODO (andrewlecuyer): If relevant instance volume (PVC) information is captured for each
// Instance contained within observedInstances, this function might no longer be necessary.
// Instead, available names could be derived by looking at observed Instances that have data
// volumes, but no associated runner.
// findAvailableInstanceNames finds any instance names that are available for reuse within a
// specific instance set. Available instance names are determined by finding any instance PVCs
// for the instance set specified that are not currently associated with an instance, and then
// returning the instance names associated with those PVC's.
func findAvailableInstanceNames(set v1beta1.PostgresInstanceSetSpec,
observedInstances *observedInstances, clusterVolumes []*corev1.PersistentVolumeClaim) []string {
availableInstanceNames := []string{}
// first identify any PGDATA volumes for the instance set specified
setVolumes := []*corev1.PersistentVolumeClaim{}
for _, pvc := range clusterVolumes {
// ignore PGDATA PVCs that are terminating
if pvc.GetDeletionTimestamp() != nil {
continue
}
pvcSet := pvc.GetLabels()[naming.LabelInstanceSet]
pvcRole := pvc.GetLabels()[naming.LabelRole]
if pvcRole == naming.RolePostgresData && pvcSet == set.Name {
setVolumes = append(setVolumes, pvc)
}
}
// If there is a WAL volume defined for the instance set, then a matching WAL volume
// must also be found in order for the volumes to be reused. Therefore, filter out
// any available PGDATA volumes for the instance set that have no corresponding WAL
// volumes (which means new PVCs will simply be reconciled instead).
if set.WALVolumeClaimSpec != nil {
setVolumesWithWAL := []*corev1.PersistentVolumeClaim{}
for _, setVol := range setVolumes {
setVolInstance := setVol.GetLabels()[naming.LabelInstance]
for _, pvc := range clusterVolumes {
// ignore WAL PVCs that are terminating
if pvc.GetDeletionTimestamp() != nil {
continue
}
pvcSet := pvc.GetLabels()[naming.LabelInstanceSet]
pvcInstance := pvc.GetLabels()[naming.LabelInstance]
pvcRole := pvc.GetLabels()[naming.LabelRole]
if pvcRole == naming.RolePostgresWAL && pvcSet == set.Name &&
pvcInstance == setVolInstance {
setVolumesWithWAL = append(setVolumesWithWAL, pvc)
}
}
}
setVolumes = setVolumesWithWAL
}
// Determine whether or not the PVC is associated with an existing instance within the same
// instance set. If not, then the instance name associated with that PVC can be reused.
for _, pvc := range setVolumes {
pvcInstanceName := pvc.GetLabels()[naming.LabelInstance]
instance := observedInstances.byName[pvcInstanceName]
if instance == nil || instance.Runner == nil {
availableInstanceNames = append(availableInstanceNames, pvcInstanceName)
}
}
return availableInstanceNames
}
// +kubebuilder:rbac:groups="",resources="pods",verbs={delete}
// rolloutInstance redeploys the Pod of instance by deleting it. Its StatefulSet
// will recreate it according to its current PodTemplate. When instance is the
// primary of a cluster with failover, it is demoted instead.
func (r *Reconciler) rolloutInstance(
ctx context.Context, cluster *v1beta1.PostgresCluster,
instances *observedInstances, instance *Instance,
) error {
// The StatefulSet and number of Pods should have already been verified, but
// check again rather than panic.
// TODO(cbandy): The check for StatefulSet can go away if we watch Pod deletes.
if instance.Runner == nil || len(instance.Pods) != 1 {
return errors.Errorf(
"unexpected instance state during rollout: %v has %v pods",
instance.Name, len(instance.Pods))
}
pod := instance.Pods[0]
exec := func(_ context.Context, stdin io.Reader, stdout, stderr io.Writer, command ...string) error {
return r.PodExec(ctx, pod.Namespace, pod.Name, naming.ContainerDatabase, stdin, stdout, stderr, command...)
}
primary, known := instance.IsPrimary()
primary = primary && known
// When the cluster has more than one instance participating in failover,
// perform a controlled switchover to one of those instances. Patroni will
// choose the best candidate and demote the primary. It stops PostgreSQL
// using what it calls "graceful" mode: it takes an immediate checkpoint in
// the background then uses "pg_ctl" to perform a "fast" shutdown when the
// checkpoint completes.
// - https://github.com/zalando/patroni/blob/v2.0.2/patroni/ha.py#L815
// - https://www.postgresql.org/docs/current/sql-checkpoint.html
//
// NOTE(cbandy): The StatefulSet controlling this Pod reflects this change
// in its Status and triggers another reconcile.
if primary && len(instances.forCluster) > 1 {
ctx, span := tracing.Start(ctx, "patroni-change-primary")
defer span.End()
success, err := patroni.Executor(exec).ChangePrimaryAndWait(ctx, pod.Name, "")
if err = errors.WithStack(err); err == nil && !success {
err = errors.New("unable to switchover")
}
return tracing.Escape(span, err)
}
// When the cluster has only one instance for failover, perform a series of
// immediate checkpoints to increase the likelihood that a "fast" shutdown
// will complete before the SIGKILL near TerminationGracePeriodSeconds.
// - https://docs.k8s.io/concepts/workloads/pods/pod-lifecycle/#pod-termination
if primary {
graceSeconds := int64(corev1.DefaultTerminationGracePeriodSeconds)
if pod.Spec.TerminationGracePeriodSeconds != nil {
graceSeconds = *pod.Spec.TerminationGracePeriodSeconds
}
checkpoint := func(ctx context.Context) (time.Duration, error) {
ctx, span := tracing.Start(ctx, "postgresql-checkpoint")
defer span.End()
start := time.Now()
stdout, stderr, err := postgres.Executor(exec).
ExecInDatabasesFromQuery(ctx, `SELECT pg_catalog.current_database()`,
`SET statement_timeout = :'timeout'; CHECKPOINT;`,
map[string]string{
"timeout": fmt.Sprintf("%ds", graceSeconds),
"ON_ERROR_STOP": "on", // Abort when any one statement fails.
"QUIET": "on", // Do not print successful statements to stdout.
})
err = errors.WithStack(err)
elapsed := time.Since(start)
logging.FromContext(ctx).V(1).Info("attempted checkpoint",
"duration", elapsed, "stdout", stdout, "stderr", stderr)
return elapsed, tracing.Escape(span, err)
}
duration, err := checkpoint(ctx)
threshold := time.Duration(graceSeconds/2) * time.Second
// The first checkpoint could be flushing up to "checkpoint_timeout"
// or "max_wal_size" worth of data. Try once more to get a sense of
// how long "fast" shutdown might take.
if err == nil && duration > threshold {
duration, err = checkpoint(ctx)
}
// Communicate the lack or slowness of CHECKPOINT and shutdown anyway.
if err != nil {
r.Recorder.Eventf(cluster, corev1.EventTypeWarning, "NoCheckpoint",
"Unable to checkpoint primary before shutdown: %v", err)
} else if duration > threshold {
r.Recorder.Eventf(cluster, corev1.EventTypeWarning, "SlowCheckpoint",
"Shutting down primary despite checkpoint taking over %v", duration)
}
}
// Delete the Pod so its controlling StatefulSet will recreate it. Patroni
// will receive a SIGTERM and use "pg_ctl" to perform a "fast" shutdown of
// PostgreSQL without taking a checkpoint.
// - https://github.com/zalando/patroni/blob/v2.0.2/patroni/ha.py#L1465
//
// NOTE(cbandy): This could return an apierrors.IsConflict() which should be
// retried by another reconcile (not ignored).
return errors.WithStack(
r.Writer.Delete(ctx, pod, client.Preconditions{
UID: &pod.UID,
ResourceVersion: &pod.ResourceVersion,
}))
}
// rolloutInstances compares instances to cluster and calls redeploy on those
// that need their Pod recreated. It considers the overall availability of
// cluster and minimizes Patroni failovers.
func (r *Reconciler) rolloutInstances(
ctx context.Context,
cluster *v1beta1.PostgresCluster,
instances *observedInstances,
redeploy func(context.Context, *Instance) error,
) error {
var err error
var consider []*Instance
var numAvailable int
var numSpecified int
ctx, span := tracing.Start(ctx, "rollout-instances")
defer span.End()
for _, set := range cluster.Spec.InstanceSets {
numSpecified += int(*set.Replicas)
}
for _, instance := range instances.forCluster {
// Skip instances that have no set in cluster spec. They should not be
// redeployed and should not count toward availability.
if instance.Spec == nil {
continue
}
// Skip instances that are or might be terminating. They should not be
// redeployed right now and cannot count toward availability.
if terminating, known := instance.IsTerminating(); !known || terminating {
continue
}
if available, known := instance.IsAvailable(); known && available {
numAvailable++
}
if matches, known := instance.PodMatchesPodTemplate(); known && !matches {
consider = append(consider, instance)
continue
}
}
const maxUnavailable = 1
numUnavailable := numSpecified - numAvailable
// When multiple instances need to redeploy, sort them so the lowest
// priority instances are first.
if len(consider) > 1 {
sort.Sort(byPriority(consider))
}
tracing.Int(span, "instances", len(instances.forCluster))
tracing.Int(span, "specified", numSpecified)
tracing.Int(span, "available", numAvailable)
tracing.Int(span, "considering", len(consider))
// Redeploy instances up to the allowed maximum while "rolling over" any
// unavailable instances.
// - https://issue.k8s.io/67250
for _, instance := range consider {
if err == nil {
if available, known := instance.IsAvailable(); known && !available {
err = redeploy(ctx, instance)
} else if numUnavailable < maxUnavailable {
err = redeploy(ctx, instance)
numUnavailable++
}
}
}
return tracing.Escape(span, err)
}
// scaleDownInstances removes extra instances from a cluster until it matches
// the spec. This function can delete the primary instance and force the
// cluster to failover under two conditions:
// - If the instance set that contains the primary instance is removed from
// the spec
// - If the instance set that contains the primary instance is updated to
// have 0 replicas
//
// If either of these conditions are met then the primary instance will be
// marked for deletion and deleted after all other instances
func (r *Reconciler) scaleDownInstances(
ctx context.Context,
cluster *v1beta1.PostgresCluster,
observedInstances *observedInstances,
) error {
// want defines the number of replicas we want for each instance set
want := map[string]int{}
for _, set := range cluster.Spec.InstanceSets {
want[set.Name] = int(*set.Replicas)
}
// grab all pods for the cluster using the observed instances
var podCount int
for i := range observedInstances.forCluster {
podCount += len(observedInstances.forCluster[i].Pods)
}
pods := make([]corev1.Pod, 0, podCount)
for instanceIndex := range observedInstances.forCluster {
for podIndex := range observedInstances.forCluster[instanceIndex].Pods {
pods = append(pods, *observedInstances.forCluster[instanceIndex].Pods[podIndex])
}
}
// namesToKeep defines the names of any instances that should be kept
namesToKeep := sets.NewString()
for _, pod := range podsToKeep(pods, want) {
namesToKeep.Insert(pod.Labels[naming.LabelInstance])
}
for _, instance := range observedInstances.forCluster {
for _, pod := range instance.Pods {
if !namesToKeep.Has(pod.Labels[naming.LabelInstance]) {
err := r.deleteInstance(ctx, cluster, pod.Labels[naming.LabelInstance])
if err != nil {
return err
}
}
}
}
return nil
}
// podsToKeep takes a list of pods and a map containing
// the number of replicas we want for each instance set
// then returns a list of the pods that we want to keep
func podsToKeep(instances []corev1.Pod, want map[string]int) []corev1.Pod {
f := func(instances []corev1.Pod, want int) []corev1.Pod {
keep := []corev1.Pod{}
if want > 0 {
for _, instance := range instances {
if instance.Labels[naming.LabelRole] == "master" {
keep = append(keep, instance)
}
}
}