-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
api.go
83 lines (76 loc) · 1.93 KB
/
api.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
package backup
import (
"context"
"encoding/json"
"strings"
"beryju.io/gravity/pkg/roles/backup/types"
"github.com/swaggest/usecase"
"github.com/swaggest/usecase/status"
clientv3 "go.etcd.io/etcd/client/v3"
"go.uber.org/zap"
)
type APIBackupStartInput struct {
Wait bool `query:"wait" required:"true"`
}
func (r *Role) APIBackupStart() usecase.Interactor {
u := usecase.NewInteractor(func(ctx context.Context, input APIBackupStartInput, output *BackupStatus) error {
if input.Wait {
o := r.SaveSnapshot()
output.Duration = o.Duration
output.Error = o.Error
output.Filename = o.Filename
output.Size = o.Size
output.Status = o.Status
} else {
go r.SaveSnapshot()
output.Status = BackupStatusStarted
}
return nil
})
u.SetName("backup.start")
u.SetTitle("Backup start")
u.SetTags("roles/backup")
return u
}
type APIBackupStatus struct {
BackupStatus
Node string `json:"node"`
}
type APIBackupStatusOutput struct {
Status []APIBackupStatus `json:"status" required:"true"`
}
func (r *Role) APIBackupStatus() usecase.Interactor {
u := usecase.NewInteractor(func(ctx context.Context, input struct{}, output *APIBackupStatusOutput) error {
prefix := r.i.KV().Key(
types.KeyRole,
types.KeyStatus,
).Prefix(true).String()
rawStatus, err := r.i.KV().Get(
r.ctx,
prefix,
clientv3.WithPrefix(),
)
if err != nil {
return status.Wrap(err, status.Internal)
}
for _, rs := range rawStatus.Kvs {
var s BackupStatus
err := json.Unmarshal(rs.Value, &s)
if err != nil {
r.log.Warn("failed to unmarshal status", zap.Error(err))
continue
}
keyParts := strings.Split(strings.TrimPrefix(string(rs.Key), prefix), "/")
output.Status = append(output.Status, APIBackupStatus{
BackupStatus: s,
Node: keyParts[0],
})
}
return nil
})
u.SetName("backup.status")
u.SetTitle("Backup status")
u.SetTags("roles/backup")
u.SetExpectedErrors(status.Internal)
return u
}