helpers.py 14 KB

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