-
Notifications
You must be signed in to change notification settings - Fork 0
/
backupld
executable file
·400 lines (369 loc) · 10.6 KB
/
backupld
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
# backupld - A backup framework for LemonDigits.com
# Author: Joe Eaves
# Start Date: 12/03/14
# Dependencies / Setup
set -o pipefail
. cpfb
messageMacrofier() {
echo "$(echo $@ | m4 \
-D name="$BACKUP_NAME" \
-D date="$TODAY_DATE" \
-D timestamp="$TIMESTAMP" \
-D fail_count="$FAIL_COUNT" \
- \
)"
}
TODAY_DATE="$(date +%Y%m%d)"
TIMESTAMP="$(date +%s)"
FAIL_COUNT=0
LOG="$(mktemp /tmp/backupld_XXXXXX)"
MYSQL_OUTPUT="$(mktemp -d /tmp/backupld.mysql.XXXXXX)"
MYSQL_CONF="$MYSQL_OUTPUT/.my.cnf"
parseConfig "$1" || let FAIL_COUNT+=1
# Make sure this exists, even if missing from the config.
declare -A LOCAL_BACKUP_DIRS
# Check backup_name specials
BACKUP_NAME="$(messageMacrofier $BACKUP_NAME)"
[[ -n "$BACKUP_STORE" ]] && mkdir -p "$BACKUP_STORE"
function finish {
rm -rf "$MYSQL_OUTPUT"
rm -rf "$LOG"
}
trap finish EXIT
getArchiveString() {
if [[ -n "$BACKUP_HOST" ]]; then
echo "$BACKUP_HOST:$1.attic"
else
echo "$BACKUP_STORE/$1.attic"
fi
}
# Logic
createBackup() {
local archive_string="$(getArchiveString $1)"
echo "--- [Create] Backup for $1::$2" | printMessage
[[ ! -e "$archive_string" ]] && attic init "$archive_string"
attic create --stats "$archive_string::$BACKUP_NAME" "$2" --exclude .forever --exclude tmp 2>&1 | printMessage
exitCode=$?
if [[ $exitCode -eq 0 ]]; then
echo "--- [Create] Completed successfully" | printMessage
return 0
else
echo "--- [Create] Completed unsuccessfully" | printMessage
let FAIL_COUNT+=1
return 1
fi
}
pruneBackup() {
echo "--- [Prune] Backup for $1::$2" | printMessage
local keeps=
local hourly=
local daily=
local weekly=
local monthly=
[[ "${PRUNE_HOURLY[default]}" ]] && hourly="-H ${PRUNE_HOURLY[default]}"
[[ "${PRUNE_HOURLY[$1]}" ]] && hourly="-H ${PRUNE_HOURLY[$1]}"
[[ "${hourly: -1}" -eq 0 ]] && hourly=
keeps="$hourly"
[[ "${PRUNE_DAILY[default]}" ]] && daily="-d ${PRUNE_DAILY[default]}"
[[ "${PRUNE_DAILY[$1]}" ]] && daily="-d ${PRUNE_DAILY[$1]}"
[[ "${daily: -1}" -eq 0 ]] && daily=
keeps="$keeps $daily"
[[ "${PRUNE_WEEKLY[default]}" ]] && weekly="-w ${PRUNE_WEEKLY[default]}"
[[ "${PRUNE_WEEKLY[$1]}" ]] && weekly="-w ${PRUNE_WEEKLY[$1]}"
[[ "${weekly: -1}" -eq 0 ]] && weekly=
keeps="$keeps $weekly"
[[ "${PRUNE_MONTHLY[default]}" ]] && monthly="-m ${PRUNE_MONTHLY[default]}"
[[ "${PRUNE_MONTHLY[$1]}" ]] && monthly="-m ${PRUNE_MONTHLY[$1]}"
[[ "${monthly: -1}" -eq 0 ]] && monthly=
keeps="$keeps $monthly"
[[ "${PRUNE_YEARLY[default]}" ]] && yearly="-y ${PRUNE_YEARLY[default]}"
[[ "${PRUNE_YEARLY[$1]}" ]] && yearly="-y ${PRUNE_YEARLY[$1]}"
[[ "${yearly: -1}" -eq 0 ]] && yearly=
keeps="$keeps $yearly"
attic prune --stats -v "$(getArchiveString $1)" $keeps 2>&1 | printMessage
exitCode=$?
if [[ $exitCode -eq 0 ]]; then
echo "--- [Prune] Completed successfully" | printMessage
return 0
else
echo "--- [Prune] Completed unsuccessfully" | printMessage
let FAIL_COUNT+=1
return 1
fi
}
checkBackup() {
echo "--- [Check $(date +%A)] Backup for $1::$2" | printMessage
attic check "$(getArchiveString $1)" 2>&1 | printMessage
exitCode=$?
if [[ $exitCode -eq 0 ]]; then
echo "--- [Check] Completed successfully" | printMessage
return 0
else
echo "--- [Check] Completed unsuccessfully" | printMessage
let FAIL_COUNT+=1
return 1
fi
}
extractBackup() {
local timestamp="latest" # Can be $1 or something in future!
local reponame="$1"
echo "--- [Extract] $reponame::$timestamp" | printMessage
if [[ "$timestamp" == "latest" ]]; then
local archivename="$(listArchives $reponame | tail -n 1 | awk '{print $1}')"
fi
echo "--- ...found $archivename..." | printMessage
attic extract "$(getArchiveString $reponame)::$archivename" 2>&1 | printMessage
exitCode=$?
if [[ $exitCode -eq 0 ]]; then
echo "--- [Extract] Completed successfully" | printMessage
else
echo "--- [Extract] Completed unsuccessfully" | printMessage
let FAIL_COUNT+=1
fi
notifyUsers
return $FAIL_COUNT
}
listArchives() {
attic list "$(getArchiveString $1)" 2>&1
}
checkEncryption() {
if [[ -n "$1" ]]; then
export ATTIC_PASSPHRASE="$1"
return 0
fi
return 1
}
dumpDatabase() {
mkdir -p "$MYSQL_OUTPUT/$database"
local splitString
IFS=';' read -a splitString <<< "$2"
local hostname="${splitString[0]}"
echo "--- [DBDump $BACKUP_NAME] Backup for $hostname::$1" | printMessage
cat > "$MYSQL_CONF" <<ENDOFCNF
[mysqldump]
user=${splitString[1]}
password=${splitString[2]}
#no-create-db=TRUE
#skip-comments=TRUE
#disable-keys=TRUE
add-drop-table=TRUE
#complete-insert=FALSE
extended-insert=TRUE
#skip-add-locks=TRUE
lock-tables=FALSE
single-transaction=TRUE
routines=TRUE
triggers=TRUE
log-error="$LOG"
dump-date=TRUE
quote-names=TRUE
ENDOFCNF
# Now lets run the thing!
if mysqldump --defaults-file="$MYSQL_CONF" -h "$hostname" "$1" > "$MYSQL_OUTPUT/$database/$hostname.$1.sql"; then
ret=0
else
let FAIL_COUNT+=1
ret=1
fi
rm -rf "$MYSQL_CONF"
return $ret
}
runBackups() {
echo "#### backupld - Starting ####" | printMessage
## MySQL dumps
for database in "${!MYSQL_DBS[@]}"; do
dumpDatabase "$database" "${MYSQL_DBS[$database]}"
LOCAL_BACKUP_DIRS["$database"]="$MYSQL_OUTPUT/$database"
done
echo -en "\n" | printMessage
## Directory backups with Attic
for dir in "${!LOCAL_BACKUP_DIRS[@]}"; do
local dirPath="$(echo ${LOCAL_BACKUP_DIRS[$dir]} | awk -F';' '{print $1}')"
if checkEncryption "$(echo ${LOCAL_BACKUP_DIRS[$dir]} | awk -F';' '{print $2}')"; then
echo "--- ...enabled encryption..." | printMessage
elif [[ -n "$ATTIC_PASSPHRASE" ]]; then
export ATTIC_PASSPHRASE= # Can we use 'unset' here?
echo "--- ...disabled encryption..." | printMessage
fi
if createBackup "$dir" "$dirPath"; then
pruneBackup "$dir" "$dirPath"
if [[ $(date +%u) -eq $BACKUP_CHECK_DAY ]]; then
checkBackup "$dir" "$dirPath"
fi
echo -en "\n" | printMessage
fi
done
if [[ -n "$BACKUP_POST_HOOK" ]]; then
echo "--- [PostHook $BACKUP_NAME] Calling $BACKUP_POST_HOOK" | printMessage
$BACKUP_POST_HOOK | printMessage
echo "--- [PostHook $BACKUP_NAME] Complete" | printMessage
let FAIL_COUNT+=$?
fi
if [[ "$FAIL_COUNT" -gt 0 ]]; then
echo "#### backupld - Unuccessful ####" | printMessage
else
echo "#### backupld - Successful ####" | printMessage
fi
# Cleanup
notifyUsers
return $FAIL_COUNT
}
notifyUsers() {
local user
if [[ "$NOTIFY_TYPE" == "email" ]]; then
for user in "${NOTIFY_USERS[@]}"; do
notifyByEmail "$(echo $user | cut -d';' -f1)" "$(echo $user | cut -d';' -f2)"
[[ $? -ne 0 ]] && let FAIL_COUNT+=1 && return 1
done
elif [[ "$NOTIFY_TYPE" == "pushover" ]]; then
notifyByPushover
[[ $? -ne 0 ]] && let FAIL_COUNT+=1 && return 1
elif [[ "$NOTIFY_TYPE" == "file" ]]; then
for user in "${NOTIFY_USERS[@]}"; do
notifyByFile "$(echo $user | cut -d';' -f1)" "$(echo $user | cut -d';' -f2)"
[[ $? -ne 0 ]] && let FAIL_COUNT+=1 && return 1
done
fi
}
notifyByEmail() {
local subject="$BACKUP_NAME, Failure Count $FAIL_COUNT"
local message="[backupld] Completed with failure count: $FAIL_COUNT. Log attached."
local fromName="backupld"
local fromAddress="backupld@$NOTIFY_FROM_DOMAIN"
local LOGb="$(cat $LOG | base64 -w 0)"
[[ "$NOTIFY_MESSAGE" ]] && message="$(messageMacrofier $NOTIFY_MESSAGE)"
[[ "$NOTIFY_EMAIL_SUBJECT" ]] && subject="$(messageMacrofier $NOTIFY_EMAIL_SUBJECT)"
if [[ "$NOTIFY_SENDGRID" ]]; then
local tmpOut="$(mktemp /tmp/XXXXX)"
cat > "$tmpOut" <<ENDOFOUT
{
"personalizations": [
{
"to": [
{"name": "$1", "email": "$2"}
],
"subject": "$subject"
}
],
"from": {
"name": "$fromName",
"email": "$fromAddress"
},
"content": [
{
"type": "text",
"value": "$message\n"
}
],
"attachments": [
{"type": "application/octet-stream", "filename": "$(basename $LOG).txt", "content": "$LOGb"}
]
}
ENDOFOUT
local output=$(curl -s -X "POST" \
-H "Authorization: Bearer $NOTIFY_SENDGRID" \
-H "Content-Type: application/json" \
-d @"$tmpOut" \
'https://api.sendgrid.com/v3/mail/send'
)
rm -f "$tmpOut"
echo $output
if [[ -n "$output" ]]; then
echo "ERROR: SendGrid notifcation failed for: $1 <$2>." | printMessage
echo "ERROR: $output" | printMessage
fi
elif [[ "$NOTIFY_MANDRILL" ]]; then
local tmpOut="$(mktemp /tmp/XXXXX)"
cat > "$tmpOut" <<-ENDOFOUT
{
"key": "$NOTIFY_MANDRILL",
"message": {
"text": "$message",
"subject": "$subject",
"from_email": "$fromAddress",
"from_name": "$fromName",
"to": [{"name": "$1", "email": "$2"}],
"attachments": [
{"type": "text/plain", "name": "$(basename $LOG).txt", "content": "$LOGb"}
]
}
}
ENDOFOUT
local output=$(curl -s -A 'Mandrill-Curl/1.0' \
-d @"$tmpOut" \
'https://mandrillapp.com/api/1.0/messages/send.json'
)
rm -f "$tmpOut"
if [[ ! $output =~ \"status\"\:\"queued\" ]]; then
echo "ERROR: Mandrill notifcation failed for: $1 <$2>." | printMessage
echo "ERROR: $output" | printMessage
fi
elif [[ "$NOTIFY_MAILGUN" ]]; then
local output=$(curl -s --user "api:$NOTIFY_MAILGUN" \
https://api.mailgun.net/v3/"$NOTIFY_MAILGUN_API_DOMAIN"/messages \
-F from="$fromName <$fromAddress>" \
-F to="$1 <$2>" \
-F subject="$subject" \
-F text="$message" \
-F attachment=@"$LOG" \
-F o:tag="backupld"
)
if [[ ! $output =~ \"message\"\:\ \"Queued\.\ Thank\ you\.\" ]]; then
echo "ERROR: Mailgun notifcation failed for: $1 <$2>." | printMessage
echo "ERROR: $output" | printMessage
let FAIL_COUNT+=1
fi
else
echo "Backupld: Could not find a valid API key."
let FAIL_COUNT+=1
fi
}
notifyByPushover() {
local message="$FAIL_COUNT errors occured"
[[ "$NOTIFY_MESSAGE" ]] && message="$(messageMacrofier $NOTIFY_MESSAGE)"
if [[ "$NOTIFY_PUSHOVER_API_KEY" ]]; then
local apiKey="$NOTIFY_PUSHOVER_API_KEY"
if [[ "$NOTIFY_PUSHOVER_USER_KEY" ]]; then
local userKey="$NOTIFY_PUSHOVER_USER_KEY"
local output=$(curl -s \
https://api.pushover.net/1/messages.json \
-F "token=$apiKey" \
-F "user=$userKey" \
-F "title=[backupld] Complete" \
-F "message=$message" \
)
if [[ ! $output =~ \"status\"\:\ ?1 ]]; then
echo "ERROR: Pushover notifcation failed." | printMessage
echo "ERROR: $output" | printMessage
let FAIL_COUNT+=1
fi
else
echo "ERROR: No Pushover user key" | printMessage
let FAIL_COUNT+=1
fi
else
echo "ERROR: No Pushover API key" | printMessage
let FAIL_COUNT+=1
fi
}
notifyByFile() {
if [[ "$2" ]]; then
cp -f "$LOG" "$2"
fi
}
printMessage() {
local message
while read message; do
if [[ "$NOTIFY_ECHO" == "true" ]]; then
echo "$message"
fi
echo "$message" >> "$LOG"
done
}
if [[ "$2" == "list" ]]; then
listArchives "$3"
elif [[ "$2" == "extract" ]]; then
extractBackup "$3"
else
runBackups
fi