def main(self): self.timebomb.activate() self.child.activate() yield 1 while not (self.child._isStopped() or (self.dataReady('_trigger') and self.recv('_trigger') is True)): self.pause() yield 1 if not self.timebomb._isStopped(): self.send(producerFinished(), '_disarm') shutdown_messages = [ producerFinished(), shutdownMicroprocess(), serverShutdown(), shutdown() ] for msg in shutdown_messages: if not self.child._isStopped(): self.send( msg, "_sigkill") yield 1 yield 1 else: break self.removeChild(self.child) yield 1 if not self.child._isStopped(): self.child.stop() yield 1 if 'signal' in self.Outboxes: self.send(shutdownMicroprocess(), 'signal') yield 1
def main(self): self.Logger.activate() connectToLogger(self.Producer, self.logname) i = 0 while i < 50: print 'i = ' + str(i) i += 1 yield 1 print 'SomeChassis shutting down!' self.send(shutdownMicroprocess(), 'signal-logger') self.send(shutdownMicroprocess(), 'signal-producer')
def main(self): yield self.setup() while self.running: if self.dataReady("control"): mes = self.recv("control") if isinstance(mes, str): if mes.strip() == 'quit': self.shutdown() elif isinstance(mes, shutdownMicroprocess) or isinstance(mes, producerFinished): self.send(mes, "signal") break if self.dataReady("connected"): self.recv('connected') self.connected = True if self.dataReady("unhandled"): msg = self.recv('unhandled') self.send(('UNHANDLED', msg), 'log') if self.dataReady("inbox"): msg = self.recv('inbox') if msg == "quit": self.send(shutdownMicroprocess(), "signal") yield 1 break if self.dataReady("streamfeat"): feat = self.recv('streamfeat') if feat.register and self.register: self.send(Registration(), 'doregistration') elif self.register and not feat.register: print "The server does not support in-band registration. Closing connection." self.abort() else: self.send(feat, 'doauth') if self.dataReady("jid"): self.jid = self.recv('jid') if not self.anyReady(): self.pause() yield 1 yield shutdownMicroprocess(self, self.children, self.backplanes)
def main(self): self.control_message = None self.connectionSuccess = False self.loggedIn = False yield WaitComplete(self.waitForBanner()) if self.connectionSuccess: yield WaitComplete(self.doLogin(self.username, self.password)) if self.loggedIn: run = True while run: while not self.anyReady(): self.pause() yield 1 while self.dataReady("client_inbox"): command = self.recv("client_inbox") yield WaitComplete(self.handleCommand(command)) if command[0] == "QUIT": run = False self.sendCommand("QUIT") yield WaitComplete(self.getline(), tag="_getline5") # print "SERVER RESPONSE", self.line if self.shutdown() or self.control_message: self.send(self.control_message, "signal") # Pass on else: self.send(shutdownMicroprocess(), "signal") yield 1
def testLinearShutdown2(self): """A shutdownMicroprocess() shutdown signal will be handled properly.""" self.setup_tests() self.sendToControl(shutdownMicroprocess()) self.runUntil() self.failUnless(isinstance(self.recvSignal(), producerFinished)) self.checkStop(stopped=True)
def test_queuedNextsAbortedIfShutdownMicroprocess(self): """If a shutdownMicroprocess() is received, any messages queued on the 'next' inbox are discarded; and Carousel shuts down as soon as any current child has terminated.""" self.setup_test() self.runFor(cycles=5) self.sendToNext("BLAH") self.runFor(cycles=50) self.sendToControl(shutdownMicroprocess()) for i in range(1, 10): self.sendToNext("BLAH") self.runFor(cycles=50) self.assert_(len(self.children) == 1, "Should only be the one child") self.assert_(not self.carousel._isStopped(), "Carousel shouldn't have stopped until the child has") msg = self.children[-1].recv("control") self.assert_(isinstance(msg, (shutdownMicroprocess, producerFinished))) self.children[-1].stopNow = True self.runFor(cycles=2) self.assert_(len(self.children) == 1, "Should only be the one child") self.assert_(self.carousel._isStopped(), "Carousel should have terminated") self.assert_(self.children[0]._isStopped(), "Child should have terminated")
def testLinearShutdown2(self): """A shutdownMicroprocess() shutdown signal will be handled properly.""" self.setup_tests() self.sendToControl(shutdownMicroprocess()) self.runUntil() self.failUnless(isinstance(self.recvSignal(), producerFinished)) self.checkStop(stopped = True)
def test_queuedNextsAbortedIfShutdownMicroprocess(self): """If a shutdownMicroprocess() is received, any messages queued on the 'next' inbox are discarded; and Carousel shuts down as soon as any current child has terminated.""" self.setup_test() self.runFor(cycles=5) self.sendToNext("BLAH") self.runFor(cycles=50) self.sendToControl(shutdownMicroprocess()) for i in range(1,10): self.sendToNext("BLAH") self.runFor(cycles=50) self.assert_(len(self.children)==1, "Should only be the one child") self.assert_(not self.carousel._isStopped(), "Carousel shouldn't have stopped until the child has") msg=self.children[-1].recv("control") self.assert_(isinstance(msg,(shutdownMicroprocess,producerFinished))) self.children[-1].stopNow=True self.runFor(cycles=2) self.assert_(len(self.children)==1, "Should only be the one child") self.assert_(self.carousel._isStopped(), "Carousel should have terminated") self.assert_(self.children[0]._isStopped(), "Child should have terminated")
def test_receivesShutdownDisseminated(self): """If a graphline's "control" inbox is not specified to be wired to a child component in the graphline, then any message (including shutdown messages) flows to the "control" inbox of all children without linkages going to their "control" inbox only.""" A=MockChild() B=MockChild() C=MockChild() self.setup_initialise( A=A, B=B, C=C, linkages={ ("A","outbox"):("B","control"), # should block msg getting to B }) self.setup_activate() self.runFor(cycles=100) msg=shutdownMicroprocess() self.sendTo(msg,"control") self.runFor(cycles=2) self.assert_(A.dataReady("control")) self.assertEquals(msg, A.recv("control")) self.assert_(not(B.dataReady("control"))) self.assert_(C.dataReady("control")) self.assertEquals(msg, C.recv("control"))
def test_SplitterShutdown(self): """If producerFinished or shutdownMicroprocess is received on the 'control' inbox they are passed on and the component shuts down""" for msg in [producerFinished(self), shutdownMicroprocess(self)]: split = Splitter() Dummy = Axon.Component.component() split.link((split, "outbox"), (Dummy, "inbox")) split.link((split, "signal"), (Dummy, "control")) split.activate() for _ in xrange(0,10): split.next() self.assert_(0==len(split.outboxes["outbox"])) self.assert_(0==len(split.outboxes["signal"])) split._deliver( msg, "control" ) try: for _ in xrange(0,10): split.next() self.fail() except StopIteration: pass self.assert_(0==len(split.outboxes["outbox"])) self.assert_(1==len(split.outboxes["signal"])) # received = split._collect("signal") received = Dummy.recv("control") self.assert_( msg == received )
def test_doesNotPropagateShutdownMsg(self): """If a graphline's "signal" outbox is specified to be wired to a child component, the graphline will send any messages itself out of its "signal" outbox, before or after all children have terminated, even if a shutdownMicroprocess or producerFinished message was sent to its "control" inbox.""" A=MockChild() B=MockChild() C=MockChild() self.setup_initialise( A=A, B=B, C=C, linkages={ ("A","signal"):("","signal"), ("A","outbox"):("B","control"), }) self.setup_activate() self.runFor(cycles=100) self.sendTo(producerFinished(), "control") self.sendTo(shutdownMicroprocess(), "control") self.runFor(cycles=100) self.assert_(self.graphline in self.scheduler.listAllThreads()) self.assert_(not(self.dataReadyAt("signal"))) for child in self.children.values(): child.stopNow() self.runFor(cycles=100) self.assert_(not(self.dataReadyAt("signal")))
def test_emissionOfShutdownSignal_2(self): """When all children have terminated. If no child is wired to the Graphline's "signal" outbox, the Graphline will send out its own message. If no child is wired to the Graphline's "control" inbox and a shutdownMicroprocess message has been previously received on that inbox, then the message sent out will be that shutdownMicroprocess message.""" A=MockChild() B=MockChild() C=MockChild() self.setup_initialise(A=A, B=B, C=C, linkages={ ("A","outbox"):("B","inbox"), } ) self.setup_activate() self.runFor(cycles=100) # check nothing has been emitted yet! self.assert_(not(self.dataReadyAt("signal"))) shutdownMsg = shutdownMicroprocess(); self.sendTo(shutdownMsg,"control") self.runFor(cycles=1) for child in self.children.values(): child.stopNow() self.runFor(cycles=3) self.assert_(self.dataReadyAt("signal")) recvd=self.recvFrom("signal") self.assert_(recvd == shutdownMsg)
def stop_task(self): from Axon.Ipc import shutdownMicroprocess from Kamaelia.Util.OneShot import OneShot o = OneShot(msg=shutdownMicroprocess()) o.link((o, 'outbox'), (self.p, 'control')) o.activate()
def test_emissionOfShutdownSignal_2(self): """When all children have terminated. If no child is wired to the Graphline's "signal" outbox, the Graphline will send out its own message. If no child is wired to the Graphline's "control" inbox and a shutdownMicroprocess message has been previously received on that inbox, then the message sent out will be that shutdownMicroprocess message.""" A = MockChild() B = MockChild() C = MockChild() self.setup_initialise(A=A, B=B, C=C, linkages={ ("A", "outbox"): ("B", "inbox"), }) self.setup_activate() self.runFor(cycles=100) # check nothing has been emitted yet! self.assert_(not (self.dataReadyAt("signal"))) shutdownMsg = shutdownMicroprocess() self.sendTo(shutdownMsg, "control") self.runFor(cycles=1) for child in self.children.values(): child.stopNow() self.runFor(cycles=3) self.assert_(self.dataReadyAt("signal")) recvd = self.recvFrom("signal") self.assert_(recvd == shutdownMsg)
def main(self): self.control_message = None self.connectionSuccess = False self.loggedIn = False yield WaitComplete(self.waitForBanner()) if self.connectionSuccess: yield WaitComplete( self.doLogin(self.username, self.password)) if self.loggedIn: run = True while run: while not self.anyReady(): self.pause() yield 1 while self.dataReady("client_inbox"): command = self.recv("client_inbox") yield WaitComplete(self.handleCommand(command)) if command[0] == "QUIT": run = False self.sendCommand("QUIT") yield WaitComplete(self.getline(), tag="_getline5") # print "SERVER RESPONSE", self.line if self.shutdown() or self.control_message: self.send( self.control_message, "signal") # Pass on else: self.send(shutdownMicroprocess(), "signal") yield 1
def test_doesNotPropagateShutdownMsg(self): """If a graphline's "signal" outbox is specified to be wired to a child component, the graphline will send any messages itself out of its "signal" outbox, before or after all children have terminated, even if a shutdownMicroprocess or producerFinished message was sent to its "control" inbox.""" A = MockChild() B = MockChild() C = MockChild() self.setup_initialise(A=A, B=B, C=C, linkages={ ("A", "signal"): ("", "signal"), ("A", "outbox"): ("B", "control"), }) self.setup_activate() self.runFor(cycles=100) self.sendTo(producerFinished(), "control") self.sendTo(shutdownMicroprocess(), "control") self.runFor(cycles=100) self.assert_(self.graphline in self.scheduler.listAllThreads()) self.assert_(not (self.dataReadyAt("signal"))) for child in self.children.values(): child.stopNow() self.runFor(cycles=100) self.assert_(not (self.dataReadyAt("signal")))
def test_receivesShutdownDisseminated(self): """If a graphline's "control" inbox is not specified to be wired to a child component in the graphline, then any message (including shutdown messages) flows to the "control" inbox of all children without linkages going to their "control" inbox only.""" A = MockChild() B = MockChild() C = MockChild() self.setup_initialise( A=A, B=B, C=C, linkages={ ("A", "outbox"): ("B", "control"), # should block msg getting to B }) self.setup_activate() self.runFor(cycles=100) msg = shutdownMicroprocess() self.sendTo(msg, "control") self.runFor(cycles=2) self.assert_(A.dataReady("control")) self.assertEquals(msg, A.recv("control")) self.assert_(not (B.dataReady("control"))) self.assert_(C.dataReady("control")) self.assertEquals(msg, C.recv("control"))
def test_receivesShutdownAndPropagates(self): """If a graphline's "control" inbox and "signal" outbox are not specified to be wired to a child component in the graphline then, if a shutdownMicroprocess message is sent to the "control" inbox, it will be sent on out of the "signal" outbox once all children have terminated.""" A = MockChild() B = MockChild() C = MockChild() self.setup_initialise(A=A, B=B, C=C, linkages={ ("A", "outbox"): ("B", "control"), }) self.setup_activate() self.runFor(cycles=100) msg = shutdownMicroprocess() self.sendTo(msg, "control") self.runFor(cycles=100) self.assert_(self.graphline in self.scheduler.listAllThreads()) for child in self.children.values(): child.stopNow() self.runFor(cycles=10) self.assert_(self.graphline not in self.scheduler.listAllThreads()) self.assert_(self.dataReadyAt("signal")) self.assertEquals(msg, self.recvFrom("signal"))
def test_SplitterShutdown(self): """If producerFinished or shutdownMicroprocess is received on the 'control' inbox they are passed on and the component shuts down""" for msg in [producerFinished(self), shutdownMicroprocess(self)]: split = Splitter() Dummy = Axon.Component.component() split.link((split, "outbox"), (Dummy, "inbox")) split.link((split, "signal"), (Dummy, "control")) split.activate() for _ in xrange(0, 10): split.next() self.assert_(0 == len(split.outboxes["outbox"])) self.assert_(0 == len(split.outboxes["signal"])) split._deliver(msg, "control") try: for _ in xrange(0, 10): split.next() self.fail() except StopIteration: pass self.assert_(0 == len(split.outboxes["outbox"])) self.assert_(1 == len(split.outboxes["signal"])) # received = split._collect("signal") received = Dummy.recv("control") self.assert_(msg == received)
def handleClosedCSA(self, shutdownCSAMessage): """ handleClosedCSA(shutdownCSAMessage) -> None Terminates and unwires the protocol handler for the closing socket. Keyword arguments: shutdownCSAMessage -- shutdownCSAMessage.object is the ConnectedSocketAdapter for socket that is closing. """ connectedSocket = shutdownCSAMessage.object try: bundle = self.retrieveTrackedResourceInformation(connectedSocket) except KeyError: # This means we've actually already done this... return resourceInboxes, resourceOutboxes, (protocolHandler, controllink) = bundle self.connectedSockets = [x for x in self.connectedSockets if x != self.connectedSockets] self.unlink(thelinkage=controllink) self.send(socketShutdown(), resourceOutboxes[0]) # This is now instantly delivered self.send(shutdownMicroprocess(), resourceOutboxes[1]) # This is now instantly delivered self.removeChild(connectedSocket) self.removeChild(protocolHandler) self.deleteOutbox(resourceOutboxes[0]) # So this is now safe # This did not used to be the case. self.deleteOutbox(resourceOutboxes[1]) # So this is now safe # This did not used to be the case. self.ceaseTrackingResource(connectedSocket)
def test_receivesShutdownAndPropagates23(self): """If a graphline's "control" inbox is specified to be wired to a child component, but its "signal" outbox is not then, irrespective of what message (eg. shutdownMicroprocess) is sent to the "control" inbox, a producerFinished message will be sent on out of the "signal" outbox once all children have terminated.""" possibleMessages = [ producerFinished(), shutdownMicroprocess(), "flurble" ] for msg in possibleMessages: A=MockChild() B=MockChild() C=MockChild() self.setup_initialise( A=A, B=B, C=C, linkages={ ("","control"):("A","control"), ("A","outbox"):("B","control"), }) self.setup_activate() self.runFor(cycles=100) self.sendTo(msg,"control") self.runFor(cycles=100) self.assert_(self.graphline in self.scheduler.listAllThreads()) for child in self.children.values(): child.stopNow() self.runFor(cycles=10) self.assert_(self.graphline not in self.scheduler.listAllThreads()) self.assert_(self.dataReadyAt("signal")) recvd=self.recvFrom("signal") self.assert_(recvd != msg) self.assert_(isinstance(recvd,producerFinished))
def test_receivesShutdownAndPropagates(self): """If a graphline's "control" inbox and "signal" outbox are not specified to be wired to a child component in the graphline then, if a shutdownMicroprocess message is sent to the "control" inbox, it will be sent on out of the "signal" outbox once all children have terminated.""" A=MockChild() B=MockChild() C=MockChild() self.setup_initialise( A=A, B=B, C=C, linkages={ ("A","outbox"):("B","control"), }) self.setup_activate() self.runFor(cycles=100) msg=shutdownMicroprocess() self.sendTo(msg,"control") self.runFor(cycles=100) self.assert_(self.graphline in self.scheduler.listAllThreads()) for child in self.children.values(): child.stopNow() self.runFor(cycles=10) self.assert_(self.graphline not in self.scheduler.listAllThreads()) self.assert_(self.dataReadyAt("signal")) self.assertEquals(msg, self.recvFrom("signal"))
def main(self): #new connection data = struct.pack('!i', self.versionNumber) data += TLV(0x06, self.authCookie) self.send((CHANNEL1, data)) assert self.debugger.note("ProtocolNegotiator.main", 5, "sent handshake 1") while not self.dataReady(): yield 1 recvdflap = self.recv() assert self.debugger.note("ProtocolNegotiator.main", 5, "received FLAP " + str(recvdflap[0])) #get supported services while not self.dataReady(): yield 1 recvdflap = self.recv() #supported services snac header, reply = readSNAC(recvdflap[1]) assert self.debugger.note("ProtocolNegotiator.main", 5, "received SNAC" + str(header)) supportedFamilies = struct.unpack("!%iH" % (len(reply)/2), reply) #request service versions data = "" for family in supportedFamilies: if family in self.desiredServiceVersions: data += Double(family) + Double(self.desiredServiceVersions[family]) self.send((CHANNEL_SNAC, SNAC(0x01, 0x17, data))) #get and process accepted versions while not self.dataReady(): yield 1 recvdflap = self.recv() #accepted services snac header, reply = readSNAC(recvdflap[1]) assert self.debugger.note("ProtocolNegotiator.main", 5, "received SNAC" + str(header)) reply = unpackDoubles(reply) self.acceptedServices = dict(zip(reply[::2], reply[1::2])) assert self.debugger.note("ProtocolNegotiator.main", 5, "accepted " + str(self.acceptedServices)) #get motd while not self.dataReady(): yield 1 reply = self.recv() #motd snac assert self.debugger.note("ProtocolNegotiator.main", 5, "received motd") #request rate limits self.send((CHANNEL_SNAC, SNAC(0x01, 0x06, "", id=2))) while not self.dataReady(): yield 1 recvflap = self.recv() #rate limits header, reply = readSNAC(recvflap[1]) assert self.debugger.note("ProtocolNegotiator.main", 5, "received SNAC" + str(header)) #process rate limits numClasses, = struct.unpack('!H', reply[:2]) self.parseRateInfo(reply[2:], numClasses) ## reply = reply[2 + numClasses*LEN_RATE_CLASS:] ## self.parseRateGroups(reply) snac_body = struct.pack("!%iH" % numClasses, *self.rateInfo.keys()) self.send((CHANNEL_SNAC, SNAC(0x01, 0x08, snac_body))) self.send(shutdownMicroprocess(), "signal")
def main(self): while self.n < 20: time.sleep(0.5) print "SignalPusher sending" self.send('NEXT', 'outbox') self.n += 1 yield 1 self.send(shutdownMicroprocess(), 'signal')
def test_connectorshutsdown_shutdownmicroprocess(self): """main - shutdownMicroprocess->control - This test confirms that the connector shuts itself down when it is sent a shutdownMicroprocess message.""" self.tester.send(shutdownMicroprocess(), "signal") self.deliver() self.connector.next() self.connector.next() self.failUnlessRaises(StopIteration, self.connector.next)
def test_shutdownMicroprocess2(self): """mainBody - Checks that the Comparator sends a producerFinished when sent a shutdownMicroprocess message on its control box""" self.testerA.send(shutdownMicroprocess(), "signal") try: self.runtestsystem() except: # Bad form except for the fact that this is tested in test_shutdownMicroprocess1 pass self.failUnless(isinstance(self.testerA.recv("control"), producerFinished))
def main(self): yield self.initializeComponents() yield 1 self.send_stream_header() self.running = True while self.running: if self.dataReady("tcp-control"): mes = self.recv("tcp-control") if isinstance(mes, shutdownMicroprocess) or \ isinstance(mes, producerFinished): self.stopping() self.log(mes.message, prefix='ERROR') self.socket_error(mes.message) self.send(shutdownMicroprocess(), "signal") yield 1 self.running = False if self.dataReady("control"): mes = self.recv("control") if isinstance(mes, shutdownMicroprocess) or \ isinstance(mes, producerFinished): self.stopping() self.send(shutdownMicroprocess(), "signal") yield 1 self.running = False if self.dataReady("tlssuccess"): self.recv("tlssuccess") yield 1 self.tls_ok() yield 1 if self.dataReady("inbox"): data = self.recv('inbox') try: self.parser.feed(data) except SAXParseException, exc: self.log(traceback=True) if self.running and not self.anyReady(): self.pause() yield 1
def test_shutdownMicroprocess2(self): """mainBody - Checks that the Comparator sends a producerFinished when sent a shutdownMicroprocess message on its control box""" self.testerA.send(shutdownMicroprocess(), "signal") try: self.runtestsystem() except: # Bad form except for the fact that this is tested in test_shutdownMicroprocess1 pass self.failUnless( isinstance(self.testerA.recv("control"), producerFinished))
def main(self): lasttime = time.time() life = 1 #runs for 1 seconds while time.time() < lasttime + life: yield 1 if self.dataReady(): print self.recv() self.send(shutdownMicroprocess(), "signal") #close the socket print "shutdownMicroprocess sent" yield 1
def shutdown(self): while self.dataReady("control"): msg = self.recv("control") if isinstance(msg, producerFinished) or isinstance(msg, shutdownMicroprocess): self.done = True if self.dataReady("_quitevents"): self.done = True if self.done: self.send(shutdownMicroprocess(), 'signal') return True
def shutdown(self): """Checks for control messages""" while self.dataReady("control"): msg = self.recv("control") if isinstance(msg, producerFinished) or isinstance(msg, shutdownMicroprocess): self.done = True if self.dataReady("_quitevents"): self.done = True if self.done: self.send(shutdownMicroprocess(), 'signal') return True
def exeunt(self, actorName): self.send("EXIT: " + actorName + "\n", "outbox") if actorName in self.actors: (actor, outboxes, linkages) = self.actors[actorName] self.send(shutdownMicroprocess(self), outboxes['signal']) yield 1 for box in outboxes.keys(): self.postoffice.deregisterlinkage(thelinkage=linkages[box]) self.deleteOutbox(outboxes[box]) del self.actors[actorName]
def handleGraphstepShutdown(self): dontcontinue = False message = None for message in self.Inbox("_control"): if isinstance(message,status): if message.status() == "fail": # Don't abort early, but don't continue after this graphstep message = shutdownMicroprocess() dontcontinue = True self.shutdownChildComponents(message) return dontcontinue
def needShutdown(self): # FIXME: Inconsistent with other components. Original comment for this claimed standard name was confusing. Is it? """Checks for control messages""" while self.dataReady("control"): msg = self.recv("control") if (isinstance(msg, producerFinished) or isinstance(msg, shutdownMicroprocess)): self.done = True if self.dataReady("_quitevents"): self.done = True if self.done: self.send(shutdownMicroprocess(), 'signal') return True
def testFeedsAndShutdownsPriority(self): feedobj = self.generateFeedObj(FEED_URL) # It doesn't matter as long as there is a shutdownMicroprocess message self.put(feedobj, 'inbox') self.put(feedobj, 'inbox') self.put(feedobj, 'inbox') self.put(shutdownMicroprocess(), 'control') self.assertOutboxEmpty('outbox') self.assertTrue(isinstance(self.get('signal'), shutdownMicroprocess)) self.assertOutboxEmpty('signal')
def exeunt(self, actorName): self.send("EXIT: "+actorName+"\n", "outbox") if actorName in self.actors: (actor, outboxes, linkages) = self.actors[actorName] self.send(shutdownMicroprocess(self), outboxes['signal']) yield 1 for box in outboxes.keys(): self.postoffice.deregisterlinkage(thelinkage = linkages[box]) self.deleteOutbox(outboxes[box]) del self.actors[actorName]
def needShutdown( self ): # FIXME: Inconsistent with other components. Original comment for this claimed standard name was confusing. Is it? """Checks for control messages""" while self.dataReady("control"): msg = self.recv("control") if isinstance(msg, producerFinished) or isinstance(msg, shutdownMicroprocess): self.done = True if self.dataReady("_quitevents"): self.done = True if self.done: self.send(shutdownMicroprocess(), "signal") return True
def _releaseService(self, handle): try: name = self.serviceUsageHandles[handle] except KeyError: raise "NO SUCH HANDLE" del self.serviceUsageHandles[handle] service = self.services[name] service['refcount'] -= 1 if service['refcount'] == 0: service['instance']._deliver(shutdownMicroprocess(), "control") del service['instance']
def main(self): self.addChildren(self.item) self.item.activate() dontcontinue = False for graphstep in self.sequence: stopping = 0 links = self.link_graphstep(graphstep) if dontcontinue: break while True: # Let sub graphstep run, and wait for completion. Sleep as much as possible. if not self.anyReady(): self.pause() yield 1 dontcontinue = self.handleGraphstepShutdown() if self.anyStopped(): all_stopped = True # Assume if self.item._isStopped(): print "Warning: Child died before completion", self.item self.shutdownChildComponents(shutdownMicroprocess()) dontcontinue = True for child in self.childComponents(): # Check assumption if child == self.item: continue all_stopped = all_stopped and child._isStopped() if all_stopped: break else: stopping += 1 if (stopping % 1000) == 0: print "Warning one child exited, but others haven't after", stopping, "loops" yield 1 if dontcontinue: break for link in links: self.unlink(thelinkage=link) self.link( (self, "_signal"), (self.item, "control") ) self.send( producerFinished(), "_signal")
def runClient(self, sock=None): # The various numbers yielded here indicate progress through the function, and # nothing else specific. try: sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) yield 0.3 self.sock = sock # We need this for shutdown later try: sock.setblocking(0) yield 0.6 try: while not self.safeConnect(sock): if self.shutdown(): return yield 1 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 255) status = sock.setsockopt( socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, socket.inet_aton(self.remote[0]) + socket.inet_aton("0.0.0.0")) yield newComponent(*self.setupCSA(sock)) while self.waitCSAClose(): self.pause() yield 2 raise Finality except Exception, x: result = sock.shutdown(2) yield 3 raise x # XXXX If X is not finality, an error message needs to get sent _somewhere_ else # The logical place to send the error is to the signal outbox except Exception, x: sock.close() yield 4, x # XXXX If X is not finality, an error message needs to get sent _somewhere_ else raise x except Finality: yield 5 except socket.error, e: # We now do the flipside of setupCSA, whether we had an error or not # A safe error relates to a disconnected server, and unsafe error is generally # bad. However either way, it's gone, let's let the person using this # component know, shutdown everything, and get outta here. # pass self.send(shutdownMicroprocess(self), "signal")
def handleClosedCSA(self, shutdownCSAMessage): """ handleClosedCSA(shutdownCSAMessage) -> None Terminates and unwires the protocol handler for the closing socket. Keyword arguments: shutdownCSAMessage -- shutdownCSAMessage.object is the ConnectedSocketAdapter for socket that is closing. """ # print (shutdownCSAMessage) # print (shutdownCSAMessage.object) connectedSocket = shutdownCSAMessage.object # print ("CLOSING", connectedSocket) try: bundle = self.retrieveTrackedResourceInformation(connectedSocket) # print ("BUNDLE", bundle) except KeyError: # This means we've actually already done this... return resourceInboxes, resourceOutboxes, (protocolHandler, controllink) = bundle # print (bundle) self.connectedSockets = [ x for x in self.connectedSockets if x != connectedSocket ] if controllink: self.unlink(thelinkage=controllink) # else: # print ("Control Link is null, not unlinking") self.send(socketShutdown(), resourceOutboxes[0]) # This is now instantly delivered self.send(shutdownMicroprocess(), resourceOutboxes[1]) # This is now instantly delivered self.removeChild(connectedSocket) self.removeChild(protocolHandler) self.deleteOutbox(resourceOutboxes[0]) # So this is now safe # This did not used to be the case. self.deleteOutbox(resourceOutboxes[1]) # So this is now safe # This did not used to be the case. # print ("CEASING TRACKING", self._resourceStore) self.ceaseTrackingResource(connectedSocket)
def main(self): yield self.setup() while 1: if self.dataReady("control"): mes = self.recv("control") if isinstance(mes, str): if mes.strip() == 'quit': self.shutdown() elif isinstance(mes, shutdownMicroprocess) or isinstance(mes, producerFinished): self.send(mes, "signal") break if self.dataReady("inbox"): msg = self.recv('inbox') if msg == "quit": self.send(shutdownMicroprocess(), "signal") yield 1 break if self.dataReady("streamfeat"): feat = self.recv('streamfeat') if feat.register and self.register: self.send(Registration(), 'doregistration') elif self.register and not feat.register: print "The server does not support in-band registration. Closing connection." self.abort() else: self.send(feat, 'doauth') if self.dataReady("jid"): self.jid = self.recv('jid') if not self.anyReady(): self.pause() yield 1 yield 1 self.stop() print "You can hit Ctrl-C to shutdown all processes now."
def main(self): yield self.setup() while 1: while self.dataReady("control"): mes = self.recv("control") if isinstance(mes, str): if mes.strip() == 'quit': self.shutdown() elif isinstance(mes, shutdownMicroprocess) or isinstance(mes, producerFinished): self.send(mes, "signal") break while self.dataReady("inbox"): msg = self.recv('inbox') if msg == "quit": self.send(shutdownMicroprocess(), "signal") yield 1 break while self.dataReady("streamfeat"): feat = self.recv('streamfeat') if feat.register and self.register: self.send(Registration(), 'doregistration') elif self.register and not feat.register: print "The server does not support in-band registration. Closing connection." self.abort() else: self.send(feat, 'doauth') while self.dataReady("jid"): self.jid = self.recv('jid') if not self.anyReady(): self.pause() yield 1 yield 1 self.stop() print "You can hit Ctrl-C to shutdown all processes now."
def main(self): done = False while not done: while self.dataReady("inbox"): data = self.recv("inbox") if data[0].upper() == "PIPELINE": for output in PipelineWriter.generatePipeline(data[1]): self.send(output, "outbox") self.send(None, "outbox") while self.dataReady("control"): msg = self.recv("control") if isinstance(msg, producerFinished) or isinstance(msg, shutdownMicroprocess): done = True self.send(shutdownMicroprocess(self), "signal") if not done: self.pause() yield 1
def runClient(self,sock=None): # The various numbers yielded here indicate progress through the function, and # nothing else specific. try: sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) yield 0.3 self.sock = sock # We need this for shutdown later try: sock.setblocking(0); yield 0.6 try: while not self.safeConnect(sock): if self.shutdown(): return yield 1 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 255) status = sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, socket.inet_aton(self.remote[0]) + socket.inet_aton("0.0.0.0")) yield newComponent(*self.setupCSA(sock)) while self.waitCSAClose(): self.pause() yield 2 raise Finality except Exception, x: result = sock.shutdown(2) ; yield 3 raise x # XXXX If X is not finality, an error message needs to get sent _somewhere_ else # The logical place to send the error is to the signal outbox except Exception, x: sock.close() ; yield 4,x # XXXX If X is not finality, an error message needs to get sent _somewhere_ else raise x except Finality: yield 5 except socket.error, e: # We now do the flipside of setupCSA, whether we had an error or not # A safe error relates to a disconnected server, and unsafe error is generally # bad. However either way, it's gone, let's let the person using this # component know, shutdown everything, and get outta here. # pass self.send(shutdownMicroprocess(self), "signal")
def test_shutdown(self): """Shuts down in response to a shutdownMicroprocess message""" for msg in [producerFinished(self), shutdownMicroprocess(self)]: normaliser = directionNormaliser().activate() for _ in xrange(0, 10): normaliser.next() self.assert_(0 == len(normaliser.outboxes["outbox"])) self.assert_(0 == len(normaliser.outboxes["signal"])) normaliser._deliver(msg, "control") try: for _ in xrange(0, 10): normaliser.next() self.fail() except StopIteration: pass self.assert_(0 == len(normaliser.outboxes["outbox"])) self.assert_(1 == len(normaliser.outboxes["signal"])) received = normaliser._collect("signal") self.assert_(msg == received)
def main(self): done = False while not done: while self.dataReady("inbox"): data = self.recv("inbox") if data[0].upper() == "PIPELINE": for output in PipelineWriter.generatePipeline(data[1]): self.send(output, "outbox") self.send(None, "outbox") while self.dataReady("control"): msg = self.recv("control") if isinstance(msg, producerFinished) or isinstance( msg, shutdownMicroprocess): done = True self.send(shutdownMicroprocess(self), "signal") if not done: self.pause() yield 1
def test_receivesShutdownAndPropagates23(self): """If a graphline's "control" inbox is specified to be wired to a child component, but its "signal" outbox is not then, irrespective of what message (eg. shutdownMicroprocess) is sent to the "control" inbox, a producerFinished message will be sent on out of the "signal" outbox once all children have terminated.""" possibleMessages = [ producerFinished(), shutdownMicroprocess(), "flurble" ] for msg in possibleMessages: A = MockChild() B = MockChild() C = MockChild() self.setup_initialise(A=A, B=B, C=C, linkages={ ("", "control"): ("A", "control"), ("A", "outbox"): ("B", "control"), }) self.setup_activate() self.runFor(cycles=100) self.sendTo(msg, "control") self.runFor(cycles=100) self.assert_(self.graphline in self.scheduler.listAllThreads()) for child in self.children.values(): child.stopNow() self.runFor(cycles=10) self.assert_(self.graphline not in self.scheduler.listAllThreads()) self.assert_(self.dataReadyAt("signal")) recvd = self.recvFrom("signal") self.assert_(recvd != msg) self.assert_(isinstance(recvd, producerFinished))
def main(self): yield 1 self.link((self, 'outbox'), (self, 'inbox')) self.send(None, "outbox") while 1: if self.dataReady("control"): mes = self.recv("control") if isinstance(mes, shutdownMicroprocess) or \ isinstance(mes, producerFinished): self.send(shutdownMicroprocess(), "signal") break if self.dataReady("inbox"): self.recv("inbox") self.bus.publish("main") self.send(None, "outbox") if not self.anyReady(): self.pause() yield 1 self.bus = None