Skip to content
This repository was archived by the owner on Nov 29, 2020. It is now read-only.

Commit 2785992

Browse files
committed
add MAX_BACKUPS to limit the number of backups
1 parent e770059 commit 2785992

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -25,4 +25,5 @@ Moreover, if you link `tutum/mongodb-backup` to a mongodb container(e.g. `tutum/
2525
MONGODB_PASS the password of your mongodb database
2626
MONGODB_DB the database name to dump. If not specified, it will dump all the databases
2727
EXTRA_OPTS the extra options to pass to mongodump command
28-
CRON_TIME the interval of cron job to run mongodump. "0 0 * * *" by default, which is every day at 00:00
28+
CRON_TIME the interval of cron job to run mongodump. `0 0 * * *` by default, which is every day at 00:00
29+
MAX_BACKUPS the number of backups to keep. When reaching the limit, the old backup will be discarded. No limit, by default

run.sh

+25-2
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,33 @@ MONGODB_PASS=${MONGODB_PASS:-${MONGODB_ENV_MONGODB_PASS}}
1717
[[ ( -n "${MONGODB_PASS}" ) ]] && PASS_STR=" --password ${MONGODB_PASS}"
1818
[[ ( -n "${MONGODB_DB}" ) ]] && USER_STR=" --db ${MONGODB_DB}"
1919

20-
CMD="mongodump --out /backup/"'$(date +\%Y.\%m.\%d.\%H\%M\%S)'" --host ${MONGODB_HOST} --port ${MONGODB_PORT} ${USER_STR}${PASS_STR}${DB_STR} ${EXTRA_OPTS}"
21-
echo "${CRON_TIME} ${CMD} >> /mongo_backup.log 2>&1" > /crontab.conf
20+
BACKUP_CMD="mongodump --out /backup/"'$(date +\%Y.\%m.\%d.\%H\%M\%S)'" --host ${MONGODB_HOST} --port ${MONGODB_PORT} ${USER_STR}${PASS_STR}${DB_STR} ${EXTRA_OPTS}"
21+
22+
23+
echo "=> Creating backup script"
24+
cat <<EOF >> /backup.sh
25+
#!/bin/bash
26+
MAX_BACKUPS=${MAX_BACKUPS}
27+
28+
echo "=> Starting backup"
29+
if [ -n "\${MAX_BACKUPS}" ]; then
30+
while [ \$(ls /backup -N1 | wc -l) -ge \${MAX_BACKUPS} ];
31+
do
32+
BACKUP_TO_BE_DELETED=\$(ls /backup -N1 | sort | head -n 1)
33+
echo "Deleting backup \${BACKUP_TO_BE_DELETED}"
34+
rm -rf /backup/\${BACKUP_TO_BE_DELETED}
35+
done
36+
fi
37+
${BACKUP_CMD}
38+
echo "=> Backup done"
39+
EOF
40+
chmod +x /backup.sh
41+
42+
echo "${CRON_TIME} /backup.sh >> /mongo_backup.log 2>&1" > /crontab.conf
43+
echo "=> Adding cron job"
2244
crontab /crontab.conf
2345
crontab -l
2446
touch /mongo_backup.log
2547
tail -F /mongo_backup.log &
48+
echo "=> Running cron job"
2649
exec cron -f

0 commit comments

Comments
 (0)