Skip to content

Instantly share code, notes, and snippets.

@feniix
Created December 31, 2014 19:50
Show Gist options
  • Save feniix/b1c104cb744405856a6b to your computer and use it in GitHub Desktop.
Save feniix/b1c104cb744405856a6b to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
BAKDIR=/tmp/backup
prereqs () {
cat << EOF
${0} assumes you have the following components:
* tar
* s3cmd configured (run s3cmd --configure)
* mongo
* mongodump
EOF
}
usage () {
cat << EOF
usage: ${0} [OPTIONS]
OPTIONS:
-d | --database mongo database name
-b | --bucket s3 bucket
-l | --localonly assumes local backup and does not send to s3
EXAMPLE:
${0} -d databasename -b bucketname -l true
EOF
}
if [[ $# < 1 ]]; then
usage
exit 1
fi
TAR=$(command -v tar)
S3CMD=$(command -v s3cmd)
MONGO=$(command -v mongo)
MDUMP=$(command -v mongodump)
DATE=$(date +%Y%m%d)
if [[ -z ${TAR} ]] || [[ -z ${S3CMD} ]] || [[ -z ${MONGO} ]] || [[ -z ${MDUMP} ]]; then
prereqs
echo "One of the following tools is missing: tar, s3cmd, mongo, mongodump"
fi
${S3CMD} 2>&1 | grep "Consider using --configure" >/dev/null 2>&1
if [ $? -eq 0 ]; then
echo "s3cmd needs to be configured for this script to be run"
echo "Run s3cmd --configure"
exit 1
fi
while [[ $# > 1 ]]
do
key="${1}"
shift
case ${key} in
-d|--database)
MDB="${1}"
shift
;;
-b|--bucket)
S3BUCKET="${1}"
shift
;;
-l|--localonly)
LOCALONLY="${1}"
shift
;;
esac
done
if ( test -z "${LOCALONLY}" || [ "${LOCALONLY}" == "false" ] ) && [[ -z "${S3BUCKET}" ]]; then
echo "If the backup is not local only then the S3 bucket needs to be defined"
usage
exit 1
fi
rm -rf ${BAKDIR}
mkdir -p ${BAKDIR}
pushd ${BAKDIR} > /dev/null 2>&1
BFILE=${BAKDIR}/${DATE}_${MDB}.tar.gz
echo "Locking mongo database"
${MONGO} admin --eval 'printjson(db.fsyncLock());' > /dev/null 2>&1
echo "Backing up mongo database"
${MDUMP} -d ${MDB} > /dev/null 2>&1
echo "Unlocking mongo database"
${MONGO} admin --eval 'printjson(db.fsyncUnlock());' > /dev/null 2>&1
${TAR} -czf ${BFILE} dump
if [ "${LOCALONLY}" == "false" ] || test -z ${LOCALONLY}; then
${S3CMD} put ${BFILE} s3://${S3BUCKET}/backup/${DATE}_${MDB}.tar.gz
rm -rf ${BFILE}
else
echo "Backup file is located in ${BFILE}"
fi
popd > /dev/null 2>&1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment