archiver.py 18 KB

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