-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathbackup.go
More file actions
302 lines (261 loc) Β· 7.8 KB
/
Copy pathbackup.go
File metadata and controls
302 lines (261 loc) Β· 7.8 KB
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
package main
import (
"context"
"flag"
"fmt"
"io"
"log"
"os"
"strings"
"time"
"github.com/barrydeen/haven/internal/cloud"
)
func runBackup(ctx context.Context) {
backupCmd := flag.NewFlagSet("backup", flag.ExitOnError)
relay := backupCmd.String("relay", "", "Relay name (use then the file parameter ends in jsonl)")
relayShort := backupCmd.String("r", "", "Relay name (shorthand)")
output := backupCmd.String("output", "", "Output file (shorthand)")
outputShort := backupCmd.String("o", "", "Output file (shorthand)")
toCloud := backupCmd.Bool("to-cloud", false, "Upload backup to cloud storage")
args := os.Args[2:]
var flags []string
var positionals []string
for i := 0; i < len(args); i++ {
arg := args[i]
if strings.HasPrefix(arg, "-") {
flags = append(flags, arg)
// Check if it's a flag that takes a value
// In our case, all flags (relay, r, output, o) take values, but to-cloud does not.
if arg == "--to-cloud" {
continue
}
if !strings.Contains(arg, "=") && i+1 < len(args) && !strings.HasPrefix(args[i+1], "-") {
flags = append(flags, args[i+1])
i++
}
} else {
positionals = append(positionals, arg)
}
}
err := backupCmd.Parse(append(flags, positionals...))
if err != nil {
log.Fatal("π« failed to parse backup command:", err)
return
}
targetRelay := *relay
if targetRelay == "" {
targetRelay = *relayShort
}
parsedArgs := backupCmd.Args()
fileName := "haven_backup.zip"
if len(parsedArgs) > 0 {
fileName = parsedArgs[0]
}
targetOutput := *output
if targetOutput == "" {
targetOutput = *outputShort
}
if targetOutput != "" {
fileName = targetOutput
}
initDBs()
if strings.HasSuffix(fileName, ".jsonl") {
if targetRelay == "" {
log.Fatal("π« --relay parameter is required when exporting to .jsonl")
}
if err := exportToJSONL(ctx, targetRelay, fileName); err != nil {
log.Fatal("π« export failed:", err)
}
} else {
if err := exportToZip(ctx, fileName); err != nil {
log.Fatal("π« backup failed:", err)
}
}
if *toCloud {
cloudProvider, err := getCloudProvider()
if err != nil {
log.Fatal("π« ", err)
}
if err := uploadBackupToCloud(ctx, cloudProvider, fileName); err != nil {
log.Fatal("π« ", err)
}
}
}
func runRestore(ctx context.Context) {
restoreCmd := flag.NewFlagSet("restore", flag.ExitOnError)
relay := restoreCmd.String("relay", "", "Relay name (use then the file parameter ends in jsonl)")
relayShort := restoreCmd.String("r", "", "Relay name (shorthand)")
input := restoreCmd.String("input", "", "Input file (shorthand)")
inputShort := restoreCmd.String("i", "", "Input file (shorthand)")
fromCloud := restoreCmd.Bool("from-cloud", false, "Download backup from cloud storage")
args := os.Args[2:]
var flags []string
var positionals []string
for i := 0; i < len(args); i++ {
arg := args[i]
if strings.HasPrefix(arg, "-") {
flags = append(flags, arg)
if arg == "--from-cloud" {
continue
}
if !strings.Contains(arg, "=") && i+1 < len(args) && !strings.HasPrefix(args[i+1], "-") {
flags = append(flags, args[i+1])
i++
}
} else {
positionals = append(positionals, arg)
}
}
err := restoreCmd.Parse(append(flags, positionals...))
if err != nil {
log.Fatal("π« failed to parse restore command:", err)
return
}
targetRelay := *relay
if targetRelay == "" {
targetRelay = *relayShort
}
parsedArgs := restoreCmd.Args()
fileName := "haven_backup.zip"
if len(parsedArgs) > 0 {
fileName = parsedArgs[0]
}
targetInput := *input
if targetInput == "" {
targetInput = *inputShort
}
if targetInput != "" {
fileName = targetInput
}
if *fromCloud {
cloudProvider, err := getCloudProvider()
if err != nil {
log.Fatal("π« ", err)
}
if err := downloadBackupFromCloud(ctx, cloudProvider, fileName); err != nil {
log.Fatal("π« ", err)
}
}
initDBs()
if strings.HasSuffix(fileName, ".jsonl") {
if targetRelay == "" {
log.Fatal("π« --relay parameter is required when restoring from .jsonl")
}
if err := importFromJSONL(ctx, targetRelay, fileName); err != nil {
log.Fatal("π« restore failed:", err)
}
} else {
if err := importFromZip(ctx, fileName); err != nil {
log.Fatal("π« restore failed:", err)
}
}
}
// startPeriodicCloudBackups periodically backs up the database to a cloud provider.
// Supported providers are S3, AWS (deprecated), and GCP (deprecated).
// The backup interval is defined by the BACKUP_INTERVAL_HOURS environment variable.
// For more details on configuration, see docs/backup.md#periodic-cloud-backups.
func startPeriodicCloudBackups(ctx context.Context) {
cloudProvider, err := getCloudProvider()
if err != nil {
log.Printf("β οΈ Cloud backup disabled: %v", err)
return
}
ticker := time.NewTicker(time.Duration(config.BackupIntervalHours) * time.Hour)
defer ticker.Stop()
zipFileName := "haven_backup.zip"
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
log.Println("β° starting periodic backup...")
if err := exportToZip(ctx, zipFileName); err != nil {
log.Println("π« error exporting to zip:", err)
continue
}
if err := uploadBackupToCloud(ctx, cloudProvider, zipFileName); err != nil {
log.Println("π« error uploading to cloud:", err)
continue
}
// delete the file
err = os.Remove(zipFileName)
if err != nil {
log.Println("π« error deleting local backup file:", err)
}
}
}
}
func getCloudProvider() (cloud.Provider, error) {
if config.BackupProvider == "none" || config.BackupProvider == "" {
return nil, fmt.Errorf("no backup provider set")
} else if config.BackupProvider != "s3" {
return nil, fmt.Errorf("backup provider %q not supported", config.BackupProvider)
}
cloudProvider, err := cloud.NewGenericS3Provider(
config.S3Config.Endpoint,
config.S3Config.AccessKeyID,
config.S3Config.SecretKey,
config.S3Config.Region,
)
if err != nil {
return nil, err
}
return cloudProvider, nil
}
func downloadBackupFromCloud(ctx context.Context, downloader cloud.Downloader, fileName string) error {
log.Printf("π₯ downloading %q from S3 Bucket...\n", fileName)
reader, err := downloader.Download(ctx, config.S3Config.BucketName, fileName)
if err != nil {
return fmt.Errorf("failed to download %s from %s: %w", fileName, config.S3Config.BucketName, err)
}
defer func() {
if err := reader.Close(); err != nil {
log.Println("π« error closing cloud reader:", err)
}
}()
file, err := os.Create(fileName)
if err != nil {
return fmt.Errorf("failed to create local file %s: %w", fileName, err)
}
defer func() {
if err := file.Close(); err != nil {
log.Println("π« error closing local file:", err)
}
}()
_, err = io.Copy(file, reader)
if err != nil {
return fmt.Errorf("failed to save %s: %w", fileName, err)
}
log.Printf("β
Successfully downloaded %q from %q\n", fileName, config.S3Config.BucketName)
return nil
}
func uploadBackupToCloud(ctx context.Context, uploader cloud.Uploader, fileName string) error {
log.Println("π uploading backup to S3 Bucket...")
file, err := os.Open(fileName)
if err != nil {
return err
}
defer func() {
if err := file.Close(); err != nil {
log.Println("π« error closing db zip file:", err)
}
}()
fileInfo, err := file.Stat()
if err != nil {
return fmt.Errorf("failed to load %s: %w", fileName, err)
}
err = uploader.Upload(ctx, config.S3Config.BucketName, fileName, file, fileInfo.Size(), getBackupContentType(fileName))
if err != nil {
return fmt.Errorf("failed to upload %s to %s: %w", fileName, config.S3Config.BucketName, err)
}
log.Printf("β
Successfully uploaded %q to %q\n", fileName, config.S3Config.BucketName)
return nil
}
func getBackupContentType(fileNane string) string {
if strings.HasSuffix(fileNane, ".zip") {
return "application/zip"
} else if strings.HasSuffix(fileNane, ".jsonl") {
return "application/jsonl"
}
return ""
}