-
Notifications
You must be signed in to change notification settings - Fork 488
/
backup_controller.go
655 lines (576 loc) · 21.1 KB
/
backup_controller.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
// Copyright 2019 PingCAP, Inc.
//
// 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package backup
import (
"fmt"
"time"
perrors "github.com/pingcap/errors"
"github.com/pingcap/tidb-operator/pkg/apis/pingcap/v1alpha1"
"github.com/pingcap/tidb-operator/pkg/backup/backup"
"github.com/pingcap/tidb-operator/pkg/controller"
"github.com/pingcap/tidb-operator/pkg/metrics"
batchv1 "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/util/workqueue"
"k8s.io/klog/v2"
)
// Controller controls backup.
type Controller struct {
deps *controller.Dependencies
// control returns an interface capable of syncing a backup.
// Abstracted out for testing.
control ControlInterface
// backups that need to be synced.
queue workqueue.RateLimitingInterface
}
// NewController creates a backup controller.
func NewController(deps *controller.Dependencies) *Controller {
c := &Controller{
deps: deps,
control: NewDefaultBackupControl(deps.Clientset, backup.NewBackupManager(deps)),
queue: workqueue.NewNamedRateLimitingQueue(
controller.NewControllerRateLimiter(1*time.Second, 100*time.Second),
"backup",
),
}
backupInformer := deps.InformerFactory.Pingcap().V1alpha1().Backups()
jobInformer := deps.KubeInformerFactory.Batch().V1().Jobs()
backupInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: c.updateBackup,
UpdateFunc: func(old, cur interface{}) {
c.updateBackup(cur)
},
DeleteFunc: c.updateBackup,
})
jobInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
DeleteFunc: c.deleteJob,
})
return c
}
// Name returns backup controller name.
func (c *Controller) Name() string {
return "backup"
}
// Run runs the backup controller.
func (c *Controller) Run(workers int, stopCh <-chan struct{}) {
defer utilruntime.HandleCrash()
defer c.queue.ShutDown()
klog.Info("Starting backup controller")
defer klog.Info("Shutting down backup controller")
for i := 0; i < workers; i++ {
go wait.Until(c.worker, time.Second, stopCh)
}
<-stopCh
}
// worker runs a worker goroutine that invokes processNextWorkItem until the the controller's queue is closed
func (c *Controller) worker() {
for c.processNextWorkItem() {
}
}
// processNextWorkItem dequeues items, processes them, and marks them done. It enforces that the syncHandler is never
// invoked concurrently with the same key.
func (c *Controller) processNextWorkItem() bool {
metrics.ActiveWorkers.WithLabelValues(c.Name()).Add(1)
defer metrics.ActiveWorkers.WithLabelValues(c.Name()).Add(-1)
key, quit := c.queue.Get()
if quit {
return false
}
defer c.queue.Done(key)
if err := c.sync(key.(string)); err != nil {
if perrors.Find(err, controller.IsRequeueError) != nil {
klog.Infof("Backup: %v, still need sync: %v, requeuing", key.(string), err)
c.queue.AddRateLimited(key)
} else if perrors.Find(err, controller.IsIgnoreError) != nil {
klog.V(4).Infof("Backup: %v, ignore err: %v", key.(string), err)
} else {
utilruntime.HandleError(fmt.Errorf("Backup: %v, sync failed, err: %v, requeuing", key.(string), err))
c.queue.AddRateLimited(key)
}
} else {
c.queue.Forget(key)
}
return true
}
// sync syncs the given backup.
func (c *Controller) sync(key string) error {
startTime := time.Now()
defer func() {
duration := time.Since(startTime)
metrics.ReconcileTime.WithLabelValues(c.Name()).Observe(duration.Seconds())
klog.V(4).Infof("Finished syncing Backup %q (%v)", key, duration)
}()
ns, name, err := cache.SplitMetaNamespaceKey(key)
if err != nil {
return err
}
backup, err := c.deps.BackupLister.Backups(ns).Get(name)
if errors.IsNotFound(err) {
klog.Infof("Backup has been deleted %v", key)
return nil
}
if err != nil {
return err
}
return c.syncBackup(backup.DeepCopy())
}
func (c *Controller) syncBackup(backup *v1alpha1.Backup) error {
return c.control.UpdateBackup(backup)
}
func (c *Controller) updateBackup(cur interface{}) {
newBackup := cur.(*v1alpha1.Backup)
ns := newBackup.GetNamespace()
name := newBackup.GetName()
if newBackup.DeletionTimestamp != nil {
// the backup is being deleted, we need to do some cleanup work, enqueue backup.
klog.Infof("backup %s/%s is being deleted", ns, name)
c.enqueueBackup(newBackup)
return
}
if v1alpha1.IsBackupInvalid(newBackup) {
klog.V(4).Infof("backup %s/%s is invalid, skipping.", ns, name)
return
}
if v1alpha1.IsBackupComplete(newBackup) {
klog.V(4).Infof("backup %s/%s is Complete, skipping.", ns, name)
return
}
if v1alpha1.IsBackupFailed(newBackup) {
// when volume backup is failed, the initializing job may not stop immediately, we need stop it.
jobRunning, err := c.isVolumeBackupInitializeJobRunning(newBackup)
if err != nil {
klog.Errorf("Fail to check if initialize job of volume backup %s/%s is running, error %v", ns, name, err)
return
}
if jobRunning {
klog.V(4).Infof("volume backup %s/%s failed but initialize job is running, enqueue", ns, name)
c.enqueueBackup(newBackup)
}
klog.V(4).Infof("backup %s/%s is Failed, skipping.", ns, name)
return
}
// for teardown phase, we should always reconcile it before it is complete or failed to resume gc and pd schedule
if newBackup.Spec.Mode == v1alpha1.BackupModeVolumeSnapshot &&
newBackup.Spec.FederalVolumeBackupPhase == v1alpha1.FederalVolumeBackupTeardown {
klog.V(4).Infof("backup object %s/%s enqueue", ns, name)
c.enqueueBackup(newBackup)
return
}
// TODO: log backup check all subcommand job's pod status
if newBackup.Spec.Mode != v1alpha1.BackupModeLog {
// we will create backup job when we mark backup as scheduled status,
// but the backup job or its pod may failed due to insufficient resources or other reasons in k8s,
// we should detect this kind of failure and try to restart backup according to spec.backoffRetryPolicy.
jobFailed, reason, originalReason, err := c.detectBackupJobFailure(newBackup)
if err != nil {
klog.Errorf("Fail to detect backup %s/%s failure, error %v", ns, name, err)
return
}
if jobFailed {
// retry backup after detect failure
if err := c.retryAfterFailureDetected(newBackup, reason, originalReason); err != nil {
klog.Errorf("Fail to restart snapshot backup %s/%s, error %v", ns, name, err)
}
return
}
}
// volume backup has multiple phases, we should always reconcile it before it is complete or failed
if newBackup.Spec.Mode == v1alpha1.BackupModeVolumeSnapshot {
klog.V(4).Infof("backup object %s/%s enqueue", ns, name)
c.enqueueBackup(newBackup)
return
}
if v1alpha1.IsBackupScheduled(newBackup) || v1alpha1.IsBackupRunning(newBackup) || v1alpha1.IsBackupPrepared(newBackup) || v1alpha1.IsLogBackupStopped(newBackup) {
klog.V(4).Infof("backup %s/%s is already Scheduled, Running, Preparing or Failed, skipping.", ns, name)
return
}
klog.V(4).Infof("backup object %s/%s enqueue", ns, name)
c.enqueueBackup(newBackup)
}
func (c *Controller) deleteJob(obj interface{}) {
job, ok := obj.(*batchv1.Job)
if !ok {
return
}
ns := job.GetNamespace()
jobName := job.GetName()
backup := c.resolveBackupFromJob(ns, job)
if backup == nil {
return
}
klog.V(4).Infof("Job %s/%s deleted through %v.", ns, jobName, utilruntime.GetCaller())
c.updateBackup(backup)
}
func (c *Controller) resolveBackupFromJob(namespace string, job *batchv1.Job) *v1alpha1.Backup {
owner := metav1.GetControllerOf(job)
if owner == nil {
return nil
}
if owner.Kind != controller.BackupControllerKind.Kind {
return nil
}
backup, err := c.deps.BackupLister.Backups(namespace).Get(owner.Name)
if err != nil {
return nil
}
if owner.UID != backup.UID {
return nil
}
return backup
}
// enqueueBackup enqueues the given backup in the work queue.
func (c *Controller) enqueueBackup(obj interface{}) {
key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj)
if err != nil {
utilruntime.HandleError(fmt.Errorf("cound't get key for object %+v: %v", obj, err))
return
}
c.queue.Add(key)
}
// detectBackupJobFailure detect backup job or pod failure.
// it will record failure info to backup status, it is to realize reentrant logic for spec.backoffRetryPolicy. so it only record snapshot backup failed now.
func (c *Controller) detectBackupJobFailure(backup *v1alpha1.Backup) (
jobFailed bool, reason string, originalReason string, err error) {
var (
ns = backup.GetNamespace()
name = backup.GetName()
)
// if failure was recorded, get reason from backup status
if c.isFailureAlreadyRecorded(backup) {
reason = backup.Status.BackoffRetryStatus[len(backup.Status.BackoffRetryStatus)-1].RetryReason
originalReason = backup.Status.BackoffRetryStatus[len(backup.Status.BackoffRetryStatus)-1].OriginalReason
return true, reason, originalReason, nil
}
// check whether backup job failed by checking their status
jobFailed, reason, originalReason, err = c.isBackupJobFailed(backup)
if err != nil {
klog.Errorf("Fail to check backup %s/%s job status, %v", ns, name, err)
return false, "", "", err
}
// not failed, make sure reason and originalReason are empty when not failed
if !jobFailed {
return false, "", "", nil
}
klog.Infof("Detect backup %s/%s job failed, will retry, reason %s, original reason %s ", ns, name, reason, originalReason)
// record failure when detect failure
err = c.recordDetectedFailure(backup, reason, originalReason)
if err != nil {
klog.Errorf("failed to record detected failed %s for backup %s/%s", reason, ns, name)
}
return jobFailed, reason, originalReason, nil
}
func (c *Controller) isFailureAlreadyRecorded(backup *v1alpha1.Backup) bool {
// just snapshot backup record failure now
if backup.Spec.Mode != v1alpha1.BackupModeSnapshot {
return false
}
// retrying
if isBackoffRetrying(backup) {
return true
}
// no record
if len(backup.Status.BackoffRetryStatus) == 0 {
return false
}
// latest failure is done, this failure should be a new one and no records
if isCurrentBackoffRetryDone(backup) {
return false
}
return true
}
func (c *Controller) recordDetectedFailure(backup *v1alpha1.Backup, reason, originalReason string) error {
ns := backup.GetNamespace()
name := backup.GetName()
if backup.Spec.Mode != v1alpha1.BackupModeSnapshot {
return nil
}
retryNum := len(backup.Status.BackoffRetryStatus) + 1
detectFailedAt := metav1.Now()
minDuration, err := time.ParseDuration(backup.Spec.BackoffRetryPolicy.MinRetryDuration)
if err != nil {
klog.Errorf("fail to parse minRetryDuration %s of backup %s/%s, %v", backup.Spec.BackoffRetryPolicy.MinRetryDuration, ns, name, err)
return err
}
duration := time.Duration(minDuration.Nanoseconds() << (retryNum - 1))
expectedRetryAt := metav1.NewTime(detectFailedAt.Add(duration))
// update
newStatus := &controller.BackupUpdateStatus{
RetryNum: &retryNum,
DetectFailedAt: &detectFailedAt,
ExpectedRetryAt: &expectedRetryAt,
RetryReason: &reason,
OriginalReason: &originalReason,
}
klog.Infof("Record backup %s/%s retry status, %v", ns, name, newStatus)
if err := c.control.UpdateStatus(backup, nil, newStatus); err != nil {
klog.Errorf("Fail to update the retry status of backup %s/%s, %v", ns, name, err)
return err
}
return nil
}
// retryAfterFailureDetected retry detect failure according to spec.backoffRetryPolicy.
// it only retry snapshot backup now. for others, it will marking failed directly.
func (c *Controller) retryAfterFailureDetected(backup *v1alpha1.Backup, reason, originalReason string) error {
var (
ns = backup.GetNamespace()
name = backup.GetName()
err error
)
// not snapshot backup, just mark as failed
if backup.Spec.Mode != v1alpha1.BackupModeSnapshot {
conditionType := v1alpha1.BackupFailed
if backup.Spec.Mode == v1alpha1.BackupModeVolumeSnapshot {
conditionType = v1alpha1.VolumeBackupFailed
}
err = c.control.UpdateStatus(backup, &v1alpha1.BackupCondition{
Type: conditionType,
Status: corev1.ConditionTrue,
Reason: "AlreadyFailed",
Message: fmt.Sprintf("reason %s, original reason %s", reason, originalReason),
}, nil)
if err != nil {
klog.Errorf("Fail to update the condition of backup %s/%s, %v", ns, name, err)
return err
}
return nil
}
// retry snapshot backup according to backoff policy
err = c.retrySnapshotBackupAccordingToBackoffPolicy(backup)
if err != nil {
klog.Errorf("Fail to retry snapshot backup %s/%s according to backoff policy , %v", ns, name, err)
return err
}
klog.Infof("Retry snapshot backup %s/%s according to backoff policy", ns, name)
return nil
}
func (c *Controller) isBackupJobFailed(backup *v1alpha1.Backup) (
jobFailed bool, reason string, originalReason string, err error) {
ns := backup.GetNamespace()
name := backup.GetName()
jobName := backup.GetBackupJobName()
job, err := c.deps.JobLister.Jobs(ns).Get(jobName)
if err != nil && !errors.IsNotFound(err) {
klog.Errorf("Fail to get job %s for backup %s/%s, error %v ", jobName, ns, name, err)
return false, "", "", err
}
if job != nil {
for _, condition := range job.Status.Conditions {
if condition.Type == batchv1.JobFailed && condition.Status == corev1.ConditionTrue {
reason = fmt.Sprintf("Job %s has failed", jobName)
originalReason = condition.Reason
return true, reason, originalReason, nil
}
}
}
return false, "", "", nil
}
func (c *Controller) isVolumeBackupInitializeJobRunning(backup *v1alpha1.Backup) (bool, error) {
if backup.Spec.Mode != v1alpha1.BackupModeVolumeSnapshot {
return false, nil
}
ns, backupName := backup.Namespace, backup.Name
jobName := backup.GetVolumeBackupInitializeJobName()
job, err := c.deps.JobLister.Jobs(ns).Get(jobName)
if err != nil {
if errors.IsNotFound(err) {
return false, nil
} else {
klog.Errorf("Fail to get job %s for backup %s/%s, error %v ", jobName, ns, backupName, err)
return false, err
}
}
for _, condition := range job.Status.Conditions {
if (condition.Type == batchv1.JobFailed || condition.Type == batchv1.JobComplete) && condition.Status == corev1.ConditionTrue {
return false, nil
}
}
return true, nil
}
// retrySnapshotBackupAccordingToBackoffPolicy retry snapshot backup according to spec.backoffRetryPolicy.
// the main logic is reentrant:
// 1. check whether is retrying which is marked as BackupRetryFailed,
// if true, clean job and mark RealRetryAt which means current retry is done.
// 2. check whether is retry done, skip.
// 3. check whether exceed retry limit, if true, mark as failed.
// 4. check whether exceed the retry interval which is recorded as ExpectedRetryAt,
// the value is the time detect failure + MinRetryDuration << (retry num -1),
// if true, mark as BackupRetryFailed, if not, wait to next loop.
// 5. after mark as BackupRetryFailed, the logic will back to 1 in next loop.
func (c *Controller) retrySnapshotBackupAccordingToBackoffPolicy(backup *v1alpha1.Backup) error {
if len(backup.Status.BackoffRetryStatus) == 0 {
return nil
}
var (
ns = backup.GetNamespace()
name = backup.GetName()
now = time.Now()
err error
failedReason string
retryRecord = backup.Status.BackoffRetryStatus[len(backup.Status.BackoffRetryStatus)-1]
)
klog.V(4).Infof("retry backup %s/%s, retry reason %s, original reason %s", ns, name, retryRecord.RetryReason, retryRecord.OriginalReason)
// check retrying
if isBackoffRetrying(backup) {
return c.doRetryFailedBackup(backup)
}
// check retry done
if isCurrentBackoffRetryDone(backup) {
return nil
}
// check is exceed retry limit
isExceedRetryTimes := isExceedRetryTimes(backup)
if isExceedRetryTimes {
failedReason = fmt.Sprintf("exceed retry times, max is %d, failed reason %s, original reason %s", backup.Spec.BackoffRetryPolicy.MaxRetryTimes, retryRecord.RetryReason, retryRecord.OriginalReason)
}
isRetryTimeout, err := isRetryTimeout(backup, &now)
if err != nil {
klog.Errorf("fail to check whether the retry is timeout, backup is %s/%s, %v", ns, name, err)
return err
}
if isRetryTimeout {
failedReason = fmt.Sprintf("retry timeout, max is %s, failed reason %s, original reason %s", backup.Spec.BackoffRetryPolicy.RetryTimeout, retryRecord.RetryReason, retryRecord.OriginalReason)
}
if isExceedRetryTimes || isRetryTimeout {
klog.Infof("backup %s/%s exceed retry limit, failed reason %s", ns, name, failedReason)
err = c.control.UpdateStatus(backup, &v1alpha1.BackupCondition{
Type: v1alpha1.BackupFailed,
Status: corev1.ConditionTrue,
Reason: "AlreadyFailed",
Message: failedReason,
}, nil)
if err != nil {
klog.Errorf("Fail to update the condition of backup %s/%s, %v", ns, name, err)
return err
}
return nil
}
// check is time to retry
if !isTimeToRetry(backup, &now) {
klog.V(4).Infof("backup %s/%s is not the time to retry, expected retry time is %s, now is %s", ns, name, retryRecord.ExpectedRetryAt, now)
return nil
}
klog.V(4).Infof("backup %s/%s is the time to retry, expected retry time is %s, now is %s", ns, name, retryRecord.ExpectedRetryAt, now)
// update retry status
err = c.control.UpdateStatus(backup, &v1alpha1.BackupCondition{
Type: v1alpha1.BackupRetryTheFailed,
Status: corev1.ConditionTrue,
Reason: "RetryFailedBackup",
Message: fmt.Sprintf("reason %s, original reason %s", retryRecord.RetryReason, retryRecord.OriginalReason),
}, nil)
if err != nil {
klog.Errorf("Fail to update the retry status of backup %s/%s, %v", ns, name, err)
return err
}
return nil
}
func isExceedRetryTimes(backup *v1alpha1.Backup) bool {
records := backup.Status.BackoffRetryStatus
if len(records) == 0 {
return false
}
currentRetryNum := records[len(records)-1].RetryNum
return currentRetryNum > backup.Spec.BackoffRetryPolicy.MaxRetryTimes
}
func isRetryTimeout(backup *v1alpha1.Backup, now *time.Time) (bool, error) {
records := backup.Status.BackoffRetryStatus
if len(records) == 0 {
return false, nil
}
firstDetectAt := records[0].DetectFailedAt
retryTimeout, err := time.ParseDuration(backup.Spec.BackoffRetryPolicy.RetryTimeout)
if err != nil {
klog.Errorf("fail to parse retryTimeout %s of backup %s/%s, %v", backup.Spec.BackoffRetryPolicy.RetryTimeout, backup.Namespace, backup.Name, err)
return false, err
}
return now.Unix()-firstDetectAt.Unix() > int64(retryTimeout)/int64(time.Second), nil
}
func isTimeToRetry(backup *v1alpha1.Backup, now *time.Time) bool {
if len(backup.Status.BackoffRetryStatus) == 0 {
return false
}
retryRecord := backup.Status.BackoffRetryStatus[len(backup.Status.BackoffRetryStatus)-1]
return time.Now().Unix() > retryRecord.ExpectedRetryAt.Unix()
}
func (c *Controller) cleanBackupOldJobIfExist(backup *v1alpha1.Backup) error {
ns := backup.GetNamespace()
name := backup.GetName()
jobName := backup.GetBackupJobName()
oldJob, err := c.deps.JobLister.Jobs(ns).Get(jobName)
if err != nil && !errors.IsNotFound(err) {
klog.Errorf("Fail to get job %s for backup %s/%s, error %v ", jobName, ns, name, err)
return nil
}
if oldJob != nil {
if err := c.deps.JobControl.DeleteJob(backup, oldJob); err != nil {
klog.Errorf("backup %s/%s delete job %s failed, err: %v", ns, name, jobName, err)
return nil
}
}
return nil
}
func (c *Controller) doRetryFailedBackup(backup *v1alpha1.Backup) error {
ns := backup.GetNamespace()
name := backup.GetName()
klog.V(4).Infof("backup %s/%s is retrying after it has been scheduled", ns, name)
// retry done
if isCurrentBackoffRetryDone(backup) {
// clean job is asynchronous, we need enqueue again,
// the backup status will be scheduled after create new job, and then this reconcile is really done.
c.enqueueBackup(backup)
return nil
}
// clean job
err := c.cleanBackupOldJobIfExist(backup)
if err != nil {
klog.Errorf("Fail to clean job of backup %s/%s, error is %v", ns, name, err)
return err
}
// retry done, mark RealRetryAt
RealRetryStatus := &controller.BackupUpdateStatus{
RealRetryAt: &metav1.Time{Time: time.Now()},
}
// add restart condition to clean data before run br command
err = c.control.UpdateStatus(backup, &v1alpha1.BackupCondition{
Type: v1alpha1.BackupRestart,
Status: corev1.ConditionTrue,
}, RealRetryStatus)
if err != nil {
klog.Errorf("Fail to update the condition of backup %s/%s, %v", ns, name, err)
return err
}
c.enqueueBackup(backup)
return nil
}
func isBackoffRetrying(backup *v1alpha1.Backup) bool {
if backup.Spec.Mode != v1alpha1.BackupModeSnapshot {
return false
}
if len(backup.Status.BackoffRetryStatus) == 0 {
return false
}
return backup.Status.Phase == v1alpha1.BackupRetryTheFailed
}
func isCurrentBackoffRetryDone(backup *v1alpha1.Backup) bool {
if backup.Spec.Mode != v1alpha1.BackupModeSnapshot {
return false
}
if len(backup.Status.BackoffRetryStatus) == 0 {
return false
}
return backup.Status.BackoffRetryStatus[len(backup.Status.BackoffRetryStatus)-1].RealRetryAt != nil
}