This repository was archived by the owner on Mar 2, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathrestore.go
368 lines (304 loc) · 8.97 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
package restic
import (
"archive/tar"
"bytes"
"compress/gzip"
"encoding/json"
"fmt"
"io"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/go-logr/logr"
"github.com/vshn/wrestic/logging"
"github.com/vshn/wrestic/s3"
)
const (
FolderRestore RestoreType = "folder"
S3Restore RestoreType = "s3"
)
// RestoreType defines the type for a restore.
type RestoreType string
// RestoreOptions holds options for a single restore, like type and destination.
type RestoreOptions struct {
RestoreType RestoreType
RestoreDir string
RestoreFilter string
Verify bool
S3Destination S3Bucket
}
type S3Bucket struct {
Endpoint string
AccessKey string
SecretKey string
}
type fileNode struct {
Name string `json:"name"`
Type string `json:"type"`
Path string `json:"path"`
UID int `json:"uid"`
GID int `json:"gid"`
Size int64 `json:"size"`
Mode int `json:"mode"`
Mtime time.Time `json:"mtime"`
Atime time.Time `json:"atime"`
Ctime time.Time `json:"ctime"`
StructType string `json:"struct_type"`
}
// Restore triggers a restore of a snapshot
func (r *Restic) Restore(snapshotID string, options RestoreOptions, tags ArrayOpts) error {
restorelogger := r.logger.WithName("restore")
restorelogger.Info("restore initialised")
if len(tags) > 0 {
restorelogger.Info("loading snapshots", "tags", tags.String)
} else {
restorelogger.Info("loading all snapshots from repositoy")
}
err := r.Snapshots(tags)
if err != nil {
return err
}
latestSnap, err := r.getLatestSnapshot(snapshotID, restorelogger)
if err != nil {
return err
}
var stats *RestoreStats
switch options.RestoreType {
case FolderRestore:
err = r.folderRestore(options.RestoreDir, latestSnap, options.RestoreFilter, options.Verify, restorelogger)
stats = &RestoreStats{
RestoreLocation: options.RestoreDir,
RestoredFiles: []string{"not supported for folder restores"},
SnapshotID: latestSnap.ID,
}
case S3Restore:
stats = &RestoreStats{}
err = r.s3Restore(restorelogger, latestSnap, stats)
default:
err = fmt.Errorf("no valid restore type")
}
if stats != nil && err == nil {
err = r.statsHandler.SendWebhook(stats)
if err != nil {
return err
}
}
return err
}
func (r *Restic) getLatestSnapshot(snapshotID string, log logr.Logger) (Snapshot, error) {
snapshot := Snapshot{}
if len(r.snapshots) == 0 {
err := fmt.Errorf("no snapshots available")
log.Error(err, "no snapshots available")
return snapshot, err
}
if snapshotID == "" {
log.Info("no snapshot defined, using latest one")
snapshot = r.snapshots[len(r.snapshots)-1]
log.Info("found snapshot", "date", snapshot.Time)
return snapshot, nil
}
for i := range r.snapshots {
// Doing substrings so we can also use short IDs here.
if strings.HasPrefix(r.snapshots[i].ID, snapshotID) {
return r.snapshots[i], nil
}
}
err := fmt.Errorf("no Snapshot found with ID %v", snapshotID)
log.Error(err, "the snapshot does not exist")
return snapshot, err
}
func (r *Restic) folderRestore(restoreDir string, snapshot Snapshot, restoreFilter string, verify bool, log logr.Logger) error {
var linkedDir string
var trim bool
trim, err := strconv.ParseBool(os.Getenv("TRIM_RESTOREPATH"))
if err != nil {
trim = true
}
if trim {
linkedDir, err = r.linkRestorePaths(snapshot, restoreDir)
if err != nil {
return err
}
defer os.RemoveAll(linkedDir)
} else {
linkedDir = restoreDir
}
args := []string{"restore", snapshot.ID, "--target", linkedDir}
if restoreFilter != "" {
args = append(args, "--include", restoreFilter)
}
if verify {
args = append(args, "--verify")
}
opts := CommandOptions{
Path: r.resticPath,
Args: args,
StdOut: logging.NewInfoWriter(log.WithName("restic")),
StdErr: logging.NewErrorWriter(log.WithName("restic")),
}
cmd := NewCommand(r.ctx, log, opts)
cmd.Run()
return nil
}
// linkRestorePaths will trim away the first two levels of the snapshotpath
// then create the first level as a folder in the temp dir and the second
// level as a symlink pointing to the mounted volume (usually /restore). It
// returns that temp path as the string used for the actual restore.This way the
// root of the backed up PVC will be the root of the restored PVC thus creating
// a carbon copy of the original and ready to be used again.
func (r *Restic) linkRestorePaths(snapshot Snapshot, restoreDir string) (string, error) {
// wrestic snapshots only every contain exactly one path
splitted := strings.Split(snapshot.Paths[0], "/")
joined := filepath.Join(splitted[:3]...)
restoreRoot := filepath.Join(os.TempDir(), "wresticRestore")
absolute := filepath.Join(restoreRoot, joined)
makePath := filepath.Dir(absolute)
err := os.MkdirAll(restoreDir, os.ModeDir+os.ModePerm)
if err != nil {
return "", err
}
err = os.MkdirAll(makePath, os.ModeDir+os.ModePerm)
if err != nil {
return "", err
}
err = os.Symlink(restoreDir, absolute)
if err != nil {
return "", err
}
return restoreRoot, nil
}
func (r *Restic) parsePath(paths []string) string {
return path.Base(paths[len(paths)-1])
}
func (r *Restic) s3Restore(log logr.Logger, snapshot Snapshot, stats *RestoreStats) error {
log.Info("S3 chosen as restore destination")
snapDate := snapshot.Time.Format(time.RFC3339)
PVCName := r.parsePath(snapshot.Paths)
fileName := fmt.Sprintf("backup-%v-%v-%v.tar.gz", snapshot.Hostname, PVCName, snapDate)
stats.RestoreLocation = fmt.Sprintf("%s/%s", os.Getenv(RestoreS3EndpointEnv), fileName)
stats.SnapshotID = snapshot.ID
s3Client := s3.New(os.Getenv(RestoreS3EndpointEnv), os.Getenv(RestoreS3AccessKeyIDEnv), os.Getenv(RestoreS3SecretAccessKey))
err := s3Client.Connect()
if err != nil {
return err
}
uploadReadPipe, uploadWritePipe := io.Pipe()
latestSnap, err := r.getLatestSnapshot(snapshot.ID, log)
if err != nil {
return err
}
snapRoot, tarHeader := r.getSnapshotRoot(latestSnap, log, stats)
zipWriter := gzip.NewWriter(uploadWritePipe)
errorChannel := r.startS3Upload(fileName, uploadReadPipe, s3Client)
finalWriter := io.WriteCloser(zipWriter)
// If it's an stdin backup we restore we'll only have to write one header
// as stdin backups only contain one vritual file.
if tarHeader != nil {
tw := tar.NewWriter(zipWriter)
err := tw.WriteHeader(tarHeader)
if err != nil {
return err
}
finalWriter = tw
defer tw.Close()
}
opts := CommandOptions{
Path: r.resticPath,
Args: []string{
"dump",
latestSnap.ID,
snapRoot,
},
StdOut: finalWriter,
StdErr: logging.NewErrorWriter(log.WithName("restic")),
}
log.Info("starting restore", "s3 filename", fileName)
cmd := NewCommand(r.ctx, log, opts)
cmd.Run()
defer log.Info("restore finished")
// We need to close the writers in a specific order
err = finalWriter.Close()
if err != nil {
return err
}
err = zipWriter.Close()
if err != nil {
return err
}
// Send EOF so minio client knows it's finished
// or else the chanel will block forever
err = uploadWritePipe.Close()
if err != nil {
return err
}
return <-errorChannel
}
func (r *Restic) startS3Upload(fileName string, uploadReadPipe io.Reader, s3Client *s3.Client) chan error {
errorChannel := make(chan error)
go func() {
errorChannel <- s3Client.Upload(s3.UploadObject{
Name: fileName,
ObjectStream: uploadReadPipe,
})
}()
return errorChannel
}
// getSnapshotRoot will return the correct root to trigger the restore. If the
// snapshot was done as a stdin backup it will also return a tar header.
func (r *Restic) getSnapshotRoot(snapshot Snapshot, log logr.Logger, stats *RestoreStats) (string, *tar.Header) {
buf := bytes.Buffer{}
opts := CommandOptions{
Path: r.resticPath,
Args: []string{
"ls",
snapshot.ID,
"--json",
},
StdOut: &buf,
}
cmd := NewCommand(r.ctx, log, opts)
cmd.Run()
// A backup from stdin will always contain exactly one file when executing ls.
// This logic will also work if it's not a stdin backup. For the sake of the
// dump this is the same case.
split := strings.Split(buf.String(), "\n")
amountOfFiles, lastNode := r.countFileNodes(split, stats)
if amountOfFiles == 1 {
return lastNode.Path, r.getTarHeaderFromFileNode(lastNode)
}
return snapshot.Paths[len(snapshot.Paths)-1], nil
}
func (r *Restic) getTarHeaderFromFileNode(file *fileNode) *tar.Header {
filePath := strings.Replace(file.Path, "/", "", 1)
return &tar.Header{
Name: filePath,
Size: file.Size,
Mode: int64(file.Mode),
Uid: file.UID,
Gid: file.GID,
ModTime: file.Mtime,
AccessTime: file.Atime,
ChangeTime: file.Ctime,
}
}
func (r *Restic) countFileNodes(rawJSON []string, stats *RestoreStats) (int, *fileNode) {
count := 0
lastNode := &fileNode{}
for _, fileJSON := range rawJSON {
node := &fileNode{}
err := json.Unmarshal([]byte(fileJSON), node)
if err != nil {
continue
}
if node.Type == "file" {
count++
lastNode = node
stats.RestoredFiles = append(stats.RestoredFiles, node.Path)
}
}
return count, lastNode
}