forked from velero-io/velero
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpod_volume_restore_controller.go
More file actions
1125 lines (925 loc) · 38.1 KB
/
pod_volume_restore_controller.go
File metadata and controls
1125 lines (925 loc) · 38.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright The Velero Contributors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package controller
import (
"context"
"fmt"
"strings"
"time"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
corev1api "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/kubernetes"
clocks "k8s.io/utils/clock"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/builder"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/event"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
veleroapishared "github.com/vmware-tanzu/velero/pkg/apis/velero/shared"
velerov1api "github.com/vmware-tanzu/velero/pkg/apis/velero/v1"
"github.com/vmware-tanzu/velero/pkg/constant"
"github.com/vmware-tanzu/velero/pkg/datapath"
"github.com/vmware-tanzu/velero/pkg/exposer"
"github.com/vmware-tanzu/velero/pkg/nodeagent"
repository "github.com/vmware-tanzu/velero/pkg/repository/manager"
"github.com/vmware-tanzu/velero/pkg/restorehelper"
velerotypes "github.com/vmware-tanzu/velero/pkg/types"
"github.com/vmware-tanzu/velero/pkg/uploader"
"github.com/vmware-tanzu/velero/pkg/util"
"github.com/vmware-tanzu/velero/pkg/util/kube"
)
func NewPodVolumeRestoreReconciler(
client client.Client,
mgr manager.Manager,
kubeClient kubernetes.Interface,
dataPathMgr *datapath.Manager,
counter *exposer.VgdpCounter,
nodeName string,
preparingTimeout time.Duration,
resourceTimeout time.Duration,
backupRepoConfigs map[string]string,
cacheVolumeConfigs *velerotypes.CachePVC,
podResources corev1api.ResourceRequirements,
logger logrus.FieldLogger,
dataMovePriorityClass string,
privileged bool,
repoConfigMgr repository.ConfigManager,
podLabels map[string]string,
podAnnotations map[string]string,
) *PodVolumeRestoreReconciler {
return &PodVolumeRestoreReconciler{
client: client,
mgr: mgr,
kubeClient: kubeClient,
logger: logger.WithField("controller", "PodVolumeRestore"),
nodeName: nodeName,
clock: &clocks.RealClock{},
podResources: podResources,
backupRepoConfigs: backupRepoConfigs,
cacheVolumeConfigs: cacheVolumeConfigs,
dataPathMgr: dataPathMgr,
vgdpCounter: counter,
preparingTimeout: preparingTimeout,
resourceTimeout: resourceTimeout,
exposer: exposer.NewPodVolumeExposer(kubeClient, logger),
cancelledPVR: make(map[string]time.Time),
dataMovePriorityClass: dataMovePriorityClass,
privileged: privileged,
repoConfigMgr: repoConfigMgr,
podLabels: podLabels,
podAnnotations: podAnnotations,
}
}
type PodVolumeRestoreReconciler struct {
client client.Client
mgr manager.Manager
kubeClient kubernetes.Interface
logger logrus.FieldLogger
nodeName string
clock clocks.WithTickerAndDelayedExecution
podResources corev1api.ResourceRequirements
backupRepoConfigs map[string]string
cacheVolumeConfigs *velerotypes.CachePVC
exposer exposer.PodVolumeExposer
dataPathMgr *datapath.Manager
vgdpCounter *exposer.VgdpCounter
preparingTimeout time.Duration
resourceTimeout time.Duration
cancelledPVR map[string]time.Time
dataMovePriorityClass string
privileged bool
repoConfigMgr repository.ConfigManager
podLabels map[string]string
podAnnotations map[string]string
}
// +kubebuilder:rbac:groups=velero.io,resources=podvolumerestores,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=velero.io,resources=podvolumerestores/status,verbs=get;update;patch
// +kubebuilder:rbac:groups="",resources=pods,verbs=get
// +kubebuilder:rbac:groups="",resources=persistentvolumes,verbs=get
// +kubebuilder:rbac:groups="",resources=persistentvolumerclaims,verbs=get
func (r *PodVolumeRestoreReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
log := r.logger.WithField("PodVolumeRestore", req.NamespacedName.String())
log.Info("Reconciling PVR by advanced controller")
pvr := &velerov1api.PodVolumeRestore{}
if err := r.client.Get(ctx, types.NamespacedName{Namespace: req.Namespace, Name: req.Name}, pvr); err != nil {
if apierrors.IsNotFound(err) {
log.Warn("PVR not found, skip")
return ctrl.Result{}, nil
}
log.WithError(err).Error("Unable to get the PVR")
return ctrl.Result{}, err
}
log = log.WithField("pod", fmt.Sprintf("%s/%s", pvr.Spec.Pod.Namespace, pvr.Spec.Pod.Name))
if len(pvr.OwnerReferences) == 1 {
log = log.WithField("restore", fmt.Sprintf("%s/%s", pvr.Namespace, pvr.OwnerReferences[0].Name))
}
// Logic for clear resources when pvr been deleted
if !isPVRInFinalState(pvr) {
if !controllerutil.ContainsFinalizer(pvr, PodVolumeFinalizer) {
if err := UpdatePVRWithRetry(ctx, r.client, req.NamespacedName, log, func(pvr *velerov1api.PodVolumeRestore) bool {
if controllerutil.ContainsFinalizer(pvr, PodVolumeFinalizer) {
return false
}
controllerutil.AddFinalizer(pvr, PodVolumeFinalizer)
return true
}); err != nil {
log.WithError(err).Errorf("failed to add finalizer for PVR %s/%s", pvr.Namespace, pvr.Name)
return ctrl.Result{}, err
}
return ctrl.Result{}, nil
}
if !pvr.DeletionTimestamp.IsZero() {
if !pvr.Spec.Cancel {
log.Warnf("Cancel PVR under phase %s because it is being deleted", pvr.Status.Phase)
if err := UpdatePVRWithRetry(ctx, r.client, req.NamespacedName, log, func(pvr *velerov1api.PodVolumeRestore) bool {
if pvr.Spec.Cancel {
return false
}
pvr.Spec.Cancel = true
pvr.Status.Message = "Cancel PVR because it is being deleted"
return true
}); err != nil {
log.WithError(err).Errorf("failed to set cancel flag for PVR %s/%s", pvr.Namespace, pvr.Name)
return ctrl.Result{}, err
}
return ctrl.Result{}, nil
}
}
} else {
delete(r.cancelledPVR, pvr.Name)
if controllerutil.ContainsFinalizer(pvr, PodVolumeFinalizer) {
if err := UpdatePVRWithRetry(ctx, r.client, req.NamespacedName, log, func(pvr *velerov1api.PodVolumeRestore) bool {
if !controllerutil.ContainsFinalizer(pvr, PodVolumeFinalizer) {
return false
}
controllerutil.RemoveFinalizer(pvr, PodVolumeFinalizer)
return true
}); err != nil {
log.WithError(err).Error("error to remove finalizer")
return ctrl.Result{}, err
}
return ctrl.Result{}, nil
}
}
if pvr.Spec.Cancel {
if spotted, found := r.cancelledPVR[pvr.Name]; !found {
r.cancelledPVR[pvr.Name] = r.clock.Now()
} else {
delay := cancelDelayOthers
if pvr.Status.Phase == velerov1api.PodVolumeRestorePhaseInProgress {
delay = cancelDelayInProgress
}
if time.Since(spotted) > delay {
log.Infof("PVR %s is canceled in Phase %s but not handled in rasonable time", pvr.GetName(), pvr.Status.Phase)
if r.tryCancelPodVolumeRestore(ctx, pvr, "") {
delete(r.cancelledPVR, pvr.Name)
}
return ctrl.Result{}, nil
}
}
}
if pvr.Status.Phase == "" || pvr.Status.Phase == velerov1api.PodVolumeRestorePhaseNew {
if pvr.Spec.Cancel {
log.Infof("PVR %s is canceled in Phase %s", pvr.GetName(), pvr.Status.Phase)
_ = r.tryCancelPodVolumeRestore(ctx, pvr, "")
return ctrl.Result{}, nil
}
shouldProcess, pod, err := shouldProcess(ctx, r.client, log, pvr)
if err != nil {
return ctrl.Result{}, err
}
if !shouldProcess {
return ctrl.Result{}, nil
}
if r.vgdpCounter != nil && r.vgdpCounter.IsConstrained(ctx, r.logger) {
log.Debug("Data path initiation is constrained, requeue later")
return ctrl.Result{Requeue: true, RequeueAfter: time.Second * 5}, nil
}
log.Info("Accepting PVR")
if err := r.acceptPodVolumeRestore(ctx, pvr); err != nil {
return ctrl.Result{}, errors.Wrapf(err, "error accepting PVR %s", pvr.Name)
}
initContainerIndex := getInitContainerIndex(pod)
if initContainerIndex > 0 {
log.Warnf(`Init containers before the %s container may cause issues
if they interfere with volumes being restored: %s index %d`, restorehelper.WaitInitContainer, restorehelper.WaitInitContainer, initContainerIndex)
}
log.Info("Exposing PVR")
exposeParam := r.setupExposeParam(pvr)
if err := r.exposer.Expose(ctx, getPVROwnerObject(pvr), exposeParam); err != nil {
return r.errorOut(ctx, pvr, err, "error to expose PVR", log)
}
log.Info("PVR is exposed")
return ctrl.Result{}, nil
} else if pvr.Status.Phase == velerov1api.PodVolumeRestorePhaseAccepted {
if peekErr := r.exposer.PeekExposed(ctx, getPVROwnerObject(pvr)); peekErr != nil {
log.Errorf("Cancel PVR %s/%s because of expose error %s", pvr.Namespace, pvr.Name, peekErr)
diags := strings.Split(r.exposer.DiagnoseExpose(ctx, getPVROwnerObject(pvr)), "\n")
for _, diag := range diags {
log.Warnf("[Diagnose PVR expose]%s", diag)
}
_ = r.tryCancelPodVolumeRestore(ctx, pvr, fmt.Sprintf("found a PVR %s/%s with expose error: %s. mark it as cancel", pvr.Namespace, pvr.Name, peekErr))
} else if pvr.Status.AcceptedTimestamp != nil {
if time.Since(pvr.Status.AcceptedTimestamp.Time) >= r.preparingTimeout {
r.onPrepareTimeout(ctx, pvr)
}
}
return ctrl.Result{}, nil
} else if pvr.Status.Phase == velerov1api.PodVolumeRestorePhasePrepared {
log.Infof("PVR is prepared and should be processed by %s (%s)", pvr.Status.Node, r.nodeName)
if pvr.Status.Node != r.nodeName {
return ctrl.Result{}, nil
}
if pvr.Spec.Cancel {
log.Info("Prepared PVR is being canceled")
r.OnDataPathCancelled(ctx, pvr.GetNamespace(), pvr.GetName())
return ctrl.Result{}, nil
}
asyncBR := r.dataPathMgr.GetAsyncBR(pvr.Name)
if asyncBR != nil {
log.Info("Cancellable data path is already started")
return ctrl.Result{}, nil
}
res, err := r.exposer.GetExposed(ctx, getPVROwnerObject(pvr), r.client, r.nodeName, r.resourceTimeout)
if err != nil {
return r.errorOut(ctx, pvr, err, "exposed PVR is not ready", log)
} else if res == nil {
return r.errorOut(ctx, pvr, errors.New("no expose result is available for the current node"), "exposed PVR is not ready", log)
}
log.Info("Exposed PVR is ready and creating data path routine")
callbacks := datapath.Callbacks{
OnCompleted: r.OnDataPathCompleted,
OnFailed: r.OnDataPathFailed,
OnCancelled: r.OnDataPathCancelled,
OnProgress: r.OnDataPathProgress,
}
asyncBR, err = r.dataPathMgr.CreateMicroServiceBRWatcher(ctx, r.client, r.kubeClient, r.mgr, datapath.TaskTypeRestore,
pvr.Name, pvr.Namespace, res.ByPod.HostingPod.Name, res.ByPod.HostingContainer, pvr.Name, callbacks, false, log)
if err != nil {
if err == datapath.ConcurrentLimitExceed {
log.Debug("Data path instance is concurrent limited requeue later")
return ctrl.Result{Requeue: true, RequeueAfter: time.Second * 5}, nil
} else {
return r.errorOut(ctx, pvr, err, "error to create data path", log)
}
}
if err := r.initCancelableDataPath(ctx, asyncBR, res, log); err != nil {
log.WithError(err).Errorf("Failed to init cancelable data path for %s", pvr.Name)
r.closeDataPath(ctx, pvr.Name)
return r.errorOut(ctx, pvr, err, "error initializing data path", log)
}
terminated := false
if err := UpdatePVRWithRetry(ctx, r.client, types.NamespacedName{Namespace: pvr.Namespace, Name: pvr.Name}, log, func(pvr *velerov1api.PodVolumeRestore) bool {
if isPVRInFinalState(pvr) {
terminated = true
return false
}
pvr.Status.Phase = velerov1api.PodVolumeRestorePhaseInProgress
pvr.Status.StartTimestamp = &metav1.Time{Time: r.clock.Now()}
delete(pvr.Labels, exposer.ExposeOnGoingLabel)
return true
}); err != nil {
log.WithError(err).Warnf("Failed to update PVR %s to InProgress, will data path close and retry", pvr.Name)
r.closeDataPath(ctx, pvr.Name)
return ctrl.Result{Requeue: true, RequeueAfter: time.Second * 5}, nil
}
if terminated {
log.Warnf("PVR %s is terminated during transition from prepared", pvr.Name)
r.closeDataPath(ctx, pvr.Name)
return ctrl.Result{}, nil
}
log.Info("PVR is marked as in progress")
if err := r.startCancelableDataPath(asyncBR, pvr, res, log); err != nil {
log.WithError(err).Errorf("Failed to start cancelable data path for %s", pvr.Name)
r.closeDataPath(ctx, pvr.Name)
return r.errorOut(ctx, pvr, err, "error starting data path", log)
}
return ctrl.Result{}, nil
} else if pvr.Status.Phase == velerov1api.PodVolumeRestorePhaseInProgress {
if pvr.Spec.Cancel {
if pvr.Status.Node != r.nodeName {
return ctrl.Result{}, nil
}
log.Info("PVR is being canceled")
asyncBR := r.dataPathMgr.GetAsyncBR(pvr.Name)
if asyncBR == nil {
r.OnDataPathCancelled(ctx, pvr.GetNamespace(), pvr.GetName())
return ctrl.Result{}, nil
}
// Update status to Canceling
if err := UpdatePVRWithRetry(ctx, r.client, types.NamespacedName{Namespace: pvr.Namespace, Name: pvr.Name}, log, func(pvr *velerov1api.PodVolumeRestore) bool {
if isPVRInFinalState(pvr) {
log.Warnf("PVR %s is terminated, abort setting it to canceling", pvr.Name)
return false
}
pvr.Status.Phase = velerov1api.PodVolumeRestorePhaseCanceling
return true
}); err != nil {
log.WithError(err).Error("error updating PVR into canceling status")
return ctrl.Result{}, err
}
asyncBR.Cancel()
return ctrl.Result{}, nil
}
return ctrl.Result{}, nil
}
return ctrl.Result{}, nil
}
func (r *PodVolumeRestoreReconciler) acceptPodVolumeRestore(ctx context.Context, pvr *velerov1api.PodVolumeRestore) error {
return UpdatePVRWithRetry(ctx, r.client, types.NamespacedName{Namespace: pvr.Namespace, Name: pvr.Name}, r.logger, func(pvr *velerov1api.PodVolumeRestore) bool {
pvr.Status.AcceptedTimestamp = &metav1.Time{Time: r.clock.Now()}
pvr.Status.Phase = velerov1api.PodVolumeRestorePhaseAccepted
pvr.Status.Node = r.nodeName
if pvr.Labels == nil {
pvr.Labels = make(map[string]string)
}
pvr.Labels[exposer.ExposeOnGoingLabel] = "true"
return true
})
}
func (r *PodVolumeRestoreReconciler) tryCancelPodVolumeRestore(ctx context.Context, pvr *velerov1api.PodVolumeRestore, message string) bool {
log := r.logger.WithField("PVR", pvr.Name)
succeeded, err := funcExclusiveUpdatePodVolumeRestore(ctx, r.client, pvr, func(pvr *velerov1api.PodVolumeRestore) {
pvr.Status.Phase = velerov1api.PodVolumeRestorePhaseCanceled
if pvr.Status.StartTimestamp.IsZero() {
pvr.Status.StartTimestamp = &metav1.Time{Time: r.clock.Now()}
}
pvr.Status.CompletionTimestamp = &metav1.Time{Time: r.clock.Now()}
if message != "" {
pvr.Status.Message = message
}
delete(pvr.Labels, exposer.ExposeOnGoingLabel)
})
if err != nil {
log.WithError(err).Error("error updating PVR status")
return false
} else if !succeeded {
log.Warn("conflict in updating PVR status and will try it again later")
return false
}
r.exposer.CleanUp(ctx, getPVROwnerObject(pvr))
log.Warn("PVR is canceled")
return true
}
var funcExclusiveUpdatePodVolumeRestore = exclusiveUpdatePodVolumeRestore
func exclusiveUpdatePodVolumeRestore(ctx context.Context, cli client.Client, pvr *velerov1api.PodVolumeRestore,
updateFunc func(*velerov1api.PodVolumeRestore)) (bool, error) {
updateFunc(pvr)
err := cli.Update(ctx, pvr)
if err == nil {
return true, nil
}
// warn we won't rollback pvr values in memory when error
if apierrors.IsConflict(err) {
return false, nil
} else {
return false, err
}
}
func (r *PodVolumeRestoreReconciler) onPrepareTimeout(ctx context.Context, pvr *velerov1api.PodVolumeRestore) {
log := r.logger.WithField("PVR", pvr.Name)
log.Info("Timeout happened for preparing PVR")
succeeded, err := funcExclusiveUpdatePodVolumeRestore(ctx, r.client, pvr, func(pvr *velerov1api.PodVolumeRestore) {
pvr.Status.Phase = velerov1api.PodVolumeRestorePhaseFailed
pvr.Status.Message = "timeout on preparing PVR"
delete(pvr.Labels, exposer.ExposeOnGoingLabel)
})
if err != nil {
log.WithError(err).Warn("Failed to update PVR")
return
}
if !succeeded {
log.Warn("PVR has been updated by others")
return
}
diags := strings.Split(r.exposer.DiagnoseExpose(ctx, getPVROwnerObject(pvr)), "\n")
for _, diag := range diags {
log.Warnf("[Diagnose PVR expose]%s", diag)
}
r.exposer.CleanUp(ctx, getPVROwnerObject(pvr))
log.Info("PVR has been cleaned up")
}
func (r *PodVolumeRestoreReconciler) initCancelableDataPath(ctx context.Context, asyncBR datapath.AsyncBR, res *exposer.ExposeResult, log logrus.FieldLogger) error {
log.Info("Init cancelable PVR")
if err := asyncBR.Init(ctx, nil); err != nil {
return errors.Wrap(err, "error initializing asyncBR")
}
log.Infof("async data path init for pod %s, volume %s", res.ByPod.HostingPod.Name, res.ByPod.VolumeName)
return nil
}
func (r *PodVolumeRestoreReconciler) startCancelableDataPath(asyncBR datapath.AsyncBR, pvr *velerov1api.PodVolumeRestore, res *exposer.ExposeResult, log logrus.FieldLogger) error {
log.Info("Start cancelable PVR")
if err := asyncBR.StartRestore(pvr.Spec.SnapshotID, datapath.AccessPoint{
ByPath: res.ByPod.VolumeName,
}, pvr.Spec.UploaderSettings); err != nil {
return errors.Wrapf(err, "error starting async restore for pod %s, volume %s", res.ByPod.HostingPod.Name, res.ByPod.VolumeName)
}
log.Infof("Async restore started for pod %s, volume %s", res.ByPod.HostingPod.Name, res.ByPod.VolumeName)
return nil
}
func (r *PodVolumeRestoreReconciler) errorOut(ctx context.Context, pvr *velerov1api.PodVolumeRestore, err error, msg string, log logrus.FieldLogger) (ctrl.Result, error) {
r.exposer.CleanUp(ctx, getPVROwnerObject(pvr))
return ctrl.Result{}, UpdatePVRStatusToFailed(ctx, r.client, pvr, err, msg, r.clock.Now(), log)
}
func UpdatePVRStatusToFailed(ctx context.Context, c client.Client, pvr *velerov1api.PodVolumeRestore, err error, msg string, time time.Time, log logrus.FieldLogger) error {
log.Info("update PVR status to Failed")
if patchErr := UpdatePVRWithRetry(context.Background(), c, types.NamespacedName{Namespace: pvr.Namespace, Name: pvr.Name}, log,
func(pvr *velerov1api.PodVolumeRestore) bool {
if isPVRInFinalState(pvr) {
return false
}
pvr.Status.Phase = velerov1api.PodVolumeRestorePhaseFailed
pvr.Status.Message = errors.WithMessage(err, msg).Error()
pvr.Status.CompletionTimestamp = &metav1.Time{Time: time}
delete(pvr.Labels, exposer.ExposeOnGoingLabel)
return true
}); patchErr != nil {
log.WithError(patchErr).Warn("error updating PVR status")
}
return err
}
func shouldProcess(ctx context.Context, client client.Client, log logrus.FieldLogger, pvr *velerov1api.PodVolumeRestore) (bool, *corev1api.Pod, error) {
if !isPVRNew(pvr) {
log.Debug("PVR is not new, skip")
return false, nil, nil
}
// we filter the pods during the initialization of cache, if we can get a pod here, the pod must be in the same node with the controller
// so we don't need to compare the node anymore
pod := &corev1api.Pod{}
if err := client.Get(ctx, types.NamespacedName{Namespace: pvr.Spec.Pod.Namespace, Name: pvr.Spec.Pod.Name}, pod); err != nil {
if apierrors.IsNotFound(err) {
log.WithError(err).Debug("Pod not found on this node, skip")
return false, nil, nil
}
log.WithError(err).Error("Unable to get pod")
return false, nil, err
}
if !isInitContainerRunning(pod) {
log.Debug("Pod is not running restore-wait init container, skip")
return false, nil, nil
}
return true, pod, nil
}
func (r *PodVolumeRestoreReconciler) closeDataPath(ctx context.Context, pvrName string) {
asyncBR := r.dataPathMgr.GetAsyncBR(pvrName)
if asyncBR != nil {
asyncBR.Close(ctx)
}
r.dataPathMgr.RemoveAsyncBR(pvrName)
}
func (r *PodVolumeRestoreReconciler) SetupWithManager(mgr ctrl.Manager) error {
gp := kube.NewGenericEventPredicate(func(object client.Object) bool {
pvr := object.(*velerov1api.PodVolumeRestore)
if _, err := uploader.ValidateUploaderType(pvr.Spec.UploaderType); err != nil {
return false
}
if pvr.Status.Phase == velerov1api.PodVolumeRestorePhaseAccepted {
return true
}
if pvr.Spec.Cancel && !isPVRInFinalState(pvr) {
return true
}
if isPVRInFinalState(pvr) && !pvr.DeletionTimestamp.IsZero() {
return true
}
return false
})
s := kube.NewPeriodicalEnqueueSource(r.logger.WithField("controller", constant.ControllerPodVolumeRestore), r.client, &velerov1api.PodVolumeRestoreList{}, preparingMonitorFrequency, kube.PeriodicalEnqueueSourceOption{
Predicates: []predicate.Predicate{gp},
})
pred := kube.NewAllEventPredicate(func(obj client.Object) bool {
pvr := obj.(*velerov1api.PodVolumeRestore)
_, err := uploader.ValidateUploaderType(pvr.Spec.UploaderType)
return err == nil
})
return ctrl.NewControllerManagedBy(mgr).
For(&velerov1api.PodVolumeRestore{}, builder.WithPredicates(pred)).
WatchesRawSource(s).
Watches(&corev1api.Pod{}, handler.EnqueueRequestsFromMapFunc(r.findPVRForTargetPod)).
Watches(&corev1api.Pod{}, kube.EnqueueRequestsFromMapUpdateFunc(r.findPVRForRestorePod),
builder.WithPredicates(predicate.Funcs{
UpdateFunc: func(ue event.UpdateEvent) bool {
newObj := ue.ObjectNew.(*corev1api.Pod)
if _, ok := newObj.Labels[velerov1api.PVRLabel]; !ok {
return false
}
if newObj.Spec.NodeName == "" {
return false
}
return true
},
CreateFunc: func(event.CreateEvent) bool {
return false
},
DeleteFunc: func(de event.DeleteEvent) bool {
return false
},
GenericFunc: func(ge event.GenericEvent) bool {
return false
},
})).
Complete(r)
}
func (r *PodVolumeRestoreReconciler) findPVRForTargetPod(ctx context.Context, pod client.Object) []reconcile.Request {
list := &velerov1api.PodVolumeRestoreList{}
options := &client.ListOptions{
LabelSelector: labels.Set(map[string]string{
velerov1api.PodUIDLabel: string(pod.GetUID()),
}).AsSelector(),
}
if err := r.client.List(context.TODO(), list, options); err != nil {
r.logger.WithField("pod", fmt.Sprintf("%s/%s", pod.GetNamespace(), pod.GetName())).WithError(err).
Error("unable to list PodVolumeRestores")
return []reconcile.Request{}
}
requests := []reconcile.Request{}
for _, item := range list.Items {
if _, err := uploader.ValidateUploaderType(item.Spec.UploaderType); err != nil {
continue
}
requests = append(requests, reconcile.Request{
NamespacedName: types.NamespacedName{
Namespace: item.GetNamespace(),
Name: item.GetName(),
},
})
}
return requests
}
func (r *PodVolumeRestoreReconciler) findPVRForRestorePod(ctx context.Context, podObj client.Object) []reconcile.Request {
pod := podObj.(*corev1api.Pod)
pvr, err := findPVRByRestorePod(r.client, *pod)
log := r.logger.WithField("pod", pod.Name)
if err != nil {
log.WithError(err).Error("unable to get PVR")
return []reconcile.Request{}
} else if pvr == nil {
log.Error("get empty PVR")
return []reconcile.Request{}
}
log = log.WithFields(logrus.Fields{
"PVR": pvr.Name,
})
if _, err := uploader.ValidateUploaderType(pvr.Spec.UploaderType); err != nil {
log.WithField("uploaderType", pvr.Spec.UploaderType).Debug("skip PVR with invalid uploader type")
return []reconcile.Request{}
}
if pvr.Status.Phase != velerov1api.PodVolumeRestorePhaseAccepted {
return []reconcile.Request{}
}
if pod.Status.Phase == corev1api.PodRunning {
log.Info("Preparing PVR")
if err = UpdatePVRWithRetry(context.Background(), r.client, types.NamespacedName{Namespace: pvr.Namespace, Name: pvr.Name}, log,
func(pvr *velerov1api.PodVolumeRestore) bool {
if isPVRInFinalState(pvr) {
log.Warnf("PVR %s is terminated, abort setting it to prepared", pvr.Name)
return false
}
pvr.Status.Phase = velerov1api.PodVolumeRestorePhasePrepared
return true
}); err != nil {
log.WithError(err).Warn("failed to update PVR, prepare will halt for this PVR")
return []reconcile.Request{}
}
} else if unrecoverable, reason := kube.IsPodUnrecoverable(pod, log); unrecoverable {
err := UpdatePVRWithRetry(context.Background(), r.client, types.NamespacedName{Namespace: pvr.Namespace, Name: pvr.Name}, log,
func(pvr *velerov1api.PodVolumeRestore) bool {
if pvr.Spec.Cancel {
return false
}
pvr.Spec.Cancel = true
pvr.Status.Message = fmt.Sprintf("Cancel PVR because the exposing pod %s/%s is in abnormal status for reason %s", pod.Namespace, pod.Name, reason)
return true
})
if err != nil {
log.WithError(err).Warn("failed to cancel PVR, and it will wait for prepare timeout")
return []reconcile.Request{}
}
log.Infof("Exposed pod is in abnormal status(reason %s) and PVR is marked as cancel", reason)
} else {
return []reconcile.Request{}
}
request := reconcile.Request{
NamespacedName: types.NamespacedName{
Namespace: pvr.Namespace,
Name: pvr.Name,
},
}
return []reconcile.Request{request}
}
func isPVRNew(pvr *velerov1api.PodVolumeRestore) bool {
return pvr.Status.Phase == "" || pvr.Status.Phase == velerov1api.PodVolumeRestorePhaseNew
}
func isInitContainerRunning(pod *corev1api.Pod) bool {
// Pod volume wait container can be anywhere in the list of init containers, but must be running.
i := getInitContainerIndex(pod)
return i >= 0 &&
len(pod.Status.InitContainerStatuses)-1 >= i &&
pod.Status.InitContainerStatuses[i].State.Running != nil
}
func getInitContainerIndex(pod *corev1api.Pod) int {
// Pod volume wait container can be anywhere in the list of init containers so locate it.
for i, initContainer := range pod.Spec.InitContainers {
if initContainer.Name == restorehelper.WaitInitContainer {
return i
}
}
return -1
}
func (r *PodVolumeRestoreReconciler) OnDataPathCompleted(ctx context.Context, namespace string, pvrName string, result datapath.Result) {
defer r.dataPathMgr.RemoveAsyncBR(pvrName)
log := r.logger.WithField("PVR", pvrName)
log.WithField("PVR", pvrName).WithField("result", result.Restore).Info("Async fs restore data path completed")
var pvr velerov1api.PodVolumeRestore
if err := r.client.Get(ctx, types.NamespacedName{Name: pvrName, Namespace: namespace}, &pvr); err != nil {
log.WithError(err).Warn("Failed to get PVR on completion")
return
}
log.Info("Cleaning up exposed environment")
r.exposer.CleanUp(ctx, getPVROwnerObject(&pvr))
if err := UpdatePVRWithRetry(ctx, r.client, types.NamespacedName{Namespace: pvr.Namespace, Name: pvr.Name}, log, func(pvr *velerov1api.PodVolumeRestore) bool {
if isPVRInFinalState(pvr) {
return false
}
pvr.Status.Phase = velerov1api.PodVolumeRestorePhaseCompleted
pvr.Status.CompletionTimestamp = &metav1.Time{Time: r.clock.Now()}
delete(pvr.Labels, exposer.ExposeOnGoingLabel)
return true
}); err != nil {
log.WithError(err).Error("error updating PVR status")
} else {
log.Info("Restore completed")
}
}
func (r *PodVolumeRestoreReconciler) OnDataPathFailed(ctx context.Context, namespace string, pvrName string, err error) {
defer r.dataPathMgr.RemoveAsyncBR(pvrName)
log := r.logger.WithField("PVR", pvrName)
log.WithError(err).Error("Async fs restore data path failed")
var pvr velerov1api.PodVolumeRestore
if getErr := r.client.Get(ctx, types.NamespacedName{Name: pvrName, Namespace: namespace}, &pvr); getErr != nil {
log.WithError(getErr).Warn("Failed to get PVR on failure")
} else {
_, _ = r.errorOut(ctx, &pvr, err, "data path restore failed", log)
}
}
func (r *PodVolumeRestoreReconciler) OnDataPathCancelled(ctx context.Context, namespace string, pvrName string) {
defer r.dataPathMgr.RemoveAsyncBR(pvrName)
log := r.logger.WithField("PVR", pvrName)
log.Warn("Async fs restore data path canceled")
var pvr velerov1api.PodVolumeRestore
if getErr := r.client.Get(ctx, types.NamespacedName{Name: pvrName, Namespace: namespace}, &pvr); getErr != nil {
log.WithError(getErr).Warn("Failed to get PVR on cancel")
return
}
// cleans up any objects generated during the snapshot expose
r.exposer.CleanUp(ctx, getPVROwnerObject(&pvr))
if err := UpdatePVRWithRetry(ctx, r.client, types.NamespacedName{Namespace: pvr.Namespace, Name: pvr.Name}, log, func(pvr *velerov1api.PodVolumeRestore) bool {
if isPVRInFinalState(pvr) {
return false
}
pvr.Status.Phase = velerov1api.PodVolumeRestorePhaseCanceled
if pvr.Status.StartTimestamp.IsZero() {
pvr.Status.StartTimestamp = &metav1.Time{Time: r.clock.Now()}
}
pvr.Status.CompletionTimestamp = &metav1.Time{Time: r.clock.Now()}
delete(pvr.Labels, exposer.ExposeOnGoingLabel)
return true
}); err != nil {
log.WithError(err).Error("error updating PVR status on cancel")
} else {
delete(r.cancelledPVR, pvr.Name)
}
}
func (r *PodVolumeRestoreReconciler) OnDataPathProgress(ctx context.Context, namespace string, pvrName string, progress *uploader.Progress) {
log := r.logger.WithField("PVR", pvrName)
if err := UpdatePVRWithRetry(ctx, r.client, types.NamespacedName{Namespace: namespace, Name: pvrName}, log, func(pvr *velerov1api.PodVolumeRestore) bool {
pvr.Status.Progress = veleroapishared.DataMoveOperationProgress{TotalBytes: progress.TotalBytes, BytesDone: progress.BytesDone}
return true
}); err != nil {
log.WithError(err).Error("Failed to update progress")
}
}
func (r *PodVolumeRestoreReconciler) setupExposeParam(pvr *velerov1api.PodVolumeRestore) exposer.PodVolumeExposeParam {
log := r.logger.WithField("PVR", pvr.Name)
nodeOS, err := kube.GetNodeOS(context.Background(), pvr.Status.Node, r.kubeClient.CoreV1())
if err != nil {
log.WithError(err).Warnf("Failed to get nodeOS for node %s, use linux node-agent for hosting pod labels, annotations and tolerations", pvr.Status.Node)
}
hostingPodLabels := map[string]string{velerov1api.PVRLabel: pvr.Name}
if len(r.podLabels) > 0 {
for k, v := range r.podLabels {
hostingPodLabels[k] = v
}
} else {
for _, k := range util.ThirdPartyLabels {
if v, err := nodeagent.GetLabelValue(context.Background(), r.kubeClient, pvr.Namespace, k, nodeOS); err != nil {
if err != nodeagent.ErrNodeAgentLabelNotFound {
log.WithError(err).Warnf("Failed to check node-agent label, skip adding host pod label %s", k)
}
} else {
hostingPodLabels[k] = v
}
}
}
hostingPodAnnotation := map[string]string{}
if len(r.podAnnotations) > 0 {
for k, v := range r.podAnnotations {
hostingPodAnnotation[k] = v
}
} else {
for _, k := range util.ThirdPartyAnnotations {
if v, err := nodeagent.GetAnnotationValue(context.Background(), r.kubeClient, pvr.Namespace, k, nodeOS); err != nil {
if err != nodeagent.ErrNodeAgentAnnotationNotFound {
log.WithError(err).Warnf("Failed to check node-agent annotation, skip adding host pod annotation %s", k)
}
} else {
hostingPodAnnotation[k] = v
}
}
}
hostingPodTolerations := []corev1api.Toleration{}
for _, k := range util.ThirdPartyTolerations {
if v, err := nodeagent.GetToleration(context.Background(), r.kubeClient, pvr.Namespace, k, nodeOS); err != nil {
if err != nodeagent.ErrNodeAgentTolerationNotFound {
log.WithError(err).Warnf("Failed to check node-agent toleration, skip adding host pod toleration %s", k)
}
} else {
hostingPodTolerations = append(hostingPodTolerations, *v)
}
}
var cacheVolume *exposer.CacheConfigs
if r.cacheVolumeConfigs != nil {
if limit, err := r.repoConfigMgr.ClientSideCacheLimit(velerov1api.BackupRepositoryTypeKopia, r.backupRepoConfigs); err != nil {
log.WithError(err).Warnf("Failed to get client side cache limit for repo type %s from configs %v", velerov1api.BackupRepositoryTypeKopia, r.backupRepoConfigs)
} else {
cacheVolume = &exposer.CacheConfigs{
Limit: limit,
StorageClass: r.cacheVolumeConfigs.StorageClass,
ResidentThreshold: r.cacheVolumeConfigs.ResidentThresholdInMB << 20,
}
}
}
return exposer.PodVolumeExposeParam{
Type: exposer.PodVolumeExposeTypeRestore,
ClientNamespace: pvr.Spec.Pod.Namespace,
ClientPodName: pvr.Spec.Pod.Name,
ClientPodVolume: pvr.Spec.Volume,
HostingPodLabels: hostingPodLabels,
HostingPodAnnotations: hostingPodAnnotation,
HostingPodTolerations: hostingPodTolerations,
OperationTimeout: r.resourceTimeout,
Resources: r.podResources,
RestoreSize: pvr.Spec.SnapshotSize,
CacheVolume: cacheVolume,
// Priority class name for the data mover pod, retrieved from node-agent-configmap
PriorityClassName: r.dataMovePriorityClass,
Privileged: r.privileged,
}
}
func getPVROwnerObject(pvr *velerov1api.PodVolumeRestore) corev1api.ObjectReference {
return corev1api.ObjectReference{
Kind: pvr.Kind,
Namespace: pvr.Namespace,
Name: pvr.Name,
UID: pvr.UID,
APIVersion: pvr.APIVersion,
}
}
func findPVRByRestorePod(client client.Client, pod corev1api.Pod) (*velerov1api.PodVolumeRestore, error) {
if label, exist := pod.Labels[velerov1api.PVRLabel]; exist {
pvr := &velerov1api.PodVolumeRestore{}
err := client.Get(context.Background(), types.NamespacedName{
Namespace: pod.Namespace,
Name: label,
}, pvr)
if err != nil {
return nil, errors.Wrapf(err, "error to find PVR by pod %s/%s", pod.Namespace, pod.Name)
}
return pvr, nil
}
return nil, nil
}
func isPVRInFinalState(pvr *velerov1api.PodVolumeRestore) bool {
return pvr.Status.Phase == velerov1api.PodVolumeRestorePhaseFailed ||
pvr.Status.Phase == velerov1api.PodVolumeRestorePhaseCanceled ||