forked from vmware-tanzu/velero
-
Notifications
You must be signed in to change notification settings - Fork 18
/
restore_operations_controller.go
352 lines (325 loc) · 13.7 KB
/
restore_operations_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
/*
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"
"time"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
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"
velerov1api "github.com/vmware-tanzu/velero/pkg/apis/velero/v1"
"github.com/vmware-tanzu/velero/pkg/itemoperation"
"github.com/vmware-tanzu/velero/pkg/itemoperationmap"
"github.com/vmware-tanzu/velero/pkg/metrics"
"github.com/vmware-tanzu/velero/pkg/persistence"
"github.com/vmware-tanzu/velero/pkg/plugin/clientmgmt"
"github.com/vmware-tanzu/velero/pkg/util/kube"
)
const (
defaultRestoreOperationsFrequency = 10 * time.Second
)
type restoreOperationsReconciler struct {
client.Client
namespace string
logger logrus.FieldLogger
clock clocks.WithTickerAndDelayedExecution
frequency time.Duration
itemOperationsMap *itemoperationmap.RestoreItemOperationsMap
newPluginManager func(logger logrus.FieldLogger) clientmgmt.Manager
backupStoreGetter persistence.ObjectBackupStoreGetter
metrics *metrics.ServerMetrics
}
func NewRestoreOperationsReconciler(
logger logrus.FieldLogger,
namespace string,
client client.Client,
frequency time.Duration,
newPluginManager func(logrus.FieldLogger) clientmgmt.Manager,
backupStoreGetter persistence.ObjectBackupStoreGetter,
metrics *metrics.ServerMetrics,
itemOperationsMap *itemoperationmap.RestoreItemOperationsMap,
) *restoreOperationsReconciler {
abor := &restoreOperationsReconciler{
Client: client,
logger: logger,
namespace: namespace,
clock: clocks.RealClock{},
frequency: frequency,
itemOperationsMap: itemOperationsMap,
newPluginManager: newPluginManager,
backupStoreGetter: backupStoreGetter,
metrics: metrics,
}
if abor.frequency <= 0 {
abor.frequency = defaultRestoreOperationsFrequency
}
return abor
}
func (r *restoreOperationsReconciler) SetupWithManager(mgr ctrl.Manager) error {
s := kube.NewPeriodicalEnqueueSource(r.logger, mgr.GetClient(), &velerov1api.RestoreList{}, r.frequency, kube.PeriodicalEnqueueSourceOption{})
gp := kube.NewGenericEventPredicate(func(object client.Object) bool {
restore := object.(*velerov1api.Restore)
return (restore.Status.Phase == velerov1api.RestorePhaseWaitingForPluginOperations ||
restore.Status.Phase == velerov1api.RestorePhaseWaitingForPluginOperationsPartiallyFailed)
})
return ctrl.NewControllerManagedBy(mgr).
For(&velerov1api.Restore{}, builder.WithPredicates(kube.FalsePredicate{})).
Watches(s, nil, builder.WithPredicates(gp)).
Complete(r)
}
// +kubebuilder:rbac:groups=velero.io,resources=restores,verbs=get;list;watch;update
// +kubebuilder:rbac:groups=velero.io,resources=restores/status,verbs=get
func (r *restoreOperationsReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
log := r.logger.WithField("restore operations for restore", req.String())
log.Debug("restoreOperationsReconciler getting restore")
original := &velerov1api.Restore{}
if err := r.Get(ctx, req.NamespacedName, original); err != nil {
if apierrors.IsNotFound(err) {
log.WithError(err).Error("restore not found")
return ctrl.Result{}, nil
}
return ctrl.Result{}, errors.Wrapf(err, "error getting restore %s", req.String())
}
restore := original.DeepCopy()
log.Debugf("restore: %s", restore.Name)
log = r.logger.WithFields(
logrus.Fields{
"restore": req.String(),
},
)
switch restore.Status.Phase {
case velerov1api.RestorePhaseWaitingForPluginOperations, velerov1api.RestorePhaseWaitingForPluginOperationsPartiallyFailed:
// only process restores waiting for plugin operations to complete
default:
log.Debug("Restore has no ongoing plugin operations, skipping")
return ctrl.Result{}, nil
}
info, err := r.fetchBackupInfo(restore.Spec.BackupName)
if err != nil {
log.Warnf("Cannot check progress on Restore operations because backup info is unavailable %s; marking restore PartiallyFailed", err.Error())
restore.Status.Phase = velerov1api.RestorePhasePartiallyFailed
restore.Status.CompletionTimestamp = &metav1.Time{Time: r.clock.Now()}
r.metrics.RegisterRestorePartialFailure(restore.Spec.ScheduleName)
err2 := r.updateRestoreAndOperationsJSON(ctx, original, restore, nil, &itemoperationmap.OperationsForRestore{ErrsSinceUpdate: []string{err.Error()}}, false, false)
if err2 != nil {
log.WithError(err2).Error("error updating Restore")
}
return ctrl.Result{}, errors.Wrap(err, "error getting backup info")
}
pluginManager := r.newPluginManager(r.logger)
defer pluginManager.CleanupClients()
backupStore, err := r.backupStoreGetter.Get(info.location, pluginManager, r.logger)
if err != nil {
return ctrl.Result{}, errors.Wrap(err, "error getting backup store")
}
operations, err := r.itemOperationsMap.GetOperationsForRestore(backupStore, restore.Name)
if err != nil {
err2 := r.updateRestoreAndOperationsJSON(ctx, original, restore, backupStore, &itemoperationmap.OperationsForRestore{ErrsSinceUpdate: []string{err.Error()}}, false, false)
if err2 != nil {
return ctrl.Result{}, errors.Wrap(err2, "error updating Restore")
}
return ctrl.Result{}, errors.Wrap(err, "error getting restore operations")
}
stillInProgress, changes, opsCompleted, opsFailed, errs := getRestoreItemOperationProgress(restore, pluginManager, operations.Operations)
// if len(errs)>0, need to update restore errors and error log
operations.ErrsSinceUpdate = append(operations.ErrsSinceUpdate, errs...)
restore.Status.Errors += len(operations.ErrsSinceUpdate)
completionChanges := false
if restore.Status.RestoreItemOperationsCompleted != opsCompleted || restore.Status.RestoreItemOperationsFailed != opsFailed {
completionChanges = true
restore.Status.RestoreItemOperationsCompleted = opsCompleted
restore.Status.RestoreItemOperationsFailed = opsFailed
}
if changes {
operations.ChangesSinceUpdate = true
}
if len(operations.ErrsSinceUpdate) > 0 {
restore.Status.Phase = velerov1api.RestorePhaseWaitingForPluginOperationsPartiallyFailed
}
// if stillInProgress is false, restore moves to terminal phase and needs update
// if operations.ErrsSinceUpdate is not empty, then restore phase needs to change to
// RestorePhaseWaitingForPluginOperationsPartiallyFailed and needs update
// If the only changes are incremental progress, then no write is necessary, progress can remain in memory
if !stillInProgress {
if restore.Status.Phase == velerov1api.RestorePhaseWaitingForPluginOperations {
log.Infof("Marking restore %s completed", restore.Name)
restore.Status.Phase = velerov1api.RestorePhaseCompleted
restore.Status.CompletionTimestamp = &metav1.Time{Time: r.clock.Now()}
r.metrics.RegisterRestoreSuccess(restore.Spec.ScheduleName)
} else {
log.Infof("Marking restore %s FinalizingPartiallyFailed", restore.Name)
restore.Status.Phase = velerov1api.RestorePhasePartiallyFailed
restore.Status.CompletionTimestamp = &metav1.Time{Time: r.clock.Now()}
r.metrics.RegisterRestorePartialFailure(restore.Spec.ScheduleName)
}
}
err = r.updateRestoreAndOperationsJSON(ctx, original, restore, backupStore, operations, changes, completionChanges)
if err != nil {
return ctrl.Result{}, errors.Wrap(err, "error updating Restore")
}
return ctrl.Result{}, nil
}
// fetchBackupInfo checks the backup lister for a backup that matches the given name. If it doesn't
// find it, it returns an error.
func (r *restoreOperationsReconciler) fetchBackupInfo(backupName string) (backupInfo, error) {
return fetchBackupInfoInternal(r.Client, r.namespace, backupName)
}
func (r *restoreOperationsReconciler) updateRestoreAndOperationsJSON(
ctx context.Context,
original, restore *velerov1api.Restore,
backupStore persistence.BackupStore,
operations *itemoperationmap.OperationsForRestore,
changes bool,
completionChanges bool) error {
if len(operations.ErrsSinceUpdate) > 0 {
// FIXME: download/upload results
r.logger.WithField("restore", restore.Name).Infof("Restore has %d errors", len(operations.ErrsSinceUpdate))
}
removeIfComplete := true
defer func() {
// remove local operations list if complete
if removeIfComplete && (restore.Status.Phase == velerov1api.RestorePhaseCompleted ||
restore.Status.Phase == velerov1api.RestorePhasePartiallyFailed) {
r.itemOperationsMap.DeleteOperationsForRestore(restore.Name)
} else if changes {
r.itemOperationsMap.PutOperationsForRestore(operations, restore.Name)
}
}()
// update restore and upload progress if errs or complete
if len(operations.ErrsSinceUpdate) > 0 ||
restore.Status.Phase == velerov1api.RestorePhaseCompleted ||
restore.Status.Phase == velerov1api.RestorePhasePartiallyFailed {
// update file store
if backupStore != nil {
if err := r.itemOperationsMap.UploadProgressAndPutOperationsForRestore(backupStore, operations, restore.Name); err != nil {
removeIfComplete = false
return err
}
}
// update restore
err := r.Client.Patch(ctx, restore, client.MergeFrom(original))
if err != nil {
removeIfComplete = false
return errors.Wrapf(err, "error updating Restore %s", restore.Name)
}
} else if completionChanges {
// If restore is still incomplete and no new errors are found but there are some new operations
// completed, patch restore to reflect new completion numbers, but don't upload detailed json file
err := r.Client.Patch(ctx, restore, client.MergeFrom(original))
if err != nil {
return errors.Wrapf(err, "error updating Restore %s", restore.Name)
}
}
return nil
}
func getRestoreItemOperationProgress(
restore *velerov1api.Restore,
pluginManager clientmgmt.Manager,
operationsList []*itemoperation.RestoreOperation) (bool, bool, int, int, []string) {
inProgressOperations := false
changes := false
var errs []string
var completedCount, failedCount int
for _, operation := range operationsList {
if operation.Status.Phase == itemoperation.OperationPhaseNew ||
operation.Status.Phase == itemoperation.OperationPhaseInProgress {
ria, err := pluginManager.GetRestoreItemActionV2(operation.Spec.RestoreItemAction)
if err != nil {
operation.Status.Phase = itemoperation.OperationPhaseFailed
operation.Status.Error = err.Error()
errs = append(errs, err.Error())
changes = true
failedCount++
continue
}
operationProgress, err := ria.Progress(operation.Spec.OperationID, restore)
if err != nil {
operation.Status.Phase = itemoperation.OperationPhaseFailed
operation.Status.Error = err.Error()
errs = append(errs, err.Error())
changes = true
failedCount++
continue
}
if operation.Status.NCompleted != operationProgress.NCompleted {
operation.Status.NCompleted = operationProgress.NCompleted
changes = true
}
if operation.Status.NTotal != operationProgress.NTotal {
operation.Status.NTotal = operationProgress.NTotal
changes = true
}
if operation.Status.OperationUnits != operationProgress.OperationUnits {
operation.Status.OperationUnits = operationProgress.OperationUnits
changes = true
}
if operation.Status.Description != operationProgress.Description {
operation.Status.Description = operationProgress.Description
changes = true
}
started := metav1.NewTime(operationProgress.Started)
if operation.Status.Started == nil && !operationProgress.Started.IsZero() ||
operation.Status.Started != nil && *(operation.Status.Started) != started {
operation.Status.Started = &started
changes = true
}
updated := metav1.NewTime(operationProgress.Updated)
if operation.Status.Updated == nil && !operationProgress.Updated.IsZero() ||
operation.Status.Updated != nil && *(operation.Status.Updated) != updated {
operation.Status.Updated = &updated
changes = true
}
if operationProgress.Completed {
if operationProgress.Err != "" {
operation.Status.Phase = itemoperation.OperationPhaseFailed
operation.Status.Error = operationProgress.Err
errs = append(errs, operationProgress.Err)
changes = true
failedCount++
continue
}
operation.Status.Phase = itemoperation.OperationPhaseCompleted
changes = true
completedCount++
continue
}
// cancel operation if past timeout period
if operation.Status.Created.Time.Add(restore.Spec.ItemOperationTimeout.Duration).Before(time.Now()) {
_ = ria.Cancel(operation.Spec.OperationID, restore)
operation.Status.Phase = itemoperation.OperationPhaseFailed
operation.Status.Error = "Asynchronous action timed out"
errs = append(errs, operation.Status.Error)
changes = true
failedCount++
continue
}
if operation.Status.Phase == itemoperation.OperationPhaseNew &&
operation.Status.Started != nil {
operation.Status.Phase = itemoperation.OperationPhaseInProgress
changes = true
}
// if we reach this point, the operation is still running
inProgressOperations = true
} else if operation.Status.Phase == itemoperation.OperationPhaseCompleted {
completedCount++
} else if operation.Status.Phase == itemoperation.OperationPhaseFailed {
failedCount++
}
}
return inProgressOperations, changes, completedCount, failedCount, errs
}