forked from Lucretius/vault_raft_snapshot_agent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
223 lines (175 loc) · 5.17 KB
/
main.go
File metadata and controls
223 lines (175 loc) · 5.17 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
package main
import (
"context"
"fmt"
"io"
"log/slog"
"os"
"os/signal"
"syscall"
"time"
"github.com/Boostport/vault_raft_snapshot_agent/config"
"github.com/Boostport/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 listenForReload() chan os.Signal {
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGHUP)
return sig
}
func main() {
done := listenForInterruptSignals()
reload := listenForReload()
var (
snapshotter *snapshot_agent.Snapshotter
c *config.Configuration
configuredFrequency time.Duration
snapshotTimeout time.Duration
reloadedTimeout *time.Duration
)
slog.Info("Reading configuration...")
snapshotter, c, configuredFrequency, snapshotTimeout = loadConfig()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var lastSuccessfulUploads snapshot_agent.LastUpload
for {
frequency := configuredFrequency
if snapshotter.TokenExpiration.Before(time.Now()) {
switch c.VaultAuthMethod {
case "k8s":
err := snapshotter.SetClientTokenFromK8sAuth(c)
if err != nil {
slog.Error(fmt.Sprintf("Unable to get token from k8s auth: %s", err))
os.Exit(1)
}
case "token":
// Do nothing as vault agent will auto-renew the token
default:
err := snapshotter.SetClientTokenFromAppRole(c)
if err != nil {
slog.Error(fmt.Sprintf("Unable to get token from approle: %s", err))
os.Exit(1)
}
}
}
leader, err := snapshotter.API.Sys().Leader()
if err != nil {
slog.Error(err.Error())
slog.Error("Unable to determine leader instance. The snapshot agent will only run on the leader node. Are you running this daemon on a Vault instance?")
os.Exit(1)
}
leaderIsSelf := leader.IsSelf
if !leaderIsSelf {
slog.Info("Not running on leader node, skipping.")
} else {
if lastSuccessfulUploads == nil {
lastSuccessfulUploads, err = snapshotter.GetLastSuccessfulUploads(ctx)
if err != nil {
slog.Error(fmt.Sprintf("Unable to get last successful uploads: %s", err))
os.Exit(1)
}
frequency = lastSuccessfulUploads.NextBackupIn(configuredFrequency)
} else if reloadedTimeout != nil {
frequency = *reloadedTimeout
reloadedTimeout = nil
}
}
started := time.Now()
ends := started.Add(frequency)
expires := time.NewTimer(frequency)
select {
case <-expires.C:
if leaderIsSelf {
runBackup(ctx, snapshotter, snapshotTimeout)
}
case <-reload:
slog.Info("Reloading configuration...")
oldFrequency := configuredFrequency
snapshotter, c, configuredFrequency, snapshotTimeout = loadConfig()
if !expires.Stop() {
<-expires.C
}
if oldFrequency != configuredFrequency {
if started.Add(configuredFrequency).After(ends) {
timeout := started.Add(configuredFrequency).Sub(time.Now())
reloadedTimeout = &timeout
} else {
timeout := time.Duration(0)
reloadedTimeout = &timeout
}
} else {
timeout := ends.Sub(time.Now())
reloadedTimeout = &timeout
}
case <-done:
os.Exit(1)
}
}
}
func runBackup(ctx context.Context, snapshotter *snapshot_agent.Snapshotter, snapshotTimeout time.Duration) {
slog.Info("Starting backup.")
snapshot, err := os.CreateTemp("", "snapshot")
if err != nil {
slog.Error(fmt.Sprintf("Unable to create temporary snapshot file: %s", err))
return
}
defer os.Remove(snapshot.Name())
ctx, cancel := context.WithTimeout(ctx, snapshotTimeout)
defer cancel()
err = snapshotter.API.Sys().RaftSnapshotWithContext(ctx, snapshot)
if err != nil {
slog.Error(fmt.Sprintf("Unable to generate snapshot: %s", err))
return
}
_, err = snapshot.Seek(0, io.SeekStart)
if err != nil {
slog.Error(fmt.Sprintf("Unable to seek to start of snapshot file: %s", err))
return
}
now := time.Now().UnixNano()
snapshotter.Lock()
defer snapshotter.Unlock()
for uploaderType, uploader := range snapshotter.Uploaders {
snapshotPath, err := uploader.Upload(ctx, snapshot, now)
if err != nil {
slog.Error(fmt.Sprintf("Unable to upload %s snapshot (%s): %s", uploaderType, snapshotPath, err))
return
}
slog.Info(fmt.Sprintf("Successfully uploaded %s snapshot (%s)", uploaderType, snapshotPath))
}
slog.Info("Backup completed.")
}
func loadConfig() (*snapshot_agent.Snapshotter, *config.Configuration, time.Duration, time.Duration) {
c, err := config.ReadConfig()
if err != nil {
slog.Error("Configuration could not be found")
os.Exit(1)
}
snapshotter, err := snapshot_agent.NewSnapshotter(c)
if err != nil {
slog.Error(fmt.Sprintf("Cannot instantiate snapshotter: %s", err))
os.Exit(1)
}
configuredFrequency, err := time.ParseDuration(c.Frequency)
if err != nil {
configuredFrequency = time.Hour
}
snapshotTimeout := 60 * time.Second
if c.SnapshotTimeout != "" {
snapshotTimeout, err = time.ParseDuration(c.SnapshotTimeout)
if err != nil {
slog.Error(fmt.Sprintf("Unable to parse snapshot timeout: %s", err))
os.Exit(1)
}
}
return snapshotter, c, configuredFrequency, snapshotTimeout
}