multi.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. """
  2. Managing Gateway Groups and interactions with multiple channels.
  3. (c) 2008-2014, Holger Krekel and others
  4. """
  5. import sys
  6. import atexit
  7. from functools import partial
  8. from execnet import XSpec
  9. from execnet import gateway_io, gateway_bootstrap
  10. from execnet.gateway_base import reraise, trace, get_execmodel
  11. from threading import Lock
  12. NO_ENDMARKER_WANTED = object()
  13. class Group(object):
  14. """ Gateway Groups. """
  15. defaultspec = "popen"
  16. def __init__(self, xspecs=(), execmodel="thread"):
  17. """ initialize group and make gateways as specified.
  18. execmodel can be 'thread' or 'eventlet'.
  19. """
  20. self._gateways = []
  21. self._autoidcounter = 0
  22. self._autoidlock = Lock()
  23. self._gateways_to_join = []
  24. # we use the same execmodel for all of the Gateway objects
  25. # we spawn on our side. Probably we should not allow different
  26. # execmodels between different groups but not clear.
  27. # Note that "other side" execmodels may differ and is typically
  28. # specified by the spec passed to makegateway.
  29. self.set_execmodel(execmodel)
  30. for xspec in xspecs:
  31. self.makegateway(xspec)
  32. atexit.register(self._cleanup_atexit)
  33. @property
  34. def execmodel(self):
  35. return self._execmodel
  36. @property
  37. def remote_execmodel(self):
  38. return self._remote_execmodel
  39. def set_execmodel(self, execmodel, remote_execmodel=None):
  40. """ Set the execution model for local and remote site.
  41. execmodel can be one of "thread" or "eventlet" (XXX gevent).
  42. It determines the execution model for any newly created gateway.
  43. If remote_execmodel is not specified it takes on the value
  44. of execmodel.
  45. NOTE: Execution models can only be set before any gateway is created.
  46. """
  47. if self._gateways:
  48. raise ValueError("can not set execution models if "
  49. "gateways have been created already")
  50. if remote_execmodel is None:
  51. remote_execmodel = execmodel
  52. self._execmodel = get_execmodel(execmodel)
  53. self._remote_execmodel = get_execmodel(remote_execmodel)
  54. def __repr__(self):
  55. idgateways = [gw.id for gw in self]
  56. return "<Group %r>" % idgateways
  57. def __getitem__(self, key):
  58. if isinstance(key, int):
  59. return self._gateways[key]
  60. for gw in self._gateways:
  61. if gw == key or gw.id == key:
  62. return gw
  63. raise KeyError(key)
  64. def __contains__(self, key):
  65. try:
  66. self[key]
  67. return True
  68. except KeyError:
  69. return False
  70. def __len__(self):
  71. return len(self._gateways)
  72. def __iter__(self):
  73. return iter(list(self._gateways))
  74. def makegateway(self, spec=None):
  75. """create and configure a gateway to a Python interpreter.
  76. The ``spec`` string encodes the target gateway type
  77. and configuration information. The general format is::
  78. key1=value1//key2=value2//...
  79. If you leave out the ``=value`` part a True value is assumed.
  80. Valid types: ``popen``, ``ssh=hostname``, ``socket=host:port``.
  81. Valid configuration::
  82. id=<string> specifies the gateway id
  83. python=<path> specifies which python interpreter to execute
  84. execmodel=model 'thread', 'eventlet', 'gevent' model for execution
  85. chdir=<path> specifies to which directory to change
  86. nice=<path> specifies process priority of new process
  87. env:NAME=value specifies a remote environment variable setting.
  88. If no spec is given, self.defaultspec is used.
  89. """
  90. if not spec:
  91. spec = self.defaultspec
  92. if not isinstance(spec, XSpec):
  93. spec = XSpec(spec)
  94. self.allocate_id(spec)
  95. if spec.execmodel is None:
  96. spec.execmodel = self.remote_execmodel.backend
  97. if spec.via:
  98. assert not spec.socket
  99. master = self[spec.via]
  100. proxy_channel = master.remote_exec(gateway_io)
  101. proxy_channel.send(vars(spec))
  102. proxy_io_master = gateway_io.ProxyIO(proxy_channel, self.execmodel)
  103. gw = gateway_bootstrap.bootstrap(proxy_io_master, spec)
  104. elif spec.popen or spec.ssh or spec.vagrant_ssh:
  105. io = gateway_io.create_io(spec, execmodel=self.execmodel)
  106. gw = gateway_bootstrap.bootstrap(io, spec)
  107. elif spec.socket:
  108. from execnet import gateway_socket
  109. io = gateway_socket.create_io(spec, self, execmodel=self.execmodel)
  110. gw = gateway_bootstrap.bootstrap(io, spec)
  111. else:
  112. raise ValueError("no gateway type found for {!r}".format(spec._spec))
  113. gw.spec = spec
  114. self._register(gw)
  115. if spec.chdir or spec.nice or spec.env:
  116. channel = gw.remote_exec("""
  117. import os
  118. path, nice, env = channel.receive()
  119. if path:
  120. if not os.path.exists(path):
  121. os.mkdir(path)
  122. os.chdir(path)
  123. if nice and hasattr(os, 'nice'):
  124. os.nice(nice)
  125. if env:
  126. for name, value in env.items():
  127. os.environ[name] = value
  128. """)
  129. nice = spec.nice and int(spec.nice) or 0
  130. channel.send((spec.chdir, nice, spec.env))
  131. channel.waitclose()
  132. return gw
  133. def allocate_id(self, spec):
  134. """ (re-entrant) allocate id for the given xspec object. """
  135. if spec.id is None:
  136. with self._autoidlock:
  137. id = "gw" + str(self._autoidcounter)
  138. self._autoidcounter += 1
  139. if id in self:
  140. raise ValueError("already have gateway with id {!r}".format(id))
  141. spec.id = id
  142. def _register(self, gateway):
  143. assert not hasattr(gateway, '_group')
  144. assert gateway.id
  145. assert id not in self
  146. self._gateways.append(gateway)
  147. gateway._group = self
  148. def _unregister(self, gateway):
  149. self._gateways.remove(gateway)
  150. self._gateways_to_join.append(gateway)
  151. def _cleanup_atexit(self):
  152. trace("=== atexit cleanup {!r} ===".format(self))
  153. self.terminate(timeout=1.0)
  154. def terminate(self, timeout=None):
  155. """ trigger exit of member gateways and wait for termination
  156. of member gateways and associated subprocesses. After waiting
  157. timeout seconds try to to kill local sub processes of popen-
  158. and ssh-gateways. Timeout defaults to None meaning
  159. open-ended waiting and no kill attempts.
  160. """
  161. while self:
  162. vias = {}
  163. for gw in self:
  164. if gw.spec.via:
  165. vias[gw.spec.via] = True
  166. for gw in self:
  167. if gw.id not in vias:
  168. gw.exit()
  169. def join_wait(gw):
  170. gw.join()
  171. gw._io.wait()
  172. def kill(gw):
  173. trace("Gateways did not come down after timeout: %r" % gw)
  174. gw._io.kill()
  175. safe_terminate(self.execmodel, timeout, [
  176. (partial(join_wait, gw), partial(kill, gw))
  177. for gw in self._gateways_to_join
  178. ])
  179. self._gateways_to_join[:] = []
  180. def remote_exec(self, source, **kwargs):
  181. """ remote_exec source on all member gateways and return
  182. MultiChannel connecting to all sub processes.
  183. """
  184. channels = []
  185. for gw in self:
  186. channels.append(gw.remote_exec(source, **kwargs))
  187. return MultiChannel(channels)
  188. class MultiChannel:
  189. def __init__(self, channels):
  190. self._channels = channels
  191. def __len__(self):
  192. return len(self._channels)
  193. def __iter__(self):
  194. return iter(self._channels)
  195. def __getitem__(self, key):
  196. return self._channels[key]
  197. def __contains__(self, chan):
  198. return chan in self._channels
  199. def send_each(self, item):
  200. for ch in self._channels:
  201. ch.send(item)
  202. def receive_each(self, withchannel=False):
  203. assert not hasattr(self, '_queue')
  204. l = []
  205. for ch in self._channels:
  206. obj = ch.receive()
  207. if withchannel:
  208. l.append((ch, obj))
  209. else:
  210. l.append(obj)
  211. return l
  212. def make_receive_queue(self, endmarker=NO_ENDMARKER_WANTED):
  213. try:
  214. return self._queue
  215. except AttributeError:
  216. self._queue = None
  217. for ch in self._channels:
  218. if self._queue is None:
  219. self._queue = ch.gateway.execmodel.queue.Queue()
  220. def putreceived(obj, channel=ch):
  221. self._queue.put((channel, obj))
  222. if endmarker is NO_ENDMARKER_WANTED:
  223. ch.setcallback(putreceived)
  224. else:
  225. ch.setcallback(putreceived, endmarker=endmarker)
  226. return self._queue
  227. def waitclose(self):
  228. first = None
  229. for ch in self._channels:
  230. try:
  231. ch.waitclose()
  232. except ch.RemoteError:
  233. if first is None:
  234. first = sys.exc_info()
  235. if first:
  236. reraise(*first)
  237. def safe_terminate(execmodel, timeout, list_of_paired_functions):
  238. workerpool = execmodel.WorkerPool()
  239. def termkill(termfunc, killfunc):
  240. termreply = workerpool.spawn(termfunc)
  241. try:
  242. termreply.get(timeout=timeout)
  243. except IOError:
  244. killfunc()
  245. replylist = []
  246. for termfunc, killfunc in list_of_paired_functions:
  247. reply = workerpool.spawn(termkill, termfunc, killfunc)
  248. replylist.append(reply)
  249. for reply in replylist:
  250. reply.get()
  251. workerpool.waitall()
  252. default_group = Group()
  253. makegateway = default_group.makegateway
  254. set_execmodel = default_group.set_execmodel