forked from Drivetech/mongodump-s3
-
Notifications
You must be signed in to change notification settings - Fork 6
/
backup.sh
executable file
·61 lines (52 loc) · 1.72 KB
/
backup.sh
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
#!/usr/bin/env sh
OPTIONS=`python3 /usr/local/bin/mongouri`
OPTIONS="$OPTIONS $EXTRA_OPTIONS"
DEFAULT_BACKUP_NAME="$(date -u +%Y-%m-%d_%H-%M-%S)_UTC.gz"
BACKUP_NAME=${BACKUP_NAME:-$DEFAULT_BACKUP_NAME}
LOCAL_BACKUP_ROOT_FOLDER="/backup"
LOCAL_DUMP_LOCATION="$LOCAL_BACKUP_ROOT_FOLDER/dump"
notify() {
if [ "${SLACK_URI}" ]; then
message="$BACKUP_NAME has been backed up at s3://${S3_BUCKET}/${S3_PATH}/${BACKUP_NAME}"
if [ "${1}" != "0" ]; then
message="Unable to backup $BACKUP_NAME at s3://${S3_BUCKET}/${S3_PATH}/${BACKUP_NAME}. See Logs."
fi
curl -X POST --data-urlencode "payload={\"text\": \"$message\"}" $SLACK_URI
fi
}
# Run backup
mongodump ${OPTIONS} -o "${LOCAL_DUMP_LOCATION}"
status=$?
if [ "${status}" -eq "1" ]; then
echo "ERROR: Mongodump failed."
notify 1
exit 1
fi
# Compress backup
tar -cvzf "${LOCAL_BACKUP_ROOT_FOLDER}/${BACKUP_NAME}" "${LOCAL_DUMP_LOCATION}"
# If the AWS_S3_ENDPOINT variable isn't empty, then populate the --endpoint-url parameter to use a custom S3 compatable endpoint
if [ ! -z "$AWS_S3_ENDPOINT" ]; then
ENDPOINT="--endpoint-url=$AWS_S3_ENDPOINT"
fi
# Upload backup
aws $ENDPOINT s3 cp "${LOCAL_BACKUP_ROOT_FOLDER}/${BACKUP_NAME}" "s3://${S3_BUCKET}/${S3_PATH}/${BACKUP_NAME}"
status=$?
echo $status
if [ "${status}" != "0" ]; then
echo "ERROR: AWS Upload failed."
notify 1
exit 1
fi
notify 0
# Delete temp files
rm -rf "${LOCAL_DUMP_LOCATION}"
# Delete backup files
if [ -n "${MAX_BACKUPS}" ]; then
while [ $(ls ${LOCAL_BACKUP_ROOT_FOLDER} -w 1 | wc -l) -gt ${MAX_BACKUPS} ];
do
BACKUP_TO_BE_DELETED=$(ls /backup -w 1 | sort | head -n 1)
rm -rf ${LOCAL_BACKUP_ROOT_FOLDER}/${BACKUP_TO_BE_DELETED}
done
else
rm -rf ${LOCAL_BACKUP_ROOT_FOLDER}/*
fi