This repository has been archived by the owner on Jul 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
baku.py
201 lines (158 loc) · 6.44 KB
/
baku.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
from datetime import datetime
import argparse
import glob
import os
import shutil
import pysftp
import config
if config.DESTINATION_FOLDER:
BAKU_DEST_PATH = config.DESTINATION_FOLDER
else:
BAKU_DEST_PATH = '{}/backups'.format(os.getcwd())
LAST_BACKUP_FILENAME = 'last'
def load_args():
parser = argparse.ArgumentParser(prog='baku.py')
parser.add_argument('-c', '--cron', action='store_true')
parser.add_argument('-f', '--force', action='store_true')
parser.add_argument('-s', '--sync', action='store_true')
return parser.parse_args()
def run_backups(hosts_config, backups_config):
for backup in backups_config:
source_host = hosts_config[backup['hostname']]
user = source_host.get('username')
password = source_host.get('password')
ip = source_host.get('ip')
private_key = source_host.get('private_key')
private_pass = source_host.get('private_key_pass')
# TODO if host has custom port
get_backup_file(ip, user, password, backup, private_key, private_pass)
return
def get_backup_file(ip, user, password, backup_file_details, private_key=None,
private_pass=None):
destination_path = '{}/{}'.format(
BAKU_DEST_PATH,
backup_file_details['destination']
)
prepare_destination_folder(destination_path)
filename = backup_file_details['filename']
remote_location = backup_file_details['location']
backup_file_extension = filename.split('.', maxsplit=1)[-1]
backup_date = datetime.now().strftime("%Y-%m-%d")
# TODO: remove daily from filename
dest_file = '{}daily-{}.{}'.format(
destination_path, backup_date, backup_file_extension
)
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
if private_key:
with pysftp.Connection(
ip, username=user, private_key=private_key,
private_key_pass=private_pass, cnopts=cnopts
) as sftp:
with sftp.cd(remote_location):
print('[*] Downloading {}...'.format(
backup_file_details.get('name', '')
))
sftp.get(filename, localpath=dest_file)
print('[+] Downloaded {}'.format(
backup_file_details.get('name', '')
))
else:
with pysftp.Connection(
ip, username=user, password=password, cnopts=cnopts
) as sftp:
with sftp.cd(backup_file_details['location']):
print('[*] Downloading {}...'.format(
backup_file_details.get('name', '')
))
sftp.get(backup_file_details['filename'], localpath=dest_file)
print('[+] Downloaded {}'.format(
backup_file_details.get('name', '')
))
copy_file_as_last_backup(dest_file, destination_path, config.DEFAULT_LAST_FILENAME)
return
def prepare_destination_folder(destination_path):
if not os.path.exists(destination_path):
os.makedirs(destination_path)
return
def copy_file_as_last_backup(file_to_copy, dest_path, default_last_filename):
file_extension = file_to_copy.split('.', 1)[1]
default_last_filename += '.' + file_extension
shutil.copy2(file_to_copy, dest_path + default_last_filename)
return
def validate_backup_file(backups_config):
# TODO: this function will call a validator to check the file integrity
pass
def reorder_backup_files(backups_config):
today = datetime.today()
for backup_info in backups_config:
reorder_yearly_backup_files(today, backup_info)
reorder_monthly_backup_files(today, backup_info)
reorder_weekly_backup_files(today, backup_info)
reorder_daily_backup_files(today, backup_info)
return
def reorder_yearly_backup_files(today, backup_info):
current_day_of_year = today.timetuple().tm_yday
file_extension = '.' + backup_info['filename'].split('.', 1)[1]
dest_path = BAKU_DEST_PATH + '/' + backup_info['destination']
if current_day_of_year == 1:
yearly_filename = 'yearly-{}{}'.format(
str(today.date()), file_extension
)
print('creating {}'.format(yearly_filename))
shutil.copy2(
dest_path + config.DEFAULT_LAST_FILENAME + file_extension,
dest_path + yearly_filename
)
return
def reorder_monthly_backup_files(today, backup_info):
current_day_of_month = today.day
file_extension = '.' + backup_info['filename'].split('.', 1)[1]
dest_path = BAKU_DEST_PATH + '/' + backup_info['destination']
if current_day_of_month == 1:
# TODO: check if file already exists
monthly_filename = 'monthly-{}{}'.format(
str(today.date()), file_extension
)
print('creating {}'.format(monthly_filename))
shutil.copy2(
dest_path + config.DEFAULT_LAST_FILENAME + file_extension,
dest_path + monthly_filename
)
return
def reorder_weekly_backup_files(today, backup_info):
current_day_of_week = today.isoweekday()
file_extension = '.' + backup_info['filename'].split('.', 1)[1]
dest_path = BAKU_DEST_PATH + '/' + backup_info['destination']
if current_day_of_week == 1:
# TODO: check if file already exists
weekly_filename = 'weekly-{}{}'.format(
str(today.date()), file_extension
)
print('creating {}'.format(weekly_filename))
shutil.copy2(
dest_path + config.DEFAULT_LAST_FILENAME + file_extension,
dest_path + weekly_filename
)
return
def reorder_daily_backup_files(today, backup_info):
backup_dir = BAKU_DEST_PATH + '/' + backup_info.get('destination')
daily_files = glob.glob(backup_dir + 'daily*')
default_max_files = config.DEFAULT_DAILY_LIMIT
max_daily_files = int(backup_info.get('daily_limit', default_max_files))
while len(daily_files) > max_daily_files:
oldest_backup = min(daily_files, key=os.path.getctime)
print('removing {}'.format(oldest_backup))
os.remove(oldest_backup)
daily_files = glob.glob(backup_dir + 'daily*')
return
if __name__ == '__main__':
args = load_args()
if args.cron:
run_backups(config.hosts, config.backups)
validate_backup_file(config.backups)
reorder_backup_files(config.backups)
elif args.sync:
reorder_backup_files(config.backups)
elif args.force:
raise NotImplementedError('Forced backup not implemented yet')