-
Notifications
You must be signed in to change notification settings - Fork 0
/
snapshot.go
79 lines (68 loc) · 1.92 KB
/
snapshot.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
package duckron
import (
"fmt"
"log"
"os"
"time"
)
var (
// ErrConnectionFailed, failed to connect database
ErrConnectionFailed = newError("connection", "failed to connect database")
// ErrFolderCreationFailed, failed to create folder
ErrFolderCreationFailed = newError("folder", "failed to create folder")
// ErrSnapshotFailed, failed to take snapshot
ErrSnapshotFailed = newError("snapshot", "failed to take snapshot")
)
type snapshotManager struct {
client DatabaseConnection
options *snapshotOptions
timer *Timer
}
type snapshotOptions struct {
interval time.Duration
format string
destination string
}
func NewSnapshotManager(client DatabaseConnection, options *snapshotOptions) (*snapshotManager, *Error) {
if options == nil {
options = &snapshotOptions{
interval: 60,
format: "parquet",
destination: "./snapshots",
}
}
if err := client.Ping(); err != nil {
return nil, ErrConnectionFailed.wrap(err)
}
timer := NewTimer(options.interval)
return &snapshotManager{client: client, options: options, timer: timer}, nil
}
func (sm *snapshotManager) take(errChan chan *Error) *Error {
if err := createDirectoryIfNotExists(sm.options.destination); err != nil {
return ErrFolderCreationFailed.wrap(err)
}
go func(errChan chan *Error) {
sm.timer.Start(
func() *Error {
log.Println("Taking snapshot")
dest := buildSnapshotDestinationPath(sm.options.destination)
if err := sm.client.Snapshot(sm.options.format, dest); err != nil {
errChan <- ErrSnapshotFailed.wrap(err)
return ErrSnapshotFailed.wrap(err)
}
return nil
},
)
}(errChan)
return nil
}
func createDirectoryIfNotExists(path string) error {
if _, err := os.Stat(path); os.IsNotExist(err) {
return os.MkdirAll(path, os.ModePerm)
}
return nil
}
func buildSnapshotDestinationPath(destination string) string {
timestamp := time.Now().Unix()
return fmt.Sprintf("%s/%d", destination, timestamp)
}