archiver.py 19 KB

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