helpers.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  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: 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 format_time(t):
  224. """Format datetime suitable for fixed length list output
  225. """
  226. if abs((datetime.now() - t).days) < 365:
  227. return t.strftime('%b %d %H:%M')
  228. else:
  229. return t.strftime('%b %d %Y')
  230. def format_timedelta(td):
  231. """Format timedelta in a human friendly format
  232. """
  233. # Since td.total_seconds() requires python 2.7
  234. ts = (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10 ** 6) / float(10 ** 6)
  235. s = ts % 60
  236. m = int(ts / 60) % 60
  237. h = int(ts / 3600) % 24
  238. txt = '%.2f seconds' % s
  239. if m:
  240. txt = '%d minutes %s' % (m, txt)
  241. if h:
  242. txt = '%d hours %s' % (h, txt)
  243. if td.days:
  244. txt = '%d days %s' % (td.days, txt)
  245. return txt
  246. def format_file_mode(mod):
  247. """Format file mode bits for list output
  248. """
  249. def x(v):
  250. return ''.join(v & m and s or '-'
  251. for m, s in ((4, 'r'), (2, 'w'), (1, 'x')))
  252. return '%s%s%s' % (x(mod // 64), x(mod // 8), x(mod))
  253. def format_file_size(v):
  254. """Format file size into a human friendly format
  255. """
  256. if abs(v) > 10**12:
  257. return '%.2f TB' % (v / 10**12)
  258. elif abs(v) > 10**9:
  259. return '%.2f GB' % (v / 10**9)
  260. elif abs(v) > 10**6:
  261. return '%.2f MB' % (v / 10**6)
  262. elif abs(v) > 10**3:
  263. return '%.2f kB' % (v / 10**3)
  264. else:
  265. return '%d B' % v
  266. def format_archive(archive):
  267. return '%-36s %s' % (archive.name, to_localtime(archive.ts).strftime('%c'))
  268. class IntegrityError(Error):
  269. """Data integrity error"""
  270. def memoize(function):
  271. cache = {}
  272. def decorated_function(*args):
  273. try:
  274. return cache[args]
  275. except KeyError:
  276. val = function(*args)
  277. cache[args] = val
  278. return val
  279. return decorated_function
  280. @memoize
  281. def uid2user(uid, default=None):
  282. try:
  283. return pwd.getpwuid(uid).pw_name
  284. except KeyError:
  285. return default
  286. @memoize
  287. def user2uid(user, default=None):
  288. try:
  289. return user and pwd.getpwnam(user).pw_uid
  290. except KeyError:
  291. return default
  292. @memoize
  293. def gid2group(gid, default=None):
  294. try:
  295. return grp.getgrgid(gid).gr_name
  296. except KeyError:
  297. return default
  298. @memoize
  299. def group2gid(group, default=None):
  300. try:
  301. return group and grp.getgrnam(group).gr_gid
  302. except KeyError:
  303. return default
  304. def posix_acl_use_stored_uid_gid(acl):
  305. """Replace the user/group field with the stored uid/gid
  306. """
  307. entries = []
  308. for entry in acl.decode('ascii').split('\n'):
  309. if entry:
  310. fields = entry.split(':')
  311. if len(fields) == 4:
  312. entries.append(':'.join([fields[0], fields[3], fields[2]]))
  313. else:
  314. entries.append(entry)
  315. return ('\n'.join(entries)).encode('ascii')
  316. class Location:
  317. """Object representing a repository / archive location
  318. """
  319. proto = user = host = port = path = archive = None
  320. ssh_re = re.compile(r'(?P<proto>ssh)://(?:(?P<user>[^@]+)@)?'
  321. r'(?P<host>[^:/#]+)(?::(?P<port>\d+))?'
  322. r'(?P<path>[^:]+)(?:::(?P<archive>.+))?$')
  323. file_re = re.compile(r'(?P<proto>file)://'
  324. r'(?P<path>[^:]+)(?:::(?P<archive>.+))?$')
  325. scp_re = re.compile(r'((?:(?P<user>[^@]+)@)?(?P<host>[^:/]+):)?'
  326. r'(?P<path>[^:]+)(?:::(?P<archive>.+))?$')
  327. def __init__(self, text):
  328. self.orig = text
  329. if not self.parse(text):
  330. raise ValueError
  331. def parse(self, text):
  332. m = self.ssh_re.match(text)
  333. if m:
  334. self.proto = m.group('proto')
  335. self.user = m.group('user')
  336. self.host = m.group('host')
  337. self.port = m.group('port') and int(m.group('port')) or None
  338. self.path = m.group('path')
  339. self.archive = m.group('archive')
  340. return True
  341. m = self.file_re.match(text)
  342. if m:
  343. self.proto = m.group('proto')
  344. self.path = m.group('path')
  345. self.archive = m.group('archive')
  346. return True
  347. m = self.scp_re.match(text)
  348. if m:
  349. self.user = m.group('user')
  350. self.host = m.group('host')
  351. self.path = m.group('path')
  352. self.archive = m.group('archive')
  353. self.proto = self.host and 'ssh' or 'file'
  354. return True
  355. return False
  356. def __str__(self):
  357. items = []
  358. items.append('proto=%r' % self.proto)
  359. items.append('user=%r' % self.user)
  360. items.append('host=%r' % self.host)
  361. items.append('port=%r' % self.port)
  362. items.append('path=%r' % self.path)
  363. items.append('archive=%r' % self.archive)
  364. return ', '.join(items)
  365. def to_key_filename(self):
  366. name = re.sub('[^\w]', '_', self.path).strip('_')
  367. if self.proto != 'file':
  368. name = self.host + '__' + name
  369. return os.path.join(get_keys_dir(), name)
  370. def __repr__(self):
  371. return "Location(%s)" % self
  372. def canonical_path(self):
  373. if self.proto == 'file':
  374. return self.path
  375. else:
  376. if self.path and self.path.startswith('~'):
  377. path = '/' + self.path
  378. elif self.path and not self.path.startswith('/'):
  379. path = '/~/' + self.path
  380. else:
  381. path = self.path
  382. return 'ssh://{}{}{}{}'.format('{}@'.format(self.user) if self.user else '',
  383. self.host,
  384. ':{}'.format(self.port) if self.port else '',
  385. path)
  386. def location_validator(archive=None):
  387. def validator(text):
  388. try:
  389. loc = Location(text)
  390. except ValueError:
  391. raise argparse.ArgumentTypeError('Invalid location format: "%s"' % text)
  392. if archive is True and not loc.archive:
  393. raise argparse.ArgumentTypeError('"%s": No archive specified' % text)
  394. elif archive is False and loc.archive:
  395. raise argparse.ArgumentTypeError('"%s" No archive can be specified' % text)
  396. return loc
  397. return validator
  398. def read_msgpack(filename):
  399. with open(filename, 'rb') as fd:
  400. return msgpack.unpack(fd)
  401. def write_msgpack(filename, d):
  402. with open(filename + '.tmp', 'wb') as fd:
  403. msgpack.pack(d, fd)
  404. fd.flush()
  405. os.fsync(fd)
  406. os.rename(filename + '.tmp', filename)
  407. def decode_dict(d, keys, encoding='utf-8', errors='surrogateescape'):
  408. for key in keys:
  409. if isinstance(d.get(key), bytes):
  410. d[key] = d[key].decode(encoding, errors)
  411. return d
  412. def remove_surrogates(s, errors='replace'):
  413. """Replace surrogates generated by fsdecode with '?'
  414. """
  415. return s.encode('utf-8', errors).decode('utf-8')
  416. _safe_re = re.compile(r'^((\.\.)?/+)+')
  417. def make_path_safe(path):
  418. """Make path safe by making it relative and local
  419. """
  420. return _safe_re.sub('', path) or '.'
  421. def daemonize():
  422. """Detach process from controlling terminal and run in background
  423. """
  424. pid = os.fork()
  425. if pid:
  426. os._exit(0)
  427. os.setsid()
  428. pid = os.fork()
  429. if pid:
  430. os._exit(0)
  431. os.chdir('/')
  432. os.close(0)
  433. os.close(1)
  434. os.close(2)
  435. fd = os.open('/dev/null', os.O_RDWR)
  436. os.dup2(fd, 0)
  437. os.dup2(fd, 1)
  438. os.dup2(fd, 2)
  439. class StableDict(dict):
  440. """A dict subclass with stable items() ordering"""
  441. def items(self):
  442. return sorted(super(StableDict, self).items())
  443. if sys.version < '3.3':
  444. # st_mtime_ns attribute only available in 3.3+
  445. def st_mtime_ns(st):
  446. return int(st.st_mtime * 1e9)
  447. # unhexlify in < 3.3 incorrectly only accepts bytes input
  448. def unhexlify(data):
  449. if isinstance(data, str):
  450. data = data.encode('ascii')
  451. return binascii.unhexlify(data)
  452. else:
  453. def st_mtime_ns(st):
  454. return st.st_mtime_ns
  455. unhexlify = binascii.unhexlify
  456. def bigint_to_int(mtime):
  457. """Convert bytearray to int
  458. """
  459. if isinstance(mtime, bytes):
  460. return int.from_bytes(mtime, 'little', signed=True)
  461. return mtime
  462. def int_to_bigint(value):
  463. """Convert integers larger than 64 bits to bytearray
  464. Smaller integers are left alone
  465. """
  466. if value.bit_length() > 63:
  467. return value.to_bytes((value.bit_length() + 9) // 8, 'little', signed=True)
  468. return value