helpers.py 17 KB

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