-
Notifications
You must be signed in to change notification settings - Fork 42
/
main.go
103 lines (92 loc) · 2.56 KB
/
main.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
package main
import (
"bytes"
"log"
"os"
"os/signal"
"syscall"
"time"
"github.com/Lucretius/vault_raft_snapshot_agent/config"
"github.com/Lucretius/vault_raft_snapshot_agent/snapshot_agent"
)
func listenForInterruptSignals() chan bool {
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
done := make(chan bool, 1)
go func() {
_ = <-sigs
done <- true
}()
return done
}
func main() {
done := listenForInterruptSignals()
log.Println("Reading configuration...")
c, err := config.ReadConfig()
if err != nil {
log.Fatalln("Configuration could not be found")
}
snapshotter, err := snapshot_agent.NewSnapshotter(c)
if err != nil {
log.Fatalln("Cannot instantiate snapshotter.", err)
}
frequency, err := time.ParseDuration(c.Frequency)
if err != nil {
frequency = time.Hour
}
for {
if snapshotter.TokenExpiration.Before(time.Now()) {
switch c.VaultAuthMethod {
case "k8s":
snapshotter.SetClientTokenFromK8sAuth(c)
default:
snapshotter.SetClientTokenFromAppRole(c)
}
}
leader, err := snapshotter.API.Sys().Leader()
if err != nil {
log.Println(err.Error())
log.Fatalln("Unable to determine leader instance. The snapshot agent will only run on the leader node. Are you running this daemon on a Vault instance?")
}
leaderIsSelf := leader.IsSelf
if !leaderIsSelf {
log.Println("Not running on leader node, skipping.")
} else {
var snapshot bytes.Buffer
err := snapshotter.API.Sys().RaftSnapshot(&snapshot)
if err != nil {
log.Fatalln("Unable to generate snapshot", err.Error())
}
now := time.Now().UnixNano()
if c.Local.Path != "" {
snapshotPath, err := snapshotter.CreateLocalSnapshot(&snapshot, c, now)
logSnapshotError("local", snapshotPath, err)
}
if c.AWS.Bucket != "" {
snapshotPath, err := snapshotter.CreateS3Snapshot(&snapshot, c, now)
logSnapshotError("aws", snapshotPath, err)
}
if c.GCP.Bucket != "" {
snapshotPath, err := snapshotter.CreateGCPSnapshot(&snapshot, c, now)
logSnapshotError("gcp", snapshotPath, err)
}
if c.Azure.ContainerName != "" {
snapshotPath, err := snapshotter.CreateAzureSnapshot(&snapshot, c, now)
logSnapshotError("azure", snapshotPath, err)
}
}
select {
case <-time.After(frequency):
continue
case <-done:
os.Exit(1)
}
}
}
func logSnapshotError(dest, snapshotPath string, err error) {
if err != nil {
log.Printf("Failed to generate %s snapshot to %s: %v\n", dest, snapshotPath, err)
} else {
log.Printf("Successfully created %s snapshot to %s\n", dest, snapshotPath)
}
}