helpers.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. import argparse
  2. import binascii
  3. import grp
  4. import msgpack
  5. import os
  6. import pwd
  7. import re
  8. import stat
  9. import sys
  10. import time
  11. from datetime import datetime, timezone, timedelta
  12. from fnmatch import translate
  13. from operator import attrgetter
  14. import fcntl
  15. import attic.hashindex
  16. import attic.chunker
  17. import attic.crypto
  18. class Error(Exception):
  19. """Error base class"""
  20. exit_code = 1
  21. def get_message(self):
  22. return 'Error: ' + type(self).__doc__.format(*self.args)
  23. class ExtensionModuleError(Error):
  24. """The Attic binary extension modules does not seem to be properly installed"""
  25. class UpgradableLock:
  26. class LockUpgradeFailed(Error):
  27. """Failed to acquire write lock on {}"""
  28. def __init__(self, path, exclusive=False):
  29. self.path = path
  30. try:
  31. self.fd = open(path, 'r+')
  32. except IOError:
  33. self.fd = open(path, 'r')
  34. if exclusive:
  35. fcntl.lockf(self.fd, fcntl.LOCK_EX)
  36. else:
  37. fcntl.lockf(self.fd, fcntl.LOCK_SH)
  38. self.is_exclusive = exclusive
  39. def upgrade(self):
  40. try:
  41. fcntl.lockf(self.fd, fcntl.LOCK_EX)
  42. except OSError as e:
  43. raise self.LockUpgradeFailed(self.path)
  44. self.is_exclusive = True
  45. def release(self):
  46. fcntl.lockf(self.fd, fcntl.LOCK_UN)
  47. self.fd.close()
  48. def check_extension_modules():
  49. import attic.platform
  50. if (attic.hashindex.API_VERSION != 1 or
  51. attic.chunker.API_VERSION != 1 or
  52. attic.crypto.API_VERSION != 1 or
  53. attic.platform.API_VERSION != 1):
  54. raise ExtensionModuleError
  55. class Manifest:
  56. MANIFEST_ID = b'\0' * 32
  57. def __init__(self, key, repository):
  58. self.archives = {}
  59. self.config = {}
  60. self.key = key
  61. self.repository = repository
  62. @classmethod
  63. def load(cls, repository, key=None):
  64. from .key import key_factory
  65. cdata = repository.get(cls.MANIFEST_ID)
  66. if not key:
  67. key = key_factory(repository, cdata)
  68. manifest = cls(key, repository)
  69. data = key.decrypt(None, cdata)
  70. manifest.id = key.id_hash(data)
  71. m = msgpack.unpackb(data)
  72. if not m.get(b'version') == 1:
  73. raise ValueError('Invalid manifest version')
  74. manifest.archives = dict((k.decode('utf-8'), v) for k,v in m[b'archives'].items())
  75. manifest.timestamp = m.get(b'timestamp')
  76. if manifest.timestamp:
  77. manifest.timestamp = manifest.timestamp.decode('ascii')
  78. manifest.config = m[b'config']
  79. return manifest, key
  80. def write(self):
  81. self.timestamp = datetime.utcnow().isoformat()
  82. data = msgpack.packb(StableDict({
  83. 'version': 1,
  84. 'archives': self.archives,
  85. 'timestamp': self.timestamp,
  86. 'config': self.config,
  87. }))
  88. self.id = self.key.id_hash(data)
  89. self.repository.put(self.MANIFEST_ID, self.key.encrypt(data))
  90. def prune_within(archives, within):
  91. multiplier = {'H': 1, 'd': 24, 'w': 24*7, 'm': 24*31, 'y': 24*365}
  92. try:
  93. hours = int(within[:-1]) * multiplier[within[-1]]
  94. except (KeyError, ValueError):
  95. # I don't like how this displays the original exception too:
  96. raise argparse.ArgumentTypeError('Unable to parse --within option: "%s"' % within)
  97. if hours <= 0:
  98. raise argparse.ArgumentTypeError('Number specified using --within option must be positive')
  99. target = datetime.now(timezone.utc) - timedelta(seconds=hours*60*60)
  100. return [a for a in archives if a.ts > target]
  101. def prune_split(archives, pattern, n, skip=[]):
  102. last = None
  103. keep = []
  104. if n == 0:
  105. return keep
  106. for a in sorted(archives, key=attrgetter('ts'), reverse=True):
  107. period = to_localtime(a.ts).strftime(pattern)
  108. if period != last:
  109. last = period
  110. if a not in skip:
  111. keep.append(a)
  112. if len(keep) == n: break
  113. return keep
  114. class Statistics:
  115. def __init__(self):
  116. self.osize = self.csize = self.usize = self.nfiles = 0
  117. def update(self, size, csize, unique):
  118. self.osize += size
  119. self.csize += csize
  120. if unique:
  121. self.usize += csize
  122. def print_(self, label, cache):
  123. total_size, total_csize, unique_size, unique_csize = cache.chunks.summarize()
  124. print()
  125. print(' Original size Compressed size Deduplicated size')
  126. print('%-15s %20s %20s %20s' % (label, format_file_size(self.osize), format_file_size(self.csize), format_file_size(self.usize)))
  127. print('All archives: %20s %20s %20s' % (format_file_size(total_size), format_file_size(total_csize), format_file_size(unique_csize)))
  128. def get_keys_dir():
  129. """Determine where to repository keys and cache"""
  130. return os.environ.get('ATTIC_KEYS_DIR',
  131. os.path.join(os.path.expanduser('~'), '.attic', 'keys'))
  132. def get_cache_dir():
  133. """Determine where to repository keys and cache"""
  134. return os.environ.get('ATTIC_CACHE_DIR',
  135. os.path.join(os.path.expanduser('~'), '.cache', 'attic'))
  136. def to_localtime(ts):
  137. """Convert datetime object from UTC to local time zone"""
  138. return datetime(*time.localtime((ts - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds())[:6])
  139. def update_excludes(args):
  140. """Merge exclude patterns from files with those on command line.
  141. Empty lines and lines starting with '#' are ignored, but whitespace
  142. is not stripped."""
  143. if hasattr(args, 'exclude_files') and args.exclude_files:
  144. if not hasattr(args, 'excludes') or args.excludes is None:
  145. args.excludes = []
  146. for file in args.exclude_files:
  147. patterns = [line.rstrip('\r\n') for line in file if not line.startswith('#')]
  148. args.excludes += [ExcludePattern(pattern) for pattern in patterns if pattern]
  149. file.close()
  150. def adjust_patterns(paths, excludes):
  151. if paths:
  152. return (excludes or []) + [IncludePattern(path) for path in paths] + [ExcludePattern('*')]
  153. else:
  154. return excludes
  155. def exclude_path(path, patterns):
  156. """Used by create and extract sub-commands to determine
  157. whether or not an item should be processed.
  158. """
  159. for pattern in (patterns or []):
  160. if pattern.match(path):
  161. return isinstance(pattern, ExcludePattern)
  162. return False
  163. # For both IncludePattern and ExcludePattern, we require that
  164. # the pattern either match the whole path or an initial segment
  165. # of the path up to but not including a path separator. To
  166. # unify the two cases, we add a path separator to the end of
  167. # the path before matching.
  168. class IncludePattern:
  169. """Literal files or directories listed on the command line
  170. for some operations (e.g. extract, but not create).
  171. If a directory is specified, all paths that start with that
  172. path match as well. A trailing slash makes no difference.
  173. """
  174. def __init__(self, pattern):
  175. self.pattern = pattern.rstrip(os.path.sep)+os.path.sep
  176. def match(self, path):
  177. return (path+os.path.sep).startswith(self.pattern)
  178. def __repr__(self):
  179. return '%s(%s)' % (type(self), self.pattern)
  180. class ExcludePattern(IncludePattern):
  181. """Shell glob patterns to exclude. A trailing slash means to
  182. exclude the contents of a directory, but not the directory itself.
  183. """
  184. def __init__(self, pattern):
  185. if pattern.endswith(os.path.sep):
  186. self.pattern = pattern+'*'+os.path.sep
  187. else:
  188. self.pattern = pattern+os.path.sep+'*'
  189. # fnmatch and re.match both cache compiled regular expressions.
  190. # Nevertheless, this is about 10 times faster.
  191. self.regex = re.compile(translate(self.pattern))
  192. def match(self, path):
  193. return self.regex.match(path+os.path.sep) is not None
  194. def __repr__(self):
  195. return '%s(%s)' % (type(self), self.pattern)
  196. def walk_path(path, skip_inodes=None):
  197. st = os.lstat(path)
  198. if skip_inodes and (st.st_ino, st.st_dev) in skip_inodes:
  199. return
  200. yield path, st
  201. if stat.S_ISDIR(st.st_mode):
  202. for f in os.listdir(path):
  203. for x in walk_path(os.path.join(path, f), skip_inodes):
  204. yield x
  205. def format_time(t):
  206. """Format datetime suitable for fixed length list output
  207. """
  208. if (datetime.now() - t).days < 365:
  209. return t.strftime('%b %d %H:%M')
  210. else:
  211. return t.strftime('%b %d %Y')
  212. def format_timedelta(td):
  213. """Format timedelta in a human friendly format
  214. """
  215. # Since td.total_seconds() requires python 2.7
  216. ts = (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10 ** 6) / float(10 ** 6)
  217. s = ts % 60
  218. m = int(ts / 60) % 60
  219. h = int(ts / 3600) % 24
  220. txt = '%.2f seconds' % s
  221. if m:
  222. txt = '%d minutes %s' % (m, txt)
  223. if h:
  224. txt = '%d hours %s' % (h, txt)
  225. if td.days:
  226. txt = '%d days %s' % (td.days, txt)
  227. return txt
  228. def format_file_mode(mod):
  229. """Format file mode bits for list output
  230. """
  231. def x(v):
  232. return ''.join(v & m and s or '-'
  233. for m, s in ((4, 'r'), (2, 'w'), (1, 'x')))
  234. return '%s%s%s' % (x(mod // 64), x(mod // 8), x(mod))
  235. def format_file_size(v):
  236. """Format file size into a human friendly format
  237. """
  238. if abs(v) > 10**12:
  239. return '%.2f TB' % (v / 10**12)
  240. elif abs(v) > 10**9:
  241. return '%.2f GB' % (v / 10**9)
  242. elif abs(v) > 10**6:
  243. return '%.2f MB' % (v / 10**6)
  244. elif abs(v) > 10**3:
  245. return '%.2f kB' % (v / 10**3)
  246. else:
  247. return '%d B' % v
  248. def format_archive(archive):
  249. return '%-36s %s' % (archive.name, to_localtime(archive.ts).strftime('%c'))
  250. class IntegrityError(Error):
  251. """Data integrity error"""
  252. def memoize(function):
  253. cache = {}
  254. def decorated_function(*args):
  255. try:
  256. return cache[args]
  257. except KeyError:
  258. val = function(*args)
  259. cache[args] = val
  260. return val
  261. return decorated_function
  262. @memoize
  263. def uid2user(uid, default=None):
  264. try:
  265. return pwd.getpwuid(uid).pw_name
  266. except KeyError:
  267. return default
  268. @memoize
  269. def user2uid(user, default=None):
  270. try:
  271. return user and pwd.getpwnam(user).pw_uid
  272. except KeyError:
  273. return default
  274. @memoize
  275. def gid2group(gid, default=None):
  276. try:
  277. return grp.getgrgid(gid).gr_name
  278. except KeyError:
  279. return default
  280. @memoize
  281. def group2gid(group, default=None):
  282. try:
  283. return group and grp.getgrnam(group).gr_gid
  284. except KeyError:
  285. return default
  286. def posix_acl_use_stored_uid_gid(acl):
  287. """Replace the user/group field with the stored uid/gid
  288. """
  289. entries = []
  290. for entry in acl.decode('ascii').split('\n'):
  291. if entry:
  292. fields = entry.split(':')
  293. if len(fields) == 4:
  294. entries.append(':'.join([fields[0], fields[3], fields[2]]))
  295. else:
  296. entries.append(entry)
  297. return ('\n'.join(entries)).encode('ascii')
  298. class Location:
  299. """Object representing a repository / archive location
  300. """
  301. proto = user = host = port = path = archive = None
  302. ssh_re = re.compile(r'(?P<proto>ssh)://(?:(?P<user>[^@]+)@)?'
  303. r'(?P<host>[^:/#]+)(?::(?P<port>\d+))?'
  304. r'(?P<path>[^:]+)(?:::(?P<archive>.+))?')
  305. file_re = re.compile(r'(?P<proto>file)://'
  306. r'(?P<path>[^:]+)(?:::(?P<archive>.+))?')
  307. scp_re = re.compile(r'((?:(?P<user>[^@]+)@)?(?P<host>[^:/]+):)?'
  308. r'(?P<path>[^:]+)(?:::(?P<archive>.+))?')
  309. def __init__(self, text):
  310. self.orig = text
  311. if not self.parse(text):
  312. raise ValueError
  313. def parse(self, text):
  314. m = self.ssh_re.match(text)
  315. if m:
  316. self.proto = m.group('proto')
  317. self.user = m.group('user')
  318. self.host = m.group('host')
  319. self.port = m.group('port') and int(m.group('port')) or None
  320. self.path = m.group('path')
  321. self.archive = m.group('archive')
  322. return True
  323. m = self.file_re.match(text)
  324. if m:
  325. self.proto = m.group('proto')
  326. self.path = m.group('path')
  327. self.archive = m.group('archive')
  328. return True
  329. m = self.scp_re.match(text)
  330. if m:
  331. self.user = m.group('user')
  332. self.host = m.group('host')
  333. self.path = m.group('path')
  334. self.archive = m.group('archive')
  335. self.proto = self.host and 'ssh' or 'file'
  336. return True
  337. return False
  338. def __str__(self):
  339. items = []
  340. items.append('proto=%r' % self.proto)
  341. items.append('user=%r' % self.user)
  342. items.append('host=%r' % self.host)
  343. items.append('port=%r' % self.port)
  344. items.append('path=%r' % self.path)
  345. items.append('archive=%r' % self.archive)
  346. return ', '.join(items)
  347. def to_key_filename(self):
  348. name = re.sub('[^\w]', '_', self.path).strip('_')
  349. if self.proto != 'file':
  350. name = self.host + '__' + name
  351. return os.path.join(get_keys_dir(), name)
  352. def __repr__(self):
  353. return "Location(%s)" % self
  354. def location_validator(archive=None):
  355. def validator(text):
  356. try:
  357. loc = Location(text)
  358. except ValueError:
  359. raise argparse.ArgumentTypeError('Invalid location format: "%s"' % text)
  360. if archive is True and not loc.archive:
  361. raise argparse.ArgumentTypeError('"%s": No archive specified' % text)
  362. elif archive is False and loc.archive:
  363. raise argparse.ArgumentTypeError('"%s" No archive can be specified' % text)
  364. return loc
  365. return validator
  366. def read_msgpack(filename):
  367. with open(filename, 'rb') as fd:
  368. return msgpack.unpack(fd)
  369. def write_msgpack(filename, d):
  370. with open(filename + '.tmp', 'wb') as fd:
  371. msgpack.pack(d, fd)
  372. fd.flush()
  373. os.fsync(fd)
  374. os.rename(filename + '.tmp', filename)
  375. def decode_dict(d, keys, encoding='utf-8', errors='surrogateescape'):
  376. for key in keys:
  377. if isinstance(d.get(key), bytes):
  378. d[key] = d[key].decode(encoding, errors)
  379. return d
  380. def remove_surrogates(s, errors='replace'):
  381. """Replace surrogates generated by fsdecode with '?'
  382. """
  383. return s.encode('utf-8', errors).decode('utf-8')
  384. _safe_re = re.compile('^((..)?/+)+')
  385. def make_path_safe(path):
  386. """Make path safe by making it relative and local
  387. """
  388. return _safe_re.sub('', path) or '.'
  389. def daemonize():
  390. """Detach process from controlling terminal and run in background
  391. """
  392. pid = os.fork()
  393. if pid:
  394. os._exit(0)
  395. os.setsid()
  396. pid = os.fork()
  397. if pid:
  398. os._exit(0)
  399. os.chdir('/')
  400. os.close(0)
  401. os.close(1)
  402. os.close(2)
  403. fd = os.open('/dev/null', os.O_RDWR)
  404. os.dup2(fd, 0)
  405. os.dup2(fd, 1)
  406. os.dup2(fd, 2)
  407. class StableDict(dict):
  408. """A dict subclass with stable items() ordering"""
  409. def items(self):
  410. return sorted(super(StableDict, self).items())
  411. if sys.version < '3.3':
  412. # st_mtime_ns attribute only available in 3.3+
  413. def st_mtime_ns(st):
  414. return int(st.st_mtime * 1e9)
  415. # unhexlify in < 3.3 incorrectly only accepts bytes input
  416. def unhexlify(data):
  417. if isinstance(data, str):
  418. data = data.encode('ascii')
  419. return binascii.unhexlify(data)
  420. else:
  421. def st_mtime_ns(st):
  422. return st.st_mtime_ns
  423. unhexlify = binascii.unhexlify