def setup(): global timer reactor.callWhenRunning(create_shell_server) reactor.startRunning() timer = RepeatingTimer(0.01, catch_up, daemon=True) timer.start() logging.info("Debug terminal initialized.")
def run(self, installSignalHandlers=None): if installSignalHandlers is None: installSignalHandlers = self.installSignalHandlers # main loop, executed in a dedicated greenlet from twisted.internet import reactor assert Hub.state in [1, 3], ('run function is not reentrant', Hub.state) if Hub.state == 1: reactor.startRunning(installSignalHandlers=installSignalHandlers) elif not reactor.running: # if we're here, then reactor was explicitly stopped with reactor.stop() # restarting reactor (like we would do after an exception) in this case # is not an option. raise AssertionError("reactor is not running") try: self.mainLoop(reactor) except: # an exception in the mainLoop is a normal operation (e.g. user's # signal handler could raise an exception). In this case we will re-enter # the main loop at the next switch. Hub.state = 3 raise
def setup(): global timer reactor.callWhenRunning(create_shell_server) reactor.startRunning() timer = RepeatingTimer(0.01, catch_up, daemon=True) timer.start() logging.info("Debug terminal initialized.")
def main(): #global temp #lcd = Adafruit_CharLCD(pins_db=[23, 17, 27, 22]) #lcd.clear() #lcd.begin(16,1) site = server.Site(Simple()) reactor.listenTCP(8081, site) reactor.startRunning(False) while True: #lcd.clear() lcd.home() sleep(0.05) print 'Temp: %1.1fC' % (temp) lcd.message(datetime.now().strftime('%b %d %H:%M:%S\n')) lcd.message('Temp: %1.1f\337C ' % (temp) ) #lcd.clear() #sleep(0.05) #lcd.message(datetime.now().strftime('%b %d %H:%M:%S\n')) #lcd.message('Temp: -22C') reactor.iterate() sleep(2)
def OnInit(self): model.Application.OnInit(self) reactor.startRunning() wx.EVT_TIMER(self, 999999, self.OnTimer) self.twistedTimer = wx.Timer(self, 999999) self.twistedTimer.Start(250, False) return True
def OnInit(self): # Twisted Reactor code reactor.startRunning() EVT_TIMER(self, 999999, self.OnTimer) self.timer = wxTimer(self, 999999) self.timer.Start(150, False) return true
def OnInit(self): # Twisted Reactor code reactor.startRunning() EVT_TIMER(self, 999999, self.OnTimer) self.timer = wxTimer(self, 999999) self.timer.Start(150, False) return true
def OnInit(self): # Twisted Reactor Code reactor.startRunning() EVT_TIMER(self,999999,self.OnTimer) self.timer=wxTimer(self,999999) self.timer.Start(250,False) # End Twisted Code # Do whatever you need to do here return True
def OnInit(self): # Twisted Reactor Code reactor.startRunning() EVT_TIMER(self, 999999, self.OnTimer) self.timer = wxTimer(self, 999999) self.timer.Start(250, False) # End Twisted Code # Do whatever you need to do here return True
def __init__(self, host=None): if host == None: host = NetMgr.HOST reactor.connectTCP(host, NetMgr.PORT, IngressClientFactory(self)) reactor.startRunning(False) self.screen = None self.client = None self.quit = False self.failed = False
def __init__(self, port, interface, handler, debug=False): log("TwistedServer.__init__ started.", params={log_const.KEY_NAME: log_const.TWISTED_SERVER}, level="WARNING") site = server.Site(handler(debug=debug)) reactor.listenTCP(port, site, interface=interface or "") reactor.startRunning(False) log("TwistedServer.__init__ finished.", params={log_const.KEY_NAME: log_const.TWISTED_SERVER}, level="WARNING")
def main(): site = server.Site(Simple()) reactor.listenTCP(8081, site) reactor.startRunning(False) while True: lcd.home() sleep(0.05) print 'Temp: %1.1fC' % (temp) lcd.message(datetime.now().strftime('%b %d %H:%M:%S\n')) lcd.message('Temp: %1.1f\337C ' % (temp) ) reactor.iterate() sleep(2)
def RunServer(): checker = checkers.FilePasswordDB("userpasswords.txt") p = portal.Portal(realm, [checker]) reactor.listenTCP(8123, pb.PBServerFactory(p)) reactor.startRunning() try: while running: reactor.iterate() processUpdater.next() agentUpdater.next() clock.tick(settings.stepsPerSecond) except: # pass raise
def main(): OPTIONS, argv = getOptions('mmolite/config/servers.cfg', 'world server', sys.argv) if OPTIONS.username == "-": OPTIONS.username = raw_input("Username: "******"-": OPTIONS.password = raw_input("Password: "******"Setting up World Server..." dbconn.resetDB() print "Successfully" return else: print "Initialize World Server database..." dbconn.startDB() Clients.dropTable(ifExists=True) Clients.createTable() print "Run TGE dedicated server" argv.extend([ '-dedicated', '-game', 'test.mmo', '-mission', 'test.mmo/data/missions/chatspot.mis' ]) pytorque.initialize(len(argv), argv) print "World server connecting to master server: ip[%s] port[%d]" % ( OPTIONS.master_ip, OPTIONS.master_port) creds = credentials.UsernamePassword(OPTIONS.username, OPTIONS.password) world = WorldServer(OPTIONS.master_ip, OPTIONS.master_port, OPTIONS.world_port, PeerType.World, creds, WorldPortal()) world.run() #reactor.run() reactor.startRunning() #the main loop is broken out and can be combined with other frameworks rather easily while pytorque.tick(): reactorTick() #cleanup pytorque.. goodbye! pytorque.shutdown()
def main(): global clientObj global userObj Running = False OPTIONS, argv = getOptions('mmolite/config/client.cfg', 'client', sys.argv) print "MMO test client initializing torque client" if '-game' not in argv: argv.extend(['-game', 'test.mmo']) pytorque.initialize(len(argv), argv) print "MMO test client connecting to: ip[%s] port[%d]" % ( OPTIONS.master_ip, OPTIONS.master_port) clientObj = PbAuthClient() clientObj.login("Client", "tneilc", OPTIONS.master_ip, OPTIONS.master_port) userObj = PbAuthUser() # get torque object loginButton = TorqueObject("LoginButton") signupButton = TorqueObject("SignupButton") # set torque object's attribute loginButton.Command = 'LoginButton.OnButton("%s", %s);' % ( OPTIONS.master_ip, OPTIONS.master_port) signupButton.Command = 'SignupButton.OnButton("%s", %s);' % ( OPTIONS.master_ip, OPTIONS.master_port) # map python function to torque action pytorque.export(OnLoginPressed, "LoginButton", "OnButton", "Login button command", 2, 2) pytorque.export(OnSignupPressed, "SignupButton", "OnButton", "Signup button command", 2, 2) # call torque object method loginButton.setActive(0) signupButton.setActive(0) print "MMO test client running" reactor.startRunning() #the main loop is broken out and can be combined with other frameworks rather easily while pytorque.tick(): reactorTick() #cleanup pytorque.. goodbye! pytorque.shutdown() print "MMO test client quit"
def _initiateTestReactor(self, timeout=1): """ Do the steps required to initiate a reactor for testing. """ self._timeout_reached = False # Set up timeout. self._reactor_timeout_call = reactor.callLater( timeout, self._raiseReactorTimeoutError, timeout) # Don't start the reactor if it is already started. # This can happen if we prevent stop in a previous run. if reactor._started: return reactor._startedBefore = False reactor._started = False reactor._justStopped = False reactor.startRunning()
def main(): # Explicitly set dbus main loop. DBusGMainLoop(set_as_default=True) # Wake up the settings manager dbus service. try: settings_bus = SessionBus().get_object( 'org.gnome.SettingsDaemon', '/org/gnome/SettingsDaemon') except DBusException as e: dialog = gtk.MessageDialog( None, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, GSM_NOT_FOUND_MESSAGE) dialog.run() dialog.destroy() return try: settings_bus.Awake(dbus_interface='org.gnome.SettingsDaemon') except DBusException as e: # May not always be wakeable. That's Ok. pass # Create server. factory = BroadcastServerFactory('ws://localhost:1337') listenWS(factory) # Start twisted. reactor.startRunning() # Create the tray icon. Must keep reference to prevent GC. icon = createTrayIcon() #Run GTK loop. gtk.main() # Kill twisted if it's still alive. if reactor.running: reactor.stop()
def main(): global clientObj global userObj Running = False OPTIONS, argv = getOptions('mmolite/config/client.cfg', 'client', sys.argv) print "MMO test client initializing torque client" if '-game' not in argv: argv.extend(['-game', 'test.mmo']) pytorque.initialize(len(argv),argv) print "MMO test client connecting to: ip[%s] port[%d]"%(OPTIONS.master_ip, OPTIONS.master_port) clientObj = PbAuthClient() clientObj.login("Client", "tneilc", OPTIONS.master_ip, OPTIONS.master_port) userObj = PbAuthUser() # get torque object loginButton = TorqueObject("LoginButton") signupButton = TorqueObject("SignupButton") # set torque object's attribute loginButton.Command = 'LoginButton.OnButton("%s", %s);'%(OPTIONS.master_ip, OPTIONS.master_port) signupButton.Command = 'SignupButton.OnButton("%s", %s);'%(OPTIONS.master_ip, OPTIONS.master_port) # map python function to torque action pytorque.export(OnLoginPressed,"LoginButton","OnButton","Login button command",2,2) pytorque.export(OnSignupPressed,"SignupButton","OnButton","Signup button command",2,2) # call torque object method loginButton.setActive(0) signupButton.setActive(0) print "MMO test client running" reactor.startRunning() #the main loop is broken out and can be combined with other frameworks rather easily while pytorque.tick(): reactorTick() #cleanup pytorque.. goodbye! pytorque.shutdown() print "MMO test client quit"
def main(): OPTIONS, argv = getOptions('mmolite/config/servers.cfg', 'world server', sys.argv) if OPTIONS.username=="-": OPTIONS.username = raw_input("Username: "******"-": OPTIONS.password = raw_input("Password: "******"Setting up World Server..." dbconn.resetDB() print "Successfully" return else: print "Initialize World Server database..." dbconn.startDB() Clients.dropTable(ifExists=True); Clients.createTable() print "Run TGE dedicated server" argv.extend(['-dedicated', '-game', 'test.mmo', '-mission', 'test.mmo/data/missions/chatspot.mis']) pytorque.initialize(len(argv),argv) print "World server connecting to master server: ip[%s] port[%d]"%(OPTIONS.master_ip, OPTIONS.master_port) creds = credentials.UsernamePassword(OPTIONS.username, OPTIONS.password) world = WorldServer(OPTIONS.master_ip, OPTIONS.master_port, OPTIONS.world_port, PeerType.World, creds, WorldPortal()) world.run() #reactor.run() reactor.startRunning() #the main loop is broken out and can be combined with other frameworks rather easily while pytorque.tick(): reactorTick() #cleanup pytorque.. goodbye! pytorque.shutdown()
def main(): # Explicitly set dbus main loop. DBusGMainLoop(set_as_default=True) # Wake up the settings manager dbus service. try: settings_bus = SessionBus().get_object('org.gnome.SettingsDaemon', '/org/gnome/SettingsDaemon') except DBusException as e: dialog = gtk.MessageDialog(None, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, GSM_NOT_FOUND_MESSAGE) dialog.run() dialog.destroy() return try: settings_bus.Awake(dbus_interface='org.gnome.SettingsDaemon') except DBusException as e: # May not always be wakeable. That's Ok. pass # Create server. factory = BroadcastServerFactory('ws://localhost:1337') listenWS(factory) # Start twisted. reactor.startRunning() # Create the tray icon. Must keep reference to prevent GC. icon = createTrayIcon() #Run GTK loop. gtk.main() # Kill twisted if it's still alive. if reactor.running: reactor.stop()
def run(self, installSignalHandlers=None): if installSignalHandlers is None: installSignalHandlers = self.installSignalHandlers # main loop, executed in a dedicated greenlet from twisted.internet import reactor assert Hub.state in [1, 3], ('run function is not reentrant', Hub.state) if Hub.state == 1: reactor.startRunning(installSignalHandlers=installSignalHandlers) elif not reactor.running: # if we're here, then reactor was explicitly stopped with reactor.stop() # restarting reactor (like we would do after an exception) in this case # is not an option. raise AssertionError("reactor is not running") try: self.mainLoop(reactor) except: # an exception in the mainLoop is a normal operation (e.g. user's # signal handler could raise an exception). In this case we will re-enter # the main loop at the next switch. Hub.state = 3 raise
def StartWebServer(): site = server.Site(WebPage()) reactor.listenTCP(50000, site) reactor.startRunning(False)
def startReactor(): """Initialize the twisted reactor, but don't start its main loop.""" if not reactor.running: reactor.startRunning(installSignalHandlers=0)
def run(self): """Override Process run method to provide a custom wrapper for service. Shared by all local services. This provides a continuous loop for watching the child process while keeping an ear open to the main process from openContentPlatform, listening for any interrupt requests. """ try: ## Twisted import here to avoid issues with epoll on Linux from twisted.internet import reactor ## There are two types of event handlers being used here: ## self.shutdownEvent : main process tells this one to shutdown ## (e.g. on a Ctrl+C type event) ## self.canceledEvent : this process needs to restart ## Create a PID file for system administration purposes utils.pidEntryService(self.serviceName, env, self.pid) factoryArgs = (self.serviceName, self.globalSettings, self.canceledEvent, self.shutdownEvent) print('Starting local service: {}'.format(self.serviceName)) ## The following loop may look hacky at first glance, but solves a ## challenge with a mix of Python multi-processing, multi-threading, ## then Twisted's reactor and threading. ## Python threads that are not daemon types, cannot be forced closed ## when the controlling thread closes. So it's important to pass ## events all the way through, and have looping code catch/cleanup. ## Whenever the main process is being shut down, it must stop all ## sub-processes along with their work streams, which includes any ## Twisted reactors. We do that by passing shutdownEvent into the ## sub-processes. And whenever a service (sub-process) needs to ## restart, it notifies the other direction so the main process can ## verify it stopped and restart it. We do that by a canceledEvent. ## Now to the point of this verbose comment, so the reason we cannot ## call reactor.run() here, and instead cut/paste the same code, was ## to enhance 'while reactor._started' to watch for our events. reactor.callFromThread(self.serviceClass, *factoryArgs) #reactor.callWhenRunning(self.serviceClass *factoryArgs) reactor.startRunning() ## Start event wait loop while reactor._started and not self.shutdownEvent.is_set() and not self.canceledEvent.is_set(): try: ## Four lines from twisted.internet.base.mainloop: reactor.runUntilCurrent() t2 = reactor.timeout() t = reactor.running and t2 reactor.doIteration(t) except: exception = traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]) print('Exception in {}: {}'.format(self.serviceName, exception)) break if self.shutdownEvent.is_set(): print('Shutdown event received for {}'.format(self.serviceName)) self.canceledEvent.set() with suppress(Exception): time.sleep(2) print('Calling reactor stop for {}'.format(self.serviceName)) reactor.stop() time.sleep(.5) elif self.canceledEvent.is_set(): print('Canceled event received for {}'.format(self.serviceName)) with suppress(Exception): time.sleep(2) reactor.stop() time.sleep(.5) except PermissionError: exceptionOnly = traceback.format_exception_only(sys.exc_info()[0], sys.exc_info()[1]) print(' {}'.format(exceptionOnly)) print(' Stopping {}'.format(self.serviceName)) except: exception = traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]) print('Exception in {}: {}'.format(self.serviceName, exception)) ## Cleanup utils.pidRemoveService(self.serviceName, env, self.pid) ## Remove the handler to avoid duplicate lines the next time it runs with suppress(Exception): reactor.stop() print('Stopped {}'.format(self.serviceName)) ## end ServiceProcess return
def ReactorStart(): reactor.startRunning()
def run(self): """Override Process run method to provide a custom wrapper for the API. This provides a continuous loop for watching the service while keeping an ear open to the main process from openContentPlatform, listening for any interrupt requests. """ ## Setup requested log handler try: ## Twisted imports here to avoid issues with epoll on Linux from twisted.internet import reactor, ssl from twisted.python.filepath import FilePath from twisted.web.server import Site from twisted.web.wsgi import WSGIResource from twisted.python.threadpool import ThreadPool print('Starting {}'.format(self.serviceName)) self.getLocalLogger() self.logger.info('Starting {}'.format(self.serviceName)) self.logger.info('Setting up the API application...') ## Setup shared resources for our WSGIResource instances to use self.getSharedLogger() self.getSharedDbPool() ## Create a PID file for system administration purposes pidEntryService(self.serviceName, env, self.pid) ## Reference the magic WSGI throwable from our root module using Hug application = apiResourceRoot.__hug_wsgi__ ## Setup the WSGI to be hosted through Twisted's web server wsgiThreadPool = ThreadPool() wsgiThreadPool.start() ## For some reason the system event wasn't working all the time, ## so I'm adding an explicit wsgiThreadPool.stop() below as well, ## which was needed before reactor.stop() would properly cleanup. reactor.addSystemEventTrigger('after', 'shutdown', wsgiThreadPool.stop) resource = WSGIResource(reactor, wsgiThreadPool, application) self.logger.info('calling listener on {}:{}.'.format( str(self.serviceEndpoint), self.listeningPort)) if self.useCertificates: ## Use TLS to encrypt the communication certData = FilePath( os.path.join( env.privateInternalCertPath, self.globalSettings.get( 'ocpCertificateCaFile'))).getContent() certificate = ssl.PrivateCertificate.loadPEM(certData) reactor.listenSSL(self.listeningPort, Site(resource), certificate.options()) else: ## Plain text communication reactor.listenTCP(self.listeningPort, Site(resource), interface=self.serviceEndpoint) ## Normally we'd just call reactor.run() here and let twisted handle ## the wait loop while watching for signals. The problem is that we ## need openContentPlatform (parent process) to manage this process. ## So this is a bit hacky in that I'm using the reactor code, but I ## am manually calling what would be called if I just called run(): reactor.startRunning() ## Start event wait loop while reactor._started and not self.shutdownEvent.is_set(): try: ## Four lines from twisted.internet.main.mainloop: reactor.runUntilCurrent() t2 = reactor.timeout() t = reactor.running and t2 reactor.doIteration(t) except: exception = traceback.format_exception( sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]) self.logger.error('Exception in {}: {}'.format( self.serviceName, str(exception))) break if self.shutdownEvent.is_set(): self.logger.info('Process received shutdownEvent') with suppress(Exception): wsgiThreadPool.stop() with suppress(Exception): reactor.stop() except: exception = traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]) self.logger.error('Exception in {}: {}'.format( self.serviceName, str(exception))) ## Cleanup pidRemoveService(self.serviceName, env, self.pid) self.logger.info('Stopped {}'.format(self.serviceName)) print('Stopped {}'.format(self.serviceName)) ## end run return
def __init__(self, topology): self.topo = opennsa.topology.gole.parseTopology([open(topology)]) reactor.startRunning(installSignalHandlers=0) self.client,self.client_nsa = createClient() self.result=None self.error=None
def __init__(self): reactor.listenTCP(Master.SERVER_PORT, ServerFactory(self)) reactor.listenTCP(Master.CLIENT_PORT, ClientFactory(self)) reactor.startRunning(False) self.serverList = [] self.clientList = []
def ReactorStart(): reactor.startRunning()
def getUsers(self): return userList def addUser(self, user): IngressFactory.userList.append(user) def removeUser(self, user): # we expect the game will handle its end # when it receives a quit event IngressFactory.userList.remove(user) def connectionLost(self, reason): print "we lost a connection :[" factory = IngressFactory() reactor.listenTCP(PORT, factory) reactor.startRunning(False) lastSentScreen = time.time() while True: reactor.iterate() if factory.board != None: factory.board.iterate() curTime = time.time() delta = curTime - lastSentScreen if delta > 1.0 / FPS: print "delta=%f > %f so sending screen!" % (delta, 1.0 / FPS) lastSentScreen = curTime for user in factory.userList: user.sendScreen()
def _init(): reactor.startRunning(installSignalHandlers=True)
# This is a script that allows you to talk to the embedded python interpreter # using ssh. To use it, put it in the GUIScript directory and then add the # following to include.py, or issue using the python console # # import manhole # manhole.createManhole(port = 2222, users = { 'gemrb': 'password' }) # # Then you can connect using ssh to the given port and issue python commands. import GemRB from twisted.internet import reactor reactor.startRunning() GemRB.SetTickHook(lambda: reactor.iterate()) from twisted.conch import manhole, manhole_ssh from twisted.conch.insults import insults from twisted.cred import checkers, portal def createManhole(port=2222, users={'gemrb': 'password'}): """Create a twisted manhole for accessing the embedded python interpreter""" namespace = {'GemRB': GemRB} def makeProtocol(): return insults.ServerProtocol(manhole.ColoredManhole, namespace) r = manhole_ssh.TerminalRealm() r.chainedProtocolFactory = makeProtocol c = checkers.InMemoryUsernamePasswordDatabaseDontUse() for (username, password) in users.iteritems():
def main(): global sockets, networks, dhclient, state_file, state, error sockets = {} networks = {} dhclient = False state = {} state_file = '/var/lib/wpa_web/state.json' error = '' port = 80 print('wpa_web 1.0.0 (Copyright 2015 Tom Pitcher)') signal.signal(signal.SIGINT, shutdown) site = server.Site(Root()) reactor.listenTCP(port, site) reactor.startRunning(False) print('Started web server on port {}'.format(port)) # Find running wpa_supplicant process wpa_supplicant_running = False for proc in psutil.process_iter(): if proc.name() == 'wpa_supplicant': wpa_supplicant_running = True if not wpa_supplicant_running: sys.stderr.write('wpa_supplicant is not running. Use systemctl status to see if there is a startup error.\n') sys.exit(1) # Sanity checks for wpa_supplicant sockets run = '/var/run/wpa_supplicant' if os.path.isdir(run): try: for i in os.listdir(run): sockets[i] = os.path.join(run, i) except (OSError, error): sys.stderr.write('Cannot read wpa_supplicant run directory at %s. Make sure this server script has permissions to read that directory.\n' % run) sys.exit(1) else: sys.stderr.write('wpa_supplicant run directory at %s does not exist. Check wpa_supplicant is running and that its configuration has a ctrl_interface directive.\n' % run) sys.exit(1) if not sockets: sys.stderr.write('Cannot find any wpa_supplicant sockets in %s. Check wpa_supplicant is running and that its configuration has a ctrl_interface directive.\n' % run) sys.exit(1) for socket_name in sockets: if socket_name not in state: state[socket_name] = {} networks[socket_name] = [] socket = sockets.iterkeys().next() # Use the first found socket as the default set_socket(socket) print('Using socket {}'.format(socket)) restore_state() while True: reactor.iterate() time.sleep(0.001)
setpixelcolor(pixels, i, Color(0,0,0) ) #print LVarray[count]+ ":" +LVarray[count + 1]+ ":" +LVarray[count +2]+ " | " #setpixelcolor(pixels, i, Color(244,0,244) ) count += 3 writestrip(pixels) #root = Resource() #this is the directory where the Web interface code lives root = File("lampwww") #root.putChild("", File("lampwww")) root.putChild("API", lampAPI()) factory = Site(root) reactor.listenTCP(80, factory) reactor.startRunning(False) #The primary loop, each loop is one drawn frame and one check to see if we have a new web request while True: reactor.iterate() if MODE == -1: datastream(ledpixels) if MODE == 0: #lights off, but keep turning them off in case interference turns some on offmode(ledpixels) if MODE == 1: rainsim(ledpixels) if MODE == 2: clockdraw(ledpixels) if MODE == 3: #rainbowcycle(ledpixels, 0.00)
def run(self): """Override Process run method to provide a custom wrapper for service. Shared by all networked services. This provides a continuous loop for watching the child process while keeping an ear open to the main process from openContentPlatform, listening for any interrupt requests. """ try: ## Twisted import here to avoid issues with epoll on Linux from twisted.internet import reactor, ssl ## There are two types of event handlers being used here: ## self.shutdownEvent : main process tells this one to shutdown ## (e.g. on a Ctrl+C type event) ## self.canceledEvent : this process needs to restart serviceEndpoint = self.globalSettings.get('serviceIpAddress') useCertificates = self.globalSettings.get('useCertificates', True) ## Create a PID file for system administration purposes utils.pidEntryService(self.serviceName, env, self.pid) ## Network job services use networkService, which is a shared lib ## directed by additional input parameters; set args accordingly: factoryArgs = None if (self.serviceName == 'ContentGatheringService' or self.serviceName == 'UniversalJobService'): factoryArgs = (self.serviceName, self.globalSettings, self.canceledEvent, self.shutdownEvent, self.moduleType, self.clientEndpointTable, self.clientResultsTable, self.serviceResultsTable, self.serviceJobTable, self.serviceHealthTable, self.pkgPath, self.serviceSettings, self.serviceLogSetup) else: factoryArgs = (self.serviceName, self.globalSettings, self.canceledEvent, self.shutdownEvent) if useCertificates: ## Use TLS to encrypt the communication certData = FilePath( os.path.join( env.privateInternalCertPath, self.globalSettings.get( 'ocpCertificateCaFile'))).getContent() certificate = ssl.PrivateCertificate.loadPEM(certData) print('Starting encrypted service: {}'.format( self.serviceName)) reactor.listenSSL(self.listeningPort, self.serviceFactory(*factoryArgs), certificate.options()) else: ## Plain text communication print('Starting plain text service: {}'.format( self.serviceName)) reactor.listenTCP(self.listeningPort, self.serviceFactory(*factoryArgs), interface=serviceEndpoint) ## The following loop may look hacky at first glance, but solves a ## challenge with a mix of Python multi-processing, multi-threading, ## then Twisted's reactor and threading. ## Python threads that are not daemon types, cannot be forced closed ## when the controlling thread closes. So it's important to pass ## events all the way through, and have looping code catch/cleanup. ## Whenever the main process is being shut down, it must stop all ## sub-processes along with their work streams, which includes any ## Twisted reactors. We do that by passing shutdownEvent into the ## sub-processes. And whenever a service (sub-process) needs to ## restart, it notifies the other direction so the main process can ## verify it stopped and restart it. We do that by a canceledEvent. ## Now to the point of this verbose comment, so the reason we cannot ## call reactor.run() here, and instead cut/paste the same code, was ## to enhance 'while reactor._started' to watch for our events. reactor.startRunning() ## Start event wait loop while reactor._started and not self.shutdownEvent.is_set( ) and not self.canceledEvent.is_set(): try: ## Four lines from twisted.internet.base.mainloop: reactor.runUntilCurrent() t2 = reactor.timeout() t = reactor.running and t2 reactor.doIteration(t) except: exception = traceback.format_exception( sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]) print('Exception in {}: {}'.format(self.serviceName, exception)) break if self.shutdownEvent.is_set(): print('Shutdown event received for {}'.format( self.serviceName)) self.canceledEvent.set() with suppress(Exception): time.sleep(2) print('Calling reactor stop for {}'.format( self.serviceName)) reactor.stop() time.sleep(.5) elif self.canceledEvent.is_set(): print('Canceled event received for {}'.format( self.serviceName)) with suppress(Exception): time.sleep(2) reactor.stop() time.sleep(.5) except PermissionError: exceptionOnly = traceback.format_exception_only( sys.exc_info()[0], sys.exc_info()[1]) print(' {}'.format(exceptionOnly)) print(' Stopping {}'.format(self.serviceName)) except: exception = traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]) print('Exception in {}: {}'.format(self.serviceName, exception)) ## Cleanup utils.pidRemoveService(self.serviceName, env, self.pid) with suppress(Exception): reactor.stop() print('Stopped {}'.format(self.serviceName)) ## end ServiceProcess return
server_events.trigger(event, args) def registerPolicyEventHandler(event, func): '''Call function when policy event has been executed.''' policy_events.connect(event, func) class policyHandler(object): '''Decorator which registers a function as a policy event handler.''' def __init__(self, name): self.name = name def __call__(self, f): self.__doc__ = f.__doc__ self.__name__ = f.__name__ registerPolicyEventHandler(self.name, f) return f def triggerPolicyEvent(event, args): '''Trigger policy event with arguments.''' return policy_events.trigger(event, args) @eventHandler('serverTick') def update(gm,sm): reactor.runUntilCurrent() reactor.doIteration(0) @eventHandler('reload') def onReload(): server_events.events.clear() reactor.startRunning()
if success: if status == 400: status = 200 result = {"success": True, "result": data} else: result = {"success": False, "message": str(data)} result = json.dumps(result, indent=4) self.set_status(status) if callback: self.write(callback + '(' + result + ');') else: self.write(result) if __name__ == "__main__": topo = "/home/ralph/pwl-topo.owl" topo = "/home/ralph/src/nordunet/opennsa/test-topology.owl" ocli = onsaClient.Instance(topo) app = tornado.web.Application([ (r"/(.*)", Querier, { 'topology': topo }), ]) app.listen(8080) io = tornado.ioloop.IOLoop.instance() reactor.startRunning(installSignalHandlers=0) tornado.ioloop.PeriodicCallback(reactor.iterate, 10).start() io.start() io.stop() reactor.stop()
return self._respond(e, success=False) def _respond(self, data, callback=None, success=False, status=400): if success: if status==400: status=200 result={"success": True, "result" : data} else: result={"success": False, "message" : str(data)} result=json.dumps(result, indent=4) self.set_status(status) if callback: self.write(callback + '(' + result + ');') else: self.write(result) if __name__ == "__main__": topo="/home/ralph/pwl-topo.owl" topo="/home/ralph/src/nordunet/opennsa/test-topology.owl" ocli=onsaClient.Instance(topo) app = tornado.web.Application([ (r"/(.*)", Querier, {'topology':topo}), ]) app.listen(8080) io=tornado.ioloop.IOLoop.instance() reactor.startRunning(installSignalHandlers=0) tornado.ioloop.PeriodicCallback(reactor.iterate,10).start() io.start() io.stop() reactor.stop()
def __init__(self, port, interface): site = server.Site(PrometheusMonitoringHandler()) reactor.listenTCP(port, site, interface=interface or "") reactor.startRunning(False)
def _init(): reactor.startRunning(installSignalHandlers=True)
def main(): usage = "usage: %prog (-T|-W) [.. options ..] <corpus file>" parser = OptionParser(usage=usage) parser.add_option("-T", "--twitter", action="store_true", default=False, help="operate on Twitter corpus") parser.add_option("-W", "--web", action="store_true", default=False, help="operate on Web corpus") parser.add_option("-o", "--outfile", action="store", type="string", help="output data to file (CSV)") parser.add_option("-G", "--save-graphs", action="store", type="string", help="output graphs to GEXF files") parser.add_option("-q", "--quiet", action="store_true", default=False, help="display only errors") parser.add_option( "-v", "--verbose", action="store_true", default=False, help="display informative messages (default)" ) parser.add_option("-d", "--debug", action="store_true", default=False, help="display debug messages") parser.add_option("-S", "--sql-debug", action="store_true", default=False, help="display SQL requests") parser.add_option("-n", "--offline", action="store_true", default=False, help="do not fetch external data") parser.add_option( "-i", "--interactive", action="store_true", default=False, help="launch interactive prompt after processing data", ) (options, args) = parser.parse_args() t, w = options.twitter, options.web if (t and w) or (not t and not w): parser.error("need to specify exactly one of -T and -W") verbosity = 2 if options.debug else (0 if options.quiet else 1) level = {0: logging.WARNING, 1: logging.INFO, 2: logging.DEBUG}[verbosity] sqla_level = logging.INFO if options.sql_debug else logging.WARNING logging.basicConfig(stream=sys.stderr, level=level) logging.getLogger("sqlalchemy.engine").setLevel(sqla_level) config = SafeConfigParser() with open("ipinion.ini") as f: config.readfp(f) if w: corpus = WebCorpus(config) dbname = "store.web.db" else: corpus = TwitterCorpus(config) dbname = "store.twitter.db" u, v, w = gc.get_threshold() gc.set_threshold(u, v * 4, w * 10) engine = create_engine("sqlite:///" + dbname) corpus.create_or_upgrade_db(engine) logger = logging.getLogger("load") for fn in args: logger.info("loading incremental dataset %r...", fn) n = corpus.load_file(fn) logger.info("%d items read", n) # Initialize reactor reactor.startRunning(installSignalHandlers=False) must_stop = [] def reactor_loop(): # This is very crude but avoids reliance on private reactor data while reactor.running and not must_stop: reactor.iterate(0.1) must_stop[:] = [] def after_fetch(_): corpus.recompute_data() if options.save_graphs: logger = logging.getLogger("save") base, ext = os.path.splitext(options.save_graphs) if not ext: ext = ".gexf" for suffix, g in corpus.graphes().items(): gfn = base + suffix + ext logger.info("saving %d nodes and %d edges to %r..." % (len(g), g.number_of_edges(), gfn)) nx.write_gexf(g, gfn) if options.outfile: corpus.save_data(options.outfile) must_stop.append(None) def on_failure(failure): must_stop.append(None) failure.printTraceback(elideFrameworkCode=True) reactor.crash() os._exit(1) corpus.preprocess_data() if not options.offline: d = corpus.fetch_external_data() else: d = maybeDeferred(lambda: None) d.addCallback(after_fetch) d.addErrback(on_failure) try: reactor_loop() if options.interactive: enable_readline_completion() gvars = ("config", "corpus", "engine", "options") for var in gvars: globals()[var] = locals()[var] interact("Available variables: %r" % (gvars,), None, globals()) finally: reactor.stop() # Needed after stop to properly terminate the reactor reactor_loop()