archiver.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. import argparse
  2. from datetime import datetime
  3. from operator import attrgetter
  4. import os
  5. import stat
  6. import sys
  7. from .archive import Archive
  8. from .store import Store
  9. from .cache import Cache
  10. from .key import Key
  11. from .helpers import location_validator, format_time, \
  12. format_file_mode, IncludePattern, ExcludePattern, exclude_path, to_localtime, \
  13. get_cache_dir, format_timedelta, prune_split, Manifest, Location
  14. from .remote import StoreServer, RemoteStore
  15. class Archiver(object):
  16. def __init__(self):
  17. self.exit_code = 0
  18. def open_store(self, location, create=False):
  19. if location.proto == 'ssh':
  20. return RemoteStore(location, create=create)
  21. else:
  22. return Store(location.path, create=create)
  23. def print_error(self, msg, *args):
  24. msg = args and msg % args or msg
  25. self.exit_code = 1
  26. print >> sys.stderr, msg
  27. def print_verbose(self, msg, *args, **kw):
  28. if self.verbose:
  29. msg = args and msg % args or msg
  30. if kw.get('newline', True):
  31. print msg
  32. else:
  33. print msg,
  34. def do_serve(self, args):
  35. return StoreServer().serve()
  36. def do_init(self, args):
  37. print 'Initializing store "%s"' % args.store.orig
  38. store = self.open_store(args.store, create=True)
  39. key = Key.create(store, args.store.to_key_filename(), password=args.password)
  40. print 'Key file "%s" created.' % key.path
  41. print 'Remember that this file (and password) is needed to access your data. Keep it safe!'
  42. print
  43. manifest = Manifest(store, key, dont_load=True)
  44. manifest.write()
  45. store.commit()
  46. return self.exit_code
  47. def do_chpasswd(self, args):
  48. if os.path.isfile(args.store_or_file):
  49. key = Key()
  50. key.open(args.store_or_file)
  51. else:
  52. store = self.open_store(Location(args.store_or_file))
  53. key = Key(store)
  54. key.chpasswd()
  55. print 'Key file "%s" updated' % key.path
  56. return self.exit_code
  57. def do_create(self, args):
  58. t0 = datetime.now()
  59. store = self.open_store(args.archive)
  60. key = Key(store)
  61. manifest = Manifest(store, key)
  62. cache = Cache(store, key, manifest)
  63. archive = Archive(store, key, manifest, args.archive.archive, cache=cache,
  64. create=True, checkpoint_interval=args.checkpoint_interval)
  65. # Add darc cache dir to inode_skip list
  66. skip_inodes = set()
  67. try:
  68. st = os.stat(get_cache_dir())
  69. skip_inodes.add((st.st_ino, st.st_dev))
  70. except IOError:
  71. pass
  72. # Add local store dir to inode_skip list
  73. if not args.archive.host:
  74. try:
  75. st = os.stat(args.archive.path)
  76. skip_inodes.add((st.st_ino, st.st_dev))
  77. except IOError:
  78. pass
  79. for path in args.paths:
  80. if args.dontcross:
  81. try:
  82. restrict_dev = os.lstat(path).st_dev
  83. except OSError, e:
  84. self.print_error('%s: %s', path, e)
  85. continue
  86. else:
  87. restrict_dev = None
  88. self._process(archive, cache, args.patterns, skip_inodes, path, restrict_dev)
  89. archive.save()
  90. if args.stats:
  91. t = datetime.now()
  92. diff = t - t0
  93. print '-' * 40
  94. print 'Archive name: %s' % args.archive.archive
  95. print 'Archive fingerprint: %s' % archive.id.encode('hex')
  96. print 'Start time: %s' % t0.strftime('%c')
  97. print 'End time: %s' % t.strftime('%c')
  98. print 'Duration: %s' % format_timedelta(diff)
  99. archive.stats.print_()
  100. print '-' * 40
  101. return self.exit_code
  102. def _process(self, archive, cache, patterns, skip_inodes, path, restrict_dev):
  103. if exclude_path(path, patterns):
  104. return
  105. try:
  106. st = os.lstat(path)
  107. except OSError, e:
  108. self.print_error('%s: %s', path, e)
  109. return
  110. if (st.st_ino, st.st_dev) in skip_inodes:
  111. return
  112. # Entering a new filesystem?
  113. if restrict_dev and st.st_dev != restrict_dev:
  114. return
  115. # Ignore unix sockets
  116. if stat.S_ISSOCK(st.st_mode):
  117. return
  118. self.print_verbose(path)
  119. if stat.S_ISDIR(st.st_mode):
  120. archive.process_dir(path, st)
  121. try:
  122. entries = os.listdir(path)
  123. except OSError, e:
  124. self.print_error('%s: %s', path, e)
  125. else:
  126. for filename in sorted(entries):
  127. self._process(archive, cache, patterns, skip_inodes,
  128. os.path.join(path, filename), restrict_dev)
  129. elif stat.S_ISLNK(st.st_mode):
  130. archive.process_symlink(path, st)
  131. elif stat.S_ISFIFO(st.st_mode):
  132. archive.process_fifo(path, st)
  133. elif stat.S_ISREG(st.st_mode):
  134. try:
  135. archive.process_file(path, st, cache)
  136. except IOError, e:
  137. self.print_error('%s: %s', path, e)
  138. else:
  139. self.print_error('Unknown file type: %s', path)
  140. def do_extract(self, args):
  141. def start_cb(item):
  142. self.print_verbose(item['path'])
  143. def extract_cb(item):
  144. if exclude_path(item['path'], args.patterns):
  145. return
  146. if stat.S_ISDIR(item['mode']):
  147. dirs.append(item)
  148. archive.extract_item(item, args.dest, start_cb, restore_attrs=False)
  149. else:
  150. archive.extract_item(item, args.dest, start_cb)
  151. if dirs and not item['path'].startswith(dirs[-1]['path']):
  152. def cb(_, __, item):
  153. # Extract directories twice to make sure mtime is correctly restored
  154. archive.extract_item(item, args.dest)
  155. store.add_callback(cb, dirs.pop(-1))
  156. store = self.open_store(args.archive)
  157. key = Key(store)
  158. manifest = Manifest(store, key)
  159. archive = Archive(store, key, manifest, args.archive.archive)
  160. dirs = []
  161. archive.iter_items(extract_cb)
  162. store.flush_rpc()
  163. while dirs:
  164. archive.extract_item(dirs.pop(-1), args.dest)
  165. return self.exit_code
  166. def do_delete(self, args):
  167. store = self.open_store(args.archive)
  168. key = Key(store)
  169. manifest = Manifest(store, key)
  170. cache = Cache(store, key, manifest)
  171. archive = Archive(store, key, manifest, args.archive.archive, cache=cache)
  172. archive.delete(cache)
  173. return self.exit_code
  174. def do_list(self, args):
  175. def callback(item):
  176. type = tmap.get(item['mode'] / 4096, '?')
  177. mode = format_file_mode(item['mode'])
  178. size = 0
  179. if type == '-':
  180. try:
  181. size = sum(size for _, size, _ in item['chunks'])
  182. except KeyError:
  183. pass
  184. mtime = format_time(datetime.fromtimestamp(item['mtime']))
  185. if 'source' in item:
  186. if type == 'l':
  187. extra = ' -> %s' % item['source']
  188. else:
  189. type = 'h'
  190. extra = ' link to %s' % item['source']
  191. else:
  192. extra = ''
  193. print '%s%s %-6s %-6s %8d %s %s%s' % (type, mode, item['user'],
  194. item['group'], size, mtime,
  195. item['path'], extra)
  196. store = self.open_store(args.src)
  197. key = Key(store)
  198. manifest = Manifest(store, key)
  199. if args.src.archive:
  200. tmap = {1: 'p', 2: 'c', 4: 'd', 6: 'b', 010: '-', 012: 'l', 014: 's'}
  201. archive = Archive(store, key, manifest, args.src.archive)
  202. archive.iter_items(callback)
  203. store.flush_rpc()
  204. else:
  205. for archive in sorted(Archive.list_archives(store, key, manifest), key=attrgetter('ts')):
  206. print '%-20s %s' % (archive.metadata['name'], to_localtime(archive.ts).strftime('%c'))
  207. return self.exit_code
  208. def do_verify(self, args):
  209. store = self.open_store(args.archive)
  210. key = Key(store)
  211. manifest = Manifest(store, key)
  212. archive = Archive(store, key, manifest, args.archive.archive)
  213. def start_cb(item):
  214. self.print_verbose('%s ...', item['path'], newline=False)
  215. def result_cb(item, success):
  216. if success:
  217. self.print_verbose('OK')
  218. else:
  219. self.print_verbose('ERROR')
  220. self.print_error('%s: verification failed' % item['path'])
  221. def callback(item):
  222. if exclude_path(item['path'], args.patterns):
  223. return
  224. if stat.S_ISREG(item['mode']) and 'chunks' in item:
  225. archive.verify_file(item, start_cb, result_cb)
  226. archive.iter_items(callback)
  227. store.flush_rpc()
  228. return self.exit_code
  229. def do_info(self, args):
  230. store = self.open_store(args.archive)
  231. key = Key(store)
  232. manifest = Manifest(store, key)
  233. cache = Cache(store, key, manifest)
  234. archive = Archive(store, key, manifest, args.archive.archive, cache=cache)
  235. stats = archive.calc_stats(cache)
  236. print 'Name:', archive.name
  237. print 'Fingerprint: %s' % archive.id.encode('hex')
  238. print 'Hostname:', archive.metadata['hostname']
  239. print 'Username:', archive.metadata['username']
  240. print 'Time:', to_localtime(archive.ts).strftime('%c')
  241. print 'Command line:', ' '.join(archive.metadata['cmdline'])
  242. stats.print_()
  243. return self.exit_code
  244. def do_prune(self, args):
  245. store = self.open_store(args.store)
  246. key = Key(store)
  247. manifest = Manifest(store, key)
  248. cache = Cache(store, key, manifest)
  249. archives = list(sorted(Archive.list_archives(store, key, manifest, cache),
  250. key=attrgetter('ts'), reverse=True))
  251. if args.hourly + args.daily + args.weekly + args.monthly + args.yearly == 0:
  252. self.print_error('At least one of the "hourly", "daily", "weekly", "monthly" or "yearly" '
  253. 'settings must be specified')
  254. return 1
  255. if args.prefix:
  256. archives = [archive for archive in archives if archive.name.startswith(args.prefix)]
  257. keep = []
  258. if args.hourly:
  259. keep += prune_split(archives, '%Y-%m-%d %H', args.hourly)
  260. if args.daily:
  261. keep += prune_split(archives, '%Y-%m-%d', args.daily, keep)
  262. if args.weekly:
  263. keep += prune_split(archives, '%Y-%V', args.weekly, keep)
  264. if args.monthly:
  265. keep += prune_split(archives, '%Y-%m', args.monthly, keep)
  266. if args.yearly:
  267. keep += prune_split(archives, '%Y', args.yearly, keep)
  268. keep.sort(key=attrgetter('ts'), reverse=True)
  269. to_delete = [a for a in archives if a not in keep]
  270. for archive in keep:
  271. self.print_verbose('Keeping archive "%s"' % archive.name)
  272. for archive in to_delete:
  273. self.print_verbose('Purging archive "%s"', archive.name)
  274. archive.delete(cache)
  275. return self.exit_code
  276. def run(self, args=None):
  277. dot_path = os.path.join(os.path.expanduser('~'), '.darc')
  278. if not os.path.exists(dot_path):
  279. os.mkdir(dot_path)
  280. os.mkdir(os.path.join(dot_path, 'keys'))
  281. os.mkdir(os.path.join(dot_path, 'cache'))
  282. common_parser = argparse.ArgumentParser(add_help=False)
  283. common_parser.add_argument('-v', '--verbose', dest='verbose', action='store_true',
  284. default=False,
  285. help='Verbose output')
  286. parser = argparse.ArgumentParser(description='DARC - Deduplicating Archiver')
  287. subparsers = parser.add_subparsers(title='Available subcommands')
  288. subparser = subparsers.add_parser('serve', parents=[common_parser])
  289. subparser.set_defaults(func=self.do_serve)
  290. subparser = subparsers.add_parser('init', parents=[common_parser])
  291. subparser.set_defaults(func=self.do_init)
  292. subparser.add_argument('-p', '--password', dest='password',
  293. help='Protect store key with password (Default: prompt)')
  294. subparser.add_argument('store',
  295. type=location_validator(archive=False),
  296. help='Store to create')
  297. subparser = subparsers.add_parser('change-password', parents=[common_parser])
  298. subparser.set_defaults(func=self.do_chpasswd)
  299. subparser.add_argument('store_or_file', metavar='STORE_OR_KEY_FILE',
  300. type=str,
  301. help='Key file to operate on')
  302. subparser = subparsers.add_parser('create', parents=[common_parser])
  303. subparser.set_defaults(func=self.do_create)
  304. subparser.add_argument('-s', '--stats', dest='stats',
  305. action='store_true', default=False,
  306. help='Print statistics for the created archive')
  307. subparser.add_argument('-i', '--include', dest='patterns',
  308. type=IncludePattern, action='append',
  309. help='Include condition')
  310. subparser.add_argument('-e', '--exclude', dest='patterns',
  311. type=ExcludePattern, action='append',
  312. help='Include condition')
  313. subparser.add_argument('-c', '--checkpoint-interval', dest='checkpoint_interval',
  314. type=int, default=300, metavar='SECONDS',
  315. help='Write checkpointe ever SECONDS seconds (Default: 300)')
  316. subparser.add_argument('--do-not-cross-mountpoints', dest='dontcross',
  317. action='store_true', default=False,
  318. help='Do not cross mount points')
  319. subparser.add_argument('archive', metavar='ARCHIVE',
  320. type=location_validator(archive=True),
  321. help='Archive to create')
  322. subparser.add_argument('paths', metavar='PATH', nargs='+', type=str,
  323. help='Paths to add to archive')
  324. subparser = subparsers.add_parser('extract', parents=[common_parser])
  325. subparser.set_defaults(func=self.do_extract)
  326. subparser.add_argument('-i', '--include', dest='patterns',
  327. type=IncludePattern, action='append',
  328. help='Include condition')
  329. subparser.add_argument('-e', '--exclude', dest='patterns',
  330. type=ExcludePattern, action='append',
  331. help='Include condition')
  332. subparser.add_argument('archive', metavar='ARCHIVE',
  333. type=location_validator(archive=True),
  334. help='Archive to create')
  335. subparser.add_argument('dest', metavar='DEST', type=str, nargs='?',
  336. help='Where to extract files')
  337. subparser = subparsers.add_parser('delete', parents=[common_parser])
  338. subparser.set_defaults(func=self.do_delete)
  339. subparser.add_argument('archive', metavar='ARCHIVE',
  340. type=location_validator(archive=True),
  341. help='Archive to delete')
  342. subparser = subparsers.add_parser('list', parents=[common_parser])
  343. subparser.set_defaults(func=self.do_list)
  344. subparser.add_argument('src', metavar='SRC', type=location_validator(),
  345. help='Store/Archive to list contents of')
  346. subparser = subparsers.add_parser('verify', parents=[common_parser])
  347. subparser.set_defaults(func=self.do_verify)
  348. subparser.add_argument('-i', '--include', dest='patterns',
  349. type=IncludePattern, action='append',
  350. help='Include condition')
  351. subparser.add_argument('-e', '--exclude', dest='patterns',
  352. type=ExcludePattern, action='append',
  353. help='Include condition')
  354. subparser.add_argument('archive', metavar='ARCHIVE',
  355. type=location_validator(archive=True),
  356. help='Archive to verity integrity of')
  357. subparser = subparsers.add_parser('info', parents=[common_parser])
  358. subparser.set_defaults(func=self.do_info)
  359. subparser.add_argument('archive', metavar='ARCHIVE',
  360. type=location_validator(archive=True),
  361. help='Archive to display information about')
  362. subparser = subparsers.add_parser('prune', parents=[common_parser])
  363. subparser.set_defaults(func=self.do_prune)
  364. subparser.add_argument('-H', '--hourly', dest='hourly', type=int, default=0,
  365. help='Number of hourly archives to keep')
  366. subparser.add_argument('-d', '--daily', dest='daily', type=int, default=0,
  367. help='Number of daily archives to keep')
  368. subparser.add_argument('-w', '--weekly', dest='weekly', type=int, default=0,
  369. help='Number of daily archives to keep')
  370. subparser.add_argument('-m', '--monthly', dest='monthly', type=int, default=0,
  371. help='Number of monthly archives to keep')
  372. subparser.add_argument('-y', '--yearly', dest='yearly', type=int, default=0,
  373. help='Number of yearly archives to keep')
  374. subparser.add_argument('-p', '--prefix', dest='prefix', type=str,
  375. help='Only consider archive names starting with this prefix')
  376. subparser.add_argument('store', metavar='STORE',
  377. type=location_validator(archive=False),
  378. help='Store to prune')
  379. args = parser.parse_args(args)
  380. self.verbose = args.verbose
  381. return args.func(args)
  382. def main():
  383. archiver = Archiver()
  384. sys.exit(archiver.run())
  385. if __name__ == '__main__':
  386. main()