-
Notifications
You must be signed in to change notification settings - Fork 56
/
vrg_volrep.go
2603 lines (2059 loc) · 91.4 KB
/
vrg_volrep.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
// SPDX-FileCopyrightText: The RamenDR authors
// SPDX-License-Identifier: Apache-2.0
package controllers
import (
"errors"
"fmt"
"reflect"
"strconv"
"strings"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/go-logr/logr"
volrep "github.com/csi-addons/kubernetes-csi-addons/api/replication.storage/v1alpha1"
corev1 "k8s.io/api/core/v1"
storagev1 "k8s.io/api/storage/v1"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
ramendrv1alpha1 "github.com/ramendr/ramen/api/v1alpha1"
rmnutil "github.com/ramendr/ramen/internal/controller/util"
)
const (
// defaultVRCAnnotationKey is the default annotation key for VolumeReplicationClass
defaultVRCAnnotationKey = "replication.storage.openshift.io/is-default-class"
)
func logWithPvcName(log logr.Logger, pvc *corev1.PersistentVolumeClaim) logr.Logger {
return log.WithValues("pvc", types.NamespacedName{Name: pvc.Name, Namespace: pvc.Namespace}.String())
}
// reconcileVolRepsAsPrimary creates/updates VolumeReplication CR for each pvc
// from pvcList. If it fails (even for one pvc), then requeue is set to true.
func (v *VRGInstance) reconcileVolRepsAsPrimary() {
for idx := range v.volRepPVCs {
pvc := &v.volRepPVCs[idx]
pvcNamespacedName := types.NamespacedName{Name: pvc.Name, Namespace: pvc.Namespace}
log := v.log.WithValues("pvc", pvcNamespacedName.String())
if v.pvcUnprotectVolRepIfDeleted(*pvc, log) {
continue
}
if err := v.updateProtectedPVCs(pvc); err != nil {
v.requeue()
continue
}
requeueResult, skip := v.preparePVCForVRProtection(pvc, log)
if requeueResult {
v.requeue()
continue
}
if skip {
continue
}
// If VR did not reach primary state, it is fine to still upload the PV and continue processing
requeueResult, _, err := v.processVRAsPrimary(pvcNamespacedName, pvc, log)
if requeueResult {
v.requeue()
}
if err != nil {
log.Info("Failure in getting or creating VolumeReplication resource for PersistentVolumeClaim",
"errorValue", err)
continue
}
// Protect the PVC's PV object stored in etcd by uploading it to S3
// store(s). Note that the VRG is responsible only to protect the PV
// object of each PVC of the subscription. However, the PVC object
// itself is assumed to be protected along with other k8s objects in the
// subscription, such as, the deployment, pods, services, etc., by an
// entity external to the VRG a la IaC.
if err := v.uploadPVandPVCtoS3Stores(pvc, log); err != nil {
log.Info("Requeuing due to failure to upload PV object to S3 store(s)",
"errorValue", err)
v.requeue()
continue
}
log.Info("Successfully processed VolumeReplication for PersistentVolumeClaim")
}
}
// reconcileVolRepsAsSecondary reconciles VolumeReplication resources for the VRG as secondary
func (v *VRGInstance) reconcileVolRepsAsSecondary() bool {
requeue := false
for idx := range v.volRepPVCs {
pvc := &v.volRepPVCs[idx]
log := logWithPvcName(v.log, pvc)
if err := v.updateProtectedPVCs(pvc); err != nil {
requeue = true
continue
}
requeueResult, skip := v.preparePVCForVRProtection(pvc, log)
if requeueResult {
requeue = true
continue
}
if skip {
continue
}
// If VR is not ready as Secondary, we can ignore it here, either a future VR change or the requeue would
// reconcile it to the desired state.
requeueResult, _, skip = v.reconcileVRAsSecondary(pvc, log)
if requeueResult {
requeue = true
continue
}
if skip {
continue
}
log.Info("Successfully processed VolumeReplication for PersistentVolumeClaim")
}
return requeue
}
// reconcileVRAsSecondary checks for PVC readiness to move to Secondary and subsequently updates the VR
// backing the PVC to secondary. It reports completion status of the VR request with the following values:
// requeue (bool): If the request needs to be requeued
// ready (bool): If desired state is achieved and hence VR is ready
// skip (bool): If the VR can be currently skipped for processing
func (v *VRGInstance) reconcileVRAsSecondary(pvc *corev1.PersistentVolumeClaim, log logr.Logger) (bool, bool, bool) {
const (
requeue bool = true
skip bool = true
)
if !v.isPVCReadyForSecondary(pvc, log) {
return requeue, false, skip
}
pvcNamespacedName := types.NamespacedName{Name: pvc.Name, Namespace: pvc.Namespace}
requeueResult, ready, err := v.processVRAsSecondary(pvcNamespacedName, pvc, log)
if err != nil {
log.Info("Failure in getting or creating VolumeReplication resource for PersistentVolumeClaim",
"errorValue", err)
}
return requeueResult, ready, !skip
}
// isPVCReadyForSecondary checks if a PVC is ready to be marked as Secondary
func (v *VRGInstance) isPVCReadyForSecondary(pvc *corev1.PersistentVolumeClaim, log logr.Logger) bool {
const ready bool = true
// If PVC is not being deleted, it is not ready for Secondary, unless action is failover
if v.instance.Spec.Action != ramendrv1alpha1.VRGActionFailover && !rmnutil.ResourceIsDeleted(pvc) {
log.Info("VolumeReplication cannot become Secondary, as its PersistentVolumeClaim is not marked for deletion")
msg := "unable to transition to Secondary as PVC is not deleted"
v.updatePVCDataReadyCondition(pvc.Namespace, pvc.Name, VRGConditionReasonProgressing, msg)
return !ready
}
return !v.isPVCInUse(pvc, log, "Secondary transition")
}
func (v *VRGInstance) isPVCInUse(pvc *corev1.PersistentVolumeClaim, log logr.Logger, operation string) bool {
pvcNamespacedName := types.NamespacedName{Name: pvc.Name, Namespace: pvc.Namespace}
const inUse bool = true
// Check if any pod definitions exist referencing the PVC
inUseByPod, err := rmnutil.IsPVCInUseByPod(v.ctx, v.reconciler.Client, log, pvcNamespacedName, false)
if err != nil || inUseByPod {
msg := operation + " failed as PVC is potentially in use by a pod"
log.Info(msg, "errorValue", err)
v.updatePVCDataReadyCondition(pvc.Namespace, pvc.Name, VRGConditionReasonProgressing, msg)
return inUse
}
// No pod is mounting the PVC - do additional check to make sure no volume attachment exists
vaPresent, err := rmnutil.IsPVAttachedToNode(v.ctx, v.reconciler.Client, log, pvc)
if err != nil || vaPresent {
msg := operation + " failed as PersistentVolume for PVC is still attached to node(s)"
log.Info(msg, "errorValue", err)
v.updatePVCDataReadyCondition(pvc.Namespace, pvc.Name, VRGConditionReasonProgressing, msg)
return inUse
}
return !inUse
}
// updateProtectedPVCs updates the list of ProtectedPVCs with the passed in PVC
func (v *VRGInstance) updateProtectedPVCs(pvc *corev1.PersistentVolumeClaim) error {
// IF MetroDR, skip PVC update
if v.instance.Spec.Sync != nil {
return nil
}
pvcNamespacedName := types.NamespacedName{Name: pvc.Name, Namespace: pvc.Namespace}
storageClass, err := v.getStorageClass(pvcNamespacedName)
if err != nil {
v.log.Info(fmt.Sprintf("Failed to get the storageclass for pvc %s",
pvcNamespacedName))
return fmt.Errorf("failed to get the storageclass for pvc %s (%w)",
pvcNamespacedName, err)
}
volumeReplicationClass, err := v.selectVolumeReplicationClass(pvcNamespacedName)
if err != nil {
return fmt.Errorf("failed to find the appropriate VolumeReplicationClass (%s) %w",
v.instance.Name, err)
}
protectedPVC := v.findProtectedPVC(pvc.GetNamespace(), pvc.GetName())
if protectedPVC == nil {
protectedPVC = v.addProtectedPVC(pvc.GetNamespace(), pvc.GetName())
}
protectedPVC.ProtectedByVolSync = false
protectedPVC.StorageClassName = pvc.Spec.StorageClassName
protectedPVC.Labels = pvc.Labels
protectedPVC.AccessModes = pvc.Spec.AccessModes
protectedPVC.Resources = pvc.Spec.Resources
setPVCStorageIdentifiers(protectedPVC, storageClass, volumeReplicationClass)
return nil
}
func setPVCStorageIdentifiers(
protectedPVC *ramendrv1alpha1.ProtectedPVC,
storageClass *storagev1.StorageClass,
volumeReplicationClass *volrep.VolumeReplicationClass,
) {
protectedPVC.StorageIdentifiers.StorageProvisioner = storageClass.Provisioner
if value, ok := storageClass.Labels[StorageIDLabel]; ok {
protectedPVC.StorageIdentifiers.StorageID.ID = value
if modes, ok := storageClass.Labels[MModesLabel]; ok {
protectedPVC.StorageIdentifiers.StorageID.Modes = MModesFromCSV(modes)
}
}
if value, ok := volumeReplicationClass.GetLabels()[VolumeReplicationIDLabel]; ok {
protectedPVC.StorageIdentifiers.ReplicationID.ID = value
if modes, ok := volumeReplicationClass.GetLabels()[MModesLabel]; ok {
protectedPVC.StorageIdentifiers.ReplicationID.Modes = MModesFromCSV(modes)
}
}
}
func MModesFromCSV(modes string) []ramendrv1alpha1.MMode {
mModes := []ramendrv1alpha1.MMode{}
for _, mode := range strings.Split(modes, ",") {
switch mode {
case string(ramendrv1alpha1.MModeFailover):
mModes = append(mModes, ramendrv1alpha1.MModeFailover)
default:
// ignore unknown modes (TODO: should we error instead?)
continue
}
}
return mModes
}
// preparePVCForVRProtection processes prerequisites of any PVC that needs VR protection. It returns
// a requeue if preparation failed, and returns skip if PVC can be skipped for VR protection
func (v *VRGInstance) preparePVCForVRProtection(pvc *corev1.PersistentVolumeClaim,
log logr.Logger,
) (bool, bool) {
const (
requeue bool = true
skip bool = true
)
// if PVC protection is complete, return
if pvc.Annotations[pvcVRAnnotationProtectedKey] == pvcVRAnnotationProtectedValue {
return !requeue, !skip
}
// Dont requeue. There will be a reconcile request when predicate sees that pvc is ready.
if skipResult, msg := skipPVC(pvc, log); skipResult {
// @msg should not be nil as the decision is to skip the pvc.
// msg should contain info on why that decision was made.
if msg == "" {
msg = "PVC not ready"
}
// Since pvc is skipped, mark the condition for the PVC as progressing. Even for
// deletion this applies where if the VR protection finalizer is absent for pvc and
// it is being deleted.
v.updatePVCDataReadyCondition(pvc.Namespace, pvc.Name, VRGConditionReasonProgressing, msg)
return !requeue, skip
}
return v.protectPVC(pvc, log), !skip
}
func (v *VRGInstance) protectPVC(pvc *corev1.PersistentVolumeClaim, log logr.Logger) bool {
const requeue = true
vrg := v.instance
ownerAdded := false
switch comparison := rmnutil.ObjectOwnerSetIfNotAlready(pvc, vrg); comparison {
case rmnutil.Absent:
ownerAdded = true
case rmnutil.Same:
case rmnutil.Different:
msg := "PVC owned by another resource"
log.Info(msg, "owner", rmnutil.OwnerNamespacedName(pvc).String())
v.updatePVCDataReadyCondition(pvc.Namespace, pvc.Name, VRGConditionReasonError, msg)
return !requeue
}
// Add VR finalizer to PVC for deletion protection
if finalizerAdded := controllerutil.AddFinalizer(pvc, PvcVRFinalizerProtected); finalizerAdded || ownerAdded {
log1 := log.WithValues("add finalizer", finalizerAdded, "add owner", ownerAdded)
if err := v.reconciler.Update(v.ctx, pvc); err != nil {
msg := "Failed to update PVC to add owner and/or Protected Finalizer"
log1.Info(msg, "error", err)
v.updatePVCDataReadyCondition(pvc.Namespace, pvc.Name, VRGConditionReasonError, msg)
return requeue
}
log1.Info("Updated PVC", "finalizers", pvc.GetFinalizers(), "labels", pvc.GetLabels())
}
if err := v.retainPVForPVC(*pvc, log); err != nil { // Change PV `reclaimPolicy` to "Retain"
log.Info("Requeuing, as retaining PersistentVolume failed", "errorValue", err)
msg := "Failed to retain PV for PVC"
v.updatePVCDataReadyCondition(pvc.Namespace, pvc.Name, VRGConditionReasonError, msg)
return requeue
}
// Annotate that PVC protection is complete, skip if being deleted
if !rmnutil.ResourceIsDeleted(pvc) {
if err := v.addProtectedAnnotationForPVC(pvc, log); err != nil {
log.Info("Requeuing, as annotating PersistentVolumeClaim failed", "errorValue", err)
msg := "Failed to add protected annotatation to PVC"
v.updatePVCDataReadyCondition(pvc.Namespace, pvc.Name, VRGConditionReasonError, msg)
return requeue
}
}
return !requeue
}
// This function indicates whether to proceed with the pvc processing
// or not. It mainly checks the following things.
// - Whether pvc is bound or not. If not bound, then no need to
// process the pvc any further. It can be skipped until it is ready.
// - Whether the pvc is being deleted and VR protection finalizer is
// not there. If the finalizer is there, then VolumeReplicationGroup
// need to remove the finalizer for the pvc being deleted. However,
// if the finalizer is not there, then no need to process the pvc
// any further and it can be skipped. The pvc will go away eventually.
func skipPVC(pvc *corev1.PersistentVolumeClaim, log logr.Logger) (bool, string) {
if pvc.Status.Phase != corev1.ClaimBound {
log.Info("Skipping handling of VR as PersistentVolumeClaim is not bound", "pvcPhase", pvc.Status.Phase)
msg := "PVC not bound yet"
// v.updateProtectedPVCCondition(pvc.Name, VRGConditionReasonProgressing, msg)
return true, msg
}
return isPVCDeletedAndNotProtected(pvc, log)
}
func isPVCDeletedAndNotProtected(pvc *corev1.PersistentVolumeClaim, log logr.Logger) (bool, string) {
// If PVC deleted but not yet protected with a finalizer, skip it!
if !containsString(pvc.Finalizers, PvcVRFinalizerProtected) && rmnutil.ResourceIsDeleted(pvc) {
log.Info("Skipping PersistentVolumeClaim, as it is marked for deletion and not yet protected")
msg := "Skipping pvc marked for deletion"
// v.updateProtectedPVCCondition(pvc.Name, VRGConditionReasonProgressing, msg)
return true, msg
}
return false, ""
}
// preparePVCForVRDeletion
func (v *VRGInstance) preparePVCForVRDeletion(pvc *corev1.PersistentVolumeClaim,
log logr.Logger,
) error {
vrg := v.instance
pv, err := v.getPVFromPVC(pvc)
if err != nil {
log.Error(err, "Failed to get PV for VR deletion")
return err
}
// For Async mode, we want to change the retention policy back to delete
// and remove the annotation.
// For Sync mode, we don't want to set the retention policy to delete as
// both the primary and the secondary VRG map to the same volume. The only
// state where a delete retention policy is required for the sync mode is
// when the VRG is primary.
// Further, the PV will go to Available state, when the workload is moved back
// to the current cluster, in case the PVC has been deleted (cases like STS the
// PVC may not be deleted). This is achieved by clearing the required claim ref.
// such that the PV can bind back to a recreated PVC. func ref.: updateExistingPVForSync
if v.instance.Spec.Async != nil || v.instance.Spec.ReplicationState == ramendrv1alpha1.Primary {
undoPVRetention(&pv)
}
delete(pv.Annotations, pvcVRAnnotationArchivedKey)
if err := v.reconciler.Update(v.ctx, &pv); err != nil {
log.Error(err, "Failed to update PersistentVolume for VR deletion")
return fmt.Errorf("failed to update PersistentVolume %s claimed by %s/%s"+
"for deletion of VR owned by VolumeReplicationGroup %s/%s, %w",
pvc.Spec.VolumeName, pvc.Namespace, pvc.Name, v.instance.Namespace, v.instance.Name, err)
}
log.Info("Deleted ramen annotations from PersistentVolume", "pv", pv.Name)
ownerRemoved := rmnutil.ObjectOwnerUnsetIfSet(pvc, vrg)
// Remove VR finalizer from PVC and the annotation (PVC maybe left behind, so remove the annotation)
finalizerRemoved := controllerutil.RemoveFinalizer(pvc, PvcVRFinalizerProtected)
delete(pvc.Annotations, pvcVRAnnotationProtectedKey)
delete(pvc.Annotations, pvcVRAnnotationArchivedKey)
log1 := log.WithValues("owner removed", ownerRemoved, "finalizer removed", finalizerRemoved)
if err := v.reconciler.Update(v.ctx, pvc); err != nil {
log1.Error(err, "Failed to update PersistentVolumeClaim for VR deletion")
return fmt.Errorf("failed to update PersistentVolumeClaim %s/%s"+
"for deletion of VR owned by VolumeReplicationGroup %s/%s, %w",
pvc.Namespace, pvc.Name, v.instance.Namespace, v.instance.Name, err)
}
log1.Info("Deleted ramen annotations, labels, and finallizers from PersistentVolumeClaim",
"annotations", pvc.GetAnnotations(), "labels", pvc.GetLabels(), "finalizers", pvc.GetFinalizers())
return nil
}
// retainPVForPVC updates the PV reclaim policy to retain for a given PVC
func (v *VRGInstance) retainPVForPVC(pvc corev1.PersistentVolumeClaim, log logr.Logger) error {
// Get PV bound to PVC
pv := &corev1.PersistentVolume{}
pvObjectKey := client.ObjectKey{
Name: pvc.Spec.VolumeName,
}
if err := v.reconciler.Get(v.ctx, pvObjectKey, pv); err != nil {
log.Error(err, "Failed to get PersistentVolume", "volumeName", pvc.Spec.VolumeName)
return fmt.Errorf("failed to get PersistentVolume resource (%s) for"+
" PersistentVolumeClaim resource (%s/%s) belonging to VolumeReplicationGroup (%s/%s), %w",
pvc.Spec.VolumeName, pvc.Namespace, pvc.Name, v.instance.Namespace, v.instance.Name, err)
}
// Check reclaimPolicy of PV, if already set to retain
if pv.Spec.PersistentVolumeReclaimPolicy == corev1.PersistentVolumeReclaimRetain {
return nil
}
// if not retained, retain PV, and add an annotation to denote this is updated for VR needs
pv.Spec.PersistentVolumeReclaimPolicy = corev1.PersistentVolumeReclaimRetain
if pv.ObjectMeta.Annotations == nil {
pv.ObjectMeta.Annotations = map[string]string{}
}
pv.ObjectMeta.Annotations[pvVRAnnotationRetentionKey] = pvVRAnnotationRetentionValue
if err := v.reconciler.Update(v.ctx, pv); err != nil {
log.Error(err, "Failed to update PersistentVolume reclaim policy")
return fmt.Errorf("failed to update PersistentVolume resource (%s) reclaim policy for"+
" PersistentVolumeClaim resource (%s/%s) belonging to VolumeReplicationGroup (%s/%s), %w",
pvc.Spec.VolumeName, pvc.Namespace, pvc.Name, v.instance.Namespace, v.instance.Name, err)
}
return nil
}
// undoPVRetention updates the PV reclaim policy back to its saved state
func undoPVRetention(pv *corev1.PersistentVolume) {
if v, ok := pv.ObjectMeta.Annotations[pvVRAnnotationRetentionKey]; !ok || v != pvVRAnnotationRetentionValue {
return
}
pv.Spec.PersistentVolumeReclaimPolicy = corev1.PersistentVolumeReclaimDelete
delete(pv.ObjectMeta.Annotations, pvVRAnnotationRetentionKey)
}
func (v *VRGInstance) generateArchiveAnnotation(gen int64) string {
return fmt.Sprintf("%s-%s", pvcVRAnnotationArchivedVersionV1, strconv.Itoa(int(gen)))
}
func (v *VRGInstance) isArchivedAlready(pvc *corev1.PersistentVolumeClaim, log logr.Logger) bool {
pvHasAnnotation := false
pvcHasAnnotation := false
pv, err := v.getPVFromPVC(pvc)
if err != nil {
log.Error(err, "Failed to get PV to check if archived")
return false
}
pvcDesiredValue := v.generateArchiveAnnotation(pvc.Generation)
if v, ok := pvc.ObjectMeta.Annotations[pvcVRAnnotationArchivedKey]; ok && (v == pvcDesiredValue) {
pvcHasAnnotation = true
}
pvDesiredValue := v.generateArchiveAnnotation(pv.Generation)
if v, ok := pv.ObjectMeta.Annotations[pvcVRAnnotationArchivedKey]; ok && (v == pvDesiredValue) {
pvHasAnnotation = true
}
if !pvHasAnnotation || !pvcHasAnnotation {
return false
}
return true
}
// Upload PV to the list of S3 stores in the VRG spec
func (v *VRGInstance) uploadPVandPVCtoS3Stores(pvc *corev1.PersistentVolumeClaim, log logr.Logger) (err error) {
if v.isArchivedAlready(pvc, log) {
msg := fmt.Sprintf("PV cluster data already protected for PVC %s", pvc.Name)
v.updatePVCClusterDataProtectedCondition(pvc.Namespace, pvc.Name,
VRGConditionReasonUploaded, msg)
return nil
}
// Error out if VRG has no S3 profiles
numProfilesToUpload := len(v.instance.Spec.S3Profiles)
if numProfilesToUpload == 0 {
msg := "Error uploading PV cluster data because VRG spec has no S3 profiles"
v.updatePVCClusterDataProtectedCondition(pvc.Namespace, pvc.Name,
VRGConditionReasonUploadError, msg)
v.log.Info(msg)
return fmt.Errorf("error uploading cluster data of PV %s because VRG spec has no S3 profiles",
pvc.Name)
}
s3Profiles, err := v.UploadPVandPVCtoS3Stores(pvc, log)
if err != nil {
return fmt.Errorf("failed to upload PV/PVC with error (%w). Uploaded to %v S3 profile(s)", err, s3Profiles)
}
numProfilesUploaded := len(s3Profiles)
if numProfilesUploaded != numProfilesToUpload {
// Merely defensive as we don't expect to reach here
msg := fmt.Sprintf("Uploaded PV/PVC cluster data to only %d of %d S3 profile(s): %v",
numProfilesUploaded, numProfilesToUpload, s3Profiles)
v.log.Info(msg)
v.updatePVCClusterDataProtectedCondition(pvc.Namespace, pvc.Name,
VRGConditionReasonUploadError, msg)
return fmt.Errorf(msg)
}
if err := v.addArchivedAnnotationForPVC(pvc, log); err != nil {
msg := fmt.Sprintf("failed to add archived annotation for PVC (%s/%s) with error (%v)",
pvc.Namespace, pvc.Name, err)
v.log.Info(msg)
v.updatePVCClusterDataProtectedCondition(pvc.Namespace, pvc.Name,
VRGConditionReasonClusterDataAnnotationFailed, msg)
return fmt.Errorf(msg)
}
msg := fmt.Sprintf("Done uploading PV/PVC cluster data to %d of %d S3 profile(s): %v",
numProfilesUploaded, numProfilesToUpload, s3Profiles)
v.log.Info(msg)
v.updatePVCClusterDataProtectedCondition(pvc.Namespace, pvc.Name,
VRGConditionReasonUploaded, msg)
return nil
}
func (v *VRGInstance) UploadPVandPVCtoS3Store(s3ProfileName string, pvc *corev1.PersistentVolumeClaim) error {
if s3ProfileName == "" {
return fmt.Errorf("missing S3 profiles, failed to protect cluster data for PVC %s", pvc.Name)
}
objectStore, err := v.getObjectStorer(s3ProfileName)
if err != nil {
return fmt.Errorf("error getting object store, failed to protect cluster data for PVC %s, %w", pvc.Name, err)
}
pv, err := v.getPVFromPVC(pvc)
if err != nil {
return fmt.Errorf("error getting PV for PVC, failed to protect cluster data for PVC %s to s3Profile %s, %w",
pvc.Name, s3ProfileName, err)
}
return v.UploadPVAndPVCtoS3(s3ProfileName, objectStore, &pv, pvc)
}
func (v *VRGInstance) UploadPVAndPVCtoS3(s3ProfileName string, objectStore ObjectStorer,
pv *corev1.PersistentVolume, pvc *corev1.PersistentVolumeClaim,
) error {
if err := UploadPV(objectStore, v.s3KeyPrefix(), pv.Name, *pv); err != nil {
var aerr awserr.Error
if errors.As(err, &aerr) {
// Treat any aws error as a persistent error
v.cacheObjectStorer(s3ProfileName, nil,
fmt.Errorf("persistent error while uploading to s3 profile %s, will retry later", s3ProfileName))
}
err := fmt.Errorf("error uploading PV to s3Profile %s, failed to protect cluster data for PVC %s, %w",
s3ProfileName, pvc.Name, err)
return err
}
pvcNamespacedName := types.NamespacedName{Namespace: pvc.Namespace, Name: pvc.Name}
pvcNamespacedNameString := pvcNamespacedName.String()
if err := UploadPVC(objectStore, v.s3KeyPrefix(), pvcNamespacedNameString, *pvc); err != nil {
err := fmt.Errorf("error uploading PVC to s3Profile %s, failed to protect cluster data for PVC %s, %w",
s3ProfileName, pvcNamespacedNameString, err)
return err
}
return nil
}
func (v *VRGInstance) UploadPVandPVCtoS3Stores(pvc *corev1.PersistentVolumeClaim,
log logr.Logger,
) ([]string, error) {
succeededProfiles := []string{}
// Upload the PV to all the S3 profiles in the VRG spec
for _, s3ProfileName := range v.instance.Spec.S3Profiles {
err := v.UploadPVandPVCtoS3Store(s3ProfileName, pvc)
if err != nil {
v.updatePVCClusterDataProtectedCondition(pvc.Namespace, pvc.Name, VRGConditionReasonUploadError, err.Error())
rmnutil.ReportIfNotPresent(v.reconciler.eventRecorder, v.instance, corev1.EventTypeWarning,
rmnutil.EventReasonUploadFailed, err.Error())
return succeededProfiles, err
}
succeededProfiles = append(succeededProfiles, s3ProfileName)
}
return succeededProfiles, nil
}
func (v *VRGInstance) getPVFromPVC(pvc *corev1.PersistentVolumeClaim) (corev1.PersistentVolume, error) {
pv := corev1.PersistentVolume{}
volumeName := pvc.Spec.VolumeName
pvObjectKey := client.ObjectKey{Name: volumeName}
// Get PV from k8s
if err := v.reconciler.Get(v.ctx, pvObjectKey, &pv); err != nil {
return pv, fmt.Errorf("failed to get PV %v from PVC %v, %w",
pvObjectKey, client.ObjectKeyFromObject(pvc), err)
}
return pv, nil
}
func (v *VRGInstance) getObjectStorer(s3ProfileName string) (ObjectStorer, error) {
objectStore, err := v.getCachedObjectStorer(s3ProfileName)
if objectStore != nil || err != nil {
return objectStore, err
}
objectStore, _, err = v.reconciler.ObjStoreGetter.ObjectStore(
v.ctx,
v.reconciler.APIReader,
s3ProfileName,
v.namespacedName,
v.log)
if err != nil {
err = fmt.Errorf("error creating object store for s3Profile %s, %w", s3ProfileName, err)
}
v.cacheObjectStorer(s3ProfileName, objectStore, err)
return objectStore, err
}
func (v *VRGInstance) getCachedObjectStorer(s3ProfileName string) (ObjectStorer, error) {
if cachedObjectStore, ok := v.objectStorers[s3ProfileName]; ok {
return cachedObjectStore.storer, cachedObjectStore.err
}
return nil, nil
}
func (v *VRGInstance) cacheObjectStorer(s3ProfileName string, objectStore ObjectStorer, err error) {
v.objectStorers[s3ProfileName] = cachedObjectStorer{
storer: objectStore,
err: err,
}
}
// reconcileVRsForDeletion cleans up VR resources managed by VRG and also cleans up changes made to PVCs
// TODO: Currently removes VR requests unconditionally, needs to ensure it is managed by VRG
func (v *VRGInstance) reconcileVRsForDeletion() {
v.pvcsUnprotectVolRep(v.volRepPVCs)
}
func (v *VRGInstance) pvcUnprotectVolRepIfDeleted(
pvc corev1.PersistentVolumeClaim, log logr.Logger,
) (pvcDeleted bool) {
pvcDeleted = rmnutil.ResourceIsDeleted(&pvc)
if !pvcDeleted {
return
}
log.Info("PVC unprotect VR", "deletion time", pvc.GetDeletionTimestamp())
v.pvcUnprotectVolRep(pvc, log)
return
}
func (v *VRGInstance) pvcUnprotectVolRep(pvc corev1.PersistentVolumeClaim, log logr.Logger) {
vrg := v.instance
if !v.ramenConfig.VolumeUnprotectionEnabled {
log.Info("Volume unprotection disabled")
return
}
if vrg.Spec.Async != nil && !VolumeUnprotectionEnabledForAsyncVolRep {
log.Info("Volume unprotection disabled for async mode")
return
}
if err := v.pvAndPvcObjectReplicasDelete(pvc, log); err != nil {
log.Error(err, "PersistentVolume and PersistentVolumeClaim replicas deletion failed")
v.requeue()
} else {
v.pvcsUnprotectVolRep([]corev1.PersistentVolumeClaim{pvc})
}
v.pvcStatusDeleteIfPresent(pvc.Namespace, pvc.Name, log)
}
func (v *VRGInstance) pvcsUnprotectVolRep(pvcs []corev1.PersistentVolumeClaim) {
for idx := range pvcs {
pvc := &pvcs[idx]
log := logWithPvcName(v.log, pvc)
// If the pvc does not have the VR protection finalizer, then one of the
// 2 possibilities (assuming pvc is not being deleted).
// 1) This pvc has not yet been processed by VRG before this deletion came on VRG
// 2) The VolRep resource associated with this pvc has been successfully deleted and
// the VR protection finalizer has been successfully removed. No need to process.
// If not all PVCs are processed during deletion,
// requeue the deletion request, as related events are not guaranteed
if !containsString(pvc.Finalizers, PvcVRFinalizerProtected) {
log.Info("pvc does not contain VR protection finalizer. Skipping it")
continue
}
requeueResult, skip := v.preparePVCForVRProtection(pvc, log)
if requeueResult || skip {
v.requeue()
continue
}
vrMissing, requeueResult := v.reconcileMissingVR(pvc, log)
if vrMissing || requeueResult {
v.requeue()
continue
}
if v.reconcileVRForDeletion(pvc, log) {
v.requeue()
continue
}
log.Info("Successfully processed VolumeReplication for PersistentVolumeClaim", "VR instance",
v.instance.Name)
}
}
func (v *VRGInstance) reconcileVRForDeletion(pvc *corev1.PersistentVolumeClaim, log logr.Logger) bool {
const requeue = true
pvcNamespacedName := types.NamespacedName{Name: pvc.Name, Namespace: pvc.Namespace}
if v.instance.Spec.ReplicationState == ramendrv1alpha1.Secondary {
requeueResult, ready, skip := v.reconcileVRAsSecondary(pvc, log)
if requeueResult {
log.Info("Requeuing due to failure in reconciling VolumeReplication resource as secondary")
return requeue
}
if skip || !ready {
log.Info("Skipping further processing of VolumeReplication resource as it is not ready",
"skip", skip, "ready", ready)
return !requeue
}
} else {
requeueResult, ready, err := v.processVRAsPrimary(pvcNamespacedName, pvc, log)
switch {
case err != nil:
log.Info("Requeuing due to failure in getting or creating VolumeReplication resource for PersistentVolumeClaim",
"errorValue", err)
fallthrough
case requeueResult:
return requeue
case !ready:
return requeue
}
}
return v.undoPVCFinalizersAndPVRetention(pvc, log)
}
func (v *VRGInstance) undoPVCFinalizersAndPVRetention(pvc *corev1.PersistentVolumeClaim, log logr.Logger) bool {
const requeue = true
pvcNamespacedName := types.NamespacedName{Name: pvc.Name, Namespace: pvc.Namespace}
if err := v.deleteVR(pvcNamespacedName, log); err != nil {
log.Info("Requeuing due to failure in finalizing VolumeReplication resource for PersistentVolumeClaim",
"errorValue", err)
return requeue
}
if err := v.preparePVCForVRDeletion(pvc, log); err != nil {
log.Info("Requeuing due to failure in preparing PersistentVolumeClaim for VolumeReplication deletion",
"errorValue", err)
return requeue
}
return !requeue
}
// reconcileMissingVR determines if VR is missing, and if missing completes other steps required for
// reconciliation during deletion.
//
// VR can be missing:
// - if no VR was created post initial processing, by when VRG was deleted. In this case no PV was also
// uploaded, as VR is created first before PV is uploaded.
// - if VR was deleted in a prior reconcile, during VRG deletion, but steps post VR deletion were not
// completed, at this point a deleted VR is also not processed further (its generation would have been
// updated)
//
// Returns 2 booleans:
// - the first indicating if VR is missing or not, to enable further VR processing if needed
// - the next indicating any required requeue of the request, due to errors in determining VR presence
func (v *VRGInstance) reconcileMissingVR(pvc *corev1.PersistentVolumeClaim, log logr.Logger) (bool, bool) {
const (
requeue = true
vrMissing = true
)
if v.instance.Spec.Async == nil {
return !vrMissing, !requeue
}
volRep := &volrep.VolumeReplication{}
vrNamespacedName := types.NamespacedName{Name: pvc.Name, Namespace: pvc.Namespace}
err := v.reconciler.Get(v.ctx, vrNamespacedName, volRep)
if err == nil {
if rmnutil.ResourceIsDeleted(volRep) {
log.Info("Requeuing due to processing a deleted VR")
return !vrMissing, requeue
}
return !vrMissing, !requeue
}
if !k8serrors.IsNotFound(err) {
log.Info("Requeuing due to failure in getting VR resource", "errorValue", err)
return !vrMissing, requeue
}
log.Info("Unprotecting PVC as VR is missing")
if err := v.preparePVCForVRDeletion(pvc, log); err != nil {
log.Info("Requeuing due to failure in preparing PersistentVolumeClaim for deletion",
"errorValue", err)
return vrMissing, requeue
}
return vrMissing, !requeue
}
func (v *VRGInstance) deleteClusterDataInS3Stores(log logr.Logger) error {
log.Info("Delete cluster data in", "s3Profiles", v.instance.Spec.S3Profiles)
keyPrefix := v.s3KeyPrefix()
return v.s3StoresDo(
func(s ObjectStorer) error { return s.DeleteObjectsWithKeyPrefix(keyPrefix) },
fmt.Sprintf("delete objects with key prefix %s", keyPrefix),
)
}
func (v *VRGInstance) pvAndPvcObjectReplicasDelete(pvc corev1.PersistentVolumeClaim, log logr.Logger) error {
vrg := v.instance
log.Info("Delete PV and PVC object replicas", "s3Profiles", vrg.Spec.S3Profiles)
keyPrefix := v.s3KeyPrefix()
pvcNamespacedName := client.ObjectKeyFromObject(&pvc)
keys := []string{
TypedObjectKey(keyPrefix, pvc.Spec.VolumeName, corev1.PersistentVolume{}),
TypedObjectKey(keyPrefix, pvcNamespacedName.String(), corev1.PersistentVolumeClaim{}),
}
if pvc.Namespace == vrg.Namespace {
keys = append(keys, TypedObjectKey(keyPrefix, pvc.Name, corev1.PersistentVolumeClaim{}))
}
return v.s3StoresDo(
func(s ObjectStorer) error { return s.DeleteObjects(keys...) },
fmt.Sprintf("delete object replicas %v", keys),
)
}
func (v *VRGInstance) s3StoresDo(do func(ObjectStorer) error, msg string) error {
for _, s3ProfileName := range v.instance.Spec.S3Profiles {
if s3ProfileName == NoS3StoreAvailable {
v.log.Info("NoS3 available to clean")
continue
}
if err := v.s3StoreDo(do, msg, s3ProfileName); err != nil {
return fmt.Errorf("%s using profile %s, err %w", msg, s3ProfileName, err)
}
}
return nil
}
func (v *VRGInstance) s3StoreDo(do func(ObjectStorer) error, msg, s3ProfileName string) (err error) {
objectStore, _, err := v.reconciler.ObjStoreGetter.ObjectStore(
v.ctx,
v.reconciler.APIReader,
s3ProfileName,
v.namespacedName, // debugTag
v.log,
)
if err != nil {