helpers.py 16 KB

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