/
backup.go
255 lines (223 loc) · 6.13 KB
/
backup.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
package backup
import (
"context"
"fmt"
"net/url"
"os"
"strings"
"sync"
"time"
"github.com/0x07cf-dev/go-backup/internal/config"
"github.com/0x07cf-dev/go-backup/internal/logger"
"github.com/0x07cf-dev/go-backup/internal/notify"
//_ "github.com/rclone/rclone/backend/drive"
//_ "github.com/rclone/rclone/backend/dropbox"
_ "github.com/rclone/rclone/backend/local"
//_ "github.com/rclone/rclone/backend/s3"
_ "github.com/rclone/rclone/backend/webdav"
)
type BackupSession struct {
Opts *BackupOpts
Machine *config.Machine
Notifier *notify.Notifier
// Internals
context context.Context
processed map[string]bool
mu sync.Mutex
}
type BackupOpts struct {
Remote string
RemoteRoot string
Language string
Uploading bool
Simulate bool
Unattended bool
Debug bool
}
type BackupOptFunc func(*BackupOpts)
func defaultBackupOpts() *BackupOpts {
// Determine system language
lang := os.Getenv("LANG")
if lang == "" {
lang = os.Getenv("LC_MESSAGES")
}
p := strings.Split(lang, "_")
if len(p) > 0 && len(p[0]) > 0 {
logger.Debugf("Detected system language: '%s' (%s)", p[0], lang)
} else {
lang = "en"
}
return &BackupOpts{
Uploading: true,
Simulate: false,
Unattended: false,
Debug: false,
Language: lang,
}
}
func WithRemote(remote string) BackupOptFunc {
return func(opts *BackupOpts) {
if remote != "" {
opts.Remote = remote
}
}
}
func WithRemoteRoot(remoteRoot string) BackupOptFunc {
return func(opts *BackupOpts) {
opts.RemoteRoot = remoteRoot
}
}
func WithDownload() BackupOptFunc {
return func(opts *BackupOpts) {
opts.Uploading = false
}
}
func WithSimulation(simulate bool) BackupOptFunc {
return func(opts *BackupOpts) {
opts.Simulate = simulate
}
}
func WithInteractivity(interactive bool) BackupOptFunc {
return func(opts *BackupOpts) {
opts.Unattended = !interactive
}
}
func WithDebug(debug bool) BackupOptFunc {
return func(opts *BackupOpts) {
opts.Debug = debug
}
}
func WithLanguage(lang string) BackupOptFunc {
return func(opts *BackupOpts) {
opts.Language = lang
}
}
func NewSession(ctx context.Context, options ...BackupOptFunc) *BackupSession {
opts := defaultBackupOpts()
for _, fn := range options {
fn(opts)
}
// Load current machine parameters from configuration
machine, err := config.GetCurrentMachine()
if err != nil {
logger.Fatal(err.Error())
}
// Load notifier parameters from environment
notifier, err := notify.NewNotifierFromEnv()
if err != nil {
logger.Errorf("Error creating notifier: %s", err.Error())
logger.Error("The backup will still be performed, but notifications will not be sent.")
}
return &BackupSession{
Opts: opts,
Machine: machine,
Notifier: notifier,
context: ctx,
processed: make(map[string]bool),
}
}
func (session *BackupSession) Backup() {
t0 := time.Now()
wg := sync.WaitGroup{}
numPaths := len(session.Machine.Paths)
numPreCmds := len(session.Machine.Pre)
numPostCmds := len(session.Machine.Post)
if numPaths == 0 && numPreCmds == 0 && numPostCmds == 0 {
logger.Error("Nothing to do. Please take a look at the configuration file.")
return
}
// Ternary operator is sometimes useful :(
var sb strings.Builder
if session.Opts.Uploading {
sb.WriteString("Upload ")
} else {
sb.WriteString("Download ")
}
if session.Opts.Simulate {
sb.WriteString("Simulation ")
} else {
sb.WriteString("Session ")
}
if session.Opts.Remote == "" {
sb.WriteString("(local)")
} else {
sb.WriteString(fmt.Sprintf("(%s)", session.Opts.Remote))
}
logger.Info(sb.String())
// Health
session.Heartbeat("start", false)
// Execute pre commands
preErrCh := make(chan BackupError, numPreCmds)
if numPreCmds > 0 {
logger.Info("Executing pre-transfer commands...")
executeCmds(preErrCh, session.Machine.Pre, session.Machine.Output)
}
close(preErrCh)
// Spawn transfer goroutines
transferErrCh := make(chan BackupError, numPaths)
if numPaths > 0 {
logger.Debug("Spawning transfer routines...")
if session.Opts.Uploading {
for _, path := range session.Machine.Paths {
wg.Add(1)
go session.uploadPath(path, &wg, transferErrCh, session.Opts.Simulate)
}
} else {
for _, path := range session.Machine.Paths {
wg.Add(1)
go session.downloadPath(path, &wg, transferErrCh, session.Opts.Simulate)
}
}
// Sync goroutines
wg.Wait()
}
close(transferErrCh)
// Execute post commands
postErrCh := make(chan BackupError, numPostCmds)
if numPostCmds > 0 {
logger.Info("Executing post-transfer commands...")
executeCmds(postErrCh, session.Machine.Post, session.Machine.Output)
}
close(postErrCh)
// Notify status to user
logger.Info("BACKUP DONE!")
status, statusEmoji := getStatus(transferErrCh, preErrCh, postErrCh, session.Opts.Language)
session.NotifyStatus(status, statusEmoji, "package")
// Ping healthchecks
session.Heartbeat("", true)
logger.Infof("ALL DONE! Time taken: %v\n", time.Since(t0))
}
func (session *BackupSession) Heartbeat(endpoint string, withLog bool) {
if session.Notifier != nil {
if !session.Opts.Unattended {
logger.Debugf("Session is non-interactive: heartbeat will not be sent. %v", session.Notifier.HealthMonitors)
return
}
resp, err := session.Notifier.SendHeartbeats(endpoint, withLog)
if err != nil {
logger.Errorf("Error sending heartbeat: %s", err)
}
logger.Debugf("Heartbeat Status: '%s'", resp)
} else if session.Opts.Unattended {
logger.Info("Heartbeats are not configured.")
}
}
func (session *BackupSession) NotifyStatus(status string, statusTags ...string) {
if session.Notifier != nil {
msgTitle := fmt.Sprintf(
"%s - %s",
strings.ToUpper(session.Machine.Hostname),
strings.ToTitle(session.Notifier.Topic),
)
msgTags := make([]string, 0, len(statusTags)+2)
msgTags = append(msgTags, statusTags...)
msgTags = append(msgTags, session.Machine.Hostname, session.Notifier.Topic)
resp, err := session.Notifier.Send(msgTitle, status, msgTags, notify.WithClickUrl(&url.URL{Host: session.Notifier.Host}))
if err != nil {
logger.Errorf("Error sending status notification: %s", err)
} else {
logger.Debugf("Notifier Status: '%s'", resp)
logger.Infof("Post-transfer notification sent.")
}
}
}