From 5e754bbc4cc2c7ba1e136492c831756091198dc3 Mon Sep 17 00:00:00 2001 From: Jean-Baptiste Jaillet Date: Tue, 25 Jul 2017 01:31:07 +0200 Subject: [PATCH] ctl: add dump in backup command if postgresql is true (#17726) --- wcs/ctl/backup.py | 42 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/wcs/ctl/backup.py b/wcs/ctl/backup.py index 1654e8b1..a479572e 100644 --- a/wcs/ctl/backup.py +++ b/wcs/ctl/backup.py @@ -17,6 +17,9 @@ import tarfile import time import os +import shutil +import zipfile +import subprocess from qommon.ctl import Command, make_option @@ -42,14 +45,18 @@ class CmdBackup(Command): if not os.path.exists(pub.app_dir): return 1 + pub.set_config() if sub_options.filename: + file_name = '' backup_filepath = sub_options.filename else: backup_dir = os.path.join(pub.app_dir, 'backups') if not os.path.exists(backup_dir): os.mkdir(backup_dir) + file_name = '%s-backup-%s%s%s-%s%s%s' % (hostname, + time.localtime()[:6]) backup_filepath = os.path.join(backup_dir, - 'backup-%s%s%s-%s%s%s.tar.gz' % time.localtime()[:6]) + '%s.tar.gz' % file_name) backup = tarfile.open(backup_filepath, mode='w:gz') for basename, dirnames, filenames in os.walk(pub.app_dir): @@ -62,5 +69,38 @@ class CmdBackup(Command): backup.close() + if pub.is_using_postgresql(): + dest_dir = os.path.dirname(backup_filepath) + db_conf = pub.cfg['postgresql'] + # use 'or' as value are at None when not set + db_name = db_conf.get('database') or '' + db_host = db_conf.get('host') or '' + db_user = db_conf.get('user') or '' + db_port = db_conf.get('port') or '' + db_pwd = db_conf.get('password') or '' + if db_pwd: + os.environ['PGPASSWORD'] = db_pwd + + if not file_name: + file_name = '%s-backup-%s%s%s-%s%s%s' % (hostname, + time.localtime()[:6]) + dump_path = os.path.join(dest_dir, '%s.dump' % file_name) + + subprocess.check_call(['pg_dump', '-Oc', '-h', db_host, + '-U', db_user, '-p', db_port, + '-w', '-f', dump_path, '-d', db_name]) + if db_pwd: + os.environ.pop('PGPASSWORD') + + zip_path = os.path.join(dest_dir, '%s.zip' % file_name) + with zipfile.ZipFile(zip_path, 'a') as zip_file: + zip_file.write(backup_filepath, + os.path.basename(backup_filepath)) + zip_file.write(dump_path, + os.path.basename(dump_path)) + + os.remove(backup_filepath) + os.remove(dump_path) + CmdBackup.register() -- 2.11.0