Skip to content

Instantly share code, notes, and snippets.

@Koronen
Created August 12, 2014 12:29
Show Gist options
  • Save Koronen/b31b5782bb9c86e9abee to your computer and use it in GitHub Desktop.
Save Koronen/b31b5782bb9c86e9abee to your computer and use it in GitHub Desktop.
#!/bin/bash
# Written by: Victor Koronen <victor.koronen@sqore.com>
# Based on: https://github.com/RGBboy/mongodb-s3-backup
# Dependencies: s3cmd (http://s3tools.org)
set -e
if [[ $# < 1 ]] ; then
echo "Usage: $0 S3_URL"
exit 1
fi
S3_URL=$1
WORKING_DIR=${TMPDIR:-/var/tmp}
TIMESTAMP=$(date -u "+%F-%H%M%S")
ARCHIVE_DIRNAME="mongodb-backup-$TIMESTAMP"
ARCHIVE_PATH="$WORKING_DIR/$ARCHIVE_DIRNAME.tar.gz"
DUMP_PATH="$WORKING_DIR/$ARCHIVE_DIRNAME"
# Lock the database
# Note there is a bug in mongo 2.2.0 where you must touch all the databases before you run mongodump
mongo admin --eval "var databaseNames = db.getMongo().getDBNames(); for (var i in databaseNames) { printjson(db.getSiblingDB(databaseNames[i]).getCollectionNames()) }; printjson(db.fsyncLock());"
# Dump the database
mongodump --out "$DUMP_PATH"
# Unlock the database
mongo admin --eval "printjson(db.fsyncUnlock());"
# Tar Gzip the file
tar -C "$WORKING_DIR" -zcvf "$ARCHIVE_PATH" "$DUMP_PATH"
# Remove the backup directory
rm -rf "$DUMP_PATH"
# Send the file to the backup drive or S3
s3cmd put "$ARCHIVE_PATH" "$S3_URL"
# Remove the archive
rm -f "$ARCHIVE_PATH"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment