Created
May 27, 2011 14:35
-
-
Save trevorc/995365 to your computer and use it in GitHub Desktop.
Backup MongoDB locally
This file contains 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
#!/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