2
0

helpers.py 13 KB

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