<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>[12844] twext/trunk/twext</title>
</head>
<body>
<style type="text/css"><!--
#msg dl.meta { border: 1px #006 solid; background: #369; padding: 6px; color: #fff; }
#msg dl.meta dt { float: left; width: 6em; font-weight: bold; }
#msg dt:after { content:':';}
#msg dl, #msg dt, #msg ul, #msg li, #header, #footer, #logmsg { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt; }
#msg dl a { font-weight: bold}
#msg dl a:link { color:#fc3; }
#msg dl a:active { color:#ff0; }
#msg dl a:visited { color:#cc6; }
h3 { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt; font-weight: bold; }
#msg pre { overflow: auto; background: #ffc; border: 1px #fa0 solid; padding: 6px; }
#logmsg { background: #ffc; border: 1px #fa0 solid; padding: 1em 1em 0 1em; }
#logmsg p, #logmsg pre, #logmsg blockquote { margin: 0 0 1em 0; }
#logmsg p, #logmsg li, #logmsg dt, #logmsg dd { line-height: 14pt; }
#logmsg h1, #logmsg h2, #logmsg h3, #logmsg h4, #logmsg h5, #logmsg h6 { margin: .5em 0; }
#logmsg h1:first-child, #logmsg h2:first-child, #logmsg h3:first-child, #logmsg h4:first-child, #logmsg h5:first-child, #logmsg h6:first-child { margin-top: 0; }
#logmsg ul, #logmsg ol { padding: 0; list-style-position: inside; margin: 0 0 0 1em; }
#logmsg ul { text-indent: -1em; padding-left: 1em; }#logmsg ol { text-indent: -1.5em; padding-left: 1.5em; }
#logmsg > ul, #logmsg > ol { margin: 0 0 1em 0; }
#logmsg pre { background: #eee; padding: 1em; }
#logmsg blockquote { border: 1px solid #fa0; border-left-width: 10px; padding: 1em 1em 0 1em; background: white;}
#logmsg dl { margin: 0; }
#logmsg dt { font-weight: bold; }
#logmsg dd { margin: 0; padding: 0 0 0.5em 0; }
#logmsg dd:before { content:'\00bb';}
#logmsg table { border-spacing: 0px; border-collapse: collapse; border-top: 4px solid #fa0; border-bottom: 1px solid #fa0; background: #fff; }
#logmsg table th { text-align: left; font-weight: normal; padding: 0.2em 0.5em; border-top: 1px dotted #fa0; }
#logmsg table td { text-align: right; border-top: 1px dotted #fa0; padding: 0.2em 0.5em; }
#logmsg table thead th { text-align: center; border-bottom: 1px solid #fa0; }
#logmsg table th.Corner { text-align: left; }
#logmsg hr { border: none 0; border-top: 2px dashed #fa0; height: 1px; }
#header, #footer { color: #fff; background: #636; border: 1px #300 solid; padding: 6px; }
#patch { width: 100%; }
#patch h4 {font-family: verdana,arial,helvetica,sans-serif;font-size:10pt;padding:8px;background:#369;color:#fff;margin:0;}
#patch .propset h4, #patch .binary h4 {margin:0;}
#patch pre {padding:0;line-height:1.2em;margin:0;}
#patch .diff {width:100%;background:#eee;padding: 0 0 10px 0;overflow:auto;}
#patch .propset .diff, #patch .binary .diff {padding:10px 0;}
#patch span {display:block;padding:0 10px;}
#patch .modfile, #patch .addfile, #patch .delfile, #patch .propset, #patch .binary, #patch .copfile {border:1px solid #ccc;margin:10px 0;}
#patch ins {background:#dfd;text-decoration:none;display:block;padding:0 10px;}
#patch del {background:#fdd;text-decoration:none;display:block;padding:0 10px;}
#patch .lines, .info {color:#888;background:#fff;}
--></style>
<div id="msg">
<dl class="meta">
<dt>Revision</dt> <dd><a href="http://trac.calendarserver.org//changeset/12844">12844</a></dd>
<dt>Author</dt> <dd>cdaboo@apple.com</dd>
<dt>Date</dt> <dd>2014-03-07 12:48:27 -0800 (Fri, 07 Mar 2014)</dd>
</dl>
<h3>Log Message</h3>
<pre>Fix master-child slot counting issues.</pre>
<h3>Modified Paths</h3>
<ul>
<li><a href="#twexttrunktwextapplicationmasterchildpy">twext/trunk/twext/application/masterchild.py</a></li>
<li><a href="#twexttrunktwextinternetsendfdportpy">twext/trunk/twext/internet/sendfdport.py</a></li>
<li><a href="#twexttrunktwextinternettesttest_sendfdportpy">twext/trunk/twext/internet/test/test_sendfdport.py</a></li>
</ul>
</div>
<div id="patch">
<h3>Diff</h3>
<a id="twexttrunktwextapplicationmasterchildpy"></a>
<div class="modfile"><h4>Modified: twext/trunk/twext/application/masterchild.py (12843 => 12844)</h4>
<pre class="diff"><span>
<span class="info">--- twext/trunk/twext/application/masterchild.py        2014-03-07 20:38:57 UTC (rev 12843)
+++ twext/trunk/twext/application/masterchild.py        2014-03-07 20:48:27 UTC (rev 12844)
</span><span class="lines">@@ -37,7 +37,6 @@
</span><span class="cx"> import sys
</span><span class="cx"> from os import close, unlink
</span><span class="cx"> from tempfile import mkstemp
</span><del>-from functools import total_ordering
</del><span class="cx">
</span><span class="cx"> from zope.interface import implementer
</span><span class="cx">
</span><span class="lines">@@ -54,7 +53,7 @@
</span><span class="cx"> from twisted.internet.protocol import ProcessProtocol
</span><span class="cx">
</span><span class="cx"> from twext.python.log import Logger
</span><del>-from twext.internet.sendfdport import InheritingProtocolFactory
</del><ins>+from twext.internet.sendfdport import InheritingProtocolFactory, IStatus
</ins><span class="cx"> from twext.internet.sendfdport import InheritedSocketDispatcher
</span><span class="cx"> from twext.internet.sendfdport import IStatusWatcher
</span><span class="cx"> from twext.internet.sendfdport import InheritedPort
</span><span class="lines">@@ -205,7 +204,10 @@
</span><span class="cx">
</span><span class="cx"> @staticmethod
</span><span class="cx"> def newConnectionStatus(previousStatus):
</span><del>- return previousStatus + ChildStatus(unacknowledged=1)
</del><ins>+ """
+ A connection was just sent to the process, but not yet acknowledged.
+ """
+ return previousStatus.adjust(unacknowledged=1)
</ins><span class="cx">
</span><span class="cx">
</span><span class="cx"> @staticmethod
</span><span class="lines">@@ -214,40 +216,19 @@
</span><span class="cx"> # A connection has gone away in a subprocess; we should start
</span><span class="cx"> # accepting connections again if we paused (see
</span><span class="cx"> # newConnectionStatus)
</span><del>- return previousStatus - ChildStatus(acknowledged=1)
</del><ins>+ return previousStatus.adjust(acknowledged=-1)
</ins><span class="cx">
</span><span class="cx"> elif message == "0":
</span><del>- # A new process just started accepting new connections. It might
- # still have some unacknowledged connections, but any connections
- # that it acknowledged working on are now completed. (We have no
- # way of knowing whether the acknowledged connections were acted
- # upon or dropped, so we have to treat that number with a healthy
- # amount of skepticism.)
</del><ins>+ # A new process just started accepting new connections.
+ return previousStatus.restarted()
</ins><span class="cx">
</span><del>- # Do some sanity checks... no attempt to fix, but log critically
- # if there are unexpected connection counts, as that means we
- # don't know what's going on with our connection management.
-
- def checkForWeirdness(what, expected):
- n = getattr(previousStatus, what)
- if n != expected:
- MasterService.log.critical(
- "New process has {count} {type} connections, "
- "expected {expected}."
- .format(count=n, type=what, expected=expected)
- )
-
- checkForWeirdness("acknowledged", 0)
- checkForWeirdness("unacknowledged", 1)
- checkForWeirdness("unclosed", 1)
-
- return previousStatus
-
</del><span class="cx"> elif message == "+":
</span><span class="cx"> # Acknowledges that the subprocess has taken on the work.
</span><del>- return (
- previousStatus +
- ChildStatus(acknowledged=1, unacknowledged=-1, unclosed=1)
</del><ins>+ return previousStatus.adjust(
+ acknowledged=1,
+ unacknowledged=-1,
+ total=1,
+ unclosed=1,
</ins><span class="cx"> )
</span><span class="cx">
</span><span class="cx"> else:
</span><span class="lines">@@ -257,7 +238,7 @@
</span><span class="cx"> @staticmethod
</span><span class="cx"> def closeCountFromStatus(previousStatus):
</span><span class="cx"> toClose = previousStatus.unclosed
</span><del>- return (toClose, previousStatus - ChildStatus(unclosed=toClose))
</del><ins>+ return (toClose, previousStatus.adjust(unclosed=-toClose))
</ins><span class="cx">
</span><span class="cx">
</span><span class="cx"> def statusesChanged(self, statuses):
</span><span class="lines">@@ -266,22 +247,21 @@
</span><span class="cx">
</span><span class="cx"> self.log.info("Status changed: {0}".format(tuple(statuses)))
</span><span class="cx">
</span><del>- # current = sum(
- # status.effective()
- # for status in self.dispatcher.statuses
- # )
</del><ins>+# current = sum(status.effective()
+# for status in self.dispatcher.statuses)
+# self._outstandingRequests = current # preserve for or= field in log
+# maximum = self.maxRequests
+# overloaded = (current >= maximum)
+# available = len(filter(lambda x: x.active(), self.dispatcher.statuses))
+# self.overloaded = (overloaded or available == 0)
+# for f in self.factories:
+# if self.overloaded:
+# f.loadAboveMaximum()
+# else:
+# f.loadNominal()
</ins><span class="cx">
</span><del>- # maximum = self.maxRequests
- # overloaded = (current >= maximum)
</del><span class="cx">
</span><del>- # for f in self.factories:
- # if overloaded:
- # f.loadAboveMaximum()
- # else:
- # f.loadNominal()
</del><span class="cx">
</span><del>-
-
</del><span class="cx"> @implementer(IServiceMaker)
</span><span class="cx"> class MasterServiceMaker(object):
</span><span class="cx"> """
</span><span class="lines">@@ -402,7 +382,7 @@
</span><span class="cx"> from twisted.internet import reactor
</span><span class="cx">
</span><span class="cx"> inheritedSocket = self.dispatcher.addSocket()
</span><del>- inheritedFD = inheritedSocket.fileno()
</del><ins>+ inheritedFD = inheritedSocket.childSocket().fileno()
</ins><span class="cx">
</span><span class="cx"> processProtocol = ChildProcessProtocol(self, inheritedSocket)
</span><span class="cx">
</span><span class="lines">@@ -491,12 +471,14 @@
</span><span class="cx"> # FIXME: deserialize log events from child
</span><span class="cx"> # log = Logger()
</span><span class="cx">
</span><del>-
</del><span class="cx"> def __init__(self, service, inheritedSocket):
</span><span class="cx"> self.service = service
</span><span class="cx"> self.inheritedSocket = inheritedSocket
</span><span class="cx">
</span><ins>+ # Always tell any metafd socket that we have started, so it can re-initialize state.
+ self.inheritedSocket.start()
</ins><span class="cx">
</span><ins>+
</ins><span class="cx"> def outReceived(self, data):
</span><span class="cx"> # self.log.info(u"{data}", data=data)
</span><span class="cx"> sys.stdout.write(data)
</span><span class="lines">@@ -509,6 +491,8 @@
</span><span class="cx">
</span><span class="cx">
</span><span class="cx"> def processExited(self, reason):
</span><ins>+ # Always tell any metafd socket that we have started, so it can re-initialize state.
+ self.inheritedSocket.stop()
</ins><span class="cx"> self.service.childDidExit(self, reason)
</span><span class="cx">
</span><span class="cx">
</span><span class="lines">@@ -684,7 +668,7 @@
</span><span class="cx">
</span><span class="cx">
</span><span class="cx">
</span><del>-@total_ordering
</del><ins>+@implementer(IStatus)
</ins><span class="cx"> class ChildStatus(FancyStrMixin, object):
</span><span class="cx"> """
</span><span class="cx"> The status of a child process.
</span><span class="lines">@@ -693,11 +677,26 @@
</span><span class="cx"> showAttributes = (
</span><span class="cx"> "acknowledged",
</span><span class="cx"> "unacknowledged",
</span><ins>+ "total",
+ "started",
+ "abandoned",
</ins><span class="cx"> "unclosed",
</span><ins>+ "starting",
+ "stopped",
</ins><span class="cx"> )
</span><span class="cx">
</span><span class="cx">
</span><del>- def __init__(self, acknowledged=0, unacknowledged=0, unclosed=0):
</del><ins>+ def __init__(
+ self,
+ acknowledged=0,
+ unacknowledged=0,
+ total=0,
+ started=0,
+ abandoned=0,
+ unclosed=0,
+ starting=0,
+ stopped=0
+ ):
</ins><span class="cx"> """
</span><span class="cx"> Create a L{ConnectionStatus} with a number of sent connections and a
</span><span class="cx"> number of un-acknowledged connections.
</span><span class="lines">@@ -710,12 +709,32 @@
</span><span class="cx"> the subprocess which have never received a status response (a
</span><span class="cx"> "C{+}" status message).
</span><span class="cx">
</span><ins>+ @param total: The total number of acknowledged connections over
+ the lifetime of this socket.
+
+ @param started: The number of times this worker has been started.
+
+ @param abandoned: The number of connections which have been sent to
+ this worker, but were not acknowledged at the moment that the
+ worker was stopped.
+
</ins><span class="cx"> @param unclosed: The number of sockets which have been sent to the
</span><span class="cx"> subprocess but not yet closed.
</span><ins>+
+ @param starting: The process that owns this socket is starting. Do not
+ dispatch to it until we receive the started message.
+
+ @param stopped: The process that owns this socket has stopped. Do not
+ dispatch to it.
</ins><span class="cx"> """
</span><span class="cx"> self.acknowledged = acknowledged
</span><span class="cx"> self.unacknowledged = unacknowledged
</span><ins>+ self.total = total
+ self.started = started
+ self.abandoned = abandoned
</ins><span class="cx"> self.unclosed = unclosed
</span><ins>+ self.starting = starting
+ self.stopped = stopped
</ins><span class="cx">
</span><span class="cx">
</span><span class="cx"> def effectiveLoad(self):
</span><span class="lines">@@ -725,37 +744,64 @@
</span><span class="cx"> return self.acknowledged + self.unacknowledged
</span><span class="cx">
</span><span class="cx">
</span><del>- def _tuplify(self):
- return tuple(getattr(self, attr) for attr in self.showAttributes)
</del><ins>+ def active(self):
+ """
+ Is the subprocess associated with this socket available to dispatch to.
+ i.e, this socket is neither stopped nor starting
+ """
+ return self.starting == 0 and self.stopped == 0
</ins><span class="cx">
</span><span class="cx">
</span><del>- def __lt__(self, other):
- if not isinstance(other, ChildStatus):
- return NotImplemented
</del><ins>+ def start(self):
+ """
+ The child process for this L{WorkerStatus} is about to (re)start. Reset the status to indicate it
+ is starting - that should prevent any new connections being dispatched.
+ """
+ return self.reset(
+ starting=1,
+ stopped=0,
+ )
</ins><span class="cx">
</span><del>- return self.effectiveLoad() < other.effectiveLoad()
</del><span class="cx">
</span><ins>+ def restarted(self):
+ """
+ The child process for this L{WorkerStatus} has indicated it is now available to accept
+ connections, so reset the starting status so this socket will be available for dispatch.
+ """
+ return self.reset(
+ started=self.started + 1,
+ starting=0,
+ )
</ins><span class="cx">
</span><del>- def __eq__(self, other):
- if not isinstance(other, ChildStatus):
- return NotImplemented
</del><span class="cx">
</span><del>- return self._tuplify() == other._tuplify()
</del><ins>+ def stop(self):
+ """
+ The child process for this L{WorkerStatus} has stopped. Stop the socket and clear out
+ existing counters, but track abandoned connections.
+ """
+ return self.reset(
+ acknowledged=0,
+ unacknowledged=0,
+ abandoned=self.abandoned + self.unacknowledged,
+ starting=0,
+ stopped=1,
+ )
</ins><span class="cx">
</span><span class="cx">
</span><del>- def __add__(self, other):
- if not isinstance(other, ChildStatus):
- return NotImplemented
</del><ins>+ def adjust(self, **kwargs):
+ """
+ Update the L{WorkerStatus} by adding the supplied values to the specified attributes.
+ """
+ for k, v in kwargs.items():
+ newval = getattr(self, k) + v
+ setattr(self, k, max(newval, 0))
+ return self
</ins><span class="cx">
</span><del>- a = self._tuplify()
- b = other._tuplify()
- sum = [a1 + b1 for (a1, b1) in zip(a, b)]
</del><span class="cx">
</span><del>- return self.__class__(*sum)
-
-
- def __sub__(self, other):
- if not isinstance(other, ChildStatus):
- return NotImplemented
-
- return self + self.__class__(*[-x for x in other._tuplify()])
</del><ins>+ def reset(self, **kwargs):
+ """
+ Reset the L{WorkerStatus} by setting the supplied values in the specified attributes.
+ """
+ for k, v in kwargs.items():
+ setattr(self, k, v)
+ return self
</ins></span></pre></div>
<a id="twexttrunktwextinternetsendfdportpy"></a>
<div class="modfile"><h4>Modified: twext/trunk/twext/internet/sendfdport.py (12843 => 12844)</h4>
<pre class="diff"><span>
<span class="info">--- twext/trunk/twext/internet/sendfdport.py        2014-03-07 20:38:57 UTC (rev 12843)
+++ twext/trunk/twext/internet/sendfdport.py        2014-03-07 20:48:27 UTC (rev 12844)
</span><span class="lines">@@ -116,9 +116,10 @@
</span><span class="cx"> @type dispatcher: L{InheritedSocketDispatcher}
</span><span class="cx"> """
</span><span class="cx">
</span><del>- def __init__(self, dispatcher, inSocket, outSocket, status):
</del><ins>+ def __init__(self, dispatcher, inSocket, outSocket, status, slavenum):
</ins><span class="cx"> FileDescriptor.__init__(self, dispatcher.reactor)
</span><span class="cx"> self.status = status
</span><ins>+ self.slavenum = slavenum
</ins><span class="cx"> self.dispatcher = dispatcher
</span><span class="cx"> self.inSocket = inSocket
</span><span class="cx"> self.outSocket = outSocket # XXX needs to be set non-blocking by somebody
</span><span class="lines">@@ -127,6 +128,49 @@
</span><span class="cx"> self.pendingCloseSocketQueue = []
</span><span class="cx">
</span><span class="cx">
</span><ins>+ def childSocket(self):
+ """
+ Return the socket that the child process will use to communicate with the master.
+ """
+ return self.inSocket
+
+
+ def start(self):
+ """
+ The master process monitor is about to start the child process associated with this socket.
+ Update status to ensure dispatcher know what is going on.
+ """
+ self.status.start()
+ self.dispatcher.statusChanged()
+
+
+ def restarted(self):
+ """
+ The child process associated with this socket has signaled it is ready.
+ Update status to ensure dispatcher know what is going on.
+ """
+ self.status.restarted()
+ self.dispatcher.statusChanged()
+
+
+ def stop(self):
+ """
+ The master process monitor has determined the child process associated with this socket
+ has died. Update status to ensure dispatcher know what is going on.
+ """
+ self.status.stop()
+ self.dispatcher.statusChanged()
+
+
+ def remove(self):
+ """
+ Remove this socket.
+ """
+ self.status.stop()
+ self.dispatcher.statusChanged()
+ self.dispatcher.removeSocket()
+
+
</ins><span class="cx"> def sendSocketToPeer(self, skt, description):
</span><span class="cx"> """
</span><span class="cx"> Enqueue a socket to send to the subprocess.
</span><span class="lines">@@ -174,6 +218,51 @@
</span><span class="cx">
</span><span class="cx">
</span><span class="cx">
</span><ins>+class IStatus(Interface):
+ """
+ Defines the status of a socket. This keeps track of active connections etc.
+ """
+
+ def effective():
+ """
+ The current effective load.
+
+ @return: The current effective load.
+ @rtype: L{int}
+ """
+
+ def active():
+ """
+ Whether the socket should be active (able to be dispatched to).
+
+ @return: Active state.
+ @rtype: L{bool}
+ """
+
+ def start():
+ """
+ Worker process is starting. Mark status accordingly but do not make
+ it active.
+
+ @return: C{self}
+ """
+
+ def restarted():
+ """
+ Worker process has signaled it is ready so make this active.
+
+ @return: C{self}
+ """
+
+ def stop():
+ """
+ Worker process has stopped so make this inactive.
+
+ @return: C{self}
+ """
+
+
+
</ins><span class="cx"> class IStatusWatcher(Interface):
</span><span class="cx"> """
</span><span class="cx"> A provider of L{IStatusWatcher} tracks the I{status messages} reported by
</span><span class="lines">@@ -209,7 +298,6 @@
</span><span class="cx"> @return: the new status.
</span><span class="cx"> """
</span><span class="cx">
</span><del>-
</del><span class="cx"> def newConnectionStatus(previousStatus):
</span><span class="cx"> """
</span><span class="cx"> A new connection was sent to a given socket. Compute its status based
</span><span class="lines">@@ -221,7 +309,6 @@
</span><span class="cx"> @return: the socket's status after incrementing its outstanding work.
</span><span class="cx"> """
</span><span class="cx">
</span><del>-
</del><span class="cx"> def statusFromMessage(previousStatus, message):
</span><span class="cx"> """
</span><span class="cx"> A status message was received by a worker. Convert the previous status
</span><span class="lines">@@ -235,7 +322,6 @@
</span><span class="cx"> account.
</span><span class="cx"> """
</span><span class="cx">
</span><del>-
</del><span class="cx"> def closeCountFromStatus(previousStatus):
</span><span class="cx"> """
</span><span class="cx"> Based on a status previously returned from a method on this
</span><span class="lines">@@ -254,7 +340,7 @@
</span><span class="cx"> list of available sockets that connect to I{worker process}es and sends
</span><span class="cx"> inbound connections to be inherited over those sockets, by those processes.
</span><span class="cx">
</span><del>- L{InheritedSocketDispatcher} is therefore insantiated in the I{master
</del><ins>+ L{InheritedSocketDispatcher} is therefore instantiated in the I{master
</ins><span class="cx"> process}.
</span><span class="cx">
</span><span class="cx"> @ivar statusWatcher: The object which will handle status messages and
</span><span class="lines">@@ -276,27 +362,43 @@
</span><span class="cx"> @property
</span><span class="cx"> def statuses(self):
</span><span class="cx"> """
</span><del>- Yield the current status of all subprocess sockets.
</del><ins>+ Yield the current status of all subprocess sockets in the current priority order.
</ins><span class="cx"> """
</span><span class="cx"> for subsocket in self._subprocessSockets:
</span><span class="cx"> yield subsocket.status
</span><span class="cx">
</span><span class="cx">
</span><ins>+ @property
+ def slavestates(self):
+ """
+ Yield the current status of all subprocess sockets, ordered by slave number.
+ """
+ for subsocket in sorted(self._subprocessSockets, key=lambda x: x.slavenum):
+ yield (subsocket.slavenum, subsocket.status,)
+
+
+ def statusChanged(self):
+ """
+ Someone is telling us a child socket status changed.
+ """
+ self.statusWatcher.statusesChanged(self.statuses)
+
+
</ins><span class="cx"> def statusMessage(self, subsocket, message):
</span><span class="cx"> """
</span><span class="cx"> The status of a connection has changed; update all registered status
</span><span class="cx"> change listeners.
</span><span class="cx"> """
</span><del>- watcher = self.statusWatcher
- status = watcher.statusFromMessage(subsocket.status, message)
- closeCount, subsocket.status = watcher.closeCountFromStatus(status)
- watcher.statusesChanged(self.statuses)
</del><ins>+ status = self.statusWatcher.statusFromMessage(subsocket.status, message)
+ closeCount, subsocket.status = self.statusWatcher.closeCountFromStatus(status)
+ self.statusChanged()
</ins><span class="cx"> return closeCount
</span><span class="cx">
</span><span class="cx">
</span><span class="cx"> def sendFileDescriptor(self, skt, description):
</span><span class="cx"> """
</span><del>- A connection has been received. Dispatch it.
</del><ins>+ A connection has been received. Dispatch it to active sockets, sorted by
+ how much work they have.
</ins><span class="cx">
</span><span class="cx"> @param skt: the I{connection socket} (i.e.: not the listening socket)
</span><span class="cx"> @type skt: L{socket.socket}
</span><span class="lines">@@ -305,23 +407,15 @@
</span><span class="cx"> L{InheritedPort} what type of transport to create for this socket.
</span><span class="cx"> @type description: C{bytes}
</span><span class="cx"> """
</span><del>- # We want None to sort after 0 and before 1, so coerce to 0.5 - this
- # allows the master to first schedule all child process that are up but
- # not yet busy ahead of those that are still starting up.
- def sortKey(conn):
- if conn.status is None:
- return 0.5
- else:
- return conn.status
- self._subprocessSockets.sort(key=sortKey)
- selectedSocket = self._subprocessSockets[0]
</del><ins>+ self._subprocessSockets.sort(key=lambda x: x.status.effective())
+ selectedSocket = filter(lambda x: x.status.active(), self._subprocessSockets)[0]
</ins><span class="cx"> selectedSocket.sendSocketToPeer(skt, description)
</span><span class="cx"> # XXX Maybe want to send along 'description' or 'skt' or some
</span><span class="cx"> # properties thereof? -glyph
</span><span class="cx"> selectedSocket.status = self.statusWatcher.newConnectionStatus(
</span><span class="cx"> selectedSocket.status
</span><span class="cx"> )
</span><del>- self.statusWatcher.statusesChanged(self.statuses)
</del><ins>+ self.statusChanged()
</ins><span class="cx">
</span><span class="cx">
</span><span class="cx"> def startDispatching(self):
</span><span class="lines">@@ -333,7 +427,7 @@
</span><span class="cx"> subSocket.startReading()
</span><span class="cx">
</span><span class="cx">
</span><del>- def addSocket(self, socketpair=lambda: socketpair(AF_UNIX, SOCK_DGRAM)):
</del><ins>+ def addSocket(self, slavenum=0, socketpair=lambda: socketpair(AF_UNIX, SOCK_DGRAM)):
</ins><span class="cx"> """
</span><span class="cx"> Add a L{send1msg}-oriented AF_UNIX socket to the pool of sockets being
</span><span class="cx"> used for transmitting file descriptors to child processes.
</span><span class="lines">@@ -345,11 +439,11 @@
</span><span class="cx"> i, o = socketpair()
</span><span class="cx"> i.setblocking(False)
</span><span class="cx"> o.setblocking(False)
</span><del>- a = _SubprocessSocket(self, i, o, self.statusWatcher.initialStatus())
</del><ins>+ a = _SubprocessSocket(self, i, o, self.statusWatcher.initialStatus(), slavenum)
</ins><span class="cx"> self._subprocessSockets.append(a)
</span><span class="cx"> if self._isDispatching:
</span><span class="cx"> a.startReading()
</span><del>- return i
</del><ins>+ return a
</ins><span class="cx">
</span><span class="cx">
</span><span class="cx"> def removeSocket(self, skt):
</span><span class="lines">@@ -357,12 +451,7 @@
</span><span class="cx"> Removes a previously added socket from the pool of sockets being used
</span><span class="cx"> for transmitting file descriptors to child processes.
</span><span class="cx"> """
</span><del>- for a in self._subprocessSockets:
- if a.inSocket == skt:
- self._subprocessSockets.remove(a)
- break
- else:
- raise ValueError("Unknown socket: {0}".format(skt))
</del><ins>+ self._subprocessSockets.remove(skt)
</ins><span class="cx">
</span><span class="cx">
</span><span class="cx">
</span></span></pre></div>
<a id="twexttrunktwextinternettesttest_sendfdportpy"></a>
<div class="modfile"><h4>Modified: twext/trunk/twext/internet/test/test_sendfdport.py (12843 => 12844)</h4>
<pre class="diff"><span>
<span class="info">--- twext/trunk/twext/internet/test/test_sendfdport.py        2014-03-07 20:38:57 UTC (rev 12843)
+++ twext/trunk/twext/internet/test/test_sendfdport.py        2014-03-07 20:48:27 UTC (rev 12844)
</span><span class="lines">@@ -1,4 +1,3 @@
</span><del>-from twext.internet.sendfdport import IStatusWatcher
</del><span class="cx"> # -*- test-case-name: twext.internet.test.test_sendfdport -*-
</span><span class="cx"> ##
</span><span class="cx"> # Copyright (c) 2010-2014 Apple Inc. All rights reserved.
</span><span class="lines">@@ -27,6 +26,7 @@
</span><span class="cx"> from zope.interface import implementer
</span><span class="cx">
</span><span class="cx"> from twext.internet.sendfdport import InheritedSocketDispatcher
</span><ins>+from twext.internet.sendfdport import IStatusWatcher, IStatus
</ins><span class="cx">
</span><span class="cx"> from twisted.internet.interfaces import IReactorFDSet
</span><span class="cx"> from twisted.trial.unittest import TestCase
</span><span class="lines">@@ -101,6 +101,38 @@
</span><span class="cx">
</span><span class="cx">
</span><span class="cx">
</span><ins>+@verifiedImplementer(IStatus)
+class Status(object):
+ def __init__(self):
+ self.count = 0
+ self.available = False
+
+
+ def effective(self):
+ return self.count
+
+
+ def active(self):
+ return self.available
+
+
+ def start(self):
+ self.available = False
+ return self
+
+
+ def restarted(self):
+ self.available = True
+ return self
+
+
+ def stop(self):
+ self.count = 0
+ self.available = False
+ return self
+
+
+
</ins><span class="cx"> @verifiedImplementer(IStatusWatcher)
</span><span class="cx"> class Watcher(object):
</span><span class="cx"> def __init__(self, q):
</span><span class="lines">@@ -109,19 +141,21 @@
</span><span class="cx">
</span><span class="cx">
</span><span class="cx"> def newConnectionStatus(self, previous):
</span><del>- return previous + 1
</del><ins>+ previous.count += 1
+ return previous
</ins><span class="cx">
</span><span class="cx">
</span><span class="cx"> def statusFromMessage(self, previous, message):
</span><del>- return previous - 1
</del><ins>+ previous.count -= 1
+ return previous
</ins><span class="cx">
</span><span class="cx">
</span><span class="cx"> def statusesChanged(self, statuses):
</span><del>- self.q.append(list(statuses))
</del><ins>+ self.q.append([(status.count, status.available) for status in statuses])
</ins><span class="cx">
</span><span class="cx">
</span><span class="cx"> def initialStatus(self):
</span><del>- return 0
</del><ins>+ return Status()
</ins><span class="cx">
</span><span class="cx">
</span><span class="cx"> def closeCountFromStatus(self, status):
</span><span class="lines">@@ -164,9 +198,10 @@
</span><span class="cx"> two = SocketForClosing()
</span><span class="cx"> three = SocketForClosing()
</span><span class="cx">
</span><del>- self.dispatcher.addSocket(
</del><ins>+ skt = self.dispatcher.addSocket(
</ins><span class="cx"> lambda: (SocketForClosing(), SocketForClosing())
</span><span class="cx"> )
</span><ins>+ skt.restarted()
</ins><span class="cx">
</span><span class="cx"> self.dispatcher.sendFileDescriptor(one, "one")
</span><span class="cx"> self.dispatcher.sendFileDescriptor(two, "two")
</span><span class="lines">@@ -228,10 +263,11 @@
</span><span class="cx"> dispatcher.statusWatcher = Watcher(q)
</span><span class="cx"> description = "whatever"
</span><span class="cx"> # Need to have a socket that will accept the descriptors.
</span><del>- dispatcher.addSocket()
</del><ins>+ skt = dispatcher.addSocket()
+ skt.restarted()
</ins><span class="cx"> dispatcher.sendFileDescriptor(object(), description)
</span><span class="cx"> dispatcher.sendFileDescriptor(object(), description)
</span><del>- self.assertEquals(q, [[1], [2]])
</del><ins>+ self.assertEquals(q, [[(0, True)], [(1, True)], [(2, True)]])
</ins><span class="cx">
</span><span class="cx">
</span><span class="cx"> def test_statusesChangedOnStatusMessage(self):
</span><span class="lines">@@ -249,4 +285,33 @@
</span><span class="cx"> subskt = dispatcher._subprocessSockets[0]
</span><span class="cx"> dispatcher.statusMessage(subskt, message)
</span><span class="cx"> dispatcher.statusMessage(subskt, message)
</span><del>- self.assertEquals(q, [[-1], [-2]])
</del><ins>+ self.assertEquals(q, [[(-1, False)], [(-2, False)]])
+
+
+ def test_statusesChangedOnStartRestartStop(self):
+ """
+ L{_SubprocessSocket} will update its C{status} when state change.
+ """
+ q = []
+ dispatcher = self.dispatcher
+ dispatcher.statusWatcher = Watcher(q)
+ message = "whatever"
+ # Need to have a socket that will accept the descriptors.
+ subskt = dispatcher.addSocket()
+ subskt.start()
+ subskt.restarted()
+ dispatcher.sendFileDescriptor(subskt, message)
+ subskt.stop()
+ subskt.start()
+ subskt.restarted()
+ self.assertEquals(
+ q,
+ [
+ [(0, False)],
+ [(0, True)],
+ [(1, True)],
+ [(0, False)],
+ [(0, False)],
+ [(0, True)],
+ ]
+ )
</ins></span></pre>
</div>
</div>
</body>
</html>