forked from RamenDR/ramen
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathvshandler.go
More file actions
3499 lines (2748 loc) · 105 KB
/
Copy pathvshandler.go
File metadata and controls
3499 lines (2748 loc) · 105 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
// SPDX-FileCopyrightText: The RamenDR authors
// SPDX-License-Identifier: Apache-2.0
package volsync
import (
"context"
"fmt"
"os"
"slices"
"strconv"
"strings"
volsyncv1alpha1 "github.com/backube/volsync/api/v1alpha1"
"github.com/go-logr/logr"
snapv1 "github.com/kubernetes-csi/external-snapshotter/client/v8/apis/volumesnapshot/v1"
vgsv1beta1 "github.com/red-hat-storage/external-snapshotter/client/v8/apis/volumegroupsnapshot/v1beta1"
batchv1 "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
storagev1 "k8s.io/api/storage/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/tools/reference"
"k8s.io/utils/ptr"
"sigs.k8s.io/controller-runtime/pkg/client"
ctrlutil "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
ramendrv1alpha1 "github.com/ramendr/ramen/api/v1alpha1"
"github.com/ramendr/ramen/internal/controller/util"
)
const (
ServiceExportKind string = "ServiceExport"
ServiceExportGroup string = "multicluster.x-k8s.io"
ServiceExportVersion string = "v1alpha1"
VolumeSnapshotKind string = "VolumeSnapshot"
VolumeSnapshotIsDefaultAnnotation string = "snapshot.storage.kubernetes.io/is-default-class"
VolumeSnapshotIsDefaultAnnotationValue string = "true"
PodVolumePVCClaimIndexName string = "spec.volumes.persistentVolumeClaim.claimName"
VolumeAttachmentToPVIndexName string = "spec.source.persistentVolumeName"
FinalSyncTriggerString string = "vrg-final-sync"
PrepareForFinalSyncTriggerString string = "PREPARE-FOR-FINAL-SYNC-STOP-SCHEDULING"
SchedulingIntervalMinLength int = 2
CronSpecMaxDayOfMonth int = 28
VolSyncDoNotDeleteLabel = "volsync.backube/do-not-delete" // TODO: point to volsync constant once it is available
VolSyncDoNotDeleteLabelVal = "true"
// See: https://issues.redhat.com/browse/ACM-1256
// https://github.com/stolostron/backlog/issues/21824
ACMAppSubDoNotDeleteAnnotation = "apps.open-cluster-management.io/do-not-delete"
ACMAppSubDoNotDeleteAnnotationVal = "true"
OwnerNameAnnotation = "ramendr.openshift.io/owner-name"
OwnerNamespaceAnnotation = "ramendr.openshift.io/owner-namespace"
// StorageClass label
StorageIDLabel = "ramendr.openshift.io/storageid"
PVAnnotationRetentionKey = "volumereplicationgroups.ramendr.openshift.io/volsync-retained"
PVAnnotationRetentionValue = "retained"
PVCFinalizerProtected = "volumereplicationgroups.ramendr.openshift.io/pvc-volsync-protection"
// Prefix for the job that mounts unmounted PVC when RS is not found
VolSyncMountJobNamePrefix = "volsync-pvc-mount-"
)
type VSHandler struct {
ctx context.Context
client client.Client
log logr.Logger
owner metav1.Object
schedulingInterval string
volumeSnapshotClassSelector metav1.LabelSelector // volume snapshot classes to be filtered label selector
defaultCephFSCSIDriverName string
destinationCopyMethod volsyncv1alpha1.CopyMethodType
volumeSnapshotClassList *snapv1.VolumeSnapshotClassList
vrgInAdminNamespace bool
workloadStatus string
moverConfig []ramendrv1alpha1.MoverConfig
}
func NewVSHandler(ctx context.Context, client client.Client, log logr.Logger, owner metav1.Object,
asyncSpec *ramendrv1alpha1.VRGAsyncSpec, defaultCephFSCSIDriverName string, copyMethod string,
adminNamespaceVRG bool,
) *VSHandler {
vsHandler := &VSHandler{
ctx: ctx,
client: client,
log: log,
owner: owner,
defaultCephFSCSIDriverName: defaultCephFSCSIDriverName,
destinationCopyMethod: volsyncv1alpha1.CopyMethodType(copyMethod),
volumeSnapshotClassList: nil, // Do not initialize until we need it
vrgInAdminNamespace: adminNamespaceVRG,
}
if asyncSpec != nil {
vsHandler.schedulingInterval = asyncSpec.SchedulingInterval
vsHandler.volumeSnapshotClassSelector = asyncSpec.VolumeSnapshotClassSelector
}
vrg, ok := owner.(*ramendrv1alpha1.VolumeReplicationGroup)
if !ok {
log.Info("VolumeReplicationGroup(PVC) map function received non-VRG resource")
} else {
vsHandler.moverConfig = append([]ramendrv1alpha1.MoverConfig(nil), vrg.Spec.VolSync.MoverConfig...)
}
return vsHandler
}
func (v *VSHandler) GetWorkloadStatus() string {
return v.workloadStatus
}
func (v *VSHandler) GetOwner() metav1.Object {
return v.owner
}
func (v *VSHandler) GetMoverConfigForPVC(pvcName, pvcNamespace string) *ramendrv1alpha1.MoverConfig {
if len(v.moverConfig) > 0 {
for _, mc := range v.moverConfig {
if mc.PVCName == pvcName && mc.PVCNameSpace == pvcNamespace {
return &mc
}
}
}
return nil
}
func (v *VSHandler) SetWorkloadStatus(status string) {
v.workloadStatus = status
}
// returns replication destination only if create/update is successful and the RD is considered available.
// Callers should assume getting a nil replication destination back means they should retry/requeue.
//
//nolint:cyclop,funlen
func (v *VSHandler) ReconcileRD(
rdSpec ramendrv1alpha1.VolSyncReplicationDestinationSpec,
moverConfig *ramendrv1alpha1.MoverConfig) (*volsyncv1alpha1.ReplicationDestination,
*ramendrv1alpha1.VolSyncReplicationDestinationInfo, error,
) {
l := v.log.WithValues("rdSpec", rdSpec)
if !rdSpec.ProtectedPVC.ProtectedByVolSync {
return nil, nil, fmt.Errorf("protectedPVC %s is not VolSync Enabled", rdSpec.ProtectedPVC.Name)
}
// Pre-allocated shared secret - DRPC will generate and propagate this secret from hub to clusters
pskSecretName := GetVolSyncPSKSecretNameFromVRGName(v.owner.GetName())
// Need to confirm this secret exists on the cluster before proceeding, otherwise volsync will generate it
err := v.ensurePSKSecretReady(pskSecretName, rdSpec.ProtectedPVC.Namespace)
if err != nil {
return nil, nil, err
}
// Check if a ReplicationSource is still here (Can happen if transitioning from primary to secondary)
// Before creating a new RD for this PVC, make sure any ReplicationSource for this PVC is cleaned up first
// This avoids a scenario where we create an RD that immediately syncs with an RS that still exists locally
err = v.DeleteRS(rdSpec.ProtectedPVC.Name, rdSpec.ProtectedPVC.Namespace, false)
if err != nil {
return nil, nil, err
}
dstPVC, err := v.PrecreateDestPVCIfEnabled(rdSpec)
if err != nil {
return nil, nil, err
}
var rd *volsyncv1alpha1.ReplicationDestination
rd, err = v.createOrUpdateRD(rdSpec, pskSecretName, dstPVC, moverConfig)
if err != nil {
return nil, nil, err
}
if err = v.AssignRDAndRSAsOwnerToProtectedPVC(rd, rdSpec.ProtectedPVC); err != nil {
return nil, nil, err
}
err = v.ReconcileServiceExportForRD(rd)
if err != nil {
return nil, nil, err
}
return v.generateRDInfo(rdSpec, rd, l)
}
func (v *VSHandler) ensurePSKSecretReady(pskSecretName, namespace string) error {
secretExists, err := v.ValidateSecretAndAddVRGOwnerRef(pskSecretName)
if err != nil {
return err
}
if !secretExists {
return fmt.Errorf("psk secret: %s is not found", pskSecretName)
}
if v.vrgInAdminNamespace {
return v.CopySecretToPVCNamespace(pskSecretName, namespace)
}
return nil
}
func (v *VSHandler) generateRDInfo(
rdSpec ramendrv1alpha1.VolSyncReplicationDestinationSpec,
rd *volsyncv1alpha1.ReplicationDestination,
l logr.Logger,
) (*volsyncv1alpha1.ReplicationDestination, *ramendrv1alpha1.VolSyncReplicationDestinationInfo, error) {
isSubmarinerEnabled := v.IsSubmarinerEnabled()
if isSubmarinerEnabled {
err := v.ReconcileServiceExportForRD(rd)
if err != nil {
return nil, nil, err
}
}
if !RDStatusReady(rd, l) {
return nil, nil, nil
}
err := v.pruneOldSnapshots(rd.Namespace)
if err != nil {
return nil, nil, err
}
if isSubmarinerEnabled {
l.V(1).Info(fmt.Sprintf("ReplicationDestination Reconcile Complete rd=%s, Copy method: %s",
rd.Name, v.destinationCopyMethod))
return rd, nil, nil
}
if rd.Status.RsyncTLS == nil || rd.Status.RsyncTLS.Address == nil {
return nil, nil, fmt.Errorf("RD status missing rsyncTLS address for PVC %s", rdSpec.ProtectedPVC.Name)
}
rdInfo := &ramendrv1alpha1.VolSyncReplicationDestinationInfo{
ProtectedPVC: rdSpec.ProtectedPVC,
RsyncTLS: &ramendrv1alpha1.RsyncTLSConfig{
Address: *rd.Status.RsyncTLS.Address,
},
}
l.V(1).Info("ReplicationDestination Reconcile Complete (no Submariner)",
"rd", rd.Name, "copyMethod", v.destinationCopyMethod, "address", *rd.Status.RsyncTLS.Address)
return rd, rdInfo, nil
}
// For ReplicationDestination - considered ready when a sync has completed
// - rsync address should be filled out in the status
// - latest image should be set properly in the status (at least one sync cycle has completed and we have a snapshot)
func RDStatusReady(rd *volsyncv1alpha1.ReplicationDestination, log logr.Logger) bool {
if rd.Status == nil {
return false
}
if rd.Status.RsyncTLS == nil || rd.Status.RsyncTLS.Address == nil {
log.V(1).Info("ReplicationDestination waiting for Address ...")
return false
}
return true
}
func (v *VSHandler) setRDAndRSAsOwnerOfPVC(
obj client.Object,
pvc *corev1.PersistentVolumeClaim,
) error {
// Only set OwnerReference if RD and PVC are in the same namespace
if obj.GetNamespace() != pvc.Namespace {
return nil
}
// Work on a deep copy to avoid mutating caller's object
updated := pvc.DeepCopy()
kind, err := getKindRSorRD(obj)
if err != nil {
return err
}
// Create a new controller reference
ref := metav1.NewControllerRef(
obj,
volsyncv1alpha1.GroupVersion.WithKind(kind))
// Overwrite OwnerReferences with the new one
updated.SetOwnerReferences([]metav1.OwnerReference{*ref})
// Update the PVC
if err := v.client.Update(v.ctx, updated); err != nil {
v.log.Error(err, "Failed to update ProtectedPVC", "PVC", pvc.Name)
return err
}
return nil
}
func getKindRSorRD(obj runtime.Object) (string, error) {
switch obj.(type) {
case *volsyncv1alpha1.ReplicationDestination:
return "ReplicationDestination", nil
case *volsyncv1alpha1.ReplicationSource:
return "ReplicationSource", nil
default:
return "", fmt.Errorf("unsupported object type: %T", obj)
}
}
func (v *VSHandler) AssignRDAndRSAsOwnerToProtectedPVC(
obj client.Object,
protectedPVC ramendrv1alpha1.ProtectedPVC,
) error {
if protectedPVC.Name == "" || protectedPVC.Namespace == "" {
v.log.Info("No ProtectedPVC specified in ReplicationDestination spec")
return nil
}
key := types.NamespacedName{
Namespace: protectedPVC.Namespace,
Name: protectedPVC.Name,
}
pvc, err := v.getPVC(key)
if err != nil {
// todo check expected behavior in this case.
if errors.IsNotFound(err) {
v.log.Info("No ProtectedPVC found", "PVC", key)
return nil
}
v.log.Error(err, "Failed to get PVC from ProtectedPVC reference", "namespace", key.Namespace, "name", key.Name)
return err
}
if err := v.setRDAndRSAsOwnerOfPVC(obj, pvc); err != nil {
v.log.Error(err, "Failed to assign RD ownership to PVC", "pvc", pvc.Name)
return err
}
return nil
}
//nolint:funlen
func (v *VSHandler) createOrUpdateRD(
rdSpec ramendrv1alpha1.VolSyncReplicationDestinationSpec, pskSecretName string,
dstPVC *string, moverConfigSpec *ramendrv1alpha1.MoverConfig) (*volsyncv1alpha1.ReplicationDestination, error,
) {
l := v.log.WithValues("rdSpec", rdSpec)
volumeSnapshotClassName, err := v.GetVolumeSnapshotClassFromPVCStorageClass(rdSpec.ProtectedPVC.StorageClassName)
if err != nil {
return nil, err
}
pvcAccessModes := []corev1.PersistentVolumeAccessMode{corev1.ReadWriteOnce} // Default value
if len(rdSpec.ProtectedPVC.AccessModes) > 0 {
pvcAccessModes = rdSpec.ProtectedPVC.AccessModes
}
rd := &volsyncv1alpha1.ReplicationDestination{
ObjectMeta: metav1.ObjectMeta{
Name: util.GetReplicationDestinationName(rdSpec.ProtectedPVC.Name),
Namespace: rdSpec.ProtectedPVC.Namespace,
},
}
util.AddLabel(rd, util.CreatedByRamenLabel, "true")
op, err := ctrlutil.CreateOrUpdate(v.ctx, v.client, rd, func() error {
util.AddLabel(rd, util.VRGOwnerNameLabel, v.owner.GetName())
util.AddLabel(rd, util.VRGOwnerNamespaceLabel, v.owner.GetNamespace())
util.AddAnnotation(rd, OwnerNameAnnotation, v.owner.GetName())
util.AddAnnotation(rd, OwnerNamespaceAnnotation, v.owner.GetNamespace())
moverConfig := volsyncv1alpha1.MoverConfig{}
if moverConfigSpec != nil {
moverConfig = volsyncv1alpha1.MoverConfig{
MoverSecurityContext: moverConfigSpec.MoverSecurityContext,
MoverServiceAccount: moverConfigSpec.MoverServiceAccount,
}
}
rd.Spec.RsyncTLS = &volsyncv1alpha1.ReplicationDestinationRsyncTLSSpec{
ServiceType: v.GetRsyncServiceType(),
KeySecret: &pskSecretName,
ReplicationDestinationVolumeOptions: volsyncv1alpha1.ReplicationDestinationVolumeOptions{
CopyMethod: volsyncv1alpha1.CopyMethodSnapshot,
Capacity: rdSpec.ProtectedPVC.Resources.Requests.Storage(),
StorageClassName: rdSpec.ProtectedPVC.StorageClassName,
AccessModes: pvcAccessModes,
VolumeSnapshotClassName: &volumeSnapshotClassName,
DestinationPVC: dstPVC,
},
MoverConfig: moverConfig,
}
return nil
})
if err != nil {
return nil, fmt.Errorf("%w", err)
}
l.V(1).Info("ReplicationDestination createOrUpdate Complete", "op", op)
return rd, nil
}
func (v *VSHandler) IsPVCInUseByNonRDPod(pvcNamespacedName types.NamespacedName) (bool, error) {
rd := &volsyncv1alpha1.ReplicationDestination{}
// IF RD is Found, then no more checks are needed. We'll assume that the RD
// was created when the PVC was Not in use.
err := v.client.Get(v.ctx, pvcNamespacedName, rd)
if err == nil {
return false, nil
} else if !errors.IsNotFound(err) {
return false, fmt.Errorf("%w", err)
}
// PVC must not be in use
pvcInUse, err := v.pvcExistsAndInUse(pvcNamespacedName, false)
if err != nil {
return false, err
}
if pvcInUse {
return true, nil
}
// Not in-use
return false, nil
}
// Returns true only if runFinalSync is true and the final sync is done
// Returns replication source only if create/update is successful
// Callers should assume getting a nil replication source back means they should retry/requeue.
// Returns true/false if final sync is complete, and also returns an RS if one was reconciled.
//
//nolint:cyclop,funlen,gocognit,gocyclo
func (v *VSHandler) ReconcileRS(rsSpec ramendrv1alpha1.VolSyncReplicationSourceSpec,
runFinalSync bool,
moverConfig *ramendrv1alpha1.MoverConfig) (bool /* finalSyncComplete */, *volsyncv1alpha1.ReplicationSource, error,
) {
l := v.log.WithValues("rsSpec", rsSpec, "runFinalSync", runFinalSync)
l.Info("Reconciling RS")
if !rsSpec.ProtectedPVC.ProtectedByVolSync {
return false, nil, fmt.Errorf("protectedPVC %s is not VolSync Enabled", rsSpec.ProtectedPVC.Name)
}
// Pre-allocated shared secret - DRPC will generate and propagate this secret from hub to clusters
pskSecretName := GetVolSyncPSKSecretNameFromVRGName(v.owner.GetName())
// Need to confirm this secret exists on the cluster before proceeding, otherwise volsync will generate it
secretExists, err := v.ValidateSecretAndAddVRGOwnerRef(pskSecretName)
if err != nil || !secretExists {
return false, nil, err
}
if v.vrgInAdminNamespace {
// copy th secret to the namespace where the PVC is
err = v.CopySecretToPVCNamespace(pskSecretName, rsSpec.ProtectedPVC.Namespace)
if err != nil {
return false, nil, err
}
}
// Check if a ReplicationDestination is still here (Can happen if transitioning from secondary to primary)
// Before creating a new RS for this PVC, make sure any ReplicationDestination for this PVC is cleaned up first
// This avoids a scenario where we create an RS that immediately connects back to an RD that still exists locally
// Need to be sure ReconcileRS is never called prior to restoring any PVC that need to be restored from RDs first
err = v.DeleteRD(rsSpec.ProtectedPVC.Name, rsSpec.ProtectedPVC.Namespace, false)
if err != nil {
return false, nil, err
}
// When PVC is unmounted and RS for that PVC is not found, create a job to mount the PVC
mountJobReady, err := v.EnsureMountJobForUnmountedPVC(&rsSpec)
if err != nil {
return false, nil, err
}
if !mountJobReady {
return false, nil, nil // Requeue until mount job completes
}
pvcOk, err := v.validatePVCForFinalSync(rsSpec, runFinalSync)
if !pvcOk || err != nil {
existingRS, hErr := v.handlePVCNotReady(rsSpec, err)
return false, existingRS, hErr
}
replicationSource, err := v.createOrUpdateRS(rsSpec, pskSecretName, runFinalSync, moverConfig)
if err != nil {
return false, replicationSource, err
}
if replicationSource == nil {
return false, nil, nil // Requeue
}
if err = v.AssignRDAndRSAsOwnerToProtectedPVC(replicationSource, rsSpec.ProtectedPVC); err != nil {
return false, replicationSource, err
}
//
// For final sync only - check status to make sure the final sync is complete
// and also run cleanup (removes PVC we just ran the final sync from)
//
if runFinalSync && isFinalSyncComplete(replicationSource, l) {
err := v.UndoAfterFinalSync(rsSpec.ProtectedPVC.Name, rsSpec.ProtectedPVC.Namespace)
if err != nil {
return false, replicationSource, err
}
return true, replicationSource, v.CleanupAfterRSFinalSync(rsSpec.ProtectedPVC.Name, rsSpec.ProtectedPVC.Namespace)
}
l.V(1).Info("ReplicationSource Reconcile Complete")
return false, replicationSource, err
}
// Validate that the PVC is no longer in use before proceeding with the final sync.
func (v *VSHandler) validatePVCForFinalSync(rsSpec ramendrv1alpha1.VolSyncReplicationSourceSpec,
runFinalSync bool) (bool, error,
) {
if runFinalSync {
// If runFinalSync, check the PVC and make sure it's not mounted to a pod
// as we want the app to be quiesced/removed before running final sync
pvcIsMounted, err := v.pvcExistsAndInUse(util.ProtectedPVCNamespacedName(rsSpec.ProtectedPVC), false)
if err != nil {
return false, err
}
if pvcIsMounted {
v.workloadStatus = "active"
return false, nil
}
}
return true, nil
}
func isFinalSyncComplete(replicationSource *volsyncv1alpha1.ReplicationSource, log logr.Logger) bool {
if replicationSource.Status == nil || replicationSource.Status.LastManualSync != FinalSyncTriggerString {
log.V(1).Info("ReplicationSource running final sync - waiting for status ...")
return false
}
log.V(1).Info("ReplicationSource final sync complete")
return true
}
func (v *VSHandler) CleanupAfterRSFinalSync(pvcName, pvcNamespace string) error {
// Final sync is done, make sure PVC is cleaned up, Skip if we are using CopyMethodDirect
if v.IsCopyMethodDirect() {
v.log.Info("Preserving PVC to use for CopyMethodDirect", "pvcName", pvcName)
return nil
}
v.log.Info("Cleanup after final sync", "pvcName", pvcName)
return util.DeletePVC(v.ctx, v.client, pvcName, pvcNamespace, v.log)
}
//nolint:funlen
func (v *VSHandler) createOrUpdateRS(rsSpec ramendrv1alpha1.VolSyncReplicationSourceSpec,
pskSecretName string, runFinalSync bool,
moverConfigSpec *ramendrv1alpha1.MoverConfig) (*volsyncv1alpha1.ReplicationSource, error,
) {
l := v.log.WithValues("rsSpec", rsSpec, "runFinalSync", runFinalSync)
storageClass, err := v.getStorageClass(rsSpec.ProtectedPVC.StorageClassName)
if err != nil {
return nil, err
}
v.ModifyRSSpecForCephFS(&rsSpec, storageClass)
volumeSnapshotClassName, err := v.getVolumeSnapshotClassFromPVCStorageClass(storageClass)
if err != nil {
return nil, err
}
// Remote service address created for the ReplicationDestination on the secondary
// The secondary namespace will be the same as primary namespace so use the vrg.Namespace
remoteAddress, err := v.resolveRemoteAddress(rsSpec)
if err != nil {
l.Error(err, "unable to resolve remote address")
return nil, err
}
rs := &volsyncv1alpha1.ReplicationSource{
ObjectMeta: metav1.ObjectMeta{
Name: getReplicationSourceName(rsSpec.ProtectedPVC.Name),
Namespace: rsSpec.ProtectedPVC.Namespace,
},
}
util.AddLabel(rs, util.CreatedByRamenLabel, "true")
// Handle final sync by retaining the PV and creating a tmpPVC used for final sync
stop := v.setupForFinalSync(&rsSpec, runFinalSync)
if stop {
l.V(1).Info("Waiting to set up for final sync")
return nil, nil
}
op, err := ctrlutil.CreateOrUpdate(v.ctx, v.client, rs, func() error {
util.AddLabel(rs, util.VRGOwnerNameLabel, v.owner.GetName())
util.AddLabel(rs, util.VRGOwnerNamespaceLabel, v.owner.GetNamespace())
rs.Spec.SourcePVC = rsSpec.ProtectedPVC.Name
if err := v.configureReplicationSourceSpec(rs, &rsSpec, runFinalSync); err != nil {
return err
}
moverConfig := &volsyncv1alpha1.MoverConfig{}
if moverConfigSpec != nil {
moverConfig = &volsyncv1alpha1.MoverConfig{
MoverSecurityContext: moverConfigSpec.MoverSecurityContext,
MoverServiceAccount: moverConfigSpec.MoverServiceAccount,
}
}
rs.Spec.RsyncTLS = &volsyncv1alpha1.ReplicationSourceRsyncTLSSpec{
KeySecret: &pskSecretName,
Address: &remoteAddress,
ReplicationSourceVolumeOptions: volsyncv1alpha1.ReplicationSourceVolumeOptions{
// Always using CopyMethod of snapshot for now - could use 'Clone' CopyMethod for specific
// storage classes that support it in the future
CopyMethod: volsyncv1alpha1.CopyMethodSnapshot,
VolumeSnapshotClassName: &volumeSnapshotClassName,
StorageClassName: rsSpec.ProtectedPVC.StorageClassName,
AccessModes: rsSpec.ProtectedPVC.AccessModes,
},
MoverConfig: *moverConfig,
}
return nil
})
if err != nil {
return nil, fmt.Errorf("%w", err)
}
l.V(1).Info("ReplicationSource createOrUpdate Complete", "op", op)
return rs, nil
}
func (v *VSHandler) resolveRemoteAddress(rsSpec ramendrv1alpha1.VolSyncReplicationSourceSpec) (string, error) {
if util.IsSubmarinerEnabled(v.owner.GetAnnotations()) {
// Remote service address created for the ReplicationDestination on the secondary
// The secondary namespace will be the same as primary namespace so use the vrg.Namespace
remoteAddress := util.GetRemoteServiceNameForRDFromPVCName(rsSpec.ProtectedPVC.Name, rsSpec.ProtectedPVC.Namespace)
v.log.Info("Using Submariner remote address", "remoteAddress", remoteAddress)
return remoteAddress, nil
}
if rsSpec.RsyncTLS == nil {
return "", fmt.Errorf("rsSpec.RsyncTLS is nil for PVC %s", rsSpec.ProtectedPVC.Name)
}
v.log.Info("Using direct TLS remote address", "remoteAddress", rsSpec.RsyncTLS.Address)
return rsSpec.RsyncTLS.Address, nil
}
//nolint:cyclop
func (v *VSHandler) setupForFinalSync(rsSpec *ramendrv1alpha1.VolSyncReplicationSourceSpec, runFinalSync bool) bool {
const stop = true
const proceed = !stop
rs, err := v.getRS(getReplicationSourceName(rsSpec.ProtectedPVC.Name), rsSpec.ProtectedPVC.Namespace)
if err != nil {
if errors.IsNotFound(err) {
v.log.Info("ReplicationSource not found, proceeding with setup")
return proceed
}
v.log.Error(err, "Failed to retrieve ReplicationSource")
return stop
}
// If final sync is not triggered, check if it's already prepared
if !runFinalSync {
if rs.Spec.Trigger != nil && rs.Spec.Trigger.Manual == PrepareForFinalSyncTriggerString {
v.log.Info("Final sync preparation detected, waiting for confirmation to proceed")
return stop
}
return proceed
}
pvc, err := v.getPVC(types.NamespacedName{Namespace: rsSpec.ProtectedPVC.Namespace, Name: rsSpec.ProtectedPVC.Name})
if err != nil {
v.log.Error(err, "Failed to retrieve application PVC", "pvcName", rsSpec.ProtectedPVC.Name)
return stop
}
// Ensure the application PVC is deleted before proceeding with final sync
if !util.ResourceIsDeleted(pvc) {
v.log.Info("Final sync will not run until PVC is deleted", "namespace", pvc.Namespace, "name", pvc.Name)
return stop
}
// Proceed only if the ReplicationSource trigger is set for final sync
if rs.Spec.Trigger != nil && rs.Spec.Trigger.Manual == PrepareForFinalSyncTriggerString {
requeue, err := v.SetupTmpPVCForFinalSync(pvc)
if err != nil {
v.log.Error(err, "Failed to set up temporary PVC for final sync")
return stop
}
if requeue {
v.log.Info("Waiting for temporary PVC readiness before final sync")
return stop
}
}
return proceed
}
// Handles the creation and management of the tmpPVC for final sync
func (v *VSHandler) SetupTmpPVCForFinalSync(pvc *corev1.PersistentVolumeClaim) (bool, error) {
tmpPVC, err := v.getPVC(types.NamespacedName{
Namespace: pvc.Namespace,
Name: util.GetTmpPVCNameForFinalSync(pvc.Name),
})
if err != nil && errors.IsNotFound(err) {
tmpPVC, err = v.retainPVAndCreateTmpPVC(pvc)
if err != nil || tmpPVC == nil {
return true, err
}
}
// Handle the case where tmpPVC is in the ClaimLost phase
if tmpPVC.Status.Phase == corev1.ClaimLost {
v.log.Info("tmpPVC phase is lost", "pvcName", tmpPVC.GetName())
delete(tmpPVC.Annotations, "pv.kubernetes.io/bind-completed")
if err := v.client.Update(v.ctx, tmpPVC); err != nil {
return true, err
}
}
return false, nil
}
func (v *VSHandler) retainPVAndCreateTmpPVC(pvc *corev1.PersistentVolumeClaim) (*corev1.PersistentVolumeClaim, error) {
// Retain the PersistentVolume
if err := v.retainPVForPVC(*pvc); err != nil {
v.log.Info("Requeuing, as retaining PersistentVolume failed", "error", err)
return nil, err
}
// Create tmpPVC for final sync
tmpPVC, op, err := v.createTmpPVCForFinalSync(types.NamespacedName{
Namespace: pvc.Namespace,
Name: pvc.Name,
})
if err != nil {
return nil, err
}
// If tmpPVC was just created, log and requeue
if op == ctrlutil.OperationResultCreated {
v.log.Info("Tmp PVC created. Waiting before proceeding.", "pvcName", tmpPVC.GetName())
return nil, nil
}
return tmpPVC, nil
}
func (v *VSHandler) retainPVForPVC(pvc corev1.PersistentVolumeClaim) error {
l := v.log.WithValues("pvc", pvc.Name)
l.V(1).Info("retain PV for PVC")
// Get PV bound to PVC
pv := &corev1.PersistentVolume{}
pvObjectKey := client.ObjectKey{
Name: pvc.Spec.VolumeName,
}
if err := v.client.Get(v.ctx, pvObjectKey, pv); err != nil {
l.Error(err, "Failed to get pv", "volumeName", pvc.Spec.VolumeName)
return fmt.Errorf("failed to get pv (%s) for pvc (%s/%s), %w", pvc.Spec.VolumeName, pvc.Namespace, pvc.Name, err)
}
mutate := func(obj client.Object) error {
pvObj, ok := obj.(*corev1.PersistentVolume)
if !ok {
return fmt.Errorf("expected *corev1.PersistentVolume, got %T", obj)
}
if pvObj.ObjectMeta.Annotations == nil {
pvObj.ObjectMeta.Annotations = map[string]string{}
}
pvObj.ObjectMeta.Annotations[PVAnnotationRetentionKey] = PVAnnotationRetentionValue
if pvObj.Spec.ClaimRef == nil {
pvObj.Spec.ClaimRef = &corev1.ObjectReference{}
}
tmpPVCName := util.GetTmpPVCNameForFinalSync(pvc.Name)
if pvObj.Spec.PersistentVolumeReclaimPolicy == corev1.PersistentVolumeReclaimRetain &&
pvObj.Spec.ClaimRef.Name == tmpPVCName && pvObj.Spec.ClaimRef.Namespace == pvc.Namespace {
return nil
}
// if not retained, retain PV, and add an annotation to denote this is updated for VolSync needs
pvObj.Spec.PersistentVolumeReclaimPolicy = corev1.PersistentVolumeReclaimRetain
if pvObj.Spec.ClaimRef.Name != tmpPVCName {
updateClaimRef(pvObj, tmpPVCName, pvc.Namespace)
}
return nil
}
return v.updateResource(pv, mutate)
}
func (v *VSHandler) createTmpPVCForFinalSync(pvcNamespacedName types.NamespacedName,
) (*corev1.PersistentVolumeClaim, ctrlutil.OperationResult, error) {
tmpPVC, err := v.getPVC(types.NamespacedName{
Namespace: pvcNamespacedName.Namespace,
Name: util.GetTmpPVCNameForFinalSync(pvcNamespacedName.Name),
})
if err != nil {
if !errors.IsNotFound(err) {
return nil, ctrlutil.OperationResultNone, err
}
pvc, err := v.getPVC(pvcNamespacedName)
if err != nil {
return nil, ctrlutil.OperationResultNone, err
}
tmpPVC = pvc.DeepCopy()
tmpPVC.Name = util.GetTmpPVCNameForFinalSync(pvc.Name)
tmpPVC.ResourceVersion = ""
tmpPVC.UID = ""
tmpPVC.Finalizers = nil
tmpPVC.Annotations = map[string]string{} // {"ramendr/tmp-pvc-created": "yes"}
// We don't need any labels by default, but if the original PVC has a CG label,
// include it on the tmpPVC so that if the CG is enabled the tmpPVC will be included
// in the same CG as the original PVC.
// Note: We are not copying the original PVC labels, they are not copied as we don't
// want the tmpPVC to be selected by any label selectors that may have been used
// to select the original PVC (e.g. VRG PVC label selector)
// We only need the CG label if it exists.
tmpPVC.ObjectMeta.Labels = map[string]string{util.CreatedByRamenLabel: "true"}
if cgVal, ok := pvc.GetLabels()[util.ConsistencyGroupLabel]; ok {
tmpPVC.ObjectMeta.Labels[util.ConsistencyGroupLabel] = cgVal
}
} else {
v.log.V(1).Info("Found tmp PVC", "tmpPVC", tmpPVC.Name)
return tmpPVC, ctrlutil.OperationResultNone, nil
}
op, err := ctrlutil.CreateOrUpdate(v.ctx, v.client, tmpPVC, func() error {
return nil
})
if err != nil {
return nil, ctrlutil.OperationResultNone, err
}
v.log.V(1).Info("Tmp PVC created", "operation", op)
return tmpPVC, op, nil
}
func (v *VSHandler) configureReplicationSourceSpec(rs *volsyncv1alpha1.ReplicationSource,
rsSpec *ramendrv1alpha1.VolSyncReplicationSourceSpec, runFinalSync bool,
) error {
if runFinalSync {
v.log.V(1).Info("ReplicationSource - final sync")
rs.Spec.Paused = false
rs.Spec.SourcePVC = util.GetTmpPVCNameForFinalSync(rsSpec.ProtectedPVC.Name)
// Set trigger for final sync
rs.Spec.Trigger = &volsyncv1alpha1.ReplicationSourceTriggerSpec{
Manual: FinalSyncTriggerString,
}
} else {
// Set schedule trigger
scheduleCronSpec, err := v.getScheduleCronSpec()
if err != nil {
v.log.Error(err, "unable to parse schedulingInterval")
return err
}
rs.Spec.Trigger = &volsyncv1alpha1.ReplicationSourceTriggerSpec{
Schedule: scheduleCronSpec,
}
}
return nil
}
//nolint:cyclop,funlen
func (v *VSHandler) UndoAfterFinalSync(pvcName, pvcNamespace string) error {
v.log.V(1).Info("Undo after final sync", "pvcName", pvcName)
// Remove claimRef and reset the original PVC claimRef (without uid)
tmpPVC, err := v.getPVC(types.NamespacedName{
Namespace: pvcNamespace,
Name: util.GetTmpPVCNameForFinalSync(pvcName),
})
if err == nil {
err2 := v.client.Delete(v.ctx, tmpPVC)
if err2 != nil {
return err2
}
v.log.V(1).Info("Deleted tmp PVC", "pvcName", tmpPVC.GetName())
}
if err != nil {
if !errors.IsNotFound(err) {
return fmt.Errorf("wait for tmp PVC '%s' to go away", tmpPVC.GetName())
}
}
// reset the original PVC claimRef (without uid)
originalPVC, err := v.getPVC(types.NamespacedName{Namespace: pvcNamespace, Name: pvcName})
if err != nil {
if !errors.IsNotFound(err) {
return fmt.Errorf("wait for tmp PVC '%s' to go away", tmpPVC.GetName())
}
return nil // PVC is gone, nothing more to do
}
pv := &corev1.PersistentVolume{}
pvObjectKey := client.ObjectKey{
Name: originalPVC.Spec.VolumeName,
}
if err := v.client.Get(v.ctx, pvObjectKey, pv); err != nil {
v.log.Info("Failed to get PersistentVolume", "volumeName", originalPVC.Spec.VolumeName, "error", err)
return fmt.Errorf("failed to get PersistentVolume (%s), %w", pv.Name, err)
}