helpers.py 17 KB

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