@@ -2,10 +2,12 @@ package pgcluster
22
33import (
44 "context"
5+ "maps"
56
67 "github.com/pkg/errors"
78 corev1 "k8s.io/api/core/v1"
89 k8serrors "k8s.io/apimachinery/pkg/api/errors"
10+ "k8s.io/client-go/util/retry"
911 "sigs.k8s.io/controller-runtime/pkg/client"
1012
1113 "github.com/percona/percona-postgresql-operator/v2/internal/naming"
@@ -73,21 +75,38 @@ func ensureSidecarPVCs(
7375 pvc := new (corev1.PersistentVolumeClaim )
7476 pvc .Name = sidecarPVC .Name
7577 pvc .Namespace = cr .Namespace
76- pvc .Spec = sidecarPVC .Spec
77- pvc .Labels = ls
7878
79- err := cl .Get (ctx , client .ObjectKeyFromObject (pvc ), & corev1.PersistentVolumeClaim {})
80- if err == nil {
81- // already exists
82- continue
79+ if err := cl .Get (ctx , client .ObjectKeyFromObject (pvc ), pvc ); err != nil {
80+ if ! k8serrors .IsNotFound (err ) {
81+ return errors .Wrapf (err , "get %s" , client .ObjectKeyFromObject (pvc ).String ())
82+ }
83+ pvc .Spec = sidecarPVC .Spec
84+ pvc .Labels = ls
85+ if err := cl .Create (ctx , pvc ); err != nil {
86+ return errors .Wrap (err , "failed to create pvc" )
87+ }
88+ return nil
8389 }
84-
85- if ! k8serrors .IsNotFound (err ) {
86- return errors .Wrapf (err , "get %s" , client .ObjectKeyFromObject (pvc ).String ())
90+ if v := pvc .Labels [naming .LabelPerconaManagedBy ]; v != "percona-postgresql-operator" {
91+ return errors .Errorf ("PersistentVolumeClaim %s already exists and not managed by percona-postgresql-operator: %s" , client .ObjectKeyFromObject (pvc ).String (), v )
92+ }
93+ if v := pvc .Labels [naming .LabelPerconaInstance ]; v != cr .Name {
94+ return errors .Errorf ("PersistentVolumeClaim %s already exists and belongs to another cluster %s" , client .ObjectKeyFromObject (pvc ).String (), v )
8795 }
8896
89- if err := cl .Create (ctx , pvc ); err != nil {
90- return errors .Wrapf (err , "create PVC %s" , client .ObjectKeyFromObject (pvc ).String ())
97+ if err := retry .RetryOnConflict (retry .DefaultRetry , func () error {
98+ if err := cl .Get (ctx , client .ObjectKeyFromObject (pvc ), pvc ); err != nil {
99+ return err
100+ }
101+ maps .Copy (pvc .Labels , ls )
102+
103+ // It's only allowed to update resources.requests and volumeAttributesClassName
104+ pvc .Spec .Resources .Requests = sidecarPVC .Spec .Resources .Requests
105+ pvc .Spec .VolumeAttributesClassName = sidecarPVC .Spec .VolumeAttributesClassName
106+
107+ return cl .Update (ctx , pvc )
108+ }); err != nil {
109+ return errors .Wrapf (err , "update PersistentVolumeClaim %s" , client .ObjectKeyFromObject (pvc ).String ())
91110 }
92111 }
93112
0 commit comments