remote.py 12 KB

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