-
Notifications
You must be signed in to change notification settings - Fork 30
/
taskbackup.go
215 lines (189 loc) · 6.2 KB
/
taskbackup.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
package tasks
import (
"context"
"errors"
"fmt"
"slices"
"sync"
"time"
v1 "github.com/garethgeorge/backrest/gen/go/v1"
"github.com/garethgeorge/backrest/internal/hook"
"github.com/garethgeorge/backrest/internal/protoutil"
"github.com/garethgeorge/backrest/pkg/restic"
"github.com/gitploy-io/cronexpr"
"go.uber.org/zap"
)
var maxBackupErrorHistoryLength = 20 // arbitrary limit on the number of file read errors recorded in a backup operation to prevent it from growing too large.
// BackupTask is a scheduled backup operation.
type BackupTask struct {
BaseTask
scheduler func(curTime time.Time) *time.Time
}
var _ Task = &BackupTask{}
func NewScheduledBackupTask(plan *v1.Plan) (*BackupTask, error) {
sched, err := cronexpr.ParseInLocation(plan.Cron, time.Now().Location().String())
if err != nil {
return nil, fmt.Errorf("failed to parse schedule %q: %w", plan.Cron, err)
}
return &BackupTask{
BaseTask: BaseTask{
TaskName: fmt.Sprintf("backup for plan %q", plan.Id),
TaskRepoID: plan.Repo,
TaskPlanID: plan.Id,
},
scheduler: func(curTime time.Time) *time.Time {
next := sched.Next(curTime)
return &next
},
}, nil
}
func NewOneoffBackupTask(plan *v1.Plan, at time.Time) *BackupTask {
didOnce := false
return &BackupTask{
BaseTask: BaseTask{
TaskName: fmt.Sprintf("backup for plan %q", plan.Id),
TaskRepoID: plan.Repo,
TaskPlanID: plan.Id,
},
scheduler: func(curTime time.Time) *time.Time {
if didOnce {
return nil
}
didOnce = true
return &at
},
}
}
func (t *BackupTask) Next(now time.Time, runner TaskRunner) ScheduledTask {
next := t.scheduler(now)
if next == nil {
return NeverScheduledTask
}
return ScheduledTask{
Task: t,
RunAt: *next,
Op: &v1.Operation{
PlanId: t.PlanID(),
RepoId: t.RepoID(),
UnixTimeStartMs: (*next).UnixMilli(),
Status: v1.OperationStatus_STATUS_PENDING,
Op: &v1.Operation_OperationBackup{},
},
}
}
func (t *BackupTask) Run(ctx context.Context, st ScheduledTask, runner TaskRunner) error {
l := Logger(ctx, st.Task)
startTime := time.Now()
op := st.Op
backupOp := &v1.Operation_OperationBackup{
OperationBackup: &v1.OperationBackup{},
}
op.Op = backupOp
repo, err := runner.GetRepoOrchestrator(t.RepoID())
if err != nil {
return err
}
plan, err := runner.GetPlan(t.PlanID())
if err != nil {
return err
}
if err := runner.ExecuteHooks([]v1.Hook_Condition{
v1.Hook_CONDITION_SNAPSHOT_START,
}, hook.HookVars{}); err != nil {
var cancelErr *hook.HookErrorRequestCancel
if errors.As(err, &cancelErr) {
op.Status = v1.OperationStatus_STATUS_USER_CANCELLED // user visible cancelled status
op.DisplayMessage = err.Error()
return nil
}
return fmt.Errorf("hook failed: %w", err)
}
var sendWg sync.WaitGroup
lastSent := time.Now() // debounce progress updates, these can endup being very frequent.
var lastFiles []string
summary, err := repo.Backup(ctx, plan, func(entry *restic.BackupProgressEntry) {
sendWg.Wait()
if entry.MessageType == "status" {
// prevents flickering output when a status entry omits the CurrentFiles property. Largely cosmetic.
if len(entry.CurrentFiles) == 0 {
entry.CurrentFiles = lastFiles
} else {
lastFiles = entry.CurrentFiles
}
backupOp.OperationBackup.LastStatus = protoutil.BackupProgressEntryToProto(entry)
} else if entry.MessageType == "error" {
zap.S().Warnf("an unknown error was encountered in processing item: %v", entry.Item)
backupError, err := protoutil.BackupProgressEntryToBackupError(entry)
if err != nil {
zap.S().Errorf("failed to convert backup progress entry to backup error: %v", err)
return
}
if len(backupOp.OperationBackup.Errors) > maxBackupErrorHistoryLength ||
slices.ContainsFunc(backupOp.OperationBackup.Errors, func(i *v1.BackupProgressError) bool {
return i.Item == backupError.Item
}) {
return
}
backupOp.OperationBackup.Errors = append(backupOp.OperationBackup.Errors, backupError)
} else if entry.MessageType != "summary" {
zap.S().Warnf("unexpected message type %q in backup progress entry", entry.MessageType)
}
if time.Since(lastSent) <= 1000*time.Millisecond {
return
}
lastSent = time.Now()
sendWg.Add(1)
go func() {
if err := runner.UpdateOperation(op); err != nil {
zap.S().Errorf("failed to update oplog with progress for backup: %v", err)
}
sendWg.Done()
}()
})
sendWg.Wait()
if summary == nil {
summary = &restic.BackupProgressEntry{}
}
vars := hook.HookVars{
Task: t.Name(),
SnapshotStats: summary,
SnapshotId: summary.SnapshotId,
}
if err != nil {
vars.Error = err.Error()
if !errors.Is(err, restic.ErrPartialBackup) {
runner.ExecuteHooks([]v1.Hook_Condition{
v1.Hook_CONDITION_SNAPSHOT_ERROR,
v1.Hook_CONDITION_ANY_ERROR,
}, vars)
return err
} else {
vars.Error = fmt.Sprintf("partial backup, %d files may not have been read completely.", len(backupOp.OperationBackup.Errors))
runner.ExecuteHooks([]v1.Hook_Condition{
v1.Hook_CONDITION_SNAPSHOT_WARNING,
}, vars)
}
op.Status = v1.OperationStatus_STATUS_WARNING
op.DisplayMessage = "Partial backup, some files may not have been read completely."
}
runner.ExecuteHooks([]v1.Hook_Condition{
v1.Hook_CONDITION_SNAPSHOT_END,
}, vars)
op.SnapshotId = summary.SnapshotId
backupOp.OperationBackup.LastStatus = protoutil.BackupProgressEntryToProto(summary)
if backupOp.OperationBackup.LastStatus == nil {
return fmt.Errorf("expected a final backup progress entry, got nil")
}
l.Info("backup complete", zap.String("plan", plan.Id), zap.Duration("duration", time.Since(startTime)), zap.Any("summary", backupOp.OperationBackup.LastStatus))
// schedule followup tasks
at := time.Now()
if _, ok := plan.Retention.GetPolicy().(*v1.RetentionPolicy_PolicyKeepAll); plan.Retention != nil && !ok {
if err := runner.ScheduleTask(NewOneoffForgetTask(t.RepoID(), t.PlanID(), op.FlowId, at), TaskPriorityForget); err != nil {
return fmt.Errorf("failed to schedule forget task: %w", err)
}
}
if err := runner.ScheduleTask(NewOneoffIndexSnapshotsTask(t.RepoID(), at), TaskPriorityIndexSnapshots); err != nil {
return fmt.Errorf("failed to schedule index snapshots task: %w", err)
}
return nil
}