Skip to content

Instantly share code, notes, and snippets.

@trevorc
Created May 27, 2011 14:35
Show Gist options
  • Save trevorc/995365 to your computer and use it in GitHub Desktop.
Save trevorc/995365 to your computer and use it in GitHub Desktop.
Backup MongoDB locally
#!/usr/bin/env python
import os
import sys
import bisect
import shutil
import datetime
import operator
import subprocess
BACKUP_DIR = '/home/ubuntu/backups'
def fmt(dt):
return dt.replace(microsecond=0).isoformat()
if not os.path.isdir(BACKUP_DIR):
os.makedirs(BACKUP_DIR)
os.chdir(BACKUP_DIR)
now = datetime.datetime.utcnow()
null = open('/dev/null', 'w')
pipe = subprocess.Popen(
['mongodump', '-o', fmt(now)], stdout=null, stderr=subprocess.PIPE)
out, err = pipe.communicate()
for line in err.split('\n'):
if line and not line.startswith('connected to'):
sys.stderr.write(line + '\n')
backups = sorted(os.listdir('.'))
week_ago = fmt(now - datetime.timedelta(days=7))
insertion_index = bisect.bisect(backups, week_ago)
to_delete = backups[:insertion_index]
to_keep = backups[insertion_index:]
assert len(to_keep) > len(to_delete)
assert len(to_delete) < 10
for d in to_delete:
shutil.rmtree(d)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment