[CalendarServer-changes] [12843] CalendarServer/branches/release/CalendarServer-5.2-dev

source_changes at macosforge.org source_changes at macosforge.org
Fri Mar 7 12:38:57 PST 2014


Revision: 12843
          http://trac.calendarserver.org//changeset/12843
Author:   cdaboo at apple.com
Date:     2014-03-07 12:38:57 -0800 (Fri, 07 Mar 2014)
Log Message:
-----------
Fix master-child slot counting issues.

Modified Paths:
--------------
    CalendarServer/branches/release/CalendarServer-5.2-dev/calendarserver/tap/caldav.py
    CalendarServer/branches/release/CalendarServer-5.2-dev/calendarserver/tap/test/test_caldav.py
    CalendarServer/branches/release/CalendarServer-5.2-dev/twext/internet/sendfdport.py
    CalendarServer/branches/release/CalendarServer-5.2-dev/twext/internet/test/test_sendfdport.py
    CalendarServer/branches/release/CalendarServer-5.2-dev/twext/web2/metafd.py
    CalendarServer/branches/release/CalendarServer-5.2-dev/twext/web2/test/test_metafd.py

Modified: CalendarServer/branches/release/CalendarServer-5.2-dev/calendarserver/tap/caldav.py
===================================================================
--- CalendarServer/branches/release/CalendarServer-5.2-dev/calendarserver/tap/caldav.py	2014-03-07 20:24:02 UTC (rev 12842)
+++ CalendarServer/branches/release/CalendarServer-5.2-dev/calendarserver/tap/caldav.py	2014-03-07 20:38:57 UTC (rev 12843)
@@ -500,7 +500,9 @@
     def startService(self):
         for slaveNumber in xrange(0, config.MultiProcess.ProcessCount):
             if config.UseMetaFD:
-                extraArgs = dict(metaSocket=self.dispatcher.addSocket())
+                extraArgs = dict(
+                    metaSocket=self.dispatcher.addSocket(slaveNumber)
+                )
             else:
                 extraArgs = dict(inheritFDs=self.inheritFDs,
                                  inheritSSLFDs=self.inheritSSLFDs)
@@ -1802,7 +1804,6 @@
     @ivar metaSocket: an AF_UNIX/SOCK_DGRAM socket (initialized from the
         dispatcher passed to C{__init__}) that is to be inherited by the
         subprocess and used to accept incoming connections.
-
     @type metaSocket: L{socket.socket}
 
     @ivar ampSQLDispenser: a factory for AF_UNIX/SOCK_STREAM sockets that are
@@ -1835,6 +1836,30 @@
         self.ampDBSocket = None
 
 
+    def starting(self):
+        """
+        Called when the process is being started (or restarted). Allows for various initialization
+        operations to be done. The child process will itself signal back to the master when it is ready
+        to accept sockets - until then the master socket is marked as "starting" which means it is not
+        active and won't be dispatched to.
+        """
+
+        # Always tell any metafd socket that we have started, so it can re-initialize state.
+        if self.metaSocket is not None:
+            self.metaSocket.start()
+
+
+    def stopped(self):
+        """
+        Called when the process has stopped (died). The socket is marked as "stopped" which means it is
+        not active and won't be dispatched to.
+        """
+
+        # Always tell any metafd socket that we have started, so it can re-initialize state.
+        if self.metaSocket is not None:
+            self.metaSocket.stop()
+
+
     def getName(self):
         return '%s-%s' % (self.prefix, self.id)
 
@@ -1863,7 +1888,7 @@
         fds = {}
         extraFDs = []
         if self.metaSocket is not None:
-            extraFDs.append(self.metaSocket.fileno())
+            extraFDs.append(self.metaSocket.childSocket().fileno())
         if self.ampSQLDispenser is not None:
             self.ampDBSocket = self.ampSQLDispenser.dispense()
             extraFDs.append(self.ampDBSocket.fileno())
