2007-01-24 22:24:01 +08:00
|
|
|
import os
|
|
|
|
import threading
|
|
|
|
import Queue
|
|
|
|
import traceback
|
|
|
|
import atexit
|
|
|
|
import weakref
|
|
|
|
import __future__
|
|
|
|
|
|
|
|
# note that the whole code of this module (as well as some
|
|
|
|
# other modules) execute not only on the local side but
|
|
|
|
# also on any gateway's remote side. On such remote sides
|
|
|
|
# we cannot assume the py library to be there and
|
2007-02-02 09:02:55 +08:00
|
|
|
# InstallableGateway._remote_bootstrap_gateway() (located
|
2007-01-24 22:24:01 +08:00
|
|
|
# in register.py) will take care to send source fragments
|
|
|
|
# to the other side. Yes, it is fragile but we have a
|
|
|
|
# few tests that try to catch when we mess up.
|
|
|
|
|
|
|
|
# XXX the following lines should not be here
|
|
|
|
if 'ThreadOut' not in globals():
|
|
|
|
import py
|
|
|
|
from py.code import Source
|
|
|
|
from py.__.execnet.channel import ChannelFactory, Channel
|
|
|
|
from py.__.execnet.message import Message
|
|
|
|
ThreadOut = py._thread.ThreadOut
|
|
|
|
|
|
|
|
import os
|
2007-08-08 01:54:09 +08:00
|
|
|
debug = 0 # open('/tmp/execnet-debug-%d' % os.getpid() , 'wa')
|
2007-01-24 22:24:01 +08:00
|
|
|
|
|
|
|
sysex = (KeyboardInterrupt, SystemExit)
|
|
|
|
|
2007-08-08 19:45:04 +08:00
|
|
|
# ----------------------------------------------------------
|
|
|
|
# cleanup machinery (for exiting processes)
|
|
|
|
# ----------------------------------------------------------
|
|
|
|
|
|
|
|
class GatewayCleanup:
|
|
|
|
def __init__(self):
|
|
|
|
self._activegateways = weakref.WeakKeyDictionary()
|
|
|
|
atexit.register(self.cleanup_atexit)
|
|
|
|
|
|
|
|
def register(self, gateway):
|
|
|
|
assert gateway not in self._activegateways
|
|
|
|
self._activegateways[gateway] = True
|
|
|
|
|
|
|
|
def unregister(self, gateway):
|
|
|
|
del self._activegateways[gateway]
|
|
|
|
|
|
|
|
def cleanup_atexit(self):
|
|
|
|
if debug:
|
|
|
|
print >>debug, "="*20 + "cleaning up" + "=" * 20
|
|
|
|
debug.flush()
|
|
|
|
for gw in self._activegateways.keys():
|
|
|
|
gw.exit()
|
2007-08-08 20:02:55 +08:00
|
|
|
#gw.join() # should work as well
|
2007-08-08 19:45:04 +08:00
|
|
|
|
|
|
|
# ----------------------------------------------------------
|
|
|
|
# Base Gateway (used for both remote and local side)
|
|
|
|
# ----------------------------------------------------------
|
|
|
|
|
2007-01-24 22:24:01 +08:00
|
|
|
class Gateway(object):
|
2007-08-08 18:38:22 +08:00
|
|
|
class _StopExecLoop(Exception): pass
|
2007-02-02 08:34:40 +08:00
|
|
|
_ThreadOut = ThreadOut
|
2007-02-02 07:57:55 +08:00
|
|
|
remoteaddress = ""
|
2007-08-08 01:34:59 +08:00
|
|
|
_requestqueue = None
|
2007-08-08 19:45:04 +08:00
|
|
|
_cleanup = GatewayCleanup()
|
2007-08-08 01:34:59 +08:00
|
|
|
|
|
|
|
def __init__(self, io, _startcount=2):
|
2007-02-03 03:57:47 +08:00
|
|
|
""" initialize core gateway, using the given
|
2007-08-08 01:34:59 +08:00
|
|
|
inputoutput object.
|
2007-02-03 03:57:47 +08:00
|
|
|
"""
|
2007-02-02 09:02:55 +08:00
|
|
|
self._io = io
|
2007-02-03 03:57:47 +08:00
|
|
|
self._channelfactory = ChannelFactory(self, _startcount)
|
2007-08-08 19:45:04 +08:00
|
|
|
self._cleanup.register(self)
|
2007-08-08 01:34:59 +08:00
|
|
|
|
|
|
|
def _initreceive(self, requestqueue=False):
|
|
|
|
if requestqueue:
|
|
|
|
self._requestqueue = Queue.Queue()
|
|
|
|
self._receiverthread = threading.Thread(name="receiver",
|
|
|
|
target=self._thread_receiver)
|
2007-08-08 19:45:04 +08:00
|
|
|
self._receiverthread.setDaemon(1)
|
2007-08-08 01:34:59 +08:00
|
|
|
self._receiverthread.start()
|
2007-01-24 22:24:01 +08:00
|
|
|
|
|
|
|
def __repr__(self):
|
2007-02-03 03:57:47 +08:00
|
|
|
""" return string representing gateway type and status. """
|
2007-02-02 07:57:55 +08:00
|
|
|
addr = self.remoteaddress
|
2007-01-24 22:24:01 +08:00
|
|
|
if addr:
|
|
|
|
addr = '[%s]' % (addr,)
|
|
|
|
else:
|
|
|
|
addr = ''
|
2007-01-28 16:48:59 +08:00
|
|
|
try:
|
2007-08-08 01:34:59 +08:00
|
|
|
r = (self._receiverthread.isAlive() and "receiving" or
|
|
|
|
"not receiving")
|
|
|
|
s = "sending" # XXX
|
2007-02-02 09:02:55 +08:00
|
|
|
i = len(self._channelfactory.channels())
|
2007-01-28 16:48:59 +08:00
|
|
|
except AttributeError:
|
|
|
|
r = s = "uninitialized"
|
|
|
|
i = "no"
|
|
|
|
return "<%s%s %s/%s (%s active channels)>" %(
|
2007-01-24 22:24:01 +08:00
|
|
|
self.__class__.__name__, addr, r, s, i)
|
|
|
|
|
|
|
|
def _trace(self, *args):
|
|
|
|
if debug:
|
|
|
|
try:
|
|
|
|
l = "\n".join(args).split(os.linesep)
|
|
|
|
id = getid(self)
|
|
|
|
for x in l:
|
|
|
|
print >>debug, x
|
|
|
|
debug.flush()
|
|
|
|
except sysex:
|
|
|
|
raise
|
|
|
|
except:
|
|
|
|
traceback.print_exc()
|
|
|
|
|
|
|
|
def _traceex(self, excinfo):
|
|
|
|
try:
|
|
|
|
l = traceback.format_exception(*excinfo)
|
|
|
|
errortext = "".join(l)
|
|
|
|
except:
|
|
|
|
errortext = '%s: %s' % (excinfo[0].__name__,
|
|
|
|
excinfo[1])
|
|
|
|
self._trace(errortext)
|
|
|
|
|
2007-02-02 08:34:40 +08:00
|
|
|
def _thread_receiver(self):
|
2007-01-24 22:24:01 +08:00
|
|
|
""" thread to read and handle Messages half-sync-half-async. """
|
|
|
|
try:
|
|
|
|
from sys import exc_info
|
|
|
|
while 1:
|
|
|
|
try:
|
2007-02-02 09:02:55 +08:00
|
|
|
msg = Message.readfrom(self._io)
|
2007-01-24 22:24:01 +08:00
|
|
|
self._trace("received <- %r" % msg)
|
|
|
|
msg.received(self)
|
|
|
|
except sysex:
|
2007-02-11 06:16:47 +08:00
|
|
|
break
|
2007-01-24 22:24:01 +08:00
|
|
|
except EOFError:
|
|
|
|
break
|
|
|
|
except:
|
|
|
|
self._traceex(exc_info())
|
|
|
|
break
|
|
|
|
finally:
|
2007-08-08 01:34:59 +08:00
|
|
|
self._stopexec()
|
|
|
|
self._stopsend()
|
2007-02-02 09:02:55 +08:00
|
|
|
self._channelfactory._finished_receiving()
|
2007-01-24 22:24:01 +08:00
|
|
|
self._trace('leaving %r' % threading.currentThread())
|
|
|
|
|
2007-08-08 20:02:55 +08:00
|
|
|
from sys import exc_info
|
2007-03-06 20:51:18 +08:00
|
|
|
def _send(self, msg):
|
2007-08-08 01:34:59 +08:00
|
|
|
if msg is None:
|
|
|
|
self._io.close_write()
|
|
|
|
else:
|
|
|
|
try:
|
|
|
|
msg.writeto(self._io)
|
|
|
|
except:
|
2007-08-08 20:02:55 +08:00
|
|
|
excinfo = self.exc_info()
|
2007-08-08 01:34:59 +08:00
|
|
|
self._traceex(excinfo)
|
|
|
|
msg.post_sent(self, excinfo)
|
|
|
|
else:
|
|
|
|
msg.post_sent(self)
|
|
|
|
self._trace('sent -> %r' % msg)
|
2007-01-24 22:24:01 +08:00
|
|
|
|
|
|
|
def _local_redirect_thread_output(self, outid, errid):
|
|
|
|
l = []
|
|
|
|
for name, id in ('stdout', outid), ('stderr', errid):
|
|
|
|
if id:
|
2007-02-02 09:02:55 +08:00
|
|
|
channel = self._channelfactory.new(outid)
|
2007-02-02 08:34:40 +08:00
|
|
|
out = self._ThreadOut(sys, name)
|
2007-01-24 22:24:01 +08:00
|
|
|
out.setwritefunc(channel.send)
|
|
|
|
l.append((out, channel))
|
|
|
|
def close():
|
|
|
|
for out, channel in l:
|
|
|
|
out.delwritefunc()
|
|
|
|
channel.close()
|
|
|
|
return close
|
|
|
|
|
2007-08-08 01:34:59 +08:00
|
|
|
def _local_schedulexec(self, channel, sourcetask):
|
|
|
|
if self._requestqueue is not None:
|
|
|
|
self._requestqueue.put((channel, sourcetask))
|
|
|
|
else:
|
|
|
|
# we will not execute, let's send back an error
|
|
|
|
# to inform the other side
|
|
|
|
channel.close("execution disallowed")
|
|
|
|
|
|
|
|
def _servemain(self, joining=True):
|
2007-01-24 22:24:01 +08:00
|
|
|
from sys import exc_info
|
2007-08-08 01:34:59 +08:00
|
|
|
self._initreceive(requestqueue=True)
|
|
|
|
try:
|
|
|
|
while 1:
|
|
|
|
item = self._requestqueue.get()
|
|
|
|
if item is None:
|
|
|
|
self._stopsend()
|
|
|
|
break
|
|
|
|
try:
|
|
|
|
self._executetask(item)
|
2007-08-08 01:54:09 +08:00
|
|
|
except self._StopExecLoop:
|
2007-08-08 01:34:59 +08:00
|
|
|
break
|
|
|
|
finally:
|
|
|
|
self._trace("_servemain finished")
|
2007-08-08 20:02:55 +08:00
|
|
|
if joining:
|
2007-08-08 01:34:59 +08:00
|
|
|
self.join()
|
|
|
|
|
|
|
|
def remote_init_threads(self, num=None):
|
|
|
|
""" start up to 'num' threads for subsequent
|
|
|
|
remote_exec() invocations to allow concurrent
|
|
|
|
execution.
|
|
|
|
"""
|
|
|
|
if hasattr(self, '_remotechannelthread'):
|
|
|
|
raise IOError("remote threads already running")
|
|
|
|
from py.__.thread import pool
|
|
|
|
source = py.code.Source(pool, """
|
|
|
|
execpool = WorkerPool(maxthreads=%r)
|
|
|
|
gw = channel.gateway
|
|
|
|
while 1:
|
|
|
|
task = gw._requestqueue.get()
|
|
|
|
if task is None:
|
|
|
|
gw._stopsend()
|
|
|
|
execpool.shutdown()
|
|
|
|
execpool.join()
|
2007-08-08 01:54:09 +08:00
|
|
|
raise gw._StopExecLoop
|
2007-08-08 01:34:59 +08:00
|
|
|
execpool.dispatch(gw._executetask, task)
|
|
|
|
""" % num)
|
|
|
|
self._remotechannelthread = self.remote_exec(source)
|
|
|
|
|
|
|
|
def _executetask(self, item):
|
|
|
|
""" execute channel/source items. """
|
|
|
|
from sys import exc_info
|
|
|
|
channel, (source, outid, errid) = item
|
2007-01-24 22:24:01 +08:00
|
|
|
try:
|
|
|
|
loc = { 'channel' : channel }
|
|
|
|
self._trace("execution starts:", repr(source)[:50])
|
|
|
|
close = self._local_redirect_thread_output(outid, errid)
|
|
|
|
try:
|
|
|
|
co = compile(source+'\n', '', 'exec',
|
|
|
|
__future__.CO_GENERATOR_ALLOWED)
|
|
|
|
exec co in loc
|
|
|
|
finally:
|
|
|
|
close()
|
|
|
|
self._trace("execution finished:", repr(source)[:50])
|
|
|
|
except (KeyboardInterrupt, SystemExit):
|
2007-02-11 06:16:47 +08:00
|
|
|
pass
|
2007-08-08 01:54:09 +08:00
|
|
|
except self._StopExecLoop:
|
2007-08-08 01:34:59 +08:00
|
|
|
channel.close()
|
|
|
|
raise
|
2007-01-24 22:24:01 +08:00
|
|
|
except:
|
|
|
|
excinfo = exc_info()
|
|
|
|
l = traceback.format_exception(*excinfo)
|
|
|
|
errortext = "".join(l)
|
|
|
|
channel.close(errortext)
|
|
|
|
self._trace(errortext)
|
|
|
|
else:
|
|
|
|
channel.close()
|
|
|
|
|
|
|
|
def _newredirectchannelid(self, callback):
|
|
|
|
if callback is None:
|
|
|
|
return
|
|
|
|
if hasattr(callback, 'write'):
|
|
|
|
callback = callback.write
|
|
|
|
assert callable(callback)
|
|
|
|
chan = self.newchannel()
|
|
|
|
chan.setcallback(callback)
|
|
|
|
return chan.id
|
|
|
|
|
|
|
|
# _____________________________________________________________________
|
|
|
|
#
|
|
|
|
# High Level Interface
|
|
|
|
# _____________________________________________________________________
|
|
|
|
#
|
|
|
|
def newchannel(self):
|
|
|
|
""" return new channel object. """
|
2007-02-02 09:02:55 +08:00
|
|
|
return self._channelfactory.new()
|
2007-01-24 22:24:01 +08:00
|
|
|
|
|
|
|
def remote_exec(self, source, stdout=None, stderr=None):
|
2007-02-03 03:57:47 +08:00
|
|
|
""" return channel object and connect it to a remote
|
|
|
|
execution thread where the given 'source' executes
|
|
|
|
and has the sister 'channel' object in its global
|
|
|
|
namespace. The callback functions 'stdout' and
|
|
|
|
'stderr' get called on receival of remote
|
|
|
|
stdout/stderr output strings.
|
2007-01-24 22:24:01 +08:00
|
|
|
"""
|
|
|
|
try:
|
|
|
|
source = str(Source(source))
|
|
|
|
except NameError:
|
|
|
|
try:
|
|
|
|
import py
|
|
|
|
source = str(py.code.Source(source))
|
|
|
|
except ImportError:
|
|
|
|
pass
|
|
|
|
channel = self.newchannel()
|
|
|
|
outid = self._newredirectchannelid(stdout)
|
|
|
|
errid = self._newredirectchannelid(stderr)
|
2007-03-06 20:51:18 +08:00
|
|
|
self._send(Message.CHANNEL_OPEN(
|
|
|
|
channel.id, (source, outid, errid)))
|
2007-01-24 22:24:01 +08:00
|
|
|
return channel
|
|
|
|
|
2007-02-02 09:02:55 +08:00
|
|
|
def _remote_redirect(self, stdout=None, stderr=None):
|
2007-01-24 22:24:01 +08:00
|
|
|
""" return a handle representing a redirection of a remote
|
|
|
|
end's stdout to a local file object. with handle.close()
|
|
|
|
the redirection will be reverted.
|
|
|
|
"""
|
|
|
|
clist = []
|
|
|
|
for name, out in ('stdout', stdout), ('stderr', stderr):
|
|
|
|
if out:
|
|
|
|
outchannel = self.newchannel()
|
|
|
|
outchannel.setcallback(getattr(out, 'write', out))
|
|
|
|
channel = self.remote_exec("""
|
|
|
|
import sys
|
|
|
|
outchannel = channel.receive()
|
2007-02-02 08:34:40 +08:00
|
|
|
outchannel.gateway._ThreadOut(sys, %r).setdefaultwriter(outchannel.send)
|
2007-01-24 22:24:01 +08:00
|
|
|
""" % name)
|
|
|
|
channel.send(outchannel)
|
|
|
|
clist.append(channel)
|
|
|
|
for c in clist:
|
2007-02-12 23:55:48 +08:00
|
|
|
c.waitclose()
|
2007-01-24 22:24:01 +08:00
|
|
|
class Handle:
|
|
|
|
def close(_):
|
|
|
|
for name, out in ('stdout', stdout), ('stderr', stderr):
|
|
|
|
if out:
|
|
|
|
c = self.remote_exec("""
|
|
|
|
import sys
|
2007-02-02 08:34:40 +08:00
|
|
|
channel.gateway._ThreadOut(sys, %r).resetdefault()
|
2007-01-24 22:24:01 +08:00
|
|
|
""" % name)
|
2007-02-12 23:55:48 +08:00
|
|
|
c.waitclose()
|
2007-01-24 22:24:01 +08:00
|
|
|
return Handle()
|
|
|
|
|
|
|
|
def exit(self):
|
2007-08-08 01:34:59 +08:00
|
|
|
""" Try to stop all exec and IO activity. """
|
2007-08-08 19:45:04 +08:00
|
|
|
self._cleanup.unregister(self)
|
2007-08-08 01:34:59 +08:00
|
|
|
self._stopexec()
|
|
|
|
self._stopsend()
|
|
|
|
|
|
|
|
def _stopsend(self):
|
|
|
|
self._send(None)
|
|
|
|
|
|
|
|
def _stopexec(self):
|
|
|
|
if self._requestqueue is not None:
|
|
|
|
self._requestqueue.put(None)
|
2007-01-24 22:24:01 +08:00
|
|
|
|
|
|
|
def join(self, joinexec=True):
|
2007-02-03 03:57:47 +08:00
|
|
|
""" Wait for all IO (and by default all execution activity)
|
2007-08-08 01:34:59 +08:00
|
|
|
to stop. the joinexec parameter is obsolete.
|
2007-02-03 03:57:47 +08:00
|
|
|
"""
|
2007-01-24 22:24:01 +08:00
|
|
|
current = threading.currentThread()
|
2007-08-08 01:34:59 +08:00
|
|
|
if self._receiverthread.isAlive():
|
|
|
|
self._trace("joining receiver thread")
|
|
|
|
self._receiverthread.join()
|
2007-01-24 22:24:01 +08:00
|
|
|
|
|
|
|
def getid(gw, cache={}):
|
|
|
|
name = gw.__class__.__name__
|
|
|
|
try:
|
|
|
|
return cache.setdefault(name, {})[id(gw)]
|
|
|
|
except KeyError:
|
|
|
|
cache[name][id(gw)] = x = "%s:%s.%d" %(os.getpid(), gw.__class__.__name__, len(cache[name]))
|
|
|
|
return x
|
|
|
|
|