1 # Cumulus: Efficient Filesystem Backup to the Cloud
2 # Copyright (C) 2006-2009, 2012 The Cumulus Developers
3 # See the AUTHORS file for a list of contributors.
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 """Implementation of the Cumulus command-line utility program."""
21 import getpass, os, stat, sys, time
22 from optparse import OptionParser
26 # We support up to "Cumulus Snapshot v0.11" formats, but are also limited by
28 FORMAT_VERSION = min(cumulus.FORMAT_VERSION, (0, 11))
30 def check_version(format):
31 ver = cumulus.parse_metadata_version(format)
32 if ver > FORMAT_VERSION:
33 raise RuntimeError("Unsupported Cumulus format: " + format)
35 # Read a passphrase from the user and store it in the LBS_GPG_PASSPHRASE
36 # environment variable.
38 ENV_KEY = 'LBS_GPG_PASSPHRASE'
39 if not os.environ.has_key(ENV_KEY):
40 os.environ[ENV_KEY] = getpass.getpass()
42 def cmd_prune_db(args):
43 """ Delete old snapshots from the local database, though do not
44 actually schedule any segment cleaning.
45 Syntax: $0 --localdb=LOCALDB prune-db
47 db = cumulus.LocalDatabase(options.localdb)
49 # Delete old snapshots from the local database.
53 def cmd_clean(args, clean_threshold=7.0):
54 """ Run the segment cleaner.
55 Syntax: $0 --localdb=LOCALDB clean
57 db = cumulus.LocalDatabase(options.localdb)
59 # Delete old snapshots from the local database.
60 intent = float(options.intent)
61 for s in db.list_schemes():
62 db.prune_old_snapshots(s, intent)
64 # Expire segments which are poorly-utilized.
65 for s in db.get_segment_cleaning_list():
66 if s.cleaning_benefit > clean_threshold:
67 print "Cleaning segment %d (benefit %.2f)" % (s.id,
69 db.mark_segment_expired(s)
72 db.balance_expired_objects()
75 def cmd_list_snapshots(args):
76 """ List snapshots stored.
77 Syntax: $0 --data=DATADIR list-snapshots
79 store = cumulus.CumulusStore(options.store)
80 for s in sorted(store.list_snapshots()): print s
82 def cmd_list_snapshot_sizes(args):
83 """ List size of data needed for each snapshot.
84 Syntax: $0 --data=DATADIR list-snapshot-sizes
86 store = cumulus.CumulusStore(options.store)
87 backend = store.backend
90 def get_size(segment):
91 return backend.stat_generic(segment + ".tar", "segments")["size"]
92 for s in sorted(store.list_snapshots()):
93 d = cumulus.parse_full(store.load_snapshot(s))
94 check_version(d['Format'])
96 segments = set(d['Segments'].split())
97 (added, removed, addcount, remcount) = (0, 0, 0, 0)
98 for seg in segments.difference(previous):
99 added += get_size(seg)
101 for seg in previous.difference(segments):
102 removed += get_size(seg)
104 size += added - removed
106 print "%s: %.3f +%.3f -%.3f (+%d/-%d segments)" % (s, size / 1024.0**2, added / 1024.0**2, removed / 1024.0**2, addcount, remcount)
108 def cmd_garbage_collect(args):
109 """ Search for any files which are not needed by any current
110 snapshots and offer to delete them.
111 Syntax: $0 --store=DATADIR gc
113 store = cumulus.CumulusStore(options.store)
114 backend = store.backend
116 for s in store.list_snapshots():
117 d = cumulus.parse_full(store.load_snapshot(s))
118 check_version(d['Format'])
120 referenced.update(d['Segments'].split())
126 for filetype in cumulus.SEARCH_PATHS:
127 for (name, path) in store.backend.list_generic(filetype):
128 if name in referenced:
129 to_preserve.append(path)
131 to_delete.append(path)
136 raw_backend = backend.raw_backend
139 if not options.dry_run:
140 raw_backend.delete(f)
141 cmd_gc = cmd_garbage_collect
143 def cmd_read_snapshots(snapshots):
144 """ Read a snapshot file
147 store = cumulus.CumulusStore(options.store)
149 d = cumulus.parse_full(store.load_snapshot(s))
150 check_version(d['Format'])
152 print d['Segments'].split()
155 def cmd_read_metadata(args):
156 """ Produce a flattened metadata dump from a snapshot
160 store = cumulus.CumulusStore(options.store)
161 d = cumulus.parse_full(store.load_snapshot(snapshot))
162 check_version(d['Format'])
163 metadata = cumulus.read_metadata(store, d['Root'])
174 def cmd_verify_snapshots(snapshots):
175 """ Verify snapshot integrity
178 store = cumulus.CumulusStore(options.store)
180 cumulus.accessed_segments.clear()
181 print "#### Snapshot", s
182 d = cumulus.parse_full(store.load_snapshot(s))
183 check_version(d['Format'])
184 print "## Root:", d['Root']
185 metadata = cumulus.iterate_metadata(store, d['Root'])
187 if m.fields['type'] not in ('-', 'f'): continue
188 print "%s [%d bytes]" % (m.fields['name'], int(m.fields['size']))
189 verifier = cumulus.ChecksumVerifier(m.fields['checksum'])
191 for block in m.data():
192 data = store.get(block)
193 verifier.update(data)
195 if int(m.fields['size']) != size:
196 raise ValueError("File size does not match!")
197 if not verifier.valid():
198 raise ValueError("Bad checksum found")
200 # Verify that the list of segments included with the snapshot was
201 # actually accurate: covered all segments that were really read, and
202 # doesn't contain duplicates.
203 listed_segments = set(d['Segments'].split())
204 if cumulus.accessed_segments - listed_segments:
205 print "Error: Some segments not listed in descriptor!"
206 print sorted(list(cumulus.accessed_segments - listed_segments))
207 if listed_segments - cumulus.accessed_segments :
208 print "Warning: Extra unused segments listed in descriptor!"
209 print sorted(list(listed_segments - cumulus.accessed_segments))
212 def cmd_restore_snapshot(args):
213 """ Restore a snapshot, or some subset of files from it
216 store = cumulus.CumulusStore(options.store)
217 snapshot = cumulus.parse_full(store.load_snapshot(args[0]))
218 check_version(snapshot['Format'])
223 "Return true if the specified path should be included in the restore."
225 # No specification of what to restore => restore everything
226 if len(paths) == 0: return True
229 if path == p: return True
230 if path.startswith(p + "/"): return True
234 print "Warning: %s: %s" % (m.items.name, msg)
236 # Phase 1: Read the complete metadata log and create directory structure.
239 metadata_segments = {}
240 for m in cumulus.iterate_metadata(store, snapshot['Root']):
241 pathname = os.path.normpath(m.items.name)
242 while os.path.isabs(pathname):
243 pathname = pathname[1:]
244 if not matchpath(pathname): continue
246 destpath = os.path.join(destdir, pathname)
247 if m.items.type == 'd':
250 (path, filename) = os.path.split(destpath)
252 metadata_items.append((pathname, m))
253 if m.items.type in ('-', 'f'):
254 metadata_paths[pathname] = m
255 for block in m.data():
256 (segment, object, checksum, slice) \
257 = cumulus.CumulusStore.parse_ref(block)
258 if segment not in metadata_segments:
259 metadata_segments[segment] = set()
260 metadata_segments[segment].add(pathname)
263 if not os.path.isdir(path):
267 warn(m, "Error creating directory structure: %s" % (e,))
270 # Phase 2: Restore files, ordered by how data is stored in segments.
271 def restore_file(pathname, m):
272 assert m.items.type in ('-', 'f')
273 print "extract:", pathname
274 destpath = os.path.join(destdir, pathname)
276 file = open(destpath, 'wb')
277 verifier = cumulus.ChecksumVerifier(m.items.checksum)
279 for block in m.data():
280 data = store.get(block)
281 verifier.update(data)
285 if int(m.fields['size']) != size:
286 raise ValueError("File size does not match!")
287 if not verifier.valid():
288 raise ValueError("Bad checksum found")
290 while metadata_segments:
291 (segment, items) = metadata_segments.popitem()
292 print "+ Segment", segment
293 for pathname in sorted(items):
294 if pathname in metadata_paths:
295 restore_file(pathname, metadata_paths[pathname])
296 del metadata_paths[pathname]
298 print "+ Remaining files"
299 while metadata_paths:
300 (pathname, m) = metadata_paths.popitem()
301 restore_file(pathname, m)
303 # Phase 3: Restore special files (symlinks, devices).
304 # Phase 4: Restore directory permissions and modification times.
305 for (pathname, m) in reversed(metadata_items):
306 print "permissions:", pathname
307 destpath = os.path.join(destdir, pathname)
308 (path, filename) = os.path.split(destpath)
310 # TODO: Check for ../../../paths that might attempt to write outside
311 # the destination directory. Maybe also check attempts to follow
312 # symlinks pointing outside?
315 if m.items.type in ('-', 'f', 'd'):
317 elif m.items.type == 'l':
319 target = m.items.target
321 # Old (v0.2 format) name for 'target'
322 target = m.items.contents
323 os.symlink(target, destpath)
324 elif m.items.type == 'p':
326 elif m.items.type in ('c', 'b'):
327 if m.items.type == 'c':
328 mode = 0600 | stat.S_IFCHR
330 mode = 0600 | stat.S_IFBLK
331 os.mknod(destpath, mode, os.makedev(*m.items.device))
332 elif m.items.type == 's':
333 pass # TODO: Implement
335 warn(m, "Unknown type code: " + m.items.type)
339 warn(m, "Error restoring: %s" % (e,))
343 uid = m.items.user[0]
344 gid = m.items.group[0]
345 os.lchown(destpath, uid, gid)
347 warn(m, "Error restoring file ownership: %s" % (e,))
349 if m.items.type == 'l':
353 os.chmod(destpath, m.items.mode)
355 warn(m, "Error restoring file permissions: %s" % (e,))
358 os.utime(destpath, (time.time(), m.items.mtime))
360 warn(m, "Error restoring file timestamps: %s" % (e,))
365 usage = ["%prog [option]... command [arg]...", "", "Commands:"]
367 for cmd, method in globals().iteritems():
368 if cmd.startswith ('cmd_'):
369 usage.append(cmd[4:].replace('_', '-') + ':' + method.__doc__)
370 parser = OptionParser(usage="\n".join(usage))
371 parser.add_option("-v", action="store_true", dest="verbose", default=False,
372 help="increase verbosity")
373 parser.add_option("-n", action="store_true", dest="dry_run", default=False,
375 parser.add_option("--store", dest="store",
376 help="specify path to backup data store")
377 parser.add_option("--localdb", dest="localdb",
378 help="specify path to local database")
379 parser.add_option("--intent", dest="intent", default=1.0,
380 help="give expected next snapshot type when cleaning")
382 (options, args) = parser.parse_args(argv[1:])
389 method = globals().get('cmd_' + cmd.replace('-', '_'))
393 print "Unknown command:", cmd