-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtracker.go
More file actions
357 lines (317 loc) · 8.77 KB
/
tracker.go
File metadata and controls
357 lines (317 loc) · 8.77 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
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
// Track backups in SQLite.
package main
import (
"database/sql"
"log"
"os"
"path/filepath"
"time"
_ "github.com/ncruces/go-sqlite3/driver"
_ "github.com/ncruces/go-sqlite3/embed"
)
type Status int
const (
// A backup is saved locally, waiting to be uploaded.
Saved Status = iota
// A backup is already uploaded to remote storage.
Uploaded
// A backup is already uploaded and old local backup file is deleted.
Archived
)
type DatabaseTrack struct {
// The primary key ID.
ID int
// The backup time, saved in ISO 8601 format.
BackupTime time.Time
// The status of this backup.
Status Status
// The type of this backup, full or incremental.
Type string
// Optional comment.
Comment string
// Relative backup path.
Path string
}
func (track DatabaseTrack) IsFullBackup() bool {
return track.Type == "full"
}
func (track DatabaseTrack) IsIncrementalBackup() bool {
return track.Type == "incremental"
}
func (track DatabaseTrack) GetBackupPath() string {
return FormatBackupLocalPath(track.GetRelativeBackupPath())
}
func (track DatabaseTrack) GetRelativeBackupPath() string {
if track.Path != "" {
return NormalizeBackupRelativePath(track.Path)
}
if track.IsFullBackup() {
return FormatBackupRelativePath(track.BackupTime, false)
}
return FormatBackupRelativePath(track.BackupTime, true)
}
type Tracker struct {
*sql.DB
}
var tracker *Tracker
func InitializeTracker() {
db, err := sql.Open("sqlite3", sqliteDBPath)
if err != nil {
log.Fatalln(err)
}
tracker = &Tracker{db}
err = initializeTrackingDB(tracker)
if err != nil {
log.Fatalln(err)
}
}
// Initialize the tracking database.
func initializeTrackingDB(db *Tracker) error {
_, err := db.Exec(`
CREATE TABLE IF NOT EXISTS backups (
id INTEGER PRIMARY KEY AUTOINCREMENT,
backup_time TEXT NOT NULL,
status INTEGER NOT NULL,
type TEXT NOT NULL,
comment TEXT,
backup_path TEXT NOT NULL DEFAULT ''
);
`)
if err != nil {
return err
}
err = ensureBackupPathColumn(db)
if err != nil {
return err
}
return migrateBackupPaths(db)
}
func (t *Tracker) Close() error {
return t.DB.Close()
}
// Track a new backup in the database.
func (t *Tracker) TrackBackup(track DatabaseTrack) error {
_, err := t.Exec(
"INSERT INTO backups (backup_time, status, type, comment, backup_path) VALUES (?, ?, ?, ?, ?)",
track.BackupTime.Format(time.RFC3339),
track.Status,
track.Type,
track.Comment,
track.GetRelativeBackupPath(),
)
return err
}
// Update the status of a backup.
func (t *Tracker) UpdateBackupStatus(backupTime time.Time, status Status) error {
_, err := t.Exec("UPDATE backups SET status = ? WHERE backup_time = ?", status, backupTime.Format(time.RFC3339))
return err
}
// Get the last backup time.
func (t *Tracker) GetLastBackup() (DatabaseTrack, error) {
var track DatabaseTrack
var backupTimeStr string
err := t.QueryRow("SELECT id, backup_time, status, type, comment, backup_path FROM backups ORDER BY backup_time DESC LIMIT 1").Scan(&track.ID, &backupTimeStr, &track.Status, &track.Type, &track.Comment, &track.Path)
if err != nil {
return DatabaseTrack{}, err
}
track.BackupTime, err = time.Parse(time.RFC3339, backupTimeStr)
if err != nil {
return DatabaseTrack{}, err
}
return track, nil
}
// Get old full backups that exceed the local backup count and not uploaded.
func (t *Tracker) GetOldBackups() ([]DatabaseTrack, error) {
rows, err := t.Query("SELECT id, backup_time, status, type, comment, backup_path FROM backups WHERE type = 'full' AND status = 0 ORDER BY backup_time ASC")
if err != nil {
return nil, err
}
defer rows.Close()
var backups []DatabaseTrack
var allBackups []DatabaseTrack
for rows.Next() {
var bt DatabaseTrack
var backupTimeStr string
err := rows.Scan(&bt.ID, &backupTimeStr, &bt.Status, &bt.Type, &bt.Comment, &bt.Path)
if err != nil {
return nil, err
}
bt.BackupTime, err = time.Parse(time.RFC3339, backupTimeStr)
if err != nil {
return nil, err
}
allBackups = append(allBackups, bt)
}
if len(allBackups) <= config.LocalBackupCount {
return []DatabaseTrack{}, nil
}
backups = allBackups[:len(allBackups)-config.LocalBackupCount]
return backups, nil
}
// Get incremental backups associated with a full backup.
func (t *Tracker) GetIncrementalTracks(parentTrack DatabaseTrack) ([]DatabaseTrack, error) {
var nextParentTimeStr string
err := t.QueryRow("SELECT backup_time FROM backups WHERE type = 'full' AND backup_time > ? ORDER BY backup_time ASC LIMIT 1", parentTrack.BackupTime.Format(time.RFC3339)).Scan(&nextParentTimeStr)
if err != nil && err != sql.ErrNoRows {
return nil, err
}
if nextParentTimeStr == "" {
nextParentTimeStr = time.Now().Format(time.RFC3339)
}
rows, err := t.Query("SELECT id, backup_time, status, type, comment, backup_path FROM backups WHERE type = 'incremental' AND backup_time > ? AND backup_time < ? ORDER BY backup_time ASC", parentTrack.BackupTime.Format(time.RFC3339), nextParentTimeStr)
if err != nil {
return nil, err
}
defer rows.Close()
var incTracks []DatabaseTrack
for rows.Next() {
var bt DatabaseTrack
var backupTimeStr string
err := rows.Scan(&bt.ID, &backupTimeStr, &bt.Status, &bt.Type, &bt.Comment, &bt.Path)
if err != nil {
return nil, err
}
bt.BackupTime, err = time.Parse(time.RFC3339, backupTimeStr)
if err != nil {
return nil, err
}
incTracks = append(incTracks, bt)
}
return incTracks, nil
}
// Get backups that are not yet uploaded.
func (t *Tracker) GetPendingUploads() ([]DatabaseTrack, error) {
rows, err := t.Query("SELECT id, backup_time, status, type, comment, backup_path FROM backups WHERE status = 0 ORDER BY backup_time ASC")
if err != nil {
return nil, err
}
defer rows.Close()
var backups []DatabaseTrack
for rows.Next() {
var bt DatabaseTrack
var backupTimeStr string
err := rows.Scan(&bt.ID, &backupTimeStr, &bt.Status, &bt.Type, &bt.Comment, &bt.Path)
if err != nil {
return nil, err
}
bt.BackupTime, err = time.Parse(time.RFC3339, backupTimeStr)
if err != nil {
return nil, err
}
backups = append(backups, bt)
}
return backups, nil
}
func ensureBackupPathColumn(db *Tracker) error {
rows, err := db.Query("PRAGMA table_info(backups)")
if err != nil {
return err
}
defer rows.Close()
hasBackupPath := false
for rows.Next() {
var cid int
var name string
var columnType string
var notNull int
var defaultValue sql.NullString
var pk int
err = rows.Scan(&cid, &name, &columnType, ¬Null, &defaultValue, &pk)
if err != nil {
return err
}
if name == "backup_path" {
hasBackupPath = true
break
}
}
if hasBackupPath {
return nil
}
_, err = db.Exec("ALTER TABLE backups ADD COLUMN backup_path TEXT NOT NULL DEFAULT ''")
return err
}
func migrateBackupPaths(db *Tracker) error {
rows, err := db.Query("SELECT id, backup_time, type, backup_path FROM backups ORDER BY backup_time ASC")
if err != nil {
return err
}
defer rows.Close()
type backupMigration struct {
id int
time time.Time
typ string
path string
}
var migrations []backupMigration
for rows.Next() {
var migration backupMigration
var backupTimeStr string
err = rows.Scan(&migration.id, &backupTimeStr, &migration.typ, &migration.path)
if err != nil {
return err
}
migration.time, err = time.Parse(time.RFC3339, backupTimeStr)
if err != nil {
return err
}
migrations = append(migrations, migration)
}
for _, migration := range migrations {
isIncremental := migration.typ == "incremental"
newRelativePath := FormatBackupRelativePath(migration.time, isIncremental)
currentRelativePath := NormalizeBackupRelativePath(migration.path)
moveCandidates := []string{
currentRelativePath,
FormatLegacyBackupRelativePath(migration.time, isIncremental),
}
for _, oldRelativePath := range moveCandidates {
if oldRelativePath == "" || oldRelativePath == newRelativePath {
continue
}
oldPath := FormatBackupLocalPath(oldRelativePath)
newPath := FormatBackupLocalPath(newRelativePath)
err = moveLocalBackupIfExists(oldPath, newPath)
if err != nil {
return err
}
}
if currentRelativePath != newRelativePath {
_, err = db.Exec("UPDATE backups SET backup_path = ? WHERE id = ?", newRelativePath, migration.id)
if err != nil {
return err
}
}
}
return nil
}
func moveLocalBackupIfExists(oldPath string, newPath string) error {
if oldPath == newPath {
return nil
}
_, err := os.Stat(oldPath)
if err != nil {
if os.IsNotExist(err) {
return nil
}
return err
}
_, err = os.Stat(newPath)
if err == nil {
log.Printf("Skip moving local backup because target already exists: %s", newPath)
return nil
}
if !os.IsNotExist(err) {
return err
}
err = os.MkdirAll(filepath.Dir(newPath), 0755)
if err != nil {
return err
}
err = os.Rename(oldPath, newPath)
if err != nil {
return err
}
log.Printf("Moved local backup from %s to %s", oldPath, newPath)
return nil
}