@@ -1922,7 +1947,7 @@
 
         if self.metaSocket is not None:
             args.extend([
-                    "-o", "MetaFD=%s" % (self.metaSocket.fileno(),)
+                    "-o", "MetaFD=%s" % (self.metaSocket.childSocket().fileno(),)
                 ])
         if self.ampDBSocket is not None:
             args.extend([
@@ -2015,6 +2040,10 @@
             exists
         """
         class SimpleProcessObject(object):
+            def starting(self):
+                pass
+            def stopped(self):
+                pass
             def getName(self):
                 return name
             def getCommandLine(self):
@@ -2103,7 +2132,10 @@
     def processEnded(self, name):
         """
         When a child process has ended it calls me so I can fire the
-        appropriate deferred which was created in stopService
+        appropriate deferred which was created in stopService.
+
+        Also make sure to signal the dispatcher so that the socket is
+        marked as inactive.
         """
         # Cancel the scheduled _forceStopProcess function if the process
         # dies naturally
@@ -2112,6 +2144,8 @@
                 self.murder[name].cancel()
             del self.murder[name]
 
+        self.processes[name][0].stopped()
+
         del self.protocols[name]
 
         if self._reactor.seconds() - self.timeStarted[name] < self.threshold:
@@ -2198,6 +2232,8 @@
 
         childFDs.update(procObj.getFileDescriptors())
 
+        procObj.starting()
+
         args = procObj.getCommandLine()
 
         self._reactor.spawnProcess(

Modified: CalendarServer/branches/release/CalendarServer-5.2-dev/calendarserver/tap/test/test_caldav.py
===================================================================
--- CalendarServer/branches/release/CalendarServer-5.2-dev/calendarserver/tap/test/test_caldav.py	2014-03-07 20:24:02 UTC (rev 12842)
+++ CalendarServer/branches/release/CalendarServer-5.2-dev/calendarserver/tap/test/test_caldav.py	2014-03-07 20:38:57 UTC (rev 12843)
@@ -954,6 +954,14 @@
         self.args = args
 
 
+    def starting(self):
+        pass
+
+
+    def stopped(self):
+        pass
+
+
     def getCommandLine(self):
         """
         Simple command line.
@@ -1204,12 +1212,35 @@
 
 
 
+class FakeSubsocket(object):
+
+    def __init__(self, fakefd):
+        self.fakefd = fakefd
+
+
+    def childSocket(self):
+        return self.fakefd
+
+
+    def start(self):
+        pass
+
+
+    def restarted(self):
+        pass
+
+
+    def stop(self):
+        pass
+
+
+
 class FakeDispatcher(object):
     n = 3
 
     def addSocket(self):
         self.n += 1
-        return FakeFD(self.n)
+        return FakeSubsocket(FakeFD(self.n))
 
 
 

Modified: CalendarServer/branches/release/CalendarServer-5.2-dev/twext/internet/sendfdport.py
===================================================================
--- CalendarServer/branches/release/CalendarServer-5.2-dev/twext/internet/sendfdport.py	2014-03-07 20:24:02 UTC (rev 12842)
+++ CalendarServer/branches/release/CalendarServer-5.2-dev/twext/internet/sendfdport.py	2014-03-07 20:38:57 UTC (rev 12843)
@@ -94,8 +94,8 @@
     A socket in the master process pointing at a file descriptor that can be
     used to transmit sockets to a subprocess.
 
-    @ivar skt: the UNIX socket used as the sendmsg() transport.
-    @type skt: L{socket.socket}
+    @ivar outSocket: the UNIX socket used as the sendmsg() transport.
+    @type outSocket: L{socket.socket}
 
     @ivar outgoingSocketQueue: an outgoing queue of sockets to send to the
         subprocess, along with their descriptions (strings describing their
@@ -115,16 +115,61 @@
     @type dispatcher: L{InheritedSocketDispatcher}
     """
 
-    def __init__(self, dispatcher, skt, status):
+    def __init__(self, dispatcher, inSocket, outSocket, status, slavenum):
         FileDescriptor.__init__(self, dispatcher.reactor)
         self.status = status
+        self.slavenum = slavenum
         self.dispatcher = dispatcher
-        self.skt = skt          # XXX needs to be set non-blocking by somebody
-        self.fileno = skt.fileno
+        self.inSocket = inSocket
+        self.outSocket = outSocket   # XXX needs to be set non-blocking by somebody
+        self.fileno = outSocket.fileno
         self.outgoingSocketQueue = []
         self.pendingCloseSocketQueue = []
 
 
+    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()
+
+
     def sendSocketToPeer(self, skt, description):
         """
         Enqueue a socket to send to the subprocess.
@@ -138,7 +183,7 @@
         Receive a status / health message and record it.
         """
         try:
-            data, _ignore_flags, _ignore_ancillary = recvmsg(self.skt.fileno())
+            data, _ignore_flags, _ignore_ancillary = recvmsg(self.outSocket.fileno())
         except SocketError, se:
             if se.errno not in (EAGAIN, ENOBUFS):
                 raise
@@ -155,7 +200,7 @@
         while self.outgoingSocketQueue:
             skt, desc = self.outgoingSocketQueue.pop(0)
             try:
-                sendfd(self.skt.fileno(), skt.fileno(), desc)
+                sendfd(self.outSocket.fileno(), skt.fileno(), desc)
             except SocketError, se:
                 if se.errno in (EAGAIN, ENOBUFS):
                     self.outgoingSocketQueue.insert(0, (skt, desc))
@@ -170,6 +215,51 @@
 
 
 
+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}
+        """
+
+
+
 class IStatusWatcher(Interface):
     """
     A provider of L{IStatusWatcher} tracks the I{status messages} reported by
@@ -197,7 +287,7 @@
         than the somewhat more abstract language that would be accurate.
     """
 
-    def initialStatus(): #@NoSelf
+    def initialStatus():
         """
         A new socket was created and added to the dispatcher.  Compute an
         initial value for its status.
@@ -205,8 +295,7 @@
         @return: the new status.
         """
 
-
-    def newConnectionStatus(previousStatus): #@NoSelf
+    def newConnectionStatus(previousStatus):
         """
         A new connection was sent to a given socket.  Compute its status based
         on the previous status of that socket.
@@ -217,8 +306,7 @@
         @return: the socket's status after incrementing its outstanding work.
         """
 
-
-    def statusFromMessage(previousStatus, message): #@NoSelf
+    def statusFromMessage(previousStatus, message):
         """
         A status message was received by a worker.  Convert the previous status
         value (returned from L{newConnectionStatus}, L{initialStatus}, or
@@ -231,8 +319,7 @@
             account.
         """
 
-
-    def closeCountFromStatus(previousStatus): #@NoSelf
+    def closeCountFromStatus(previousStatus):
         """
         Based on a status previously returned from a method on this
         L{IStatusWatcher}, determine how many sockets may be closed.
@@ -250,7 +337,7 @@
     list of available sockets that connect to I{worker process}es and sends
     inbound connections to be inherited over those sockets, by those processes.
 
-    L{InheritedSocketDispatcher} is therefore insantiated in the I{master
+    L{InheritedSocketDispatcher} is therefore instantiated in the I{master
     process}.
 
     @ivar statusWatcher: The object which will handle status messages and
@@ -272,27 +359,43 @@
     @property
     def statuses(self):
         """
-        Yield the current status of all subprocess sockets.
+        Yield the current status of all subprocess sockets in the current priority order.
         """
         for subsocket in self._subprocessSockets:
             yield subsocket.status
 
 
+    @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)
+
+
     def statusMessage(self, subsocket, message):
         """
         The status of a connection has changed; update all registered status
         change listeners.
         """
-        watcher = self.statusWatcher
-        status = watcher.statusFromMessage(subsocket.status, message)
-        closeCount, subsocket.status = watcher.closeCountFromStatus(status)
-        watcher.statusesChanged(self.statuses)
+        status = self.statusWatcher.statusFromMessage(subsocket.status, message)
+        closeCount, subsocket.status = self.statusWatcher.closeCountFromStatus(status)
+        self.statusChanged()
         return closeCount
 
 
     def sendFileDescriptor(self, skt, description):
         """
-        A connection has been received.  Dispatch it.
+        A connection has been received.  Dispatch it to active sockets, sorted by
+        how much work they have.
 
         @param skt: the I{connection socket} (i.e.: not the listening socket)
         @type skt: L{socket.socket}
@@ -301,23 +404,15 @@
             L{InheritedPort} what type of transport to create for this socket.
         @type description: C{bytes}
         """
-        # 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]
+        self._subprocessSockets.sort(key=lambda x: x.status.effective())
+        selectedSocket = filter(lambda x: x.status.active(), self._subprocessSockets)[0]
         selectedSocket.sendSocketToPeer(skt, description)
         # XXX Maybe want to send along 'description' or 'skt' or some
         # properties thereof? -glyph
         selectedSocket.status = self.statusWatcher.newConnectionStatus(
             selectedSocket.status
         )
-        self.statusWatcher.statusesChanged(self.statuses)
+        self.statusChanged()
 
 
     def startDispatching(self):
@@ -329,7 +424,7 @@
             subSocket.startReading()
 
 
-    def addSocket(self, socketpair=lambda: socketpair(AF_UNIX, SOCK_DGRAM)):
+    def addSocket(self, slavenum=0, socketpair=lambda: socketpair(AF_UNIX, SOCK_DGRAM)):
         """
         Add a C{sendmsg()}-oriented AF_UNIX socket to the pool of sockets being
         used for transmitting file descriptors to child processes.
@@ -341,14 +436,22 @@
         i, o = socketpair()
         i.setblocking(False)
         o.setblocking(False)
-        a = _SubprocessSocket(self, o, self.statusWatcher.initialStatus())
+        a = _SubprocessSocket(self, i, o, self.statusWatcher.initialStatus(), slavenum)
         self._subprocessSockets.append(a)
         if self._isDispatching:
             a.startReading()
-        return i
+        return a
 
 
+    def removeSocket(self, skt):
+        """
+        Removes a previously added socket from the pool of sockets being used
+        for transmitting file descriptors to child processes.
+        """
+        self._subprocessSockets.remove(skt)
 
+
+
 class InheritedPort(FileDescriptor, object):
     """
     An L{InheritedPort} is an L{IReadDescriptor}/L{IWriteDescriptor} created in

Modified: CalendarServer/branches/release/CalendarServer-5.2-dev/twext/internet/test/test_sendfdport.py
===================================================================
--- CalendarServer/branches/release/CalendarServer-5.2-dev/twext/internet/test/test_sendfdport.py	2014-03-07 20:24:02 UTC (rev 12842)
+++ CalendarServer/branches/release/CalendarServer-5.2-dev/twext/internet/test/test_sendfdport.py	2014-03-07 20:38:57 UTC (rev 12843)
@@ -1,4 +1,3 @@
-from twext.internet.sendfdport import IStatusWatcher
 # -*- test-case-name: twext.internet.test.test_sendfdport -*-
 ##
 # Copyright (c) 2010-2014 Apple Inc. All rights reserved.
@@ -27,6 +26,7 @@
 from zope.interface import implementer
 
 from twext.internet.sendfdport import InheritedSocketDispatcher
+from twext.internet.sendfdport import IStatusWatcher, IStatus
 
 from twext.web2.metafd import ConnectionLimiter
 from twisted.internet.interfaces import IReactorFDSet
@@ -93,6 +93,38 @@
 
 
 
+ at 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
+
+
+
 @verifiedImplementer(IStatusWatcher)
 class Watcher(object):
     def __init__(self, q):
@@ -101,19 +133,21 @@
 
 
     def newConnectionStatus(self, previous):
-        return previous + 1
+        previous.count += 1
+        return previous
 
 
     def statusFromMessage(self, previous, message):
-        return previous - 1
+        previous.count -= 1
+        return previous
 
 
     def statusesChanged(self, statuses):
-        self.q.append(list(statuses))
+        self.q.append([(status.count, status.available) for status in statuses])
 
 
     def initialStatus(self):
-        return 0
+        return Status()
 
 
     def closeCountFromStatus(self, status):
@@ -152,9 +186,10 @@
         two = SocketForClosing()
         three = SocketForClosing()
 
-        self.dispatcher.addSocket(
+        skt = self.dispatcher.addSocket(
             lambda: (SocketForClosing(), SocketForClosing())
         )
+        skt.restarted()
 
         self.dispatcher.sendFileDescriptor(one, "one")
         self.dispatcher.sendFileDescriptor(two, "two")
@@ -214,10 +249,11 @@
         dispatcher.statusWatcher = Watcher(q)
         description = "whatever"
         # Need to have a socket that will accept the descriptors.
-        dispatcher.addSocket()
+        skt = dispatcher.addSocket()
+        skt.restarted()
         dispatcher.sendFileDescriptor(object(), description)
         dispatcher.sendFileDescriptor(object(), description)
-        self.assertEquals(q, [[1], [2]])
+        self.assertEquals(q, [[(0, True)], [(1, True)], [(2, True)]])
 
 
     def test_statusesChangedOnStatusMessage(self):
@@ -235,4 +271,33 @@
         subskt = dispatcher._subprocessSockets[0]
         dispatcher.statusMessage(subskt, message)
         dispatcher.statusMessage(subskt, message)
-        self.assertEquals(q, [[-1], [-2]])
+        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)],
+            ]
+        )

Modified: CalendarServer/branches/release/CalendarServer-5.2-dev/twext/web2/metafd.py
===================================================================
--- CalendarServer/branches/release/CalendarServer-5.2-dev/twext/web2/metafd.py	2014-03-07 20:24:02 UTC (rev 12842)
+++ CalendarServer/branches/release/CalendarServer-5.2-dev/twext/web2/metafd.py	2014-03-07 20:38:57 UTC (rev 12843)
@@ -21,12 +21,11 @@
 """
 from __future__ import print_function
 
-from functools import total_ordering
-
 from zope.interface import implementer
 
 from twext.internet.sendfdport import (
-    InheritedPort, InheritedSocketDispatcher, InheritingProtocolFactory)
+    InheritedPort, InheritedSocketDispatcher, InheritingProtocolFactory,
+    IStatus)
 from twext.internet.tcp import MaxAcceptTCPServer
 from twext.python.log import Logger
 from twext.web2.channel.http import HTTPFactory
@@ -164,17 +163,26 @@
 
 
 
- at total_ordering
+ at implementer(IStatus)
 class WorkerStatus(FancyStrMixin, object):
     """
     The status of a worker process.
     """
 
-    showAttributes = ("acknowledged unacknowledged started abandoned unclosed"
+    showAttributes = ("acknowledged unacknowledged total started abandoned unclosed starting stopped"
                       .split())
 
-    def __init__(self, acknowledged=0, unacknowledged=0, started=0,
-                 abandoned=0, unclosed=0):
+    def __init__(
+        self,
+        acknowledged=0,
+        unacknowledged=0,
+        total=0,
+        started=0,
+        abandoned=0,
+        unclosed=0,
+        starting=1,
+        stopped=0
+    ):
         """
         Create a L{ConnectionStatus} with a number of sent connections and a
         number of un-acknowledged connections.
@@ -187,20 +195,32 @@
             the subprocess which have never received a status response (a
             "C{+}" status message).
 
+        @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 restarted.
+            worker was stopped.
 
-        @param started: The number of times this worker has been started.
-
         @param unclosed: The number of sockets which have been sent to the
             subprocess but not yet closed.
+
+        @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.
         """
         self.acknowledged = acknowledged
         self.unacknowledged = unacknowledged
+        self.total = total
         self.started = started
         self.abandoned = abandoned
         self.unclosed = unclosed
+        self.starting = starting
+        self.stopped = stopped
 
 
     def effective(self):
@@ -210,43 +230,67 @@
         return self.acknowledged + self.unacknowledged
 
 
-    def restarted(self):
+    def active(self):
         """
-        The L{WorkerStatus} derived from the current status of a process and
-        the fact that it just restarted.
+        Is the subprocess associated with this socket available to dispatch to.
+        i.e, this socket is neither stopped nor starting
         """
-        return self.__class__(0, 0, self.started + 1, self.unacknowledged)
+        return self.starting == 0 and self.stopped == 0
 
 
-    def _tuplify(self):
-        return tuple(getattr(self, attr) for attr in self.showAttributes)
+    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,
+        )
 
 
-    def __lt__(self, other):
-        if not isinstance(other, WorkerStatus):
-            return NotImplemented
-        return self.effective() < other.effective()
+    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,
+        )
 
 
-    def __eq__(self, other):
-        if not isinstance(other, WorkerStatus):
-            return NotImplemented
-        return self._tuplify() == other._tuplify()
+    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,
+        )
 
 
-    def __add__(self, other):
-        if not isinstance(other, WorkerStatus):
-            return NotImplemented
-        a = self._tuplify()
-        b = other._tuplify()
-        c = [a1 + b1 for (a1, b1) in zip(a, b)]
-        return self.__class__(*c)
+    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
 
 
-    def __sub__(self, other):
-        if not isinstance(other, WorkerStatus):
-            return NotImplemented
-        return self + self.__class__(*[-x for x in other._tuplify()])
+    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
 
 
 
