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