helpers.py 12 KB

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