archiver.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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. def extract_cb(item):
  108. if exclude_path(item['path'], args.patterns):
  109. return
  110. archive.extract_item(item, args.dest, start_cb)
  111. if stat.S_ISDIR(item['mode']):
  112. dirs.append(item)
  113. if dirs and not item['path'].startswith(dirs[-1]['path']):
  114. # Extract directories twice to make sure mtime is correctly restored
  115. archive.extract_item(dirs.pop(-1), args.dest)
  116. store = self.open_store(args.archive)
  117. key = Key(store)
  118. archive = Archive(store, key, args.archive.archive)
  119. dirs = []
  120. archive.iter_items(extract_cb)
  121. store.flush_rpc()
  122. while dirs:
  123. archive.extract_item(dirs.pop(-1), args.dest)
  124. return self.exit_code
  125. def do_delete(self, args):
  126. store = self.open_store(args.archive)
  127. key = Key(store)
  128. cache = Cache(store, key)
  129. archive = Archive(store, key, args.archive.archive, cache=cache)
  130. archive.delete(cache)
  131. return self.exit_code
  132. def do_list(self, args):
  133. def callback(item):
  134. type = tmap.get(item['mode'] / 4096, '?')
  135. mode = format_file_mode(item['mode'])
  136. size = 0
  137. if type == '-':
  138. try:
  139. size = sum(size for _, size, _ in item['chunks'])
  140. except KeyError:
  141. pass
  142. mtime = format_time(datetime.fromtimestamp(item['mtime']))
  143. if 'source' in item:
  144. if type == 'l':
  145. extra = ' -> %s' % item['source']
  146. else:
  147. type = 'h'
  148. extra = ' link to %s' % item['source']
  149. else:
  150. extra = ''
  151. print '%s%s %-6s %-6s %8d %s %s%s' % (type, mode, item['user'],
  152. item['group'], size, mtime,
  153. item['path'], extra)
  154. store = self.open_store(args.src)
  155. key = Key(store)
  156. if args.src.archive:
  157. tmap = {1: 'p', 2: 'c', 4: 'd', 6: 'b', 010: '-', 012: 'l', 014: 's'}
  158. archive = Archive(store, key, args.src.archive)
  159. archive.iter_items(callback)
  160. store.flush_rpc()
  161. else:
  162. for archive in sorted(Archive.list_archives(store, key), key=attrgetter('ts')):
  163. print '%-20s %s' % (archive.metadata['name'], to_localtime(archive.ts).strftime('%c'))
  164. return self.exit_code
  165. def do_verify(self, args):
  166. store = self.open_store(args.archive)
  167. key = Key(store)
  168. archive = Archive(store, key, args.archive.archive)
  169. def start_cb(item):
  170. self.print_verbose('%s ...', item['path'].decode('utf-8'), newline=False)
  171. def result_cb(item, success):
  172. if success:
  173. self.print_verbose('OK')
  174. else:
  175. self.print_verbose('ERROR')
  176. self.print_error('%s: verification failed' % item['path'])
  177. def callback(item):
  178. if exclude_path(item['path'], args.patterns):
  179. return
  180. if stat.S_ISREG(item['mode']) and 'chunks' in item:
  181. archive.verify_file(item, start_cb, result_cb)
  182. archive.iter_items(callback)
  183. store.flush_rpc()
  184. return self.exit_code
  185. def do_info(self, args):
  186. store = self.open_store(args.archive)
  187. key = Key(store)
  188. cache = Cache(store, key)
  189. archive = Archive(store, key, args.archive.archive, cache=cache)
  190. stats = archive.stats(cache)
  191. print 'Name:', archive.metadata['name']
  192. print 'Hostname:', archive.metadata['hostname']
  193. print 'Username:', archive.metadata['username']
  194. print 'Time:', archive.metadata['time']
  195. print 'Command line:', ' '.join(archive.metadata['cmdline'])
  196. print 'Original size:', format_file_size(stats['osize'])
  197. print 'Compressed size:', format_file_size(stats['csize'])
  198. print 'Unique data:', format_file_size(stats['usize'])
  199. return self.exit_code
  200. def run(self, args=None):
  201. dot_path = os.path.join(os.path.expanduser('~'), '.darc')
  202. if not os.path.exists(dot_path):
  203. os.mkdir(dot_path)
  204. os.mkdir(os.path.join(dot_path, 'keys'))
  205. os.mkdir(os.path.join(dot_path, 'cache'))
  206. parser = argparse.ArgumentParser(description='DARC - Deduplicating Archiver')
  207. parser.add_argument('-v', '--verbose', dest='verbose', action='store_true',
  208. default=False,
  209. help='Verbose output')
  210. subparsers = parser.add_subparsers(title='Available subcommands')
  211. subparser = subparsers.add_parser('serve')
  212. subparser.set_defaults(func=self.do_serve)
  213. subparser = subparsers.add_parser('init')
  214. subparser.set_defaults(func=self.do_init)
  215. subparser.add_argument('store', metavar='ARCHIVE',
  216. type=location_validator(archive=False),
  217. help='Store to create')
  218. subparser = subparsers.add_parser('create')
  219. subparser.set_defaults(func=self.do_create)
  220. subparser.add_argument('-i', '--include', dest='patterns',
  221. type=IncludePattern, action='append',
  222. help='Include condition')
  223. subparser.add_argument('-e', '--exclude', dest='patterns',
  224. type=ExcludePattern, action='append',
  225. help='Include condition')
  226. subparser.add_argument('archive', metavar='ARCHIVE',
  227. type=location_validator(archive=True),
  228. help='Archive to create')
  229. subparser.add_argument('paths', metavar='PATH', nargs='+', type=str,
  230. help='Paths to add to archive')
  231. subparser = subparsers.add_parser('extract')
  232. subparser.set_defaults(func=self.do_extract)
  233. subparser.add_argument('-i', '--include', dest='patterns',
  234. type=IncludePattern, action='append',
  235. help='Include condition')
  236. subparser.add_argument('-e', '--exclude', dest='patterns',
  237. type=ExcludePattern, action='append',
  238. help='Include condition')
  239. subparser.add_argument('archive', metavar='ARCHIVE',
  240. type=location_validator(archive=True),
  241. help='Archive to create')
  242. subparser.add_argument('dest', metavar='DEST', type=str, nargs='?',
  243. help='Where to extract files')
  244. subparser = subparsers.add_parser('delete')
  245. subparser.set_defaults(func=self.do_delete)
  246. subparser.add_argument('archive', metavar='ARCHIVE',
  247. type=location_validator(archive=True),
  248. help='Archive to delete')
  249. subparser = subparsers.add_parser('list')
  250. subparser.set_defaults(func=self.do_list)
  251. subparser.add_argument('src', metavar='SRC', type=location_validator(),
  252. help='Store/Archive to list contents of')
  253. subparser= subparsers.add_parser('verify')
  254. subparser.set_defaults(func=self.do_verify)
  255. subparser.add_argument('-i', '--include', dest='patterns',
  256. type=IncludePattern, action='append',
  257. help='Include condition')
  258. subparser.add_argument('-e', '--exclude', dest='patterns',
  259. type=ExcludePattern, action='append',
  260. help='Include condition')
  261. subparser.add_argument('archive', metavar='ARCHIVE',
  262. type=location_validator(archive=True),
  263. help='Archive to verity integrity of')
  264. subparser= subparsers.add_parser('info')
  265. subparser.set_defaults(func=self.do_info)
  266. subparser.add_argument('archive', metavar='ARCHIVE',
  267. type=location_validator(archive=True),
  268. help='Archive to display information about')
  269. args = parser.parse_args(args)
  270. self.verbose = args.verbose
  271. return args.func(args)
  272. def main():
  273. archiver = Archiver()
  274. sys.exit(archiver.run())
  275. if __name__ == '__main__':
  276. main()