-
Notifications
You must be signed in to change notification settings - Fork 0
/
startBackup.go
368 lines (313 loc) · 7.9 KB
/
startBackup.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
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
358
359
360
361
362
363
364
365
366
367
368
package proc
import (
"fmt"
"log"
"os"
"os/signal"
"strings"
"syscall"
"github.com/robfig/cron/v3"
"gopkg.in/yaml.v3"
"github.com/jtom38/dvb/domain"
"github.com/jtom38/dvb/services/alerts"
"github.com/jtom38/dvb/services/cli"
"github.com/jtom38/dvb/services/dest"
"github.com/jtom38/dvb/services/discovery"
"github.com/jtom38/dvb/services/targets"
)
type StartBackupParams struct {
ConfigPath string
Daemon bool
}
type StartBackupClient struct {
Config domain.Config
Params StartBackupParams
}
func NewStartBackupClient(params StartBackupParams) StartBackupClient {
return StartBackupClient{
Params: params,
}
}
func (c StartBackupClient) RunProcess() error {
// Get the config file loaded into memory.
// Need this is we are running once or as a daemon
config, err := c.LoadConfig(c.Params.ConfigPath)
if err != nil {
return err
}
c.SetConfig(*config)
// If daemon is requested from param or config check
if c.Config.Daemon.Cron != "" {
log.Print("Daemon mode was requested.")
log.Printf("Backups will start at '%v'", c.Config.Daemon.Cron)
c.RunDaemon()
} else {
err = c.RunSingle()
if err != nil {
return nil
}
}
return nil
}
// This runs the tool once and closes down once its finished.
func (c StartBackupClient) RunSingle() error {
// Process all requested docker containers
for _, container := range c.Config.Backup.Docker {
err := c.ProcessDockerContainers(container)
if err != nil {
log.Print(err)
}
}
return nil
}
func (c StartBackupClient) RunDaemon() error {
// Set when we want to run the backup job
cronClient := cron.New()
_, err := cronClient.AddFunc(c.Config.Daemon.Cron, func() {
log.Print("Cron was triggered")
go c.RunSingle()
})
if err != nil {
log.Print(err)
}
cronClient.Start()
// Check if we get a request to stop the app
ch := make(chan os.Signal, 6)
signal.Notify(ch,
syscall.SIGTERM,
syscall.SIGINT,
syscall.SIGQUIT,
)
for {
req := <-ch
switch req {
case syscall.SIGTERM:
fallthrough
case syscall.SIGINT:
cronClient.Stop()
signal.Stop(ch)
return nil
case syscall.SIGQUIT:
signal.Stop(ch)
os.Exit(0)
}
}
}
func (c *StartBackupClient) SetConfig(config domain.Config) {
c.Config = config
}
func (c StartBackupClient) ProcessDockerContainers(container domain.ContainerDocker) error {
logs := domain.NewLogs()
logs.Add("The container backup has started.")
details := &domain.RunDetails{
ContainerName: container.Name,
}
// Based on the destination path, lets figure out what we should name the file
recon := discovery.NewReconClient(c.Config)
details, err := recon.DockerScout(container)
if err != nil {
logs.Error(err)
return err
}
// Start the backup process on the container
backupDockerClient := targets.NewDockerClient()
err = backupDockerClient.BackupDockerVolume(*details, container)
if err != nil {
logs.Error(err)
c.SendAlert(SendAlertParam{
Config: c.Config.Alert,
Logs: *logs,
IsError: true,
ContainerName: container.Name,
})
return err
}
logs.Add(fmt.Sprintf("Backup was created. '%v.tar'", details.Backup.FileName))
// run any post reboot requests after a backup was made
c.postRebootContainer(container.Post.Reboot)
err = c.MoveFile(*details, c.Config.Destination)
if err != nil {
logs.Error(err)
c.SendAlert(SendAlertParam{
Config: c.Config.Alert,
Logs: *logs,
IsError: true,
ContainerName: container.Name,
})
return err
}
logs.Add("Backup was moved.")
// Check if we need to remove any old backups
if c.Config.Destination.Retain.Days == 0 {
c.SendAlert(SendAlertParam{
Config: c.Config.Alert,
Logs: *logs,
IsError: false,
ContainerName: container.Name,
})
return nil
}
if c.Config.Destination.Local.Path == "" {
c.SendAlert(SendAlertParam{
Config: c.Config.Alert,
Logs: *logs,
IsError: false,
ContainerName: container.Name,
})
return nil
}
log.Print("Checking for expired files to remove")
retain := dest.NewLocalRetainClient(c.Config.Destination.Local, details.ContainerName, c.Config.Destination.Retain.Days)
for {
totalFiles, err := retain.CountFiles(".tar", retain.GetDirectoryPath())
if err != nil {
logs.Error(err)
c.SendAlert(SendAlertParam{
Config: c.Config.Alert,
Logs: *logs,
IsError: true,
ContainerName: container.Name,
})
return err
}
if totalFiles <= c.Config.Destination.Retain.Days {
break
}
err = retain.Check(".tar")
if err != nil {
logs.Error(err)
c.SendAlert(SendAlertParam{
Config: c.Config.Alert,
Logs: *logs,
IsError: true,
ContainerName: container.Name,
})
return err
}
}
logs.Add(fmt.Sprintf("No errors reported backing up '%v' 🎉", container.Name))
c.SendAlert(SendAlertParam{
Config: c.Config.Alert,
Logs: *logs,
IsError: false,
ContainerName: container.Name,
})
return nil
}
func (c StartBackupClient) LoadConfig(path string) (*domain.Config, error) {
var config domain.Config
content, err := os.ReadFile(path)
if err != nil {
return &config, err
}
err = yaml.Unmarshal(content, &config)
if err != nil {
return &config, err
}
return &config, nil
}
func (c StartBackupClient) MoveFile(details domain.RunDetails, config domain.ConfigDest) error {
var err error
if details.Dest.Local.Directory != "" {
local := dest.NewLocalClient(details.Backup.FileName, details.Backup.FullFilePath, details.ContainerName, config.Local.Path)
err = local.Move(details)
if err != nil {
return err
}
// Remove the old file
err = os.Remove(details.Backup.FullFilePath)
if err != nil {
return err
}
}
return nil
}
type SendAlertParam struct {
Config domain.ConfigAlert
Logs domain.Logs
IsError bool
ContainerName string
}
func (c StartBackupClient) SendAlert(params SendAlertParam) {
var err error
if len(params.Config.Discord.Webhooks) >= 1 {
log.Print("Sending discord alert")
err = c.sendDiscordAlert(params)
if err != nil {
log.Print(err)
}
}
if params.Config.Email.Account.Username != "" && params.Config.Email.Account.Password != "" {
log.Print("Sending email alert")
err = c.sendEmailAlert(params.Config.Email, params.Logs)
if err != nil {
log.Print(err)
}
}
}
func (c StartBackupClient) sendDiscordAlert(params SendAlertParam) error {
var color int
discordAlert := alerts.NewDiscordEmbedMessage(params.Config.Discord)
hostname, err := os.Hostname()
if err != nil {
return err
}
if params.IsError {
color = alerts.DiscordErrorColor
} else {
color = alerts.DiscordSuccessColor
}
discordAlert.AppendFields(alerts.DiscordEmbedFieldParams{
Name: "Server",
Value: hostname,
Inline: true,
})
discordAlert.AppendFields(alerts.DiscordEmbedFieldParams{
Name: "Container",
Value: params.ContainerName,
Inline: true,
})
m := strings.Join(params.Logs.Message, "\n")
discordAlert.SetBody(alerts.DiscordEmbedBodyParams{
Title: "Backup Results",
Color: color,
Description: m,
})
err = discordAlert.SendPayload()
if err != nil {
return err
}
log.Print("> OK")
return nil
}
func (c StartBackupClient) sendEmailAlert(config domain.ConfigAlertEmail, logs domain.Logs) error {
m := strings.Join(logs.Message, "<br>")
client := alerts.NewSmtpClient(config)
client.SetSubject(alerts.EmailSubjectSuccess)
client.SetBody(m)
err := client.SendAlert()
if err != nil {
return err
}
log.Print("> OK")
return nil
}
func (c StartBackupClient) postRebootContainer(names []string) {
if len(names) == 0 {
return
}
client := cli.NewDockerCliClient()
log.Print("Running Post Reboot requests")
for _, name := range names {
log.Printf("Stopping '%v'", name)
output, err := client.StopContainer(name)
if err != nil {
log.Print(output)
}
log.Printf("Starting '%v'", name)
output, err = client.StartContainer(name)
if err != nil {
log.Print(output)
}
}
}