archiver.py 13 KB

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