forked from Rudd-O/zfs-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
zmirror
executable file
·239 lines (187 loc) · 8.43 KB
/
zmirror
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import optparse
import os
import time
import sets
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
from zfslib import children_first, parents_first, chronosorted
from zfslib import Dataset, Pool, Snapshot, PoolSet, ZFSConnection
#===================== configuration =====================
parser = optparse.OptionParser("usage: %prog [-np] [-b BUFSIZE]")
parser.add_option('-n', '--dry-run', action='store_true', dest='dryrun', default=False, help='don\'t actually manipulate any file systems')
parser.add_option('-p', '--prefix', action='store', dest='prefix', default="zmirror-", help='prefix to prepend to snapshot names (default: %default)')
parser.add_option('-o', '--progress', action='store_true', dest='progress', default=False, help='show progress (depends on the executabilty of the \'bar\' program) (default: %default)')
parser.add_option('-b', '--bufsize', action='store', dest='bufsize', default=1048576, help='buffer size in bytes for network operations (default: %default)')
opts,args = parser.parse_args(sys.argv[1:])
try:
bufsize = int(opts.bufsize)
assert bufsize >= 16384
except (ValueError,AssertionError),e:
sys.stderr.write("error: bufsize must be an integer greater than 16384\n%s"%parser.get_usage())
sys.exit(os.EX_USAGE)
if len(args) == 2:
try: source_host, source_dataset_name = args[0].split(":",1)
except ValueError: source_host, source_dataset_name = "localhost",args[0]
try: destination_host, destination_dataset_name = args[1].split(":",1)
except ValueError: destination_host, destination_dataset_name = "localhost",args[1]
else:
sys.stderr.write("error: arguments are wrong\n%s"%parser.get_usage())
sys.exit(os.EX_USAGE)
snapshot_prefix = opts.prefix
snapshot_postfix = lambda: time.strftime("%Y-%m-%d-%H%M")
#===================== end configuration =================
# ================ start program algorithm ===================
src_conn = ZFSConnection(source_host)
dst_conn = ZFSConnection(destination_host)
flt = lambda x: x.name.startswith(snapshot_prefix)
snapshot_unique_name = snapshot_prefix + snapshot_postfix()
print "Mirroring dataset %s:%s into %s:%s"%(source_host,source_dataset_name,
destination_host,destination_dataset_name)
print ""
print "Assessing that the source dataset exists...",
try:
source_dataset = src_conn.pools.lookup(source_dataset_name)
print "%s: OK"%source_dataset
except KeyError:
print "No.\nError: the source dataset does not exist. Backup cannot continue"
sys.exit(2)
print ""
try: destination_dataset = dst_conn.pools.lookup(destination_dataset_name)
except KeyError: destination_dataset = None
print "Does the destination dataset exist on the destination side? ",
if destination_dataset:
print "Yes."
else:
print "No.\nError: the destination dataset does not exist. Backup cannot continue"
sys.exit(2)
print ""
print "Backing up"
print ""
# THE BACKUP ALGORITHM
backed_up_datasets = sets.Set()
for srcpath in [ x.get_path() for x in source_dataset.walk() if not isinstance(x,Snapshot) ]:
src = src_conn.pools.lookup(srcpath)
dstpath = destination_dataset_name + srcpath[len(source_dataset.get_path()):]
try: dst = dst_conn.pools.lookup(dstpath)
except KeyError: dst = None
print " Source: %s"%(srcpath)
if src.get_snapshots(flt):
for y in src.get_snapshots(flt): print " %s"%y.name
else: print " ***No snapshots***"
ssn = chronosorted([ x.name for x in src.get_snapshots(flt) ]) # Source Snapshot Names
print " Destination: %s"%(dstpath)
if dst and dst.get_snapshots(flt):
for y in dst.get_snapshots(flt): print " %s"%y.name
elif dst: print " ***No snapshots***"
else: print " Dataset does not exist yet"
if dst: dsn = chronosorted([ x.name for x in dst.get_snapshots(flt) ]) # Destination Snapshot Names
else: dsn = []
no = lambda x: len(x) == 0
one = lambda x: len(x) == 1
two = lambda x: len(x) == 2
first = lambda x: x[0]
last = lambda x: x[-1]
mksn = lambda x,y: "%s@%s"%(x,y) # make snapshot name
if no(ssn):
if no(dsn):
# no snapshots here or there
print " s0r0: snapshotting and sending full snapshot"
if not opts.dryrun:
src_conn.snapshot_recursively(srcpath,snapshot_unique_name)
src_conn.transfer(dst_conn, mksn(srcpath,snapshot_unique_name), mksn(dstpath,snapshot_unique_name),showprogress=opts.progress,bufsize=bufsize)
else:
print " s0r>0: destroying receiver side filesystems, snapshotting and sending full snapshot"
if not opts.dryrun:
dst_conn.destroy(dstpath)
src_conn.snapshot_recursively(srcpath,snapshot_unique_name)
src_conn.transfer(dst_conn, mksn(srcpath,snapshot_unique_name), mksn(dstpath,snapshot_unique_name),showprogress=opts.progress,bufsize=bufsize)
elif one(ssn):
if no(dsn):
# one snapshot on the sender, none here
print " s1r0: sending latest snapshot in full"
if not opts.dryrun:
src_conn.transfer(dst_conn, mksn(srcpath,last(ssn)), mksn(dstpath,last(ssn)),showprogress=opts.progress,bufsize=bufsize)
else:
if last(ssn) == last(dsn):
# matching snapshots on both sides
print " s1rXmatch: snapshotting and sending incremental snapshot"
if not opts.dryrun:
src_conn.snapshot_recursively(srcpath,snapshot_unique_name)
src_conn.transfer(dst_conn, mksn(srcpath,snapshot_unique_name), mksn(dstpath,snapshot_unique_name), last(ssn),showprogress=opts.progress,bufsize=bufsize)
else:
print " s1rXnomatch: destroying receiver side filesystems, sending full snapshot"
if not opts.dryrun:
dst_conn.destroy(dstpath)
src_conn.transfer(dst_conn, mksn(srcpath,last(ssn)), mksn(dstpath,last(ssn)),showprogress=opts.progress,bufsize=bufsize)
else:
if no(dsn):
# two snapshots on the sender, none here
print " s>1r0: sending latest snapshot in full"
if not opts.dryrun:
src_conn.transfer(dst_conn, mksn(srcpath,last(ssn)), mksn(dstpath,last(ssn)),showprogress=opts.progress,bufsize=bufsize)
else:
if last(ssn) == last(dsn):
# latest matching snapshots on both sides
print " s>1rXlatestmatch: Latest snapshots match on both sides, skipping"
elif last(dsn) in ssn:
# two snapshots on the sender, the old one matching here
print " s>1rXmatch: sending incremental snapshot"
if not opts.dryrun:
src_conn.transfer(dst_conn, mksn(srcpath,last(ssn)), mksn(dstpath,last(ssn)), last(dsn),showprogress=opts.progress,bufsize=bufsize)
else:
print " s2r1nomatch: destroying receiver side filesystems, sending full snapshot"
if not opts.dryrun:
dst_conn.destroy(dstpath)
src_conn.transfer(dst_conn, mksn(srcpath,last(ssn)), mksn(dstpath,last(ssn)),showprogress=opts.progress,bufsize=bufsize)
backed_up_datasets.add(dstpath)
print ""
print "Backup finished."
print ""
# THE PRUNE DELETED DATASETS ALGORITHM
# reinspect pools
src_conn.pools
dst_conn.pools
print "Removing from destination datasets not present on source"
all_datasets_in_destination = sets.Set([ x.get_path() for x in destination_dataset.walk() if not isinstance(x,Snapshot) ])
for dataset in children_first(all_datasets_in_destination - backed_up_datasets):
print " Dataset %s was not present in source during backup, removing"%dataset
if not opts.dryrun:
dst_conn.destroy(dataset)
print "Obsolete dataset removal finished"
print ""
# THE REMOVE OBSOLETE SNAPSHOTS ALGORITHM
# reinspect pools
src_conn.pools
dst_conn.pools
print "Removing non-common and old snapshots"
all_snapshots = sets.Set([ x.name for x in
list(source_dataset.walk()) + list(destination_dataset.walk())
if isinstance(x,Snapshot) and flt(x) ])
all_datasets = [ x for x in
list(source_dataset.walk()) + list(destination_dataset.walk())
if not isinstance(x,Snapshot) ]
noncommon_snapshots = sets.Set()
common_snapshots = sets.Set()
for snap in all_snapshots:
in_all = True
for dset in all_datasets:
dsetsnaps = [ c for c in dset.children if c.name == snap ]
if not dsetsnaps: in_all = False
if in_all: common_snapshots.add(snap)
else: noncommon_snapshots.add(snap)
print " Common snapshots:",common_snapshots
print " Noncommon snapshots:",noncommon_snapshots
# latest one will remain
toremove = sets.Set(chronosorted(list(common_snapshots))[:-1] + list(noncommon_snapshots))
print " Snapshots to remove:",toremove
for conn,dsets in ( (src_conn,source_dataset), (dst_conn,destination_dataset) ):
for dset in reversed(list(dsets.walk())):
if isinstance(dset,Snapshot) and dset.name in toremove:
print " Destroying %s"%dset
if not opts.dryrun:
conn.destroy(dset.get_path())
print "Snapshot removal finished"
src_conn.pools
dst_conn.pools