/
restore.go
510 lines (447 loc) · 13.5 KB
/
restore.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
package cli
import (
"context"
"fmt"
"io/ioutil"
"strconv"
"strings"
"time"
"github.com/pkg/errors"
"go.mongodb.org/mongo-driver/bson/primitive"
"gopkg.in/yaml.v2"
"github.com/percona/percona-backup-mongodb/pbm"
"github.com/percona/percona-backup-mongodb/pbm/log"
)
type restoreOpts struct {
bcp string
pitr string
pitrBase string
wait bool
ns string
rsMap string
}
type restoreRet struct {
Name string `json:"name,omitempty"`
Snapshot string `json:"snapshot,omitempty"`
PITR string `json:"point-in-time,omitempty"`
done bool
physical bool
err string
}
func (r restoreRet) HasError() bool {
return r.err != ""
}
func (r restoreRet) String() string {
switch {
case r.done:
m := "\nRestore successfully finished!\n"
if r.physical {
m += "Restart the cluster and pbm-agents, and run `pbm config --force-resync`"
}
return m
case r.err != "":
return "\n Error: " + r.err
case r.Snapshot != "":
return fmt.Sprintf("Restore of the snapshot from '%s' has started", r.Snapshot)
case r.PITR != "":
return fmt.Sprintf("Restore to the point in time '%s' has started", r.PITR)
default:
return ""
}
}
func runRestore(cn *pbm.PBM, o *restoreOpts, outf outFormat) (fmt.Stringer, error) {
nss, err := parseCLINSOption(o.ns)
if err != nil {
return nil, errors.WithMessage(err, "parse --ns option")
}
rsMap, err := parseRSNamesMapping(o.rsMap)
if err != nil {
return nil, errors.WithMessage(err, "cannot parse replset mapping")
}
if o.pitr != "" && o.bcp != "" {
return nil, errors.New("either a backup name or point in time should be set, non both together!")
}
switch {
case o.bcp != "":
m, err := restore(cn, o.bcp, nss, rsMap, outf)
if err != nil {
return nil, err
}
if !o.wait {
return restoreRet{Name: m.Name, Snapshot: o.bcp}, nil
}
typ := " logical restore.\nWaiting to finish"
if m.Type == pbm.PhysicalBackup {
typ = " physical restore.\nWaiting to finish"
}
fmt.Printf("Started%s", typ)
err = waitRestore(cn, m)
if err == nil {
return restoreRet{
done: true,
physical: m.Type == pbm.PhysicalBackup || m.Type == pbm.IncrementalBackup,
}, nil
}
if serr, ok := err.(errRestoreFailed); ok {
return restoreRet{err: serr.Error()}, nil
}
return restoreRet{err: fmt.Sprintf("%s.\n Try to check logs on node %s", err.Error(), m.Leader)}, nil
case o.pitr != "":
m, err := pitrestore(cn, o.pitr, o.pitrBase, nss, rsMap, outf)
if err != nil {
return nil, err
}
if !o.wait {
return restoreRet{PITR: o.pitr, Name: m.Name}, nil
}
fmt.Print("Started.\nWaiting to finish")
err = waitRestore(cn, m)
if err != nil {
return restoreRet{err: err.Error()}, nil
}
return restoreRet{
done: true,
PITR: o.pitr,
}, nil
default:
return nil, errors.New("undefined restore state")
}
}
func waitRestore(cn *pbm.PBM, m *pbm.RestoreMeta) error {
ep, _ := cn.GetEpoch()
l := cn.Logger().NewEvent(string(pbm.CmdRestore), m.Backup, m.OPID, ep.TS())
stg, err := cn.GetStorage(l)
if err != nil {
return errors.Wrap(err, "get storage")
}
tk := time.NewTicker(time.Second * 1)
defer tk.Stop()
var rmeta *pbm.RestoreMeta
getMeta := cn.GetRestoreMeta
if m.Type == pbm.PhysicalBackup || m.Type == pbm.IncrementalBackup {
getMeta = func(name string) (*pbm.RestoreMeta, error) {
return pbm.GetPhysRestoreMeta(name, stg, l)
}
}
for range tk.C {
fmt.Print(".")
rmeta, err = getMeta(m.Name)
if errors.Is(err, pbm.ErrNotFound) {
continue
}
if err != nil {
return errors.Wrap(err, "get restore metadata")
}
if m.Type == pbm.LogicalBackup {
clusterTime, err := cn.ClusterTime()
if err != nil {
return errors.Wrap(err, "read cluster time")
}
if rmeta.Hb.T+pbm.StaleFrameSec < clusterTime.T {
return errors.Errorf("operation staled, last heartbeat: %v", rmeta.Hb.T)
}
}
switch rmeta.Status {
case pbm.StatusDone, pbm.StatusPartlyDone:
return nil
case pbm.StatusError:
return errRestoreFailed{fmt.Sprintf("operation failed with: %s", rmeta.Error)}
}
}
return nil
}
type errRestoreFailed struct {
string
}
func (e errRestoreFailed) Error() string {
return e.string
}
func restore(cn *pbm.PBM, bcpName string, nss []string, rsMapping map[string]string, outf outFormat) (*pbm.RestoreMeta, error) {
bcp, err := cn.GetBackupMeta(bcpName)
if errors.Is(err, pbm.ErrNotFound) {
return nil, errors.Errorf("backup '%s' not found", bcpName)
}
if err != nil {
return nil, errors.Wrap(err, "get backup data")
}
if bcp.Status != pbm.StatusDone {
return nil, errors.Errorf("backup '%s' didn't finish successfully", bcpName)
}
err = checkConcurrentOp(cn)
if err != nil {
return nil, err
}
name := time.Now().UTC().Format(time.RFC3339Nano)
err = cn.SendCmd(pbm.Cmd{
Cmd: pbm.CmdRestore,
Restore: &pbm.RestoreCmd{
Name: name,
BackupName: bcpName,
Namespaces: nss,
RSMap: rsMapping,
},
})
if err != nil {
return nil, errors.Wrap(err, "send command")
}
if outf != outText {
return &pbm.RestoreMeta{
Name: name,
Backup: bcpName,
Type: bcp.Type,
}, nil
}
fmt.Printf("Starting restore %s from '%s'", name, bcpName)
var (
fn getRestoreMetaFn
ctx context.Context
cancel context.CancelFunc
)
// physical restore may take more time to start
const waitPhysRestoreStart = time.Second * 120
if bcp.Type == pbm.PhysicalBackup || bcp.Type == pbm.IncrementalBackup {
ep, _ := cn.GetEpoch()
stg, err := cn.GetStorage(cn.Logger().NewEvent(string(pbm.CmdRestore), bcpName, "", ep.TS()))
if err != nil {
return nil, errors.Wrap(err, "get storage")
}
fn = func(name string) (*pbm.RestoreMeta, error) {
return pbm.GetPhysRestoreMeta(name, stg, cn.Logger().NewEvent(string(pbm.CmdRestore), bcpName, "", ep.TS()))
}
ctx, cancel = context.WithTimeout(context.Background(), waitPhysRestoreStart)
} else {
fn = cn.GetRestoreMeta
ctx, cancel = context.WithTimeout(context.Background(), pbm.WaitActionStart)
}
defer cancel()
return waitForRestoreStatus(ctx, cn, name, fn)
}
func parseTS(t string) (ts primitive.Timestamp, err error) {
if si := strings.SplitN(t, ",", 2); len(si) == 2 {
tt, err := strconv.ParseInt(si[0], 10, 64)
if err != nil {
return ts, errors.Wrap(err, "parse clusterTime T")
}
ti, err := strconv.ParseInt(si[1], 10, 64)
if err != nil {
return ts, errors.Wrap(err, "parse clusterTime I")
}
return primitive.Timestamp{T: uint32(tt), I: uint32(ti)}, nil
}
tsto, err := parseDateT(t)
if err != nil {
return ts, errors.Wrap(err, "parse date")
}
return primitive.Timestamp{T: uint32(tsto.Unix()), I: 0}, nil
}
func pitrestore(cn *pbm.PBM, t, base string, nss []string, rsMap map[string]string, outf outFormat) (rmeta *pbm.RestoreMeta, err error) {
ts, err := parseTS(t)
if err != nil {
return nil, err
}
err = checkConcurrentOp(cn)
if err != nil {
return nil, err
}
name := time.Now().UTC().Format(time.RFC3339Nano)
err = cn.SendCmd(pbm.Cmd{
Cmd: pbm.CmdPITRestore,
PITRestore: &pbm.PITRestoreCmd{
Name: name,
TS: int64(ts.T),
I: int64(ts.I),
Bcp: base,
Namespaces: nss,
RSMap: rsMap,
},
})
if err != nil {
return nil, errors.Wrap(err, "send command")
}
if outf != outText {
return &pbm.RestoreMeta{Name: name}, nil
}
fmt.Printf("Starting restore to the point in time '%s'", t)
ctx, cancel := context.WithTimeout(context.Background(), pbm.WaitActionStart)
defer cancel()
return waitForRestoreStatus(ctx, cn, name, cn.GetRestoreMeta)
}
type getRestoreMetaFn func(name string) (*pbm.RestoreMeta, error)
func waitForRestoreStatus(ctx context.Context, cn *pbm.PBM, name string, getfn getRestoreMetaFn) (*pbm.RestoreMeta, error) {
tk := time.NewTicker(time.Second * 1)
defer tk.Stop()
var err error
meta := new(pbm.RestoreMeta)
for {
select {
case <-tk.C:
fmt.Print(".")
meta, err = getfn(name)
if errors.Is(err, pbm.ErrNotFound) {
continue
}
if err != nil {
return nil, errors.Wrap(err, "get metadata")
}
if meta == nil {
continue
}
switch meta.Status {
case pbm.StatusRunning, pbm.StatusDumpDone, pbm.StatusDone:
return meta, nil
case pbm.StatusError:
rs := ""
for _, s := range meta.Replsets {
rs += fmt.Sprintf("\n- Restore on replicaset \"%s\" in state: %v", s.Name, s.Status)
if s.Error != "" {
rs += ": " + s.Error
}
}
return nil, errors.New(meta.Error + rs)
}
case <-ctx.Done():
rs := ""
if meta != nil {
for _, s := range meta.Replsets {
rs += fmt.Sprintf("- Restore on replicaset \"%s\" in state: %v\n", s.Name, s.Status)
if s.Error != "" {
rs += ": " + s.Error
}
}
}
if rs == "" {
rs = "<no replset has started restore>\n"
}
return nil, errors.New("no confirmation that restore has successfully started. Replsets status:\n" + rs)
}
}
}
type descrRestoreOpts struct {
restore string
cfg string
}
type describeRestoreResult struct {
Name string `json:"name" yaml:"name"`
OPID string `json:"opid" yaml:"opid"`
Backup string `json:"backup" yaml:"backup"`
Type pbm.BackupType `json:"type" yaml:"type"`
Status pbm.Status `json:"status" yaml:"status"`
Error *string `json:"error,omitempty" yaml:"error,omitempty"`
Namespaces []string `json:"namespaces,omitempty" yaml:"namespaces,omitempty"`
StartTS *int64 `json:"start_ts,omitempty" yaml:"-"`
StartTime *string `json:"start,omitempty" yaml:"start,omitempty"`
PITR *int64 `json:"ts_to_restore,omitempty" yaml:"-"`
PITRTime *string `json:"time_to_restore,omitempty" yaml:"time_to_restore,omitempty"`
LastTransitionTS int64 `json:"last_transition_ts" yaml:"-"`
LastTransitionTime string `json:"last_transition_time" yaml:"last_transition_time"`
Replsets []RestoreReplset `json:"replsets" yaml:"replsets"`
}
type RestoreReplset struct {
Name string `json:"name" yaml:"name"`
Status pbm.Status `json:"status" yaml:"status"`
Error *string `json:"error,omitempty" yaml:"error,omitempty"`
LastTransitionTS int64 `json:"last_transition_ts" yaml:"-"`
LastTransitionTime string `json:"last_transition_time" yaml:"last_transition_time"`
Nodes []RestoreNode `json:"nodes,omitempty" yaml:"nodes,omitempty"`
}
type RestoreNode struct {
Name string `json:"name" yaml:"name"`
Status pbm.Status `json:"status" yaml:"status"`
Error *string `json:"error,omitempty" yaml:"error,omitempty"`
LastTransitionTS int64 `json:"last_transition_ts" yaml:"-"`
LastTransitionTime string `json:"last_transition_time" yaml:"last_transition_time"`
}
func (r describeRestoreResult) String() string {
b, err := yaml.Marshal(r)
if err != nil {
return fmt.Sprintln("error:", err)
}
return string(b)
}
func describeRestore(cn *pbm.PBM, o descrRestoreOpts) (fmt.Stringer, error) {
var res describeRestoreResult
var meta *pbm.RestoreMeta
if o.cfg != "" {
buf, err := ioutil.ReadFile(o.cfg)
if err != nil {
return nil, errors.Wrap(err, "unable to read config file")
}
var cfg pbm.Config
err = yaml.UnmarshalStrict(buf, &cfg)
if err != nil {
return nil, errors.Wrap(err, "unable to unmarshal config file")
}
l := log.New(nil, "cli", "").NewEvent("", "", "", primitive.Timestamp{})
stg, err := pbm.Storage(cfg, l)
if err != nil {
return nil, errors.Wrap(err, "get storage")
}
meta, err = pbm.GetPhysRestoreMeta(o.restore, stg, l)
if err != nil && meta == nil {
return nil, errors.Wrap(err, "get restore meta")
}
} else {
var err error
meta, err = cn.GetRestoreMeta(o.restore)
if err != nil {
return nil, errors.Wrap(err, "get restore meta")
}
}
if meta == nil {
return nil, errors.New("undefined restore meta")
}
res.Name = meta.Name
res.Backup = meta.Backup
res.Type = meta.Type
res.Status = meta.Status
res.Namespaces = meta.Namespaces
res.OPID = meta.OPID
res.LastTransitionTS = meta.LastTransitionTS
res.LastTransitionTime = time.Unix(res.LastTransitionTS, 0).UTC().Format(time.RFC3339)
if meta.Status == pbm.StatusError {
res.Error = &meta.Error
}
if meta.StartPITR != 0 {
res.StartTS = &meta.StartPITR
s := time.Unix(meta.StartPITR, 0).UTC().Format(time.RFC3339)
res.StartTime = &s
}
if meta.PITR != 0 {
res.PITR = &meta.PITR
s := time.Unix(meta.PITR, 0).UTC().Format(time.RFC3339)
res.PITRTime = &s
}
for _, rs := range meta.Replsets {
mrs := RestoreReplset{
Name: rs.Name,
Status: rs.Status,
LastTransitionTS: rs.LastTransitionTS,
LastTransitionTime: time.Unix(rs.LastTransitionTS, 0).UTC().Format(time.RFC3339),
}
if rs.Status == pbm.StatusError {
mrs.Error = &rs.Error
}
for _, node := range rs.Nodes {
mnode := RestoreNode{
Name: node.Name,
Status: node.Status,
LastTransitionTS: node.LastTransitionTS,
LastTransitionTime: time.Unix(node.LastTransitionTS, 0).UTC().Format(time.RFC3339),
}
if node.Status == pbm.StatusError {
serr := node.Error
mnode.Error = &serr
}
if rs.Status == pbm.StatusPartlyDone &&
node.Status != pbm.StatusDone &&
node.Status != pbm.StatusError {
mnode.Status = pbm.StatusError
serr := fmt.Sprintf("Node lost. Last heartbeat: %d", node.Hb.T)
mnode.Error = &serr
}
mrs.Nodes = append(mrs.Nodes, mnode)
}
res.Replsets = append(res.Replsets, mrs)
}
return res, nil
}