@@ -272,6 +316,7 @@
         self.dispatcher = InheritedSocketDispatcher(self)
         self.maxAccepts = maxAccepts
         self.maxRequests = maxRequests
+        self.overloaded = False
 
 
     def startService(self):
@@ -314,20 +359,20 @@
             # A connection has gone away in a subprocess; we should start
             # accepting connections again if we paused (see
             # newConnectionStatus)
-            return previousStatus - WorkerStatus(acknowledged=1)
+            return previousStatus.adjust(acknowledged=-1)
+
         elif message == '0':
-            # 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.)
+            # A new process just started accepting new connections.
             return previousStatus.restarted()
+
         else:
             # '+' acknowledges that the subprocess has taken on the work.
-            return previousStatus + WorkerStatus(acknowledged=1,
-                                                 unacknowledged=-1,
-                                                 unclosed=1)
+            return previousStatus.adjust(
+                acknowledged=1,
+                unacknowledged=-1,
+                total=1,
+                unclosed=1,
+            )
 
 
     def closeCountFromStatus(self, status):
@@ -335,21 +380,22 @@
         Determine the number of sockets to close from the current status.
         """
         toClose = status.unclosed
-        return (toClose, status - WorkerStatus(unclosed=toClose))
+        return (toClose, status.adjust(unclosed=-toClose))
 
 
     def newConnectionStatus(self, previousStatus):
         """
-        Determine the effect of a new connection being sent on a subprocess
-        socket.
+        A connection was just sent to the process, but not yet acknowledged.
         """
-        return previousStatus + WorkerStatus(unacknowledged=1)
+        return previousStatus.adjust(unacknowledged=1)
 
 
     def statusesChanged(self, statuses):
         """
         The L{InheritedSocketDispatcher} is reporting that the list of
-        connection-statuses have changed.
+        connection-statuses have changed. Check to see if we are overloaded
+        or if there are no active processes left. If so, stop the protocol
+        factory from processing more requests until capacity is back.
 
         (The argument to this function is currently duplicated by the
         C{self.dispatcher.statuses} attribute, which is what
@@ -360,8 +406,10 @@
         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 overloaded:
+            if self.overloaded:
                 f.loadAboveMaximum()
             else:
                 f.loadNominal()

Modified: CalendarServer/branches/release/CalendarServer-5.2-dev/twext/web2/test/test_metafd.py
===================================================================
--- CalendarServer/branches/release/CalendarServer-5.2-dev/twext/web2/test/test_metafd.py	2014-03-07 20:24:02 UTC (rev 12842)
+++ CalendarServer/branches/release/CalendarServer-5.2-dev/twext/web2/test/test_metafd.py	2014-03-07 20:38:57 UTC (rev 12843)
@@ -71,15 +71,12 @@
     def startReading(self):
         "Do nothing."
 
-
     def stopReading(self):
         "Do nothing."
 
-
     def startWriting(self):
         "Do nothing."
 
-
     def stopWriting(self):
         "Do nothing."
 
@@ -93,19 +90,15 @@
     def startReading(self):
         "Do nothing."
 
-
     def stopReading(self):
         "Do nothing."
 
-
     def startWriting(self):
         "Do nothing."
 
-
     def stopWriting(self):
         "Do nothing."
 
-
     def __init__(self, *a, **kw):
         super(ServerTransportForTesting, self).__init__(*a, **kw)
         self.reactor = None
@@ -225,12 +218,28 @@
         L{WorkerStatus.__repr__} will show all the values associated with the
         status of the worker.
         """
-        self.assertEquals(repr(WorkerStatus(1, 2, 3, 4, 5)),
-                          "<WorkerStatus acknowledged=1 unacknowledged=2 "
-                          "started=3 abandoned=4 unclosed=5>")
+        self.assertEquals(repr(WorkerStatus(1, 2, 3, 4, 5, 6, 7, 8)),
+                          "<WorkerStatus acknowledged=1 unacknowledged=2 total=3 "
+                          "started=4 abandoned=5 unclosed=6 starting=7 stopped=8>")
 
 
+    def test_workerStatusNonNegative(self):
+        """
+        L{WorkerStatus.__repr__} will show all the values associated with the
+        status of the worker.
+        """
+        w = WorkerStatus()
+        w.adjust(
+            acknowledged=1,
+            unacknowledged=-1,
+            total=1,
+        )
+        self.assertEquals(w.acknowledged, 1)
+        self.assertEquals(w.unacknowledged, 0)
+        self.assertEquals(w.total, 1)
 
+
+
 class LimiterBuilder(object):
     """
     A L{LimiterBuilder} can build a L{ConnectionLimiter} and associated objects
@@ -251,7 +260,9 @@
         self.limiter.addPortService("TCP", 4321, "127.0.0.1", 5,
                                     self.serverServiceMakerMaker(self.service))
         for ignored in xrange(socketCount):
-            self.dispatcher.addSocket()
+            subskt = self.dispatcher.addSocket()
+            subskt.start()
+            subskt.restarted()
         # Has to be running in order to add stuff.
         self.limiter.startService()
         self.port = self.service.myPort
@@ -296,7 +307,7 @@
         @param count: Amount of load to add; default to the maximum that the
             limiter.
         """
-        for x in range(count or self.limiter.maxRequests):
+        for _ignore_x in range(count or self.limiter.maxRequests):
             self.dispatcher.sendFileDescriptor(None, "SSL")
             if acknowledged:
                 self.dispatcher.statusMessage(
@@ -305,6 +316,8 @@
 
 
     def processRestart(self):
+        self.dispatcher._subprocessSockets[0].stop()
+        self.dispatcher._subprocessSockets[0].start()
         self.dispatcher.statusMessage(
             self.dispatcher._subprocessSockets[0], "0"
         )
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.macosforge.org/pipermail/calendarserver-changes/attachments/20140307/050a8afd/attachment-0001.html>


More information about the calendarserver-changes mailing list