-
-
Save rizzomichaelg/7c76731e3b37a29e5857d81f8b07666f to your computer and use it in GitHub Desktop.
Python script to back up MongoDB databases given a MongoDB URL and output directory path. If no Mongo URL is given, it will default to checking for a MONGOLAB_URI config variable with `heroku config`.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import argparse | |
import logging | |
import datetime | |
from urllib.parse import urlparse | |
import subprocess | |
import shutil | |
logging.basicConfig(level=logging.INFO) | |
parser = argparse.ArgumentParser(description='Backup Mongolab DBs') | |
parser.add_argument('-u', '--url', | |
type=str, | |
required=False, | |
default=None, | |
help='Mongo DB URL for Backups') | |
parser.add_argument('-o', '--output_dir', | |
type=str, | |
required=False, | |
default='./', | |
help='Output directory for the backup.') | |
def backup(args): | |
today = datetime.datetime.now() | |
url = args.url | |
if url is None: | |
logging.info('Fetching MONGOLAB_URI using heroku config:get') | |
url = subprocess.check_output([ | |
'heroku', | |
'config:get', | |
'MONGOLAB_URI' | |
]).strip() | |
url = urlparse(url) | |
assert url.scheme == 'mongodb', 'URL must be a MongoDB URL' | |
netloc = url.netloc | |
username = url.username | |
password = url.password | |
hostname = url.hostname | |
port = url.port | |
db = url.path[1:] | |
output_dir = os.path.abspath(os.path.join( | |
os.path.curdir, | |
args.output_dir)) | |
assert os.path.isdir(output_dir), 'Directory %s can\'t be found.' % output_dir | |
output_dir = os.path.abspath(os.path.join(output_dir, | |
'%s__%s'% ( today.strftime('%Y_%m_%d_%H%M%S'), db ) | |
)) | |
logging.info('Backing up %s from %s to %s' % (db, hostname, output_dir)) | |
backup_output = subprocess.check_output( | |
[ | |
'mongodump', | |
'-h', '%s' % hostname, | |
'-u', '%s' % username, | |
'-p', '%s' % password, | |
'-d', '%s' % db, | |
'--port', '%s' % port, | |
'-o', '%s' % output_dir | |
]) | |
logging.info(backup_output) | |
zip_result = shutil.make_archive(output_dir,'zip',output_dir) | |
logging.info(zip_result) | |
remove_result = subprocess.check_output(['rm', '-rf', output_dir]) | |
logging.info(remove_result) | |
if __name__ == '__main__': | |
args = parser.parse_args() | |
try: | |
backup(args) | |
except AssertionError as msg: | |
logging.error(msg) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment