archiver.py 17 KB

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