remote.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. from __future__ import with_statement
  2. import fcntl
  3. import msgpack
  4. import os
  5. import select
  6. from subprocess import Popen, PIPE
  7. import sys
  8. import getpass
  9. import unittest
  10. from .store import Store, StoreTestCase
  11. from .lrucache import LRUCache
  12. BUFSIZE = 10 * 1024 * 1024
  13. class StoreServer(object):
  14. def __init__(self):
  15. self.store = None
  16. def serve(self):
  17. # Make stdin non-blocking
  18. fl = fcntl.fcntl(sys.stdin.fileno(), fcntl.F_GETFL)
  19. fcntl.fcntl(sys.stdin.fileno(), fcntl.F_SETFL, fl | os.O_NONBLOCK)
  20. # Make stdout blocking
  21. fl = fcntl.fcntl(sys.stdout.fileno(), fcntl.F_GETFL)
  22. fcntl.fcntl(sys.stdout.fileno(), fcntl.F_SETFL, fl & ~os.O_NONBLOCK)
  23. unpacker = msgpack.Unpacker(use_list=False)
  24. while True:
  25. r, w, es = select.select([sys.stdin], [], [], 10)
  26. if r:
  27. data = os.read(sys.stdin.fileno(), BUFSIZE)
  28. if not data:
  29. return
  30. unpacker.feed(data)
  31. for type, msgid, method, args in unpacker:
  32. try:
  33. try:
  34. f = getattr(self, method)
  35. except AttributeError:
  36. f = getattr(self.store, method)
  37. res = f(*args)
  38. except Exception, e:
  39. sys.stdout.write(msgpack.packb((1, msgid, e.__class__.__name__, None)))
  40. else:
  41. sys.stdout.write(msgpack.packb((1, msgid, None, res)))
  42. sys.stdout.flush()
  43. if es:
  44. return
  45. def negotiate(self, versions):
  46. return 1
  47. def open(self, path, create=False):
  48. if path.startswith('/~'):
  49. path = path[1:]
  50. self.store = Store(os.path.expanduser(path), create)
  51. return self.store.id
  52. class RemoteStore(object):
  53. class RPCError(Exception):
  54. def __init__(self, name):
  55. self.name = name
  56. def __init__(self, location, create=False):
  57. self.p = None
  58. self.cache = LRUCache(256)
  59. self.to_send = ''
  60. self.extra = {}
  61. self.pending = {}
  62. self.unpacker = msgpack.Unpacker(use_list=False)
  63. self.msgid = 0
  64. self.received_msgid = 0
  65. args = ['ssh', '-p', str(location.port), '%s@%s' % (location.user or getpass.getuser(), location.host), 'darc', 'serve']
  66. self.p = Popen(args, bufsize=0, stdin=PIPE, stdout=PIPE)
  67. self.stdin_fd = self.p.stdin.fileno()
  68. self.stdout_fd = self.p.stdout.fileno()
  69. fcntl.fcntl(self.stdin_fd, fcntl.F_SETFL, fcntl.fcntl(self.stdin_fd, fcntl.F_GETFL) | os.O_NONBLOCK)
  70. fcntl.fcntl(self.stdout_fd, fcntl.F_SETFL, fcntl.fcntl(self.stdout_fd, fcntl.F_GETFL) | os.O_NONBLOCK)
  71. self.r_fds = [self.stdout_fd]
  72. self.x_fds = [self.stdin_fd, self.stdout_fd]
  73. version = self.call('negotiate', (1,))
  74. if version != 1:
  75. raise Exception('Server insisted on using unsupported protocol version %d' % version)
  76. try:
  77. self.id = self.call('open', (location.path, create))
  78. except self.RPCError, e:
  79. if e.name == 'DoesNotExist':
  80. raise Store.DoesNotExist
  81. elif e.name == 'AlreadyExists':
  82. raise Store.AlreadyExists
  83. def __del__(self):
  84. self.close()
  85. def call(self, cmd, args, wait=True):
  86. self.msgid += 1
  87. to_send = msgpack.packb((1, self.msgid, cmd, args))
  88. w_fds = [self.stdin_fd]
  89. while wait or to_send:
  90. r, w, x = select.select(self.r_fds, w_fds, self.x_fds, 1)
  91. if x:
  92. raise Exception('FD exception occured')
  93. if r:
  94. data = os.read(self.stdout_fd, BUFSIZE)
  95. if not data:
  96. raise Exception('Remote host closed connection')
  97. self.unpacker.feed(data)
  98. for type, msgid, error, res in self.unpacker:
  99. if msgid == self.msgid:
  100. assert msgid == self.msgid
  101. self.received_msgid = msgid
  102. if error:
  103. raise self.RPCError(error)
  104. else:
  105. return res
  106. else:
  107. args = self.pending.pop(msgid, None)
  108. if args is not None:
  109. self.cache[args] = msgid, res, error
  110. if w:
  111. if to_send:
  112. n = os.write(self.stdin_fd, to_send)
  113. assert n > 0
  114. to_send = to_send[n:]
  115. else:
  116. w_fds = []
  117. def _read(self):
  118. data = os.read(self.stdout_fd, BUFSIZE)
  119. if not data:
  120. raise Exception('Remote host closed connection')
  121. self.unpacker.feed(data)
  122. to_yield = []
  123. for type, msgid, error, res in self.unpacker:
  124. self.received_msgid = msgid
  125. args = self.pending.pop(msgid, None)
  126. if args is not None:
  127. self.cache[args] = msgid, res, error
  128. for args, resp, error in self.extra.pop(msgid, []):
  129. if not resp and not error:
  130. resp, error = self.cache[args][1:]
  131. to_yield.append((resp, error))
  132. for res, error in to_yield:
  133. if error:
  134. raise self.RPCError(error)
  135. else:
  136. yield res
  137. def gen_request(self, cmd, argsv, wait):
  138. data = []
  139. m = self.received_msgid
  140. for args in argsv:
  141. # Make sure to invalidate any existing cache entries for non-get requests
  142. if not args in self.cache:
  143. self.msgid += 1
  144. msgid = self.msgid
  145. self.pending[msgid] = args
  146. self.cache[args] = msgid, None, None
  147. data.append(msgpack.packb((1, msgid, cmd, args)))
  148. if wait:
  149. msgid, resp, error = self.cache[args]
  150. m = max(m, msgid)
  151. self.extra.setdefault(m, []).append((args, resp, error))
  152. return ''.join(data)
  153. def gen_cache_requests(self, cmd, peek):
  154. data = []
  155. while True:
  156. try:
  157. args = (peek()[0],)
  158. except StopIteration:
  159. break
  160. if args in self.cache:
  161. continue
  162. self.msgid += 1
  163. msgid = self.msgid
  164. self.pending[msgid] = args
  165. self.cache[args] = msgid, None, None
  166. data.append(msgpack.packb((1, msgid, cmd, args)))
  167. return ''.join(data)
  168. def call_multi(self, cmd, argsv, wait=True, peek=None):
  169. w_fds = [self.stdin_fd]
  170. left = len(argsv)
  171. data = self.gen_request(cmd, argsv, wait)
  172. self.to_send += data
  173. for args, resp, error in self.extra.pop(self.received_msgid, []):
  174. left -= 1
  175. if not resp and not error:
  176. resp, error = self.cache[args][1:]
  177. if error:
  178. raise self.RPCError(error)
  179. else:
  180. yield resp
  181. while left:
  182. r, w, x = select.select(self.r_fds, w_fds, self.x_fds, 1)
  183. if x:
  184. raise Exception('FD exception occured')
  185. if r:
  186. for res in self._read():
  187. left -= 1
  188. yield res
  189. if w:
  190. if not self.to_send and peek:
  191. self.to_send = self.gen_cache_requests(cmd, peek)
  192. if self.to_send:
  193. n = os.write(self.stdin_fd, self.to_send)
  194. assert n > 0
  195. self.to_send = self.to_send[n:]
  196. else:
  197. w_fds = []
  198. if not wait:
  199. return
  200. def commit(self, *args):
  201. self.call('commit', args)
  202. def rollback(self, *args):
  203. self.cache.clear()
  204. self.pending.clear()
  205. self.extra.clear()
  206. return self.call('rollback', args)
  207. def get(self, id):
  208. try:
  209. for res in self.call_multi('get', [(id, )]):
  210. return res
  211. except self.RPCError, e:
  212. if e.name == 'DoesNotExist':
  213. raise Store.DoesNotExist
  214. raise
  215. def get_many(self, ids, peek=None):
  216. return self.call_multi('get', [(id, ) for id in ids], peek=peek)
  217. def _invalidate(self, id):
  218. key = (id, )
  219. if key in self.cache:
  220. self.pending.pop(self.cache.pop(key)[0], None)
  221. def put(self, id, data, wait=True):
  222. resp = self.call('put', (id, data), wait=wait)
  223. self._invalidate(id)
  224. return resp
  225. def delete(self, id, wait=True):
  226. resp = self.call('delete', (id, ), wait=wait)
  227. self._invalidate(id)
  228. return resp
  229. def close(self):
  230. if self.p:
  231. self.p.stdin.close()
  232. self.p.stdout.close()
  233. self.p.wait()
  234. self.p = None
  235. class RemoteStoreTestCase(StoreTestCase):
  236. def open(self, create=False):
  237. from .helpers import Location
  238. return RemoteStore(Location('localhost:' + os.path.join(self.tmppath, 'store')), create=create)
  239. def suite():
  240. return unittest.TestLoader().loadTestsFromTestCase(RemoteStoreTestCase)
  241. if __name__ == '__main__':
  242. unittest.main()