helpers.py 12 KB

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