multi.py 10 KB

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