Skip to content

Instantly share code, notes, and snippets.

@sibelius
Last active August 29, 2015 14:16
Show Gist options
  • Save sibelius/fafaa9315df267800014 to your computer and use it in GitHub Desktop.
Save sibelius/fafaa9315df267800014 to your computer and use it in GitHub Desktop.
Mongodb backup gist
#!/usr/bin/env python
import subprocess
import os
import tarfile
import shutil
import glob
from datetime import datetime
import argparse
# your default values
DB_HOST=
DB_NAME=
DB_PASS=
DB_PORT=
DB_USER=
FMT_DATE='%Y-%m-%d'
FMT_DATETIME='%Y-%m-%d_%H-%M-%S'
def local(cmd):
"""Run a command at localhost"""
subprocess.call(cmd.split())
def backup(host, port, user, pwd):
"""Backup a mongodb database"""
now = datetime.utcnow()
date = datetime.strftime(now, FMT_DATE)
dt = datetime.strftime(now, FMT_DATETIME)
if not os.path.isdir(date):
os.mkdir(date)
output = 'mongodb-%s-%s' % (host, dt)
#local('mongodump -h %s -o %s' % (host, output))
local('mongodump -h %s:%s -o %s -u %s -p %s' % (host, port, output, user, pwd))
tar = tarfile.open('%s/%s.tar.gz' % (date, output), 'w:gz')
tar.add(output)
tar.close()
shutil.rmtree(output)
# keep just only one backup per day
if now.hour == 23:
most_recent = sorted(os.listdir(date), reverse=True)[0]
os.rename('%s/%s' % (date, most_recent), 'mongodb-day-%s-%s.tar.gz' % (DB_HOST, date))
shutil.rmtree(date)
def lst():
"""List available snapshots"""
files = glob.glob('mongodb-day-*')
get_date = lambda x: x[27:37]
if len(files) == 0:
print('No available backups')
else:
for f in files:
print(get_date(f))
def restore(date, host, port, user, pwd):
f_backup = glob.glob('mongodb-day-*-%s.tar.gz' % (date))
if len(f_backup) > 0:
print('restoring date: %s' % (date))
#local('mongorestore --drop --h %s %s' % (DB_HOST, f_backup[0]))
local('mongorestore --drop -h %s:%s -o %s -u %s -p %s' % (host, port, output, user, pwd))
else:
print('backup file not found')
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-b', help='[default] backup mongodb', action='store_true')
parser.add_argument('-l', help='list available backup dates', action='store_true')
parser.add_argument('-r', help='restore a backup', metavar='date')
parser.add_argument('-u', help='username', metavar='arg', default=DB_USER)
parser.add_argument('-p', help='password', metavar='arg', default=DB_PASS)
parser.add_argument('--host', help='mongo host to connect to', metavar='arg', default=DB_HOST)
parser.add_argument('--port', help='server port', metavar='arg', default=DB_PORT)
args = parser.parse_args()
if args.l:
lst()
elif args.r:
restore(args.r, args.host, args.port, args.u, args.p)
else:
backup(args.host, args.port, args.u, args.p)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment