helpers.py 13 KB

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