helpers.py 17 KB

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