helpers.py 14 KB

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