remote.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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()
  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 DoesNotExist(Exception):
  54. pass
  55. class AlreadyExists(Exception):
  56. pass
  57. class RPCError(Exception):
  58. def __init__(self, name):
  59. self.name = name
  60. def __init__(self, location, create=False):
  61. self.cache = LRUCache(200)
  62. self.to_send = ''
  63. self.extra = {}
  64. self.pending = {}
  65. self.unpacker = msgpack.Unpacker()
  66. self.msgid = 0
  67. self.received_msgid = 0
  68. args = ['ssh', '-p', str(location.port), '%s@%s' % (location.user or getpass.getuser(), location.host), 'darc', 'serve']
  69. self.p = Popen(args, bufsize=0, stdin=PIPE, stdout=PIPE)
  70. self.stdin_fd = self.p.stdin.fileno()
  71. self.stdout_fd = self.p.stdout.fileno()
  72. self.r_fds = [self.stdout_fd]
  73. self.x_fds = [self.stdin_fd, self.stdout_fd]
  74. version = self.call('negotiate', (1,))
  75. if version != 1:
  76. raise Exception('Server insisted on using unsupported protocol version %d' % version)
  77. self.id = self.call('open', (location.path, create))
  78. def __del__(self):
  79. self.close()
  80. def call(self, cmd, args, wait=True):
  81. self.msgid += 1
  82. self.p.stdin.write(msgpack.packb((1, self.msgid, cmd, args)))
  83. while wait:
  84. r, w, x = select.select(self.r_fds, [], self.x_fds, 1)
  85. if x:
  86. raise Exception('FD exception occured')
  87. if r:
  88. self.unpacker.feed(os.read(self.stdout_fd, BUFSIZE))
  89. for type, msgid, error, res in self.unpacker:
  90. if msgid == self.msgid:
  91. assert msgid == self.msgid
  92. self.received_msgid = msgid
  93. if error:
  94. raise self.RPCError(error)
  95. else:
  96. return res
  97. else:
  98. args = self.pending.pop(msgid, None)
  99. if args is not None:
  100. self.cache[args] = msgid, res, error
  101. def _read(self):
  102. data = os.read(self.stdout_fd, BUFSIZE)
  103. if not data:
  104. raise Exception('EOF')
  105. self.unpacker.feed(data)
  106. to_yield = []
  107. for type, msgid, error, res in self.unpacker:
  108. self.received_msgid = msgid
  109. args = self.pending.pop(msgid, None)
  110. if args is not None:
  111. self.cache[args] = msgid, res, error
  112. for args, resp, error in self.extra.pop(msgid, []):
  113. if not resp and not error:
  114. resp, error = self.cache[args][1:]
  115. to_yield.append((resp, error))
  116. for res, error in to_yield:
  117. if error:
  118. raise self.RPCError(error)
  119. else:
  120. yield res
  121. def gen_request(self, cmd, argsv, wait):
  122. data = []
  123. m = self.received_msgid
  124. for args in argsv:
  125. # Make sure to invalidate any existing cache entries for non-get requests
  126. if not args in self.cache:
  127. self.msgid += 1
  128. msgid = self.msgid
  129. self.pending[msgid] = args
  130. self.cache[args] = msgid, None, None
  131. data.append(msgpack.packb((1, msgid, cmd, args)))
  132. if wait:
  133. msgid, resp, error = self.cache[args]
  134. m = max(m, msgid)
  135. self.extra.setdefault(m, []).append((args, resp, error))
  136. return ''.join(data)
  137. def gen_cache_requests(self, cmd, peek):
  138. data = []
  139. while True:
  140. try:
  141. args = (peek()[0],)
  142. except StopIteration:
  143. break
  144. if args in self.cache:
  145. continue
  146. self.msgid += 1
  147. msgid = self.msgid
  148. self.pending[msgid] = args
  149. self.cache[args] = msgid, None, None
  150. data.append(msgpack.packb((1, msgid, cmd, args)))
  151. return ''.join(data)
  152. def call_multi(self, cmd, argsv, wait=True, peek=None):
  153. w_fds = [self.stdin_fd]
  154. left = len(argsv)
  155. data = self.gen_request(cmd, argsv, wait)
  156. self.to_send += data
  157. for args, resp, error in self.extra.pop(self.received_msgid, []):
  158. left -= 1
  159. if not resp and not error:
  160. resp, error = self.cache[args][1:]
  161. if error:
  162. raise self.RPCError(error)
  163. else:
  164. yield resp
  165. while left:
  166. r, w, x = select.select(self.r_fds, w_fds, self.x_fds, 1)
  167. if x:
  168. raise Exception('FD exception occured')
  169. if r:
  170. for res in self._read():
  171. left -= 1
  172. yield res
  173. if w:
  174. if not self.to_send and peek:
  175. self.to_send = self.gen_cache_requests(cmd, peek)
  176. if self.to_send:
  177. n = os.write(self.stdin_fd, self.to_send)
  178. assert n > 0
  179. self.to_send = self.to_send[n:]
  180. else:
  181. w_fds = []
  182. if not wait:
  183. return
  184. def commit(self, *args):
  185. self.call('commit', args)
  186. def rollback(self, *args):
  187. self.cache.clear()
  188. self.pending.clear()
  189. self.extra.clear()
  190. return self.call('rollback', args)
  191. def get(self, id):
  192. try:
  193. for res in self.call_multi('get', [(id, )]):
  194. return res
  195. except self.RPCError, e:
  196. if e.name == 'DoesNotExist':
  197. raise self.DoesNotExist
  198. raise
  199. def get_many(self, ids, peek=None):
  200. return self.call_multi('get', [(id, ) for id in ids], peek=peek)
  201. def _invalidate(self, id):
  202. key = (id, )
  203. if key in self.cache:
  204. self.pending.pop(self.cache.pop(key)[0], None)
  205. def put(self, id, data, wait=True):
  206. try:
  207. resp = self.call('put', (id, data), wait=wait)
  208. self._invalidate(id)
  209. return resp
  210. except self.RPCError, e:
  211. if e.name == 'AlreadyExists':
  212. raise self.AlreadyExists
  213. def delete(self, id, wait=True):
  214. resp = self.call('delete', (id, ), wait=wait)
  215. self._invalidate(id)
  216. return resp
  217. def close(self):
  218. if self.p:
  219. self.p.stdin.close()
  220. self.p.stdout.close()
  221. self.p.wait()
  222. self.p = None
  223. class RemoteStoreTestCase(StoreTestCase):
  224. def open(self, create=False):
  225. from .helpers import Location
  226. return RemoteStore(Location('localhost:' + os.path.join(self.tmppath, 'store')), create=create)
  227. def suite():
  228. return unittest.TestLoader().loadTestsFromTestCase(RemoteStoreTestCase)
  229. if __name__ == '__main__':
  230. unittest.main()