#!/usr/bin/python import sys import json import pprint import subprocess import os import os.path import smtplib fromAddr = 'root@server1.adaptainc.com' toAddr = 'root@server1.adaptainc.com' def mail(from_addr, to_addr, text): conn = smtplib.SMTP('localhost') try: conn.sendmail(from_addr, to_addr, text) finally: conn.close() def handleException(exc, *args, **kwargs): message = [ 'From:{0}'.format(fromAddr), 'To:{0}'.format(toAddr), 'Subject: mysql4 backup error: {0}'.format(repr(exc)), ''] message.append(repr(exc)) message += [repr(e) for e in args] message.append(pprint.pformat(kwargs)) mail(fromAddr, toAddr, '\r\n'.join(e.rstrip() for e in message)) def makedirs(path, mode): if not os.path.isdir(path): os.makedirs(path, mode) if __name__ == '__main__': input = json.loads('\n'.join(e.rstrip() for e in sys.stdin)) result, dbs = [], [] try: home_dir = input['data']['homedir'] user = input['data']['user'] db_source = subprocess.Popen('echo "show databases;" | ssh mysql4.local mysql', stdout=subprocess.PIPE, shell=True) db_pattern = '{0}_'.format(user) dbs = [e.rstrip() for e in db_source.stdout if e.startswith(db_pattern)] if len(dbs) > 0: dump_dir = os.path.join(home_dir, '__mysql4') makedirs(dump_dir, 0755) for db in dbs: filename = os.path.join(dump_dir, '{0}.sql'.format(db)) dumper = subprocess.Popen('ssh mysql4.local mysqldump -Q --hex-blob -n {db} > {file}'.format(db=db, file=filename), stdout=subprocess.PIPE, shell=True) [e for e in dumper.stdout] # consume stdout if any result.append(db) except Exception as e: handleException(e, input=input, dbs=dbs) result_print = 'mysql4 - dumped {0}\n'.format(len(result)) + '\n'.join(' - {0}'.format(e) for e in result) print 1, result_print