helpers.py 18 KB

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