-
Notifications
You must be signed in to change notification settings - Fork 0
/
backup_db.py
87 lines (67 loc) · 2.19 KB
/
backup_db.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
'''
Alob Project
2016 -2018
Author(s): R.Walker
'''
import sys
import os
import subprocess
import datetime
import boto3
KEY = 'XXX'
SECRET = 'XXX'
HOST = 'sos-ch-dk-2.exo.io'
BUCKET_NAME = 'alob'
DB_USER = 'alob'
DB_PASS = 'alob'
DB = 'alob'
DAILY_KEY = 'db/daily/{}'
MONTHLY_KEY = 'db/monthly/{}'
def backup():
'''
Backup the database and push to Single Object Storage (SOS)
'''
print('Backup started: {}'.format(datetime.datetime.now()))
BACKUP_FILE = '{}_db-{}.sql'.format(DB, datetime.date.today())
print('Backup database {}'.format(BACKUP_FILE))
cmd = ['/usr/local/bin/docker-compose exec -T db /usr/bin/mysqldump --user={} --password={} --databases {} > {}'.format(DB_USER, DB_PASS, DB, BACKUP_FILE)]
return_code = subprocess.call(cmd, shell=True)
if return_code != 0 or not os.path.exists(BACKUP_FILE):
print('Error: File {} does not exist or dump failed.'.format(BACKUP_FILE))
sys.exit(1)
s3 = boto3.resource('s3',
aws_access_key_id=KEY,
aws_secret_access_key=SECRET,
endpoint_url='https://{}'.format(HOST))
try:
s3.create_bucket(Bucket=BUCKET_NAME)
finally:
bucket = s3.Bucket(BUCKET_NAME)
#
# backup to daily
#
bucket.put_object(Key=DAILY_KEY.format(BACKUP_FILE), Body=open(BACKUP_FILE, 'rb'))
print('File written to daily buckets.')
#
# Backup to monthly on the first day of the month
#
if datetime.date.today().day == 1:
bucket.put_object(Key=MONTHLY_KEY.format(BACKUP_FILE), Body=open(BACKUP_FILE, 'rb'))
print('File written to monthly buckets.')
#
# Delete the dump
#
os.unlink(BACKUP_FILE)
#
# Check daily container and delete old buckets
#
now = datetime.datetime.now(datetime.timezone.utc)
for v in bucket.objects.filter(Prefix='db/daily'):
if (now - v.last_modified).days > 20:
print('Bucket {} deleted.'.format(v.key))
v.delete()
if __name__ == '__main__':
ROOT_DIR = os.path.abspath(os.path.dirname(__file__))
print('Change to directory: {}'.format(datetime.datetime.now()))
os.chdir(ROOT_DIR)
backup()