forked from creativeprojects/resticprofile
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
418 lines (367 loc) · 9.93 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
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
package main
import (
"fmt"
"math/rand"
"os"
"os/signal"
"runtime"
"syscall"
"text/tabwriter"
"time"
"github.com/creativeprojects/clog"
"github.com/creativeprojects/resticprofile/config"
"github.com/creativeprojects/resticprofile/constants"
"github.com/creativeprojects/resticprofile/filesearch"
"github.com/creativeprojects/resticprofile/monitor/prom"
"github.com/creativeprojects/resticprofile/monitor/status"
"github.com/creativeprojects/resticprofile/priority"
"github.com/creativeprojects/resticprofile/remote"
"github.com/creativeprojects/resticprofile/term"
"github.com/mackerelio/go-osstat/memory"
"github.com/spf13/pflag"
)
// These fields are populated by the goreleaser build
var (
version = "0.18.0-dev"
commit = ""
date = ""
builtBy = ""
)
func init() {
rand.Seed(time.Now().UnixNano() - time.Now().Unix())
}
func main() {
var exitCode = 0
var err error
// trick to run all defer functions before returning with an exit code
defer func() {
if exitCode != 0 {
os.Exit(exitCode)
}
}()
flagset, flags, flagErr := loadFlags(os.Args[1:])
if flagErr != nil && flagErr != pflag.ErrHelp {
fmt.Println(flagErr)
flagset.Usage()
exitCode = 2
return
}
if flags.wait {
// keep the console running at the end of the program
// so we can see what's going on
defer func() {
fmt.Println("\n\nPress the Enter Key to continue...")
fmt.Scanln()
}()
}
if flags.isChild {
if flags.parentPort == 0 {
exitCode = 10
return
}
}
// help
if flags.help || flagErr == pflag.ErrHelp {
flagset.Usage()
return
}
// setting up the logger - we can start logging right after
if flags.isChild {
// use a remote logger
client := remote.NewClient(flags.parentPort)
setupRemoteLogger(client)
// also redirect the terminal through the client
term.SetAllOutput(term.NewRemoteTerm(client))
// If this is running in elevated mode we'll need to send a finished signal
if flags.isChild {
defer func(port int) {
client := remote.NewClient(port)
client.Done()
}(flags.parentPort)
}
} else if flags.log != "" {
handle, err := setupTargetLogger(flags)
if err != nil {
// back to a console logger
setupConsoleLogger(flags)
clog.Errorf("cannot open log target: %s", err)
} else {
// close the log file at the end
defer handle.Close()
}
} else {
// Use the console logger
setupConsoleLogger(flags)
}
// keep this one last if possible (so it will be first at the end)
defer showPanicData()
banner()
// Deprecated in version 0.7.0
// Keep for compatibility with version 0.6.1
if flags.selfUpdate {
err = confirmAndSelfUpdate(flags.quiet, flags.verbose, version, false)
if err != nil {
clog.Error(err)
exitCode = 1
return
}
return
}
// resticprofile own commands (configuration file NOT loaded)
if len(flags.resticArgs) > 0 {
if isOwnCommand(flags.resticArgs[0], false) {
err = runOwnCommand(nil, flags.resticArgs[0], flags, flags.resticArgs[1:])
if err != nil {
clog.Error(err)
exitCode = 1
return
}
return
}
}
configFile, err := filesearch.FindConfigurationFile(flags.config)
if err != nil {
clog.Error(err)
exitCode = 1
return
}
if configFile != flags.config {
clog.Infof("using configuration file: %s", configFile)
}
c, err := config.LoadFile(configFile, flags.format)
if err != nil {
clog.Errorf("cannot load configuration file: %v", err)
exitCode = 1
return
}
global, err := c.GetGlobalSection()
if err != nil {
clog.Errorf("cannot load global configuration: %v", err)
exitCode = 1
return
}
// Check memory pressure
if global.MinMemory > 0 {
avail := free()
if avail > 0 && avail < global.MinMemory {
clog.Errorf("available memory is < %v MB (option 'min-memory' in the 'global' section)", global.MinMemory)
exitCode = 1
return
}
}
if !flags.noPriority {
err = setPriority(global.Nice, global.Priority)
if err != nil {
clog.Warning(err)
}
if global.IONice {
err = priority.SetIONice(global.IONiceClass, global.IONiceLevel)
if err != nil {
clog.Warning(err)
}
}
}
resticBinary, err := filesearch.FindResticBinary(global.ResticBinary)
if err != nil {
clog.Error("cannot find restic: ", err)
clog.Warning("you can specify the path of the restic binary in the global section of the configuration file (restic-binary)")
exitCode = 1
return
}
// The remaining arguments are going to be sent to the restic command line
resticArguments := flags.resticArgs
resticCommand := global.DefaultCommand
if len(resticArguments) > 0 {
resticCommand = resticArguments[0]
resticArguments = resticArguments[1:]
}
// resticprofile own commands (with configuration file)
if isOwnCommand(resticCommand, true) {
err = runOwnCommand(c, resticCommand, flags, resticArguments)
if err != nil {
clog.Error(err)
exitCode = 1
return
}
return
}
if c.HasProfile(flags.name) {
// if running as a systemd timer
notifyStart()
defer notifyStop()
// Single profile run
err = runProfile(c, global, flags, flags.name, resticBinary, resticArguments, resticCommand, "")
if err != nil {
clog.Error(err)
exitCode = 1
return
}
} else if c.HasProfileGroup(flags.name) {
// Group run
group, err := c.GetProfileGroup(flags.name)
if err != nil {
clog.Errorf("cannot load group '%s': %v", flags.name, err)
}
if group != nil && len(group.Profiles) > 0 {
// if running as a systemd timer
notifyStart()
defer notifyStop()
for i, profileName := range group.Profiles {
clog.Debugf("[%d/%d] starting profile '%s' from group '%s'", i+1, len(group.Profiles), profileName, flags.name)
err = runProfile(c, global, flags, profileName, resticBinary, resticArguments, resticCommand, flags.name)
if err != nil {
clog.Error(err)
exitCode = 1
return
}
}
}
} else {
clog.Errorf("profile or group not found '%s'", flags.name)
displayProfiles(os.Stdout, c)
displayGroups(os.Stdout, c)
exitCode = 1
return
}
}
func banner() {
clog.Debugf("resticprofile %s compiled with %s", version, runtime.Version())
}
func setPriority(nice int, class string) error {
var err error
if class != "" {
if classID, ok := constants.PriorityValues[class]; ok {
err = priority.SetClass(classID)
if err != nil {
return err
}
} else {
return fmt.Errorf("incorrect value '%s' for priority in global section", class)
}
return nil
}
if nice != 0 {
err = priority.SetNice(nice)
if err != nil {
return err
}
}
return nil
}
func runProfile(
c *config.Config,
global *config.Global,
flags commandLineFlags,
profileName string,
resticBinary string,
resticArguments []string,
resticCommand string,
group string,
) error {
var err error
profile, err := c.GetProfile(profileName)
if err != nil {
clog.Warning(err)
}
if profile == nil {
return fmt.Errorf("cannot load profile '%s'", profileName)
}
displayProfileDeprecationNotices(profile)
c.DisplayConfigurationIssues()
// Send the quiet/verbose down to restic as well (override profile configuration)
if flags.quiet {
profile.Quiet = true
profile.Verbose = false
}
if flags.verbose {
profile.Verbose = true
profile.Quiet = false
}
// change log filter according to profile settings
if profile.Quiet {
changeLevelFilter(clog.LevelWarning)
} else if profile.Verbose {
changeLevelFilter(clog.LevelDebug)
}
// use the broken arguments escaping (before v0.15.0)
if global.LegacyArguments {
profile.SetLegacyArg(true)
}
// Specific case for the "host" flag where an empty value should be replaced by the hostname
hostname := "none"
currentHost, err := os.Hostname()
if err == nil {
hostname = currentHost
}
profile.SetHost(hostname)
// Catch CTR-C keypress, or other signal sent by a service manager (systemd)
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM, syscall.SIGABRT)
// remove signal catch before leaving
defer signal.Stop(sigChan)
wrapper := newResticWrapper(
global,
resticBinary,
flags.dryRun,
profile,
resticCommand,
resticArguments,
sigChan,
)
if flags.noLock {
wrapper.ignoreLock()
} else if flags.lockWait > 0 {
wrapper.maxWaitOnLock(flags.lockWait)
}
// add progress receivers if necessary
if profile.StatusFile != "" {
wrapper.addProgress(status.NewProgress(profile, status.NewStatus(profile.StatusFile)))
}
if profile.PrometheusPush != "" || profile.PrometheusSaveToFile != "" {
wrapper.addProgress(prom.NewProgress(profile, prom.NewMetrics(group, version, profile.PrometheusLabels)))
}
err = wrapper.runProfile()
if err != nil {
return err
}
return nil
}
// randomBool returns true for Heads and false for Tails
func randomBool() bool {
return rand.Int31n(10000) < 5000
}
func free() uint64 {
mem, err := memory.Get()
if err != nil {
clog.Info("OS memory information not available")
return 0
}
avail := (mem.Total - mem.Used) / 1048576
clog.Debugf("memory available: %vMB", avail)
return avail
}
func showPanicData() {
if r := recover(); r != nil {
message := `
===============================================================
uh-oh! resticprofile crashed miserably :-(
Can you please open an issue on github including these details:
===============================================================
`
fmt.Fprint(os.Stderr, message)
w := tabwriter.NewWriter(os.Stderr, 0, 0, 3, ' ', 0)
_, _ = fmt.Fprintf(w, "\t%s:\t%s\n", "os", runtime.GOOS)
_, _ = fmt.Fprintf(w, "\t%s:\t%s\n", "arch", runtime.GOARCH)
if goarm > 0 {
_, _ = fmt.Fprintf(w, "\t%s:\tv%d\n", "arm", goarm)
}
_, _ = fmt.Fprintf(w, "\t%s:\t%s\n", "version", version)
_, _ = fmt.Fprintf(w, "\t%s:\t%s\n", "commit", commit)
_, _ = fmt.Fprintf(w, "\t%s:\t%s\n", "compiled", date)
_, _ = fmt.Fprintf(w, "\t%s:\t%s\n", "by", builtBy)
_, _ = fmt.Fprintf(w, "\t%s:\t%s\n", "error", r)
_, _ = fmt.Fprintf(w, "\t%s:\n%s\n", "stack", getStack(3)) // skip calls to getStack - showPanicData - panic
w.Flush()
fmt.Fprint(os.Stderr, "===============================================================\n")
}
}