archiver.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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_file_size, format_time,\
  12. format_file_mode, IncludePattern, ExcludePattern, exclude_path, to_localtime
  13. from .remote import StoreServer, RemoteStore
  14. class Archiver(object):
  15. def __init__(self):
  16. self.exit_code = 0
  17. def open_store(self, location, create=False):
  18. if location.proto == 'ssh':
  19. return RemoteStore(location, create=create)
  20. else:
  21. return Store(location.path, create=create)
  22. def print_error(self, msg, *args):
  23. msg = args and msg % args or msg
  24. if hasattr(sys.stderr, 'encoding'):
  25. msg = msg.encode(sys.stderr.encoding or 'utf-8', 'ignore')
  26. self.exit_code = 1
  27. print >> sys.stderr, msg
  28. def print_verbose(self, msg, *args, **kw):
  29. if self.verbose:
  30. msg = args and msg % args or msg
  31. if hasattr(sys.stdout, 'encoding'):
  32. msg = msg.encode(sys.stdout.encoding or 'utf-8', 'ignore')
  33. if kw.get('newline', True):
  34. print msg
  35. else:
  36. print msg,
  37. def do_serve(self, args):
  38. return StoreServer().serve()
  39. def do_init(self, args):
  40. store = self.open_store(args.store, create=True)
  41. key = Key.create(store)
  42. def do_create(self, args):
  43. store = self.open_store(args.archive)
  44. key = Key(store)
  45. try:
  46. Archive(store, key, args.archive.archive)
  47. except Archive.DoesNotExist:
  48. pass
  49. else:
  50. self.print_error('Archive already exists')
  51. return self.exit_code
  52. cache = Cache(store, key)
  53. archive = Archive(store, key, cache=cache)
  54. # Add darc cache dir to inode_skip list
  55. skip_inodes = set()
  56. try:
  57. st = os.stat(Cache.cache_dir_path())
  58. skip_inodes.add((st.st_ino, st.st_dev))
  59. except IOError:
  60. pass
  61. # Add local store dir to inode_skip list
  62. if not args.archive.host:
  63. try:
  64. st = os.stat(args.archive.path)
  65. skip_inodes.add((st.st_ino, st.st_dev))
  66. except IOError:
  67. pass
  68. for path in args.paths:
  69. self._process(archive, cache, args.patterns, skip_inodes, unicode(path))
  70. archive.save(args.archive.archive, cache)
  71. return self.exit_code
  72. def _process(self, archive, cache, patterns, skip_inodes, path):
  73. if exclude_path(path, patterns):
  74. return
  75. try:
  76. st = os.lstat(path)
  77. except OSError, e:
  78. self.print_error('%s: %s', path, e)
  79. return
  80. if (st.st_ino, st.st_dev) in skip_inodes:
  81. return
  82. self.print_verbose(path)
  83. if stat.S_ISDIR(st.st_mode):
  84. archive.process_dir(path, st)
  85. try:
  86. entries = os.listdir(path)
  87. except OSError, e:
  88. self.print_error('%s: %s', path, e)
  89. else:
  90. for filename in sorted(entries):
  91. self._process(archive, cache, patterns, skip_inodes,
  92. os.path.join(path, filename))
  93. elif stat.S_ISLNK(st.st_mode):
  94. archive.process_symlink(path, st)
  95. elif stat.S_ISFIFO(st.st_mode):
  96. archive.process_fifo(path, st)
  97. elif stat.S_ISREG(st.st_mode):
  98. try:
  99. archive.process_file(path, st, cache)
  100. except IOError, e:
  101. self.print_error('%s: %s', path, e)
  102. else:
  103. self.print_error('Unknown file type: %s', path)
  104. def do_extract(self, args):
  105. def start_cb(item):
  106. self.print_verbose(item['path'].decode('utf-8'))
  107. store = self.open_store(args.archive)
  108. key = Key(store)
  109. archive = Archive(store, key, args.archive.archive)
  110. dirs = []
  111. for item in archive.get_items():
  112. if exclude_path(item['path'], args.patterns):
  113. continue
  114. archive.extract_item(item, args.dest, start_cb)
  115. if stat.S_ISDIR(item['mode']):
  116. dirs.append(item)
  117. if dirs and not item['path'].startswith(dirs[-1]['path']):
  118. # Extract directories twice to make sure mtime is correctly restored
  119. archive.extract_item(dirs.pop(-1), args.dest)
  120. store.flush_rpc()
  121. while dirs:
  122. archive.extract_item(dirs.pop(-1), args.dest)
  123. return self.exit_code
  124. def do_delete(self, args):
  125. store = self.open_store(args.archive)
  126. key = Key(store)
  127. cache = Cache(store, key)
  128. archive = Archive(store, key, args.archive.archive, cache=cache)
  129. archive.delete(cache)
  130. return self.exit_code
  131. def do_list(self, args):
  132. store = self.open_store(args.src)
  133. key = Key(store)
  134. if args.src.archive:
  135. tmap = {1: 'p', 2: 'c', 4: 'd', 6: 'b', 010: '-', 012: 'l', 014: 's'}
  136. archive = Archive(store, key, args.src.archive)
  137. for item in archive.get_items():
  138. type = tmap.get(item['mode'] / 4096, '?')
  139. mode = format_file_mode(item['mode'])
  140. size = 0
  141. if type == '-':
  142. size = sum(size for _, size, _ in item['chunks'])
  143. mtime = format_time(datetime.fromtimestamp(item['mtime']))
  144. if 'source' in item:
  145. if type == 'l':
  146. extra = ' -> %s' % item['source']
  147. else:
  148. type = 'h'
  149. extra = ' link to %s' % item['source']
  150. else:
  151. extra = ''
  152. print '%s%s %-6s %-6s %8d %s %s%s' % (type, mode, item['user'],
  153. item['group'], size, mtime,
  154. item['path'], extra)
  155. else:
  156. for archive in sorted(Archive.list_archives(store, key), key=attrgetter('ts')):
  157. print '%-20s %s' % (archive.metadata['name'], to_localtime(archive.ts).strftime('%c'))
  158. return self.exit_code
  159. def do_verify(self, args):
  160. store = self.open_store(args.archive)
  161. key = Key(store)
  162. archive = Archive(store, key, args.archive.archive)
  163. def start_cb(item):
  164. self.print_verbose('%s ...', item['path'].decode('utf-8'), newline=False)
  165. def result_cb(item, success):
  166. if success:
  167. self.print_verbose('OK')
  168. else:
  169. self.print_verbose('ERROR')
  170. self.print_error('%s: verification failed' % item['path'])
  171. for item in archive.get_items():
  172. if exclude_path(item['path'], args.patterns):
  173. continue
  174. if stat.S_ISREG(item['mode']) and not 'source' in item:
  175. archive.verify_file(item, start_cb, result_cb)
  176. store.flush_rpc()
  177. return self.exit_code
  178. def do_info(self, args):
  179. store = self.open_store(args.archive)
  180. key = Key(store)
  181. cache = Cache(store, key)
  182. archive = Archive(store, key, args.archive.archive, cache=cache)
  183. stats = archive.stats(cache)
  184. print 'Name:', archive.metadata['name']
  185. print 'Hostname:', archive.metadata['hostname']
  186. print 'Username:', archive.metadata['username']
  187. print 'Time:', archive.metadata['time']
  188. print 'Command line:', ' '.join(archive.metadata['cmdline'])
  189. print 'Original size:', format_file_size(stats['osize'])
  190. print 'Compressed size:', format_file_size(stats['csize'])
  191. print 'Unique data:', format_file_size(stats['usize'])
  192. return self.exit_code
  193. def run(self, args=None):
  194. dot_path = os.path.join(os.path.expanduser('~'), '.darc')
  195. if not os.path.exists(dot_path):
  196. os.mkdir(dot_path)
  197. os.mkdir(os.path.join(dot_path, 'keys'))
  198. os.mkdir(os.path.join(dot_path, 'cache'))
  199. parser = argparse.ArgumentParser(description='DARC - Deduplicating Archiver')
  200. parser.add_argument('-v', '--verbose', dest='verbose', action='store_true',
  201. default=False,
  202. help='Verbose output')
  203. subparsers = parser.add_subparsers(title='Available subcommands')
  204. subparser = subparsers.add_parser('serve')
  205. subparser.set_defaults(func=self.do_serve)
  206. subparser = subparsers.add_parser('init')
  207. subparser.set_defaults(func=self.do_init)
  208. subparser.add_argument('store', metavar='ARCHIVE',
  209. type=location_validator(archive=False),
  210. help='Store to create')
  211. subparser = subparsers.add_parser('create')
  212. subparser.set_defaults(func=self.do_create)
  213. subparser.add_argument('-i', '--include', dest='patterns',
  214. type=IncludePattern, action='append',
  215. help='Include condition')
  216. subparser.add_argument('-e', '--exclude', dest='patterns',
  217. type=ExcludePattern, action='append',
  218. help='Include condition')
  219. subparser.add_argument('archive', metavar='ARCHIVE',
  220. type=location_validator(archive=True),
  221. help='Archive to create')
  222. subparser.add_argument('paths', metavar='PATH', nargs='+', type=str,
  223. help='Paths to add to archive')
  224. subparser = subparsers.add_parser('extract')
  225. subparser.set_defaults(func=self.do_extract)
  226. subparser.add_argument('-i', '--include', dest='patterns',
  227. type=IncludePattern, action='append',
  228. help='Include condition')
  229. subparser.add_argument('-e', '--exclude', dest='patterns',
  230. type=ExcludePattern, action='append',
  231. help='Include condition')
  232. subparser.add_argument('archive', metavar='ARCHIVE',
  233. type=location_validator(archive=True),
  234. help='Archive to create')
  235. subparser.add_argument('dest', metavar='DEST', type=str, nargs='?',
  236. help='Where to extract files')
  237. subparser = subparsers.add_parser('delete')
  238. subparser.set_defaults(func=self.do_delete)
  239. subparser.add_argument('archive', metavar='ARCHIVE',
  240. type=location_validator(archive=True),
  241. help='Archive to delete')
  242. subparser = subparsers.add_parser('list')
  243. subparser.set_defaults(func=self.do_list)
  244. subparser.add_argument('src', metavar='SRC', type=location_validator(),
  245. help='Store/Archive to list contents of')
  246. subparser= subparsers.add_parser('verify')
  247. subparser.set_defaults(func=self.do_verify)
  248. subparser.add_argument('-i', '--include', dest='patterns',
  249. type=IncludePattern, action='append',
  250. help='Include condition')
  251. subparser.add_argument('-e', '--exclude', dest='patterns',
  252. type=ExcludePattern, action='append',
  253. help='Include condition')
  254. subparser.add_argument('archive', metavar='ARCHIVE',
  255. type=location_validator(archive=True),
  256. help='Archive to verity integrity of')
  257. subparser= subparsers.add_parser('info')
  258. subparser.set_defaults(func=self.do_info)
  259. subparser.add_argument('archive', metavar='ARCHIVE',
  260. type=location_validator(archive=True),
  261. help='Archive to display information about')
  262. args = parser.parse_args(args)
  263. self.verbose = args.verbose
  264. return args.func(args)
  265. def main():
  266. archiver = Archiver()
  267. sys.exit(archiver.run())
  268. if __name__ == '__main__':
  269. main()