-
Notifications
You must be signed in to change notification settings - Fork 29
/
config.go
354 lines (308 loc) · 9.57 KB
/
config.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
package backupstore
import (
"bytes"
"context"
"encoding/json"
"fmt"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/gammazero/workerpool"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/slok/goresilience/timeout"
. "github.com/longhorn/backupstore/logging"
"github.com/longhorn/backupstore/types"
"github.com/longhorn/backupstore/util"
)
const (
VOLUME_SEPARATE_LAYER1 = 2
VOLUME_SEPARATE_LAYER2 = 4
VOLUME_DIRECTORY = "volumes"
VOLUME_CONFIG_FILE = "volume.cfg"
BACKUP_DIRECTORY = "backups"
BACKUP_CONFIG_PREFIX = "backup_"
CFG_SUFFIX = ".cfg"
taskTimeout = 90 * time.Second
)
func getBackupConfigName(id string) string {
return BACKUP_CONFIG_PREFIX + id + CFG_SUFFIX
}
func LoadConfigInBackupStore(driver BackupStoreDriver, filePath string, v interface{}) error {
if !driver.FileExists(filePath) {
return fmt.Errorf("cannot find %v in backupstore", filePath)
}
rc, err := driver.Read(filePath)
if err != nil {
return err
}
defer rc.Close()
log.WithFields(logrus.Fields{
LogFieldReason: LogReasonStart,
LogFieldObject: LogObjectConfig,
LogFieldKind: driver.Kind(),
LogFieldFilepath: filePath,
}).Info("Loading config in backupstore")
if err := json.NewDecoder(rc).Decode(v); err != nil {
return err
}
log.WithFields(logrus.Fields{
LogFieldReason: LogReasonComplete,
LogFieldObject: LogObjectConfig,
LogFieldKind: driver.Kind(),
LogFieldFilepath: filePath,
}).Info("Loaded config in backupstore")
return nil
}
func SaveConfigInBackupStore(driver BackupStoreDriver, filePath string, v interface{}) error {
j, err := json.Marshal(v)
if err != nil {
return err
}
log.WithFields(logrus.Fields{
LogFieldReason: LogReasonStart,
LogFieldObject: LogObjectConfig,
LogFieldKind: driver.Kind(),
LogFieldFilepath: filePath,
}).Info("Saving config in backupstore")
if err := driver.Write(filePath, bytes.NewReader(j)); err != nil {
return err
}
log.WithFields(logrus.Fields{
LogFieldReason: LogReasonComplete,
LogFieldObject: LogObjectConfig,
LogFieldKind: driver.Kind(),
LogFieldFilepath: filePath,
}).Info("Saved config in backupstore")
return nil
}
func SaveLocalFileToBackupStore(localFilePath, backupStoreFilePath string, driver BackupStoreDriver) error {
log := log.WithFields(logrus.Fields{
LogFieldReason: LogReasonStart,
LogFieldObject: LogObjectConfig,
LogFieldKind: driver.Kind(),
LogFieldFilepath: localFilePath,
LogFieldDestURL: backupStoreFilePath,
})
log.Debug()
if driver.FileExists(backupStoreFilePath) {
return fmt.Errorf("%v already exists", backupStoreFilePath)
}
if err := driver.Upload(localFilePath, backupStoreFilePath); err != nil {
return err
}
log.WithField(LogFieldReason, LogReasonComplete).Debug()
return nil
}
func SaveBackupStoreToLocalFile(driver BackupStoreDriver, backupStoreFileURL, localFilePath string) error {
log := log.WithFields(logrus.Fields{
LogFieldReason: LogReasonStart,
LogFieldObject: LogObjectConfig,
LogFieldKind: driver.Kind(),
LogFieldFilepath: localFilePath,
LogFieldSourceURL: backupStoreFileURL,
})
log.Debug()
if err := driver.Download(backupStoreFileURL, localFilePath); err != nil {
return err
}
log = log.WithFields(logrus.Fields{
LogFieldReason: LogReasonComplete,
})
log.Debug()
return nil
}
func volumeExists(driver BackupStoreDriver, volumeName string) bool {
return driver.FileExists(getVolumeFilePath(volumeName))
}
// volumeFolderExists checks if volume folder exists on backupstore
// by listing all the backup volume name based on the folders on the backupstore
// since s3 does not support checking folder exist.
func volumeFolderExists(driver BackupStoreDriver, volumeName string) (bool, error) {
jobQueues := workerpool.New(runtime.NumCPU() * 16)
defer jobQueues.StopWait()
volumeNames, err := getVolumeNames(jobQueues, driver)
if err != nil {
return false, err
}
for _, name := range volumeNames {
if volumeName == name {
return true, nil
}
}
return false, nil
}
func getVolumePath(volumeName string) string {
checksum := util.GetChecksum([]byte(volumeName))
volumeLayer1 := checksum[0:VOLUME_SEPARATE_LAYER1]
volumeLayer2 := checksum[VOLUME_SEPARATE_LAYER1:VOLUME_SEPARATE_LAYER2]
return filepath.Join(backupstoreBase, VOLUME_DIRECTORY, volumeLayer1, volumeLayer2, volumeName) + "/"
}
func getVolumeFilePath(volumeName string) string {
volumePath := getVolumePath(volumeName)
volumeCfg := VOLUME_CONFIG_FILE
return filepath.Join(volumePath, volumeCfg)
}
// getVolumeNames returns all volume names based on the folders on the backupstore
func getVolumeNames(jobQueues *workerpool.WorkerPool, driver BackupStoreDriver) ([]string, error) {
names := []string{}
volumePathBase := filepath.Join(backupstoreBase, VOLUME_DIRECTORY)
lv1Dirs, err := driver.List(volumePathBase)
if err != nil {
log.WithError(err).Warnf("Failed to list first level dirs for path %v", volumePathBase)
return names, err
}
var errs []string
lv1Trackers := make(chan types.JobResult)
lv2Trackers := make(chan types.JobResult)
defer close(lv1Trackers)
defer close(lv2Trackers)
runner := timeout.New(timeout.Config{
Timeout: taskTimeout,
})
for _, lv1Dir := range lv1Dirs {
path := filepath.Join(volumePathBase, lv1Dir)
jobQueues.Submit(func() {
lv2Paths := make([]string, 0)
err := runner.Run(context.TODO(), func(_ context.Context) error {
lv2Dirs, err := driver.List(path)
if err != nil {
logrus.WithError(err).Warnf("Failed to list second level dirs for path %v", path)
return errors.Wrapf(err, "failed to list second level dirs for path %v", path)
}
for _, lv2Dir := range lv2Dirs {
lv2Paths = append(lv2Paths, filepath.Join(path, lv2Dir))
}
return nil
})
if err != nil {
lv1Trackers <- types.JobResult{
Payload: nil,
Err: err,
}
return
}
lv1Trackers <- types.JobResult{
Payload: lv2Paths,
Err: nil,
}
})
}
lv2PathsNum := 0
for i := 0; i < len(lv1Dirs); i++ {
lv1Tracker := <-lv1Trackers
payload, err := lv1Tracker.Payload, lv1Tracker.Err
if err != nil {
errs = append(errs, err.Error())
continue
}
lv2Paths := payload.([]string)
lv2PathsNum += len(lv2Paths)
for _, lv2Path := range lv2Paths {
path := lv2Path
jobQueues.Submit(func() {
var volumeNames []string
err := runner.Run(context.TODO(), func(_ context.Context) error {
volumeNames, err = driver.List(path)
if err != nil {
logrus.WithError(err).Warnf("Failed to list volume names for path %v", path)
return errors.Wrapf(err, "failed to list second level dirs for path %v", path)
}
return nil
})
if err != nil {
lv2Trackers <- types.JobResult{
Payload: nil,
Err: err,
}
return
}
lv2Trackers <- types.JobResult{
Payload: volumeNames,
Err: nil,
}
})
}
}
for i := 0; i < lv2PathsNum; i++ {
lv2Tracker := <-lv2Trackers
payload, err := lv2Tracker.Payload, lv2Tracker.Err
if err != nil {
errs = append(errs, err.Error())
continue
}
volumeNames := payload.([]string)
names = append(names, volumeNames...)
}
if len(errs) > 0 {
return names, errors.New(strings.Join(errs, "\n"))
}
return names, nil
}
func loadVolume(driver BackupStoreDriver, volumeName string) (*Volume, error) {
v := &Volume{}
file := getVolumeFilePath(volumeName)
if err := LoadConfigInBackupStore(driver, file, v); err != nil {
return nil, err
}
// Backward compatibility
if v.CompressionMethod == "" {
log.Infof("Falling back compression method to %v for volume %v", LEGACY_COMPRESSION_METHOD, v.Name)
v.CompressionMethod = LEGACY_COMPRESSION_METHOD
}
if v.DataEngine == "" {
v.DataEngine = string(DataEngineV1)
}
return v, nil
}
func saveVolume(driver BackupStoreDriver, v *Volume) error {
return SaveConfigInBackupStore(driver, getVolumeFilePath(v.Name), v)
}
func getBackupNamesForVolume(driver BackupStoreDriver, volumeName string) ([]string, error) {
result := []string{}
fileList, err := driver.List(getBackupPath(volumeName))
if err != nil {
// path doesn't exist
return result, nil
}
return util.ExtractNames(fileList, BACKUP_CONFIG_PREFIX, CFG_SUFFIX), nil
}
func getBackupPath(volumeName string) string {
return filepath.Join(getVolumePath(volumeName), BACKUP_DIRECTORY) + "/"
}
func getBackupConfigPath(backupName, volumeName string) string {
path := getBackupPath(volumeName)
fileName := getBackupConfigName(backupName)
return filepath.Join(path, fileName)
}
func isBackupInProgress(backup *Backup) bool {
return backup != nil && backup.CreatedTime == ""
}
func loadBackup(bsDriver BackupStoreDriver, backupName, volumeName string) (*Backup, error) {
backup := &Backup{}
if err := LoadConfigInBackupStore(bsDriver, getBackupConfigPath(backupName, volumeName), backup); err != nil {
return nil, err
}
// Backward compatibility
if backup.CompressionMethod == "" {
log.Infof("Fall back compression method to %v for backup %v", LEGACY_COMPRESSION_METHOD, backup.Name)
backup.CompressionMethod = LEGACY_COMPRESSION_METHOD
}
return backup, nil
}
func saveBackup(bsDriver BackupStoreDriver, backup *Backup) error {
if backup.VolumeName == "" {
return fmt.Errorf("missing volume specifier for backup: %v", backup.Name)
}
filePath := getBackupConfigPath(backup.Name, backup.VolumeName)
return SaveConfigInBackupStore(bsDriver, filePath, backup)
}
func removeBackup(backup *Backup, bsDriver BackupStoreDriver) error {
filePath := getBackupConfigPath(backup.Name, backup.VolumeName)
if err := bsDriver.Remove(filePath); err != nil {
return err
}
log.Infof("Removed %v on backupstore", filePath)
return nil
}