-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
249 lines (199 loc) · 5.89 KB
/
main.go
File metadata and controls
249 lines (199 loc) · 5.89 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
package main
import (
"errors"
"flag"
"fmt"
"log"
"os/exec"
"strings"
)
var (
// version of restic-scheduler being run.
version = "dev"
ErrJobNotFound = errors.New("jobs not found")
)
func ReadJobs(paths []string) ([]Job, error) {
allJobs := []Job{}
for _, path := range paths {
jobs, err := ParseConfig(path)
if err != nil {
return nil, err
}
if jobs != nil {
allJobs = append(allJobs, jobs...)
}
}
if len(allJobs) == 0 {
return allJobs, fmt.Errorf("no jobs found in provided configuration: %w", ErrJobNotFound)
}
return allJobs, nil
}
// FilterJobs filters a list of jobs by a list of names.
func FilterJobs(jobs []Job, names []string) ([]Job, error) {
nameSet := NewSetFrom(names)
if nameSet.Contains("all") {
return jobs, nil
}
filteredJobs := []Job{}
for _, job := range jobs {
if nameSet.Contains(job.Name) {
filteredJobs = append(filteredJobs, job)
delete(nameSet, job.Name)
}
}
var err error
if len(nameSet) > 0 {
err = fmt.Errorf("%w: %v", ErrJobNotFound, nameSet)
}
return filteredJobs, err
}
func runBackupJobs(jobs []Job, names string) error {
if names == "" {
return nil
}
namesSlice := strings.Split(names, ",")
if len(namesSlice) == 0 {
return nil
}
jobs, filterJobErr := FilterJobs(jobs, namesSlice)
for _, job := range jobs {
if err := job.RunBackup(); err != nil {
return err
}
}
return filterJobErr
}
func runRestoreJobs(jobs []Job, names string, snapshot string) error {
if names == "" {
return nil
}
namesSlice := strings.Split(names, ",")
if len(namesSlice) == 0 {
return nil
}
jobs, filterJobErr := FilterJobs(jobs, namesSlice)
for _, job := range jobs {
if err := job.RunRestore(snapshot); err != nil {
return err
}
}
return filterJobErr
}
func runUnlockJobs(jobs []Job, names string) error {
if names == "" {
return nil
}
namesSlice := strings.Split(names, ",")
if len(namesSlice) == 0 {
return nil
}
jobs, filterJobErr := FilterJobs(jobs, namesSlice)
for _, job := range jobs {
if err := job.NewRestic().Unlock(UnlockOpts{RemoveAll: true}); err != nil {
return err
}
}
return filterJobErr
}
type Flags struct {
showVersion bool
backup string
restore string
unlock string
restoreSnapshot string
once bool
healthCheckAddr string
metricsPushGateway string
}
func readFlags() Flags {
flags := Flags{} //nolint:exhaustruct
flag.BoolVar(&flags.showVersion, "version", false, "Display the version and exit")
flag.StringVar(&flags.backup, "backup", "", "Run backup jobs now. Names are comma separated. `all` will run all.")
flag.StringVar(&flags.restore, "restore", "", "Run restore jobs now. Names are comma separated. `all` will run all.")
flag.StringVar(&flags.unlock, "unlock", "", "Unlock job repos now. Names are comma separated. `all` will run all.")
flag.BoolVar(&flags.once, "once", false, "Run jobs specified using -backup and -restore once and exit")
flag.StringVar(&flags.healthCheckAddr, "addr", "0.0.0.0:8080", "address to bind health check API")
flag.StringVar(&flags.metricsPushGateway, "push-gateway", "", "url of push gateway service for batch runs (optional)")
flag.StringVar(&JobBaseDir, "base-dir", JobBaseDir, "Base dir to create intermediate job files like SQL dumps.")
flag.StringVar(&flags.restoreSnapshot, "snapshot", "latest", "the snapshot to restore")
flag.Parse()
return flags
}
func runSpecifiedJobs(jobs []Job, backupJobs, restoreJobs, unlockJobs, snapshot string) error {
// Run specified job unlocks
if err := runUnlockJobs(jobs, unlockJobs); err != nil {
return fmt.Errorf("failed running unlock for jobs: %w", err)
}
// Run specified backup jobs
if err := runBackupJobs(jobs, backupJobs); err != nil {
return fmt.Errorf("failed running backup jobs: %w", err)
}
// Run specified restore jobs
if err := runRestoreJobs(jobs, restoreJobs, snapshot); err != nil {
return fmt.Errorf("failed running restore jobs: %w", err)
}
return nil
}
func maybePushMetrics(metricsPushGateway string) error {
if metricsPushGateway != "" {
fmt.Println("Pushing metrics to push gateway")
if err := Metrics.PushToGateway(metricsPushGateway); err != nil {
return fmt.Errorf("failed pushing metrics after jobs run: %w", err)
}
}
return nil
}
// printVersion prints the scheduler version and the restic binary version if installed on the system.
func printVersion() {
fmt.Println("restic-scheduler version:", version)
// Also display restic binary version
if resticVerOut, err := exec.Command("restic", "version").Output(); err == nil {
fmt.Printf("restic binary version: %s\n", strings.TrimSpace(string(resticVerOut)))
} else {
if _, err := exec.LookPath("restic"); err != nil {
fmt.Printf("restic binary version: unknown, restic missing from $PATH")
return
} else {
fmt.Println("failed to get restic binary version:", err)
}
}
}
func main() {
flags := readFlags()
// Print version if flag is provided
if flags.showVersion {
printVersion()
return
}
if _, err := exec.LookPath("restic"); err != nil {
log.Fatalf("Could not find restic in path. Make sure it's installed")
}
if flag.NArg() == 0 {
log.Fatalf("Requires a path to a job file, but found none")
}
jobs, err := ReadJobs(flag.Args())
if err != nil {
log.Fatalf("Failed to read jobs from files: %v", err)
}
if err := runSpecifiedJobs(jobs, flags.backup, flags.restore, flags.unlock, flags.restoreSnapshot); err != nil {
log.Fatal(err)
}
// Exit if only running once
if flags.once {
if err := maybePushMetrics(flags.metricsPushGateway); err != nil {
log.Fatal(err)
}
return
}
go func() {
_ = RunHTTPHandlers(flags.healthCheckAddr)
}()
for _, job := range jobs {
log.Printf("Refreshing metrics for job %s", job.Name)
job.RefreshMetrics()
}
// TODO: Add healthcheck handler using Job.Healthy()
if err := ScheduleAndRunJobs(jobs); err != nil {
log.Fatalf("failed running jobs: %v", err)
}
}