/
vshandler.go
2087 lines (1643 loc) · 65.8 KB
/
vshandler.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 volsync
import (
"context"
"fmt"
"strconv"
"strings"
"github.com/go-logr/logr"
snapv1 "github.com/kubernetes-csi/external-snapshotter/client/v4/apis/volumesnapshot/v1"
corev1 "k8s.io/api/core/v1"
storagev1 "k8s.io/api/storage/v1"
kerrors "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"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
ctrlutil "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
volsyncv1alpha1 "github.com/backube/volsync/api/v1alpha1"
ramendrv1alpha1 "github.com/ramendr/ramen/api/v1alpha1"
"github.com/ramendr/ramen/controllers/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"
VRGOwnerLabel string = "volumereplicationgroups-owner"
FinalSyncTriggerString string = "vrg-final-sync"
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"
)
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
}
func NewVSHandler(ctx context.Context, client client.Client, log logr.Logger, owner metav1.Object,
asyncSpec *ramendrv1alpha1.VRGAsyncSpec, defaultCephFSCSIDriverName string, copyMethod string,
) *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
}
if asyncSpec != nil {
vsHandler.schedulingInterval = asyncSpec.SchedulingInterval
vsHandler.volumeSnapshotClassSelector = asyncSpec.VolumeSnapshotClassSelector
}
return vsHandler
}
// 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.
func (v *VSHandler) ReconcileRD(
rdSpec ramendrv1alpha1.VolSyncReplicationDestinationSpec) (*volsyncv1alpha1.ReplicationDestination, error,
) {
l := v.log.WithValues("rdSpec", rdSpec)
if !rdSpec.ProtectedPVC.ProtectedByVolSync {
return 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
secretExists, err := v.validateSecretAndAddVRGOwnerRef(pskSecretName)
if err != nil || !secretExists {
return 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)
if err != nil {
return nil, err
}
dstPVC, err := v.PrecreateDestPVCIfEnabled(rdSpec)
if err != nil {
return nil, err
}
var rd *volsyncv1alpha1.ReplicationDestination
rd, err = v.createOrUpdateRD(rdSpec, pskSecretName, dstPVC)
if err != nil {
return nil, err
}
err = v.reconcileServiceExportForRD(rd)
if err != nil {
return nil, err
}
if !rdStatusReady(rd, l) {
return nil, nil
}
l.V(1).Info(fmt.Sprintf("ReplicationDestination Reconcile Complete rd=%s, Copy method: %s",
rd.Name, v.destinationCopyMethod))
return rd, 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) createOrUpdateRD(
rdSpec ramendrv1alpha1.VolSyncReplicationDestinationSpec, pskSecretName string,
dstPVC *string) (*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: getReplicationDestinationName(rdSpec.ProtectedPVC.Name),
Namespace: v.owner.GetNamespace(),
},
}
op, err := ctrlutil.CreateOrUpdate(v.ctx, v.client, rd, func() error {
if err := ctrl.SetControllerReference(v.owner, rd, v.client.Scheme()); err != nil {
l.Error(err, "unable to set controller reference")
return fmt.Errorf("%w", err)
}
util.AddLabel(rd, VRGOwnerLabel, v.owner.GetName())
util.AddAnnotation(rd, OwnerNameAnnotation, v.owner.GetName())
util.AddAnnotation(rd, OwnerNamespaceAnnotation, v.owner.GetNamespace())
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,
},
}
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(pvcName string) (bool, error) {
rd := &volsyncv1alpha1.ReplicationDestination{}
err := v.client.Get(v.ctx,
types.NamespacedName{
Name: getReplicationDestinationName(pvcName),
Namespace: v.owner.GetNamespace(),
}, rd)
// 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.
if err == nil {
return false, nil
} else if !kerrors.IsNotFound(err) {
return false, fmt.Errorf("%w", err)
}
// PVC must not be in use
pvcInUse, err := v.pvcExistsAndInUse(pvcName, 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
func (v *VSHandler) ReconcileRS(rsSpec ramendrv1alpha1.VolSyncReplicationSourceSpec,
runFinalSync bool) (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
}
// 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)
if err != nil {
return false, nil, err
}
pvcOk, err := v.validatePVCBeforeRS(rsSpec, runFinalSync)
if !pvcOk || err != nil {
// Return the replicationSource if it already exists
existingRS, getRSErr := v.getRS(getReplicationSourceName(rsSpec.ProtectedPVC.Name))
if getRSErr != nil {
return false, nil, err
}
// Return the RS here - allows status updates to understand that prev RS syncs may have completed
// (i.e. data protected == true), even though we may be indicating that finalSync has not yet completed
// because the PVC is still in-use
return false, existingRS, err
}
replicationSource, err := v.createOrUpdateRS(rsSpec, pskSecretName, runFinalSync)
if 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) {
return true, replicationSource, v.cleanupAfterRSFinalSync(rsSpec)
}
l.V(1).Info("ReplicationSource Reconcile Complete")
return false, replicationSource, err
}
// Need to validate that our PVC is no longer in use before proceeding
// If in final sync and the source PVC no longer exists, this could be from
// a 2nd call to runFinalSync and we may have already cleaned up the PVC - so if pvc does not
// exist, treat the same as not in use - continue on with reconcile of the RS (and therefore
// check status to confirm final sync is complete)
func (v *VSHandler) validatePVCBeforeRS(rsSpec ramendrv1alpha1.VolSyncReplicationSourceSpec,
runFinalSync bool) (bool, error,
) {
l := v.log.WithValues("rsSpec", rsSpec, "runFinalSync", runFinalSync)
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(rsSpec.ProtectedPVC.Name, false)
if err != nil {
return false, err
}
if pvcIsMounted {
return false, nil
}
return true, nil // Good to proceed - PVC is not in use, not mounted to node (or does not exist-should not happen)
}
// Not running final sync - if we have not yet created an RS for this PVC, then make sure a pod has mounted
// the PVC and is in "Running" state before attempting to create an RS.
// This is a best effort to confirm the app that is using the PVC is started before trying to replicate the PVC.
_, err := v.getRS(getReplicationSourceName(rsSpec.ProtectedPVC.Name))
if err != nil && kerrors.IsNotFound(err) {
l.Info("ReplicationSource does not exist yet. " +
"validating that the PVC to be protected is in use by a ready pod ...")
// RS does not yet exist - consider PVC is ok if it's mounted and in use by running pod
inUseByReadyPod, err := v.pvcExistsAndInUse(rsSpec.ProtectedPVC.Name, true /* Check mounting pod is Ready */)
if err != nil {
return false, err
}
if !inUseByReadyPod {
l.Info("PVC is not in use by ready pod, not creating RS yet ...")
return false, nil
}
l.Info("PVC is use by ready pod, proceeding to create RS ...")
return true, nil
}
if err != nil {
// Err looking up the RS, return it
return false, err
}
// Replication source already exists, no need for any pvc checking
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(rsSpec ramendrv1alpha1.VolSyncReplicationSourceSpec) 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", rsSpec.ProtectedPVC.Name)
return nil
}
v.log.Info("Cleanup after final sync", "pvcName", rsSpec.ProtectedPVC.Name)
return util.DeletePVC(v.ctx, v.client, rsSpec.ProtectedPVC.Name, v.owner.GetNamespace(), v.log)
}
//nolint:funlen
func (v *VSHandler) createOrUpdateRS(rsSpec ramendrv1alpha1.VolSyncReplicationSourceSpec,
pskSecretName string, runFinalSync bool) (*volsyncv1alpha1.ReplicationSource, error,
) {
l := v.log.WithValues("rsSpec", rsSpec, "runFinalSync", runFinalSync)
storageClass, err := v.getStorageClass(rsSpec.ProtectedPVC.StorageClassName)
if err != nil {
return nil, err
}
volumeSnapshotClassName, err := v.getVolumeSnapshotClassFromPVCStorageClass(storageClass)
if err != nil {
return nil, err
}
// Fix for CephFS (replication source only) - may need different storageclass and access modes
err = v.ModifyRSSpecForCephFS(&rsSpec, 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 := getRemoteServiceNameForRDFromPVCName(rsSpec.ProtectedPVC.Name, v.owner.GetNamespace())
rs := &volsyncv1alpha1.ReplicationSource{
ObjectMeta: metav1.ObjectMeta{
Name: getReplicationSourceName(rsSpec.ProtectedPVC.Name),
Namespace: v.owner.GetNamespace(),
},
}
op, err := ctrlutil.CreateOrUpdate(v.ctx, v.client, rs, func() error {
if err := ctrl.SetControllerReference(v.owner, rs, v.client.Scheme()); err != nil {
l.Error(err, "unable to set controller reference")
return fmt.Errorf("%w", err)
}
util.AddLabel(rs, VRGOwnerLabel, v.owner.GetName())
rs.Spec.SourcePVC = rsSpec.ProtectedPVC.Name
if runFinalSync {
l.V(1).Info("ReplicationSource - final sync")
// Change the schedule to instead use a keyword trigger - to trigger
// a final sync to happen
rs.Spec.Trigger = &volsyncv1alpha1.ReplicationSourceTriggerSpec{
Manual: FinalSyncTriggerString,
}
} else {
// Set schedule
scheduleCronSpec, err := v.getScheduleCronSpec()
if err != nil {
l.Error(err, "unable to parse schedulingInterval")
return err
}
rs.Spec.Trigger = &volsyncv1alpha1.ReplicationSourceTriggerSpec{
Schedule: scheduleCronSpec,
}
}
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,
},
}
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) PreparePVC(pvcName string, prepFinalSync, copyMethodDirect bool) error {
if prepFinalSync || copyMethodDirect {
prepared, err := v.TakePVCOwnership(pvcName)
if err != nil || !prepared {
return fmt.Errorf("waiting to take pvc ownership (%w), prepFinalSync: %t, Direct: %t",
err, prepFinalSync, copyMethodDirect)
}
}
return nil
}
// TakePVCOwnership adds do-not-delete annotation to indicate that ACM should not delete/cleanup this pvc
// when the appsub is removed and adds VRG as owner so the PVC is garbage collected when the VRG is deleted.
func (v *VSHandler) TakePVCOwnership(pvcName string) (bool, error) {
l := v.log.WithValues("pvcName", pvcName)
// Confirm PVC exists and add our VRG as ownerRef
pvc, err := v.validatePVCAndAddVRGOwnerRef(pvcName)
if err != nil {
l.Error(err, "unable to validate PVC or add ownership")
return false, err
}
err = v.client.Update(v.ctx, pvc)
if err != nil {
l.Error(err, "Error updating annotations on PVC to break appsub ownership")
return false, fmt.Errorf("error updating annotations on PVC to break appsub ownership (%w)", err)
}
return true, nil
}
// Will return true only if the pvc exists and in use - will not throw error if PVC not found
// If inUsePodMustBeReady is true, will only return true if the pod mounting the PVC is in Ready state
// If inUsePodMustBeReady is false, will run an additional volume attachment check to make sure the PV underlying
// the PVC is really detached (i.e. I/O operations complete) and therefore we can assume, quiesced.
func (v *VSHandler) pvcExistsAndInUse(pvcName string, inUsePodMustBeReady bool) (bool, error) {
pvcNamespacedName := types.NamespacedName{Namespace: v.owner.GetNamespace(), Name: pvcName}
log := v.log.WithValues("pvc", pvcNamespacedName.String())
pvc, err := v.getPVC(pvcName)
if err != nil {
if kerrors.IsNotFound(err) {
log.Info("PVC not found")
return false, nil // No error just indicate not exists (so also not in use)
}
return false, err // error accessing the PVC, return it
}
log.V(1).Info("pvc found")
inUseByPod, err := util.IsPVCInUseByPod(v.ctx, v.client, v.log, pvcNamespacedName, inUsePodMustBeReady)
if err != nil || inUseByPod || inUsePodMustBeReady {
// Return status immediately
return inUseByPod, err
}
// No pod is mounting the PVC - do additional check to make sure no volume attachment exists
return util.IsPVAttachedToNode(v.ctx, v.client, v.log, pvc)
}
func (v *VSHandler) getPVC(pvcName string) (*corev1.PersistentVolumeClaim, error) {
pvc := &corev1.PersistentVolumeClaim{}
err := v.client.Get(v.ctx,
types.NamespacedName{
Name: pvcName,
Namespace: v.owner.GetNamespace(),
}, pvc)
if err != nil {
return nil, fmt.Errorf("%w", err)
}
return pvc, nil
}
// Adds owner ref and ACM "do-not-delete" annotation to indicate that when the appsub is removed, ACM
// should not cleanup this PVC - we want it left behind so we can run a final sync
func (v *VSHandler) validatePVCAndAddVRGOwnerRef(pvcName string) (*corev1.PersistentVolumeClaim, error) {
pvc, err := v.getPVC(pvcName)
if err != nil {
return nil, err
}
v.log.Info("PVC exists", "pvcName", pvcName)
// Add annotation to indicate that ACM should not delete/cleanup this pvc when the appsub is removed
// and add VRG as owner
err = v.addAnnotationAndVRGOwnerRefAndUpdate(pvc, ACMAppSubDoNotDeleteAnnotation, ACMAppSubDoNotDeleteAnnotationVal)
if err != nil {
return nil, err
}
v.log.V(1).Info("PVC validated", "pvc name", pvcName)
return pvc, nil
}
func (v *VSHandler) validateSecretAndAddVRGOwnerRef(secretName string) (bool, error) {
secret := &corev1.Secret{}
err := v.client.Get(v.ctx,
types.NamespacedName{
Name: secretName,
Namespace: v.owner.GetNamespace(),
}, secret)
if err != nil {
if !kerrors.IsNotFound(err) {
v.log.Error(err, "Failed to get secret", "secretName", secretName)
return false, fmt.Errorf("error getting secret (%w)", err)
}
// Secret is not found
v.log.Info("Secret not found", "secretName", secretName)
return false, nil
}
v.log.Info("Secret exists", "secretName", secretName)
// Add VRG as owner
if err := v.addOwnerReferenceAndUpdate(secret, v.owner); err != nil {
v.log.Error(err, "Unable to update secret", "secretName", secretName)
return true, err
}
v.log.V(1).Info("VolSync secret validated", "secret name", secretName)
return true, nil
}
func (v *VSHandler) getRS(name string) (*volsyncv1alpha1.ReplicationSource, error) {
rs := &volsyncv1alpha1.ReplicationSource{}
err := v.client.Get(v.ctx,
types.NamespacedName{
Name: name,
Namespace: v.owner.GetNamespace(),
}, rs)
if err != nil {
return nil, fmt.Errorf("%w", err)
}
return rs, nil
}
func (v *VSHandler) DeleteRS(pvcName string) error {
// Remove a ReplicationSource by name that is owned (by parent vrg owner)
currentRSListByOwner, err := v.listRSByOwner()
if err != nil {
return err
}
for i := range currentRSListByOwner.Items {
rs := currentRSListByOwner.Items[i]
if rs.GetName() == getReplicationSourceName(pvcName) {
// Delete the ReplicationSource, log errors with cleanup but continue on
if err := v.client.Delete(v.ctx, &rs); err != nil {
v.log.Error(err, "Error cleaning up ReplicationSource", "name", rs.GetName())
} else {
v.log.Info("Deleted ReplicationSource", "name", rs.GetName())
}
}
}
return nil
}
//nolint:nestif
func (v *VSHandler) DeleteRD(pvcName string) error {
// Remove a ReplicationDestination by name that is owned (by parent vrg owner)
currentRDListByOwner, err := v.listRDByOwner()
if err != nil {
return err
}
for i := range currentRDListByOwner.Items {
rd := currentRDListByOwner.Items[i]
if rd.GetName() == getReplicationDestinationName(pvcName) {
if v.IsCopyMethodDirect() {
err := v.deleteLocalRDAndRS(&rd)
if err != nil {
return err
}
}
// Delete the ReplicationDestination, log errors with cleanup but continue on
if err := v.client.Delete(v.ctx, &rd); err != nil {
v.log.Error(err, "Error cleaning up ReplicationDestination", "name", rd.GetName())
} else {
v.log.Info("Deleted ReplicationDestination", "name", rd.GetName())
}
}
}
return nil
}
//nolint:gocognit
func (v *VSHandler) deleteLocalRDAndRS(rd *volsyncv1alpha1.ReplicationDestination) error {
latestRDImage, err := v.getRDLatestImage(rd.GetName())
if err != nil {
return err
}
v.log.V(1).Info("Clean up local resources. Latest Image for main RD", "name", latestRDImage.Name)
lrs := &volsyncv1alpha1.ReplicationSource{
ObjectMeta: metav1.ObjectMeta{
Name: getLocalReplicationName(rd.GetName()),
Namespace: v.owner.GetNamespace(),
},
}
err = v.client.Get(v.ctx, types.NamespacedName{
Name: lrs.GetName(),
Namespace: lrs.GetNamespace(),
}, lrs)
if err != nil {
if kerrors.IsNotFound(err) {
return v.deleteLocalRD(getLocalReplicationName(rd.GetName()))
}
return err
}
// For Local Direct, localRS trigger must point to the latest RD snapshot image. Otherwise,
// we wait for local final sync to take place first befor cleaning up.
if lrs.Spec.Trigger != nil && lrs.Spec.Trigger.Manual == latestRDImage.Name {
// When local final sync is complete, we cleanup all locally created resources except the app PVC
if lrs.Status != nil && lrs.Status.LastManualSync == lrs.Spec.Trigger.Manual {
err = v.cleanupLocalResources(lrs)
if err != nil {
return err
}
v.log.V(1).Info("Cleaned up local resources for RD", "name", rd.GetName())
return nil
}
}
return fmt.Errorf("waiting for local final sync to complete")
}
//nolint:gocognit
func (v *VSHandler) CleanupRDNotInSpecList(rdSpecList []ramendrv1alpha1.VolSyncReplicationDestinationSpec) error {
// Remove any ReplicationDestination owned (by parent vrg owner) that is not in the provided rdSpecList
currentRDListByOwner, err := v.listRDByOwner()
if err != nil {
return err
}
for i := range currentRDListByOwner.Items {
rd := currentRDListByOwner.Items[i]
foundInSpecList := false
for _, rdSpec := range rdSpecList {
if rd.GetName() == getReplicationDestinationName(rdSpec.ProtectedPVC.Name) {
foundInSpecList = true
break
}
}
if !foundInSpecList {
// If it is localRD, there will be no RDSpec. We shoul NOT clean it up yet.
if rd.GetLabels()[VolSyncDoNotDeleteLabel] == VolSyncDoNotDeleteLabelVal {
continue
}
// Delete the ReplicationDestination, log errors with cleanup but continue on
if err := v.client.Delete(v.ctx, &rd); err != nil {
v.log.Error(err, "Error cleaning up ReplicationDestination", "name", rd.GetName())
} else {
v.log.Info("Deleted ReplicationDestination", "name", rd.GetName())
}
}
}
return nil
}
// Make sure a ServiceExport exists to export the service for this RD to remote clusters
// See: https://access.redhat.com/documentation/en-us/red_hat_advanced_cluster_management_for_kubernetes/
// 2.4/html/services/services-overview#enable-service-discovery-submariner
func (v *VSHandler) reconcileServiceExportForRD(rd *volsyncv1alpha1.ReplicationDestination) error {
// Using unstructured to avoid needing to require serviceexport in client scheme
svcExport := &unstructured.Unstructured{}
svcExport.Object = map[string]interface{}{
"metadata": map[string]interface{}{
"name": getLocalServiceNameForRD(rd.GetName()), // Get name of the local service (this needs to be exported)
"namespace": rd.GetNamespace(),
},
}
svcExport.SetGroupVersionKind(schema.GroupVersionKind{
Group: ServiceExportGroup,
Kind: ServiceExportKind,
Version: ServiceExportVersion,
})
op, err := ctrlutil.CreateOrUpdate(v.ctx, v.client, svcExport, func() error {
// Make this ServiceExport owned by the replication destination itself rather than the VRG
// This way on relocate scenarios or failover/failback, when the RD is cleaned up the associated
// ServiceExport will get cleaned up with it.
if err := ctrlutil.SetOwnerReference(rd, svcExport, v.client.Scheme()); err != nil {
v.log.Error(err, "unable to set controller reference", "resource", svcExport)
return fmt.Errorf("%w", err)
}
return nil
})
v.log.V(1).Info("ServiceExport createOrUpdate Complete", "op", op)
if err != nil {
v.log.Error(err, "error creating or updating ServiceExport", "replication destination name", rd.GetName(),
"namespace", rd.GetNamespace())
return fmt.Errorf("error creating or updating ServiceExport (%w)", err)
}
v.log.V(1).Info("ServiceExport Reconcile Complete")
return nil
}
func (v *VSHandler) listRSByOwner() (volsyncv1alpha1.ReplicationSourceList, error) {
rsList := volsyncv1alpha1.ReplicationSourceList{}
if err := v.listByOwner(&rsList); err != nil {
v.log.Error(err, "Failed to list ReplicationSources for VRG", "vrg name", v.owner.GetName())
return rsList, err
}
return rsList, nil
}
func (v *VSHandler) listRDByOwner() (volsyncv1alpha1.ReplicationDestinationList, error) {
rdList := volsyncv1alpha1.ReplicationDestinationList{}
if err := v.listByOwner(&rdList); err != nil {
v.log.Error(err, "Failed to list ReplicationDestinations for VRG", "vrg name", v.owner.GetName())
return rdList, err
}
return rdList, nil
}
// Lists only RS/RD with VRGOwnerLabel that matches the owner
func (v *VSHandler) listByOwner(list client.ObjectList) error {
matchLabels := map[string]string{
VRGOwnerLabel: v.owner.GetName(),
}
listOptions := []client.ListOption{
client.InNamespace(v.owner.GetNamespace()),
client.MatchingLabels(matchLabels),
}
if err := v.client.List(v.ctx, list, listOptions...); err != nil {
v.log.Error(err, "Failed to list by label", "matchLabels", matchLabels)
return fmt.Errorf("error listing by label (%w)", err)
}
return nil
}
func (v *VSHandler) EnsurePVCfromRD(rdSpec ramendrv1alpha1.VolSyncReplicationDestinationSpec, failoverAction bool,
) error {
latestImage, err := v.getRDLatestImage(rdSpec.ProtectedPVC.Name)
if err != nil {
return err
}
if !isLatestImageReady(latestImage) {
noSnapErr := fmt.Errorf("unable to find LatestImage from ReplicationDestination %s", rdSpec.ProtectedPVC.Name)
v.log.Error(noSnapErr, "No latestImage", "rdSpec", rdSpec)
return noSnapErr
}
// Make copy of the ref and make sure API group is filled out correctly (shouldn't really need this part)
vsImageRef := latestImage.DeepCopy()
if vsImageRef.APIGroup == nil || *vsImageRef.APIGroup == "" {
vsGroup := snapv1.GroupName
vsImageRef.APIGroup = &vsGroup
}
v.log.Info("Latest Image for ReplicationDestination", "latestImage", vsImageRef.Name)
return v.validateSnapshotAndEnsurePVC(rdSpec, *vsImageRef, failoverAction)
}
//nolint:cyclop
func (v *VSHandler) EnsurePVCforDirectCopy(ctx context.Context,
rdSpec ramendrv1alpha1.VolSyncReplicationDestinationSpec,
) error {
logger := v.log.WithValues("pvcName", rdSpec.ProtectedPVC.Name)
if len(rdSpec.ProtectedPVC.AccessModes) == 0 {
return fmt.Errorf("accessModes must be provided for PVC %v", rdSpec.ProtectedPVC)
}
if rdSpec.ProtectedPVC.Resources.Requests.Storage() == nil {
return fmt.Errorf("capacity must be provided %v", rdSpec.ProtectedPVC)
}
pvc, err := v.getPVC(rdSpec.ProtectedPVC.Name)
if err != nil && !kerrors.IsNotFound(err) {
return err
}
if pvc != nil {
return v.removeOCMAnnotationsAndUpdate(pvc)
}
pvc = &corev1.PersistentVolumeClaim{
ObjectMeta: metav1.ObjectMeta{
Name: rdSpec.ProtectedPVC.Name,
Namespace: v.owner.GetNamespace(),
},
}
op, err := ctrlutil.CreateOrUpdate(ctx, v.client, pvc, func() error {
if err := ctrl.SetControllerReference(v.owner, pvc, v.client.Scheme()); err != nil {
return fmt.Errorf("failed to set controller reference %w", err)
}
if pvc.CreationTimestamp.IsZero() {
pvc.Spec.AccessModes = rdSpec.ProtectedPVC.AccessModes
pvc.Spec.StorageClassName = rdSpec.ProtectedPVC.StorageClassName
volumeMode := corev1.PersistentVolumeFilesystem
pvc.Spec.VolumeMode = &volumeMode
}
pvc.Spec.Resources.Requests = rdSpec.ProtectedPVC.Resources.Requests
if pvc.Labels == nil {
pvc.Labels = rdSpec.ProtectedPVC.Labels
} else {
for key, val := range rdSpec.ProtectedPVC.Labels {
pvc.Labels[key] = val
}
}
return nil
})
if err != nil {
return err
}
logger.V(1).Info("PVC created", "operation", op)
return nil
}
//nolint:nestif
func (v *VSHandler) validateSnapshotAndEnsurePVC(rdSpec ramendrv1alpha1.VolSyncReplicationDestinationSpec,
snapshotRef corev1.TypedLocalObjectReference, failoverAction bool,
) error {
snap, err := v.validateAndProtectSnapshot(snapshotRef)
if err != nil {
return err
}
if v.IsCopyMethodDirect() {
// Directly use the RD pvc
v.log.V(1).Info(fmt.Sprintf("Using copyMethod '%s'. latestImage %s. pvcName %s",
v.destinationCopyMethod, snapshotRef.Name, rdSpec.ProtectedPVC.Name))
pvc := &corev1.PersistentVolumeClaim{
ObjectMeta: metav1.ObjectMeta{
Name: rdSpec.ProtectedPVC.Name,
Namespace: v.owner.GetNamespace(),
},
}
err = ValidateObjectExists(v.ctx, v.client, pvc)
if err != nil {
return err
}
if failoverAction {
v.log.Info("Failing over. Needs to rollback to the last snapshot")
err = v.rollbackToLastSnapshot(rdSpec, snapshotRef)
if err != nil {
return err
}
}
} else {
// Restore pvc from snapshot
var restoreSize *resource.Quantity
if snap.Status != nil {