2
0

archiver.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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, '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, 'ignore')
  33. if kw.get('newline', True):
  34. print msg
  35. else:
  36. print msg,
  37. def do_init(self, args):
  38. self.open_store(args.store, create=True)
  39. return self.exit_code
  40. def do_serve(self, args):
  41. return StoreServer().serve()
  42. def do_create(self, args):
  43. store = self.open_store(args.archive)
  44. keychain = Keychain(args.keychain)
  45. try:
  46. Archive(store, keychain, args.archive.archive)
  47. except Archive.DoesNotExist:
  48. pass
  49. else:
  50. self.print_error('Archive already exists')
  51. return self.exit_code
  52. archive = Archive(store, keychain)
  53. cache = Cache(store, keychain)
  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 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. store = self.open_store(args.archive)
  106. keychain = Keychain(args.keychain)
  107. archive = Archive(store, keychain, args.archive.archive)
  108. dirs = []
  109. for item in archive.get_items():
  110. if exclude_path(item['path'], args.patterns):
  111. continue
  112. self.print_verbose(item['path'].decode('utf-8'))
  113. archive.extract_item(item, args.dest)
  114. if stat.S_ISDIR(item['mode']):
  115. dirs.append(item)
  116. if dirs and not item['path'].startswith(dirs[-1]['path']):
  117. # Extract directories twice to make sure mtime is correctly restored
  118. archive.extract_item(dirs.pop(-1), args.dest)
  119. while dirs:
  120. archive.extract_item(dirs.pop(-1), args.dest)
  121. return self.exit_code
  122. def do_delete(self, args):
  123. store = self.open_store(args.archive)
  124. keychain = Keychain(args.keychain)
  125. archive = Archive(store, keychain, args.archive.archive)
  126. cache = Cache(store, keychain)
  127. archive.delete(cache)
  128. return self.exit_code
  129. def do_list(self, args):
  130. store = self.open_store(args.src)
  131. keychain = Keychain(args.keychain)
  132. if args.src.archive:
  133. tmap = {1: 'p', 2: 'c', 4: 'd', 6: 'b', 010: '-', 012: 'l', 014: 's'}
  134. archive = Archive(store, keychain, args.src.archive)
  135. for item in archive.get_items():
  136. type = tmap.get(item['mode'] / 4096, '?')
  137. mode = format_file_mode(item['mode'])
  138. size = item.get('size', 0)
  139. mtime = format_time(datetime.fromtimestamp(item['mtime']))
  140. print '%s%s %-6s %-6s %8d %s %s' % (type, mode, item['user'],
  141. item['group'], size, mtime, item['path'])
  142. else:
  143. for archive in sorted(Archive.list_archives(store, keychain), key=attrgetter('ts')):
  144. print '%-20s %s' % (archive.metadata['name'], to_localtime(archive.ts).strftime('%c'))
  145. return self.exit_code
  146. def do_verify(self, args):
  147. store = self.open_store(args.archive)
  148. keychain = Keychain(args.keychain)
  149. archive = Archive(store, keychain, args.archive.archive)
  150. for item in archive.get_items():
  151. if stat.S_ISREG(item['mode']) and not 'source' in item:
  152. self.print_verbose('%s ...', item['path'].decode('utf-8'), newline=False)
  153. if archive.verify_file(item):
  154. self.print_verbose('OK')
  155. else:
  156. self.print_verbose('ERROR')
  157. self.print_error('%s: verification failed' % item['path'])
  158. return self.exit_code
  159. def do_info(self, args):
  160. store = self.open_store(args.archive)
  161. keychain = Keychain(args.keychain)
  162. archive = Archive(store, keychain, args.archive.archive)
  163. cache = Cache(store, keychain)
  164. osize, csize, usize = archive.stats(cache)
  165. print 'Name:', archive.metadata['name']
  166. print 'Hostname:', archive.metadata['hostname']
  167. print 'Username:', archive.metadata['username']
  168. print 'Time:', archive.metadata['time']
  169. print 'Command line:', ' '.join(archive.metadata['cmdline'])
  170. print 'Original size:', format_file_size(osize)
  171. print 'Compressed size:', format_file_size(csize)
  172. print 'Unique data:', format_file_size(usize)
  173. return self.exit_code
  174. def do_init_keychain(self, args):
  175. return Keychain.generate(args.keychain)
  176. def do_export_restricted(self, args):
  177. keychain = Keychain(args.keychain)
  178. keychain.restrict(args.output)
  179. return self.exit_code
  180. def do_keychain_chpass(self, args):
  181. return Keychain(args.keychain).chpass()
  182. def run(self, args=None):
  183. dot_path = os.path.join(os.path.expanduser('~'), '.darc')
  184. if not os.path.exists(dot_path):
  185. os.mkdir(dot_path)
  186. default_keychain = os.path.join(os.path.expanduser('~'),
  187. '.darc', 'keychain')
  188. parser = argparse.ArgumentParser(description='DARC - Deduplicating Archiver')
  189. parser.add_argument('-k', '--keychain', dest='keychain', type=str,
  190. default=default_keychain,
  191. help='Keychain to use')
  192. parser.add_argument('-v', '--verbose', dest='verbose', action='store_true',
  193. default=False,
  194. help='Verbose output')
  195. subparsers = parser.add_subparsers(title='Available subcommands')
  196. subparser = subparsers.add_parser('init-keychain')
  197. subparser.set_defaults(func=self.do_init_keychain)
  198. subparser = subparsers.add_parser('export-restricted')
  199. subparser.add_argument('output', metavar='OUTPUT', type=str,
  200. help='Keychain to create')
  201. subparser.set_defaults(func=self.do_export_restricted)
  202. subparser = subparsers.add_parser('change-password')
  203. subparser.set_defaults(func=self.do_keychain_chpass)
  204. subparser = subparsers.add_parser('init')
  205. subparser.set_defaults(func=self.do_init)
  206. subparser.add_argument('store', metavar='STORE',
  207. type=location_validator(archive=False),
  208. help='Store to initialize')
  209. subparser = subparsers.add_parser('serve')
  210. subparser.set_defaults(func=self.do_serve)
  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('archive', metavar='ARCHIVE',
  249. type=location_validator(archive=True),
  250. help='Archive to verity integrity of')
  251. subparser= subparsers.add_parser('info')
  252. subparser.set_defaults(func=self.do_info)
  253. subparser.add_argument('archive', metavar='ARCHIVE',
  254. type=location_validator(archive=True),
  255. help='Archive to display information about')
  256. args = parser.parse_args(args)
  257. self.verbose = args.verbose
  258. return args.func(args)
  259. def main():
  260. archiver = Archiver()
  261. sys.exit(archiver.run())
  262. if __name__ == '__main__':
  263. main()