remote.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. import errno
  2. import fcntl
  3. import msgpack
  4. import os
  5. import select
  6. import shutil
  7. from subprocess import Popen, PIPE
  8. import sys
  9. import tempfile
  10. from .hashindex import NSIndex
  11. from .helpers import Error, IntegrityError
  12. from .repository import Repository
  13. BUFSIZE = 10 * 1024 * 1024
  14. class ConnectionClosed(Error):
  15. """Connection closed by remote host"""
  16. class PathNotAllowed(Error):
  17. """Repository path not allowed"""
  18. class InvalidRPCMethod(Error):
  19. """RPC method is not valid"""
  20. class RepositoryServer(object):
  21. rpc_methods = (
  22. '__len__',
  23. 'check',
  24. 'commit',
  25. 'delete',
  26. 'get',
  27. 'list',
  28. 'negotiate',
  29. 'open',
  30. 'put',
  31. 'repair',
  32. 'rollback',
  33. )
  34. def __init__(self, restrict_to_paths):
  35. self.repository = None
  36. self.restrict_to_paths = restrict_to_paths
  37. def serve(self):
  38. # Make stdin non-blocking
  39. fl = fcntl.fcntl(sys.stdin.fileno(), fcntl.F_GETFL)
  40. fcntl.fcntl(sys.stdin.fileno(), fcntl.F_SETFL, fl | os.O_NONBLOCK)
  41. # Make stdout blocking
  42. fl = fcntl.fcntl(sys.stdout.fileno(), fcntl.F_GETFL)
  43. fcntl.fcntl(sys.stdout.fileno(), fcntl.F_SETFL, fl & ~os.O_NONBLOCK)
  44. unpacker = msgpack.Unpacker(use_list=False)
  45. while True:
  46. r, w, es = select.select([sys.stdin], [], [], 10)
  47. if r:
  48. data = os.read(sys.stdin.fileno(), BUFSIZE)
  49. if not data:
  50. return
  51. unpacker.feed(data)
  52. for unpacked in unpacker:
  53. if not (isinstance(unpacked, tuple) and len(unpacked) == 4):
  54. raise Exception("Unexpected RPC data format.")
  55. type, msgid, method, args = unpacked
  56. method = method.decode('ascii')
  57. try:
  58. if not method in self.rpc_methods:
  59. raise InvalidRPCMethod(method)
  60. try:
  61. f = getattr(self, method)
  62. except AttributeError:
  63. f = getattr(self.repository, method)
  64. res = f(*args)
  65. except Exception as e:
  66. sys.stdout.buffer.write(msgpack.packb((1, msgid, e.__class__.__name__, e.args)))
  67. else:
  68. sys.stdout.buffer.write(msgpack.packb((1, msgid, None, res)))
  69. sys.stdout.flush()
  70. if es:
  71. return
  72. def negotiate(self, versions):
  73. return 1
  74. def open(self, path, create=False):
  75. path = os.fsdecode(path)
  76. if path.startswith('/~'):
  77. path = path[1:]
  78. path = os.path.realpath(os.path.expanduser(path))
  79. if self.restrict_to_paths:
  80. for restrict_to_path in self.restrict_to_paths:
  81. if path.startswith(os.path.realpath(restrict_to_path)):
  82. break
  83. else:
  84. raise PathNotAllowed(path)
  85. self.repository = Repository(path, create)
  86. return self.repository.id
  87. class RemoteRepository(object):
  88. extra_test_args = []
  89. class RPCError(Exception):
  90. def __init__(self, name):
  91. self.name = name
  92. def __init__(self, location, create=False):
  93. self.location = location
  94. self.preload_ids = []
  95. self.msgid = 0
  96. self.to_send = b''
  97. self.cache = {}
  98. self.ignore_responses = set()
  99. self.responses = {}
  100. self.unpacker = msgpack.Unpacker(use_list=False)
  101. self.p = None
  102. if location.host == '__testsuite__':
  103. args = [sys.executable, '-m', 'attic.archiver', 'serve'] + self.extra_test_args
  104. else:
  105. args = ['ssh']
  106. if location.port:
  107. args += ['-p', str(location.port)]
  108. if location.user:
  109. args.append('%s@%s' % (location.user, location.host))
  110. else:
  111. args.append('%s' % location.host)
  112. args += ['attic', 'serve']
  113. self.p = Popen(args, bufsize=0, stdin=PIPE, stdout=PIPE)
  114. self.stdin_fd = self.p.stdin.fileno()
  115. self.stdout_fd = self.p.stdout.fileno()
  116. fcntl.fcntl(self.stdin_fd, fcntl.F_SETFL, fcntl.fcntl(self.stdin_fd, fcntl.F_GETFL) | os.O_NONBLOCK)
  117. fcntl.fcntl(self.stdout_fd, fcntl.F_SETFL, fcntl.fcntl(self.stdout_fd, fcntl.F_GETFL) | os.O_NONBLOCK)
  118. self.r_fds = [self.stdout_fd]
  119. self.x_fds = [self.stdin_fd, self.stdout_fd]
  120. version = self.call('negotiate', 1)
  121. if version != 1:
  122. raise Exception('Server insisted on using unsupported protocol version %d' % version)
  123. self.id = self.call('open', location.path, create)
  124. def __del__(self):
  125. self.close()
  126. def call(self, cmd, *args, **kw):
  127. for resp in self.call_many(cmd, [args], **kw):
  128. return resp
  129. def call_many(self, cmd, calls, wait=True, is_preloaded=False):
  130. if not calls:
  131. return
  132. def fetch_from_cache(args):
  133. msgid = self.cache[args].pop(0)
  134. if not self.cache[args]:
  135. del self.cache[args]
  136. return msgid
  137. calls = list(calls)
  138. waiting_for = []
  139. w_fds = [self.stdin_fd]
  140. while wait or calls:
  141. while waiting_for:
  142. try:
  143. error, res = self.responses.pop(waiting_for[0])
  144. waiting_for.pop(0)
  145. if error:
  146. if error == b'DoesNotExist':
  147. raise Repository.DoesNotExist(self.location.orig)
  148. elif error == b'AlreadyExists':
  149. raise Repository.AlreadyExists(self.location.orig)
  150. elif error == b'CheckNeeded':
  151. raise Repository.CheckNeeded(self.location.orig)
  152. elif error == b'IntegrityError':
  153. raise IntegrityError(res)
  154. elif error == b'PathNotAllowed':
  155. raise PathNotAllowed(*res)
  156. elif error == b'ObjectNotFound':
  157. raise Repository.ObjectNotFound(res[0], self.location.orig)
  158. elif error == b'InvalidRPCMethod':
  159. raise InvalidRPCMethod(*res)
  160. raise self.RPCError(error)
  161. else:
  162. yield res
  163. if not waiting_for and not calls:
  164. return
  165. except KeyError:
  166. break
  167. r, w, x = select.select(self.r_fds, w_fds, self.x_fds, 1)
  168. if x:
  169. raise Exception('FD exception occured')
  170. if r:
  171. data = os.read(self.stdout_fd, BUFSIZE)
  172. if not data:
  173. raise ConnectionClosed()
  174. self.unpacker.feed(data)
  175. for unpacked in self.unpacker:
  176. if not (isinstance(unpacked, tuple) and len(unpacked) == 4):
  177. raise Exception("Unexpected RPC data format.")
  178. type, msgid, error, res = unpacked
  179. if msgid in self.ignore_responses:
  180. self.ignore_responses.remove(msgid)
  181. else:
  182. self.responses[msgid] = error, res
  183. if w:
  184. while not self.to_send and (calls or self.preload_ids) and len(waiting_for) < 100:
  185. if calls:
  186. if is_preloaded:
  187. if calls[0] in self.cache:
  188. waiting_for.append(fetch_from_cache(calls.pop(0)))
  189. else:
  190. args = calls.pop(0)
  191. if cmd == 'get' and args in self.cache:
  192. waiting_for.append(fetch_from_cache(args))
  193. else:
  194. self.msgid += 1
  195. waiting_for.append(self.msgid)
  196. self.to_send = msgpack.packb((1, self.msgid, cmd, args))
  197. if not self.to_send and self.preload_ids:
  198. args = (self.preload_ids.pop(0),)
  199. self.msgid += 1
  200. self.cache.setdefault(args, []).append(self.msgid)
  201. self.to_send = msgpack.packb((1, self.msgid, cmd, args))
  202. if self.to_send:
  203. try:
  204. self.to_send = self.to_send[os.write(self.stdin_fd, self.to_send):]
  205. except OSError as e:
  206. # io.write might raise EAGAIN even though select indicates
  207. # that the fd should be writable
  208. if e.errno != errno.EAGAIN:
  209. raise
  210. if not self.to_send and not (calls or self.preload_ids):
  211. w_fds = []
  212. self.ignore_responses |= set(waiting_for)
  213. def check(self, repair=False):
  214. return self.call('check', repair)
  215. def commit(self, *args):
  216. return self.call('commit')
  217. def rollback(self, *args):
  218. return self.call('rollback')
  219. def __len__(self):
  220. return self.call('__len__')
  221. def list(self, limit=None, marker=None):
  222. return self.call('list', limit, marker)
  223. def get(self, id_):
  224. for resp in self.get_many([id_]):
  225. return resp
  226. def get_many(self, ids, is_preloaded=False):
  227. for resp in self.call_many('get', [(id_,) for id_ in ids], is_preloaded=is_preloaded):
  228. yield resp
  229. def put(self, id_, data, wait=True):
  230. return self.call('put', id_, data, wait=wait)
  231. def delete(self, id_, wait=True):
  232. return self.call('delete', id_, wait=wait)
  233. def close(self):
  234. if self.p:
  235. self.p.stdin.close()
  236. self.p.stdout.close()
  237. self.p.wait()
  238. self.p = None
  239. def preload(self, ids):
  240. self.preload_ids += ids
  241. class RepositoryCache:
  242. """A caching Repository wrapper
  243. Caches Repository GET operations using a temporary file
  244. """
  245. def __init__(self, repository):
  246. self.tmppath = None
  247. self.index = None
  248. self.data_fd = None
  249. self.repository = repository
  250. self.entries = {}
  251. self.initialize()
  252. def __del__(self):
  253. self.cleanup()
  254. def initialize(self):
  255. self.tmppath = tempfile.mkdtemp()
  256. self.index = NSIndex()
  257. self.data_fd = open(os.path.join(self.tmppath, 'data'), 'a+b')
  258. def cleanup(self):
  259. del self.index
  260. if self.data_fd:
  261. self.data_fd.close()
  262. if self.tmppath:
  263. shutil.rmtree(self.tmppath)
  264. def load_object(self, offset, size):
  265. self.data_fd.seek(offset)
  266. data = self.data_fd.read(size)
  267. assert len(data) == size
  268. return data
  269. def store_object(self, key, data):
  270. self.data_fd.seek(0, os.SEEK_END)
  271. self.data_fd.write(data)
  272. offset = self.data_fd.tell()
  273. self.index[key] = offset - len(data), len(data)
  274. def get(self, key):
  275. return next(self.get_many([key]))
  276. def get_many(self, keys):
  277. unknown_keys = [key for key in keys if not key in self.index]
  278. repository_iterator = zip(unknown_keys, self.repository.get_many(unknown_keys))
  279. for key in keys:
  280. try:
  281. yield self.load_object(*self.index[key])
  282. except KeyError:
  283. for key_, data in repository_iterator:
  284. if key_ == key:
  285. self.store_object(key, data)
  286. yield data
  287. break
  288. # Consume any pending requests
  289. for _ in repository_iterator:
  290. pass
  291. def cache_if_remote(repository):
  292. if isinstance(repository, RemoteRepository):
  293. return RepositoryCache(repository)
  294. return repository