-
Notifications
You must be signed in to change notification settings - Fork 0
/
autobackup
executable file
·323 lines (252 loc) · 12.2 KB
/
autobackup
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
#!/usr/bin/python2 -u
"""
# /opt/autobackup/autobackup --host=example.com --type=etc --dest=/tank/backup/example.com --save=30
# /opt/autobackup/autobackup --host=example.net --type=raw --dest=/tank/backup/example.net --save=30
# /opt/autobackup/autobackup --host=example.org --type=ovz --dest=/tank/backup/example.org --save=30
"""
import argparse
import datetime
import os
import os.path
import shutil
import subprocess
import sys
import syslog
import uuid
__author__ = "Gena Makhomed"
__contact__ = "https://github.com/makhomed/autobackup"
__license__ = "GPLv3"
__version__ = "1.1.1"
__date__ = "2020-07-07"
#######################################################################################################################
def execute_process(*args):
process = subprocess.Popen(args, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True, cwd='/')
stdoutdata, stderrdata = process.communicate()
return process.returncode, stdoutdata, stderrdata
def execute_or_exit(*args):
returncode, stdoutdata, stderrdata = execute_process(*args)
if returncode != 0:
print "fatal error: execute(", args, ") failed"
print "returncode:", returncode
print "stdout:", stdoutdata
print "stderr:", stderrdata
sys.exit(1)
return stdoutdata, stderrdata
def execute_or_warning(*args):
returncode, stdoutdata, stderrdata = execute_process(*args)
if stdoutdata != '' or stderrdata != '':
print "execute(", args, ") failed"
print "returncode:", returncode
print "stdout:", stdoutdata
print "stderr:", stderrdata
def execute(*args):
returncode, stdoutdata, stderrdata = execute_process(*args)
if returncode != 0 or stdoutdata != '' or stderrdata != '':
print "fatal error: execute(", args, ") failed"
print "returncode:", returncode
print "stdout:", stdoutdata
print "stderr:", stderrdata
sys.exit(1)
#######################################################################################################################
def zfs_list_datasets():
args = '/sbin/zfs', 'list', '-H', '-o', 'name,mountpoint'
stdoutdata, dummy_stderrdata = execute_or_exit(*args)
zfs = dict()
for line in stdoutdata.split('\n'):
if line == '':
continue
name, mountpoint = line.split('\t')
zfs[mountpoint] = name
return zfs
def zfs_list_snapshots(dataset):
args = '/sbin/zfs', 'list', '-H', '-o', 'name', '-t', 'snap', dataset
stdoutdata, dummy_stderrdata = execute_or_exit(*args)
prefix = dataset + '@'
snapshots = list()
for line in stdoutdata.split('\n'):
if line.startswith(prefix):
snapshots.append(line)
return sorted(snapshots, reverse=True)
def zfs_create_snapshot(dataset):
execute('/sbin/zfs', 'snapshot', dataset + '@' + datetime.datetime.now().strftime('autobackup.%Y-%m-%d.%H:%M:%S'))
def zfs_delete_snapshot(snapshot):
execute('/sbin/zfs', 'destroy', snapshot)
def zfs_delete_old_snapshots(dataset, save):
for snapshot in zfs_list_snapshots(dataset)[save:]:
zfs_delete_snapshot(snapshot)
#######################################################################################################################
def vzlist(host, port):
args = 'ssh', '-p', str(port), host, 'vzlist', '-a', '-H', '-o', 'ctid,layout'
stdoutdata, dummy_stderrdata = execute_or_exit(*args)
containers = dict()
for line in stdoutdata.split('\n'):
if line == '':
continue
ctid, layout = line.split()
containers[ctid] = layout
return containers
def print_containers_with_snapshots(host, port, containers):
for ctid, layout in containers.items():
if layout == 'ploop':
args = 'ssh', '-p', str(port), host, 'vzctl', 'snapshot-list', ctid, '-H'
stdoutdata, dummy_stderrdata = execute_or_exit(*args)
stdout = stdoutdata.strip()
if stdout != '':
print "container '%s' has active ploop snapshot, can't compact it" % (ctid)
def compact_all_ploop_containers(host, port, containers):
for ctid, layout in containers.items():
if layout == 'ploop':
execute_or_exit('ssh', '-p', str(port), host, 'vzctl', 'compact', ctid)
#######################################################################################################################
def create_local_dir(local_dir):
try:
os.makedirs(local_dir)
except OSError: # File exists
pass
def backup_ploop_container(host, port, ctid, mountpoint):
""" https://openvz.org/Ploop/Backup """
snid = str(uuid.uuid4())
path = os.path.join('/tmp/autobackup', snid)
execute('ssh', '-p', str(port), host, 'mkdir', '-p', path)
execute_or_exit('ssh', '-p', str(port), host, 'vzctl', 'snapshot', ctid, '--id', snid, '--skip-suspend', '--skip-config')
execute_or_exit('ssh', '-p', str(port), host, 'vzctl', 'snapshot-mount', ctid, '--id', snid, '--target', path)
local_dir = os.path.join(mountpoint, ctid)
create_local_dir(local_dir)
extra_excludes = get_excludes_from_remote_host(host, port, path, 'container ' + ctid + ' on hardware-node ' + host + ':' + str(port))
rsync(host, port, path + '/', local_dir, extra_excludes)
execute_or_exit('ssh', '-p', str(port), host, 'vzctl', 'snapshot-umount', ctid, '--id', snid)
execute_or_exit('ssh', '-p', str(port), host, 'vzctl', 'snapshot-delete', ctid, '--id', snid)
execute('ssh', '-p', str(port), host, 'rmdir', path)
def delete_orphan_backups(containers, mountpoint):
save_dirs = set(containers.keys())
save_dirs.add('hardware-node')
for backup in os.listdir(mountpoint):
if backup not in save_dirs:
shutil.rmtree(os.path.join(mountpoint, backup), ignore_errors=True)
def backup_hardware_node(host, port, mountpoint):
local_dir = os.path.join(mountpoint, 'hardware-node')
create_local_dir(local_dir)
extra_excludes = get_excludes_from_remote_host(host, port, None, 'hardware-node ' + host + ':' + str(port))
rsync(host, port, '/etc', local_dir, extra_excludes)
BUILT_IN_EXCLUDES_CONFIG = """
/dev/**
/proc/**
/sys/**
/run/**
/tank/**
/tmp/**
/var/cache/**
/var/tmp/**
/var/spool/postfix/**
/var/lib/redis/temp-*.rdb
"""
def rsync(src_host, src_port, src_dir, dest_dir, extra_excludes):
args_prefix = 'rsync', '-aqH', '--no-compress', '-e', 'ssh -p ' + str(src_port)
args_suffix = '--delete-during', '--delete-excluded', '--ignore-errors', \
'--force', '--numeric-ids', '--timeout=3600', src_host + ':' + src_dir, dest_dir
built_in_excludes = parse_exclude_conf(BUILT_IN_EXCLUDES_CONFIG, 'built-in excludes')
excludes = built_in_excludes + extra_excludes
args_excludes = list()
for entry in excludes:
args_excludes.append('--exclude')
args_excludes.append(entry)
args = list(args_prefix) + args_excludes + list(args_suffix)
execute_or_warning(*args)
#######################################################################################################################
def os_path_concat(prefix, absolute_path):
if absolute_path[0] != '/':
raise ValueError('unexpected value of absolute_path: %s' % absolute_path)
elif prefix is None:
return absolute_path
elif prefix[0] != '/':
raise ValueError('unexpected value of prefix: %s' % prefix)
else:
return os.path.join(prefix, absolute_path[1:])
def parse_exclude_conf(config, description):
excludes = list()
for line in config.split('\n'):
line = line.strip()
if line == '':
continue
elif line[0] == '#':
continue
elif line[0] != '/':
print 'WARNING: unexpected excludes.conf line "%s" from %s' % (line, description)
else:
excludes.append(line)
return excludes
EXCLUDE_CONF_ABSOLUTE_PATH = '/etc/autobackup/exclude.conf'
def get_excludes_from_remote_host(host, port, prefix, description):
exclude_conf = os_path_concat(prefix, EXCLUDE_CONF_ABSOLUTE_PATH)
command = '"if [ -f ' + exclude_conf + ' ] ; then cat ' + exclude_conf + ' ; fi"'
args = 'ssh', '-p', str(port), host, '/bin/sh', '-c', command
stdoutdata, dummy_stderrdata = execute_or_exit(*args)
return parse_exclude_conf(stdoutdata, description)
#######################################################################################################################
def etc_backup(host, port, dataset, mountpoint, save):
start = datetime.datetime.now()
syslog.syslog("etc " + host + ':' + str(port) + " started")
extra_excludes = get_excludes_from_remote_host(host, port, None, 'host ' + host + ':' + str(port))
rsync(host, port, '/etc', mountpoint, extra_excludes)
rsync(host, port, '/opt', mountpoint, extra_excludes)
zfs_create_snapshot(dataset)
zfs_delete_old_snapshots(dataset, save)
end = datetime.datetime.now()
syslog.syslog("etc " + host + ':' + str(port) + " finished, " + str(end - start).split('.')[0])
def raw_backup(host, port, dataset, mountpoint, save):
start = datetime.datetime.now()
syslog.syslog("raw " + host + ':' + str(port) + " started")
extra_excludes = get_excludes_from_remote_host(host, port, None, 'host ' + host + ':' + str(port))
rsync(host, port, '/', mountpoint, extra_excludes)
zfs_create_snapshot(dataset)
zfs_delete_old_snapshots(dataset, save)
end = datetime.datetime.now()
syslog.syslog("raw " + host + ':' + str(port) + " finished, " + str(end - start).split('.')[0])
def ovz_backup(host, port, dataset, mountpoint, save):
start = datetime.datetime.now()
syslog.syslog("ovz " + host + ':' + str(port) + " started")
containers = vzlist(host, port)
for ctid, layout in containers.items():
if layout == 'ploop':
backup_ploop_container(host, port, ctid, mountpoint)
else:
print "container '%s' at %s:%s has unsupported layout type '%s', can't backup it" % (ctid, host, str(port), layout)
backup_hardware_node(host, port, mountpoint)
delete_orphan_backups(containers, mountpoint)
zfs_create_snapshot(dataset)
zfs_delete_old_snapshots(dataset, save)
print_containers_with_snapshots(host, port, containers)
compact_all_ploop_containers(host, port, containers)
end = datetime.datetime.now()
syslog.syslog("ovz " + host + ':' + str(port) + " finished, " + str(end - start).split('.')[0])
#######################################################################################################################
def main():
parser = argparse.ArgumentParser(prog='autobackup')
parser.add_argument('--host', required=True, help="remote host to backup it on ZFS", metavar='HOST')
parser.add_argument('--port', required=False, help="remote port to backup it on ZFS", metavar='PORT', type=int, default=22)
parser.add_argument('--type', required=True, help="remote host type: etc, raw, ovz", metavar='TYPE', choices=['etc', 'raw', 'ovz'])
parser.add_argument('--dest', required=True, help="backup destination on local ZFS", metavar='PATH')
parser.add_argument('--save', required=True, help="count of saved backup snapshots", metavar='COUNT', type=int)
args = parser.parse_args()
if args.port < 1 or args.port > 65535:
print "unexpected --port value '%s', it must be between 1 and 65535" % str(args.port)
sys.exit(1)
if args.save < 1 or args.save > 90:
print "unexpected --save value '%s', it must be between 1 and 90" % str(args.save)
sys.exit(1)
args.dest = os.path.abspath(args.dest)
zfs = zfs_list_datasets()
if args.dest not in zfs:
print "unexpected --dest value '%s', it must be dedicated ZFS filesystem mountpoint" % args.dest
sys.exit(1)
if args.type == 'etc':
etc_backup(host=args.host, port=args.port, dataset=zfs[args.dest], mountpoint=args.dest, save=args.save)
elif args.type == 'raw':
raw_backup(host=args.host, port=args.port, dataset=zfs[args.dest], mountpoint=args.dest, save=args.save)
elif args.type == 'ovz':
ovz_backup(host=args.host, port=args.port, dataset=zfs[args.dest], mountpoint=args.dest, save=args.save)
else:
print "unexpected --type value '%s', it must be 'etc', 'raw' or 'ovz'" % args.type
sys.exit(1)
if __name__ == "__main__":
main()