def stop_server(server): server.stop() logger.info("Add stop callback.") ioloop = tornado.ioloop.IOLoop.instance() ioloop.add_callback(ioloop.stop) logger.info("Maybe server stopping...") os.system("taskkill /im python.exe")
def on_open(self, info: ConnectionInfo) -> None: log_data = dict(extra='[transport=%s]' % (self.session.transport_name,)) record_request_start_data(log_data) ioloop = tornado.ioloop.IOLoop.instance() self.authenticated = False self.session.user_profile = None self.close_info = None # type: Optional[CloseErrorInfo] self.did_close = False try: self.browser_session_id = info.get_cookie(settings.SESSION_COOKIE_NAME).value self.csrf_token = info.get_cookie(settings.CSRF_COOKIE_NAME).value except AttributeError: # The request didn't contain the necessary cookie values. We can't # close immediately because sockjs-tornado doesn't expect a close # inside on_open(), so do it on the next tick. self.close_info = CloseErrorInfo(403, "Initial cookie lacked required values") ioloop.add_callback(self.close) return def auth_timeout() -> None: self.close_info = CloseErrorInfo(408, "Timeout while waiting for authentication") self.close() self.timeout_handle = ioloop.call_later(10, auth_timeout) write_log_line(log_data, path='/socket/open', method='SOCKET', remote_ip=info.ip, email='unknown', client_name='?')
def fetch(self, callback): if len(self.logs) == 0: self.callback = callback else: logs, self.logs = self.logs, [] for log in logs: ioloop.add_callback(callback, log)
def enumerate_device(this_node, node_id, response): global UAVCAN_NODE_INFO, UAVCAN_NODE_CONFIG log.debug("enumerate_device({}, {!r})".format(node_id, response)) # Save the node info request and clear out the config UAVCAN_NODE_INFO[node_id] = response UAVCAN_NODE_CONFIG[node_id] = {} # Send the node info message to all connected sockets send_all(response.type.get_normalized_definition(), node_id, response) # Schedule a parameter fetch if the node is in operating mode if not response.status.mode: ioloop.add_callback(enumerate_node_params, this_node, node_id) # Check the supplied directory for updated firmware if not firmware_dir: log.debug("enumerate_device(): no firmware path specified") return # Search for firmware suitable for this device device_name = response.name.decode() available_files = firmware_files_for_device( firmware_dir, device_name, response.hardware_version.major, response.hardware_version.minor) log.debug(("enumerate_device(): found {:d} firmware file(s) " + "for device '{!s}'").format(len(available_files), device_name)) for f in available_files: log.debug(("enumerate_device(): {!s} " + "(modified {:%Y-%m-%dT%H:%M:%S})").format( f[-1], datetime.datetime.fromtimestamp(f[-2]))) # If there are files available, check the CRC of the latest version # against the CRC of the firmware on the node. if available_files: firmware_path = available_files[0][-1] with FirmwareImage(firmware_path, "rb") as f: if f.app_descriptor.image_crc != \ response.software_version.image_crc: # Version mismatch, send a BeginFirmwareUpdate with the # appropriate path. request = uavcan.protocol.file.BeginFirmwareUpdate( mode="request") request.source_node_id = this_node.node_id request.image_file_remote_path.path.encode( os.path.basename(firmware_path)) (response, response_transfer), _ = yield tornado.gen.Task( this_node.send_request, request, node_id) if response and response.error != response.ERROR_OK: msg = ("[MASTER] #{0:03d} rejected " "uavcan.protocol.file.BeginFirmwareUpdate " + "with error {1:d}: {2!s}").format( node_id, response.error, response.optional_error_message.decode()) log.error(msg) else: log.debug("enumerate_device(): device up to date")
def start_server(args): app = Flask(__name__) app.config['SECRET_KEY'] = 'secret' app.jinja_env.globals['static'] = static blueprint.url_prefix = args.url_prefix app.register_blueprint(blueprint) # app.run(port=args.port, debug=args.debug) wsgi_app = tornado.wsgi.WSGIContainer(app) condajs_ws = sockjs.tornado.SockJSRouter(views.CondaJsWebSocketRouter, '/condajs_ws') routes = condajs_ws.urls routes.append((r".*", tornado.web.FallbackHandler, dict(fallback=wsgi_app))) application = tornado.web.Application(routes, debug=args.debug) try: application.listen(args.port) except OSError as e: print("There was an error starting the server:") print(e) return ioloop = tornado.ioloop.IOLoop.instance() if not args.debug: callback = lambda: webbrowser.open_new_tab('http://localhost:%s' % args.port) ioloop.add_callback(callback) ioloop.start()
def enumerate_device(this_node, node_id, response): global UAVCAN_NODE_INFO, UAVCAN_NODE_CONFIG log.debug("enumerate_device({}, {!r})".format(node_id, response)) # Save the node info request and clear out the config UAVCAN_NODE_INFO[node_id] = response UAVCAN_NODE_CONFIG[node_id] = {} # Send the node info message to all connected sockets send_all(response.type.get_normalized_definition(), node_id, response) # Schedule a parameter fetch if the node is in operating mode if not response.status.mode: ioloop.add_callback(enumerate_node_params, this_node, node_id) # Check the supplied directory for updated firmware if not firmware_dir: log.debug("enumerate_device(): no firmware path specified") return # Search for firmware suitable for this device device_name = response.name.decode() available_files = firmware_files_for_device( firmware_dir, device_name, response.hardware_version.major, response.hardware_version.minor) log.debug(("enumerate_device(): found {:d} firmware file(s) " + "for device '{!s}'").format( len(available_files), device_name)) for f in available_files: log.debug(("enumerate_device(): {!s} " + "(modified {:%Y-%m-%dT%H:%M:%S})").format( f[-1], datetime.datetime.fromtimestamp(f[-2]))) # If there are files available, check the CRC of the latest version # against the CRC of the firmware on the node. if available_files: firmware_path = available_files[0][-1] with FirmwareImage(firmware_path, "rb") as f: if f.app_descriptor.image_crc != \ response.software_version.image_crc: # Version mismatch, send a BeginFirmwareUpdate with the # appropriate path. request = uavcan.protocol.file.BeginFirmwareUpdate( mode="request") request.source_node_id = this_node.node_id request.image_file_remote_path.path.encode( os.path.basename(firmware_path)) (response, response_transfer), _ = yield tornado.gen.Task( this_node.send_request, request, node_id) if response and response.error != response.ERROR_OK: msg = ("[MASTER] #{0:03d} rejected " "uavcan.protocol.file.BeginFirmwareUpdate " + "with error {1:d}: {2!s}").format( node_id, response.error, response.optional_error_message.decode()) log.error(msg) else: log.debug("enumerate_device(): device up to date")
def main(): options, args = get_args() ioloop = tornado.ioloop.IOLoop.instance() series = get_series_class(options)(options, ioloop) application = Application(options, series, [ ('/', IndexHandler), ('/update', UpdateHandler), ], static_path=STATIC_PATH) try: ip = get_ip_address('eth0') except IOError: ip = '127.0.0.1' tornado.httpserver.HTTPServer(application).listen(options.port, ip) url = 'http://%s:%s/' % (ip, options.port) def announce(): print >>sys.stderr, "wplot running at: " + url if options.browse: ioloop.add_callback(lambda: webbrowser.open_new_tab(url)) ioloop.add_callback(announce) try: ioloop.start() except (KeyboardInterrupt, IOError) as e: pass finally: application._stop = True
def read_callback(self, frame): ts = frame.timestamp ioloop.add_callback( lambda: self.publish('can.%03x' % frame.id, ts, frame.tojson())) if self.obd2: ioloop.add_callback(lambda: self.obd2.read(ts, frame.tojson()))
def open(self): ioloop = tornado.ioloop.IOLoop.instance() ioloop.call_later(self._KEEPALIVE_PING_TIMEOUT, self._send_ping) ioloop.add_callback(lambda: log.info('Client connected: {0}'.format(self))) self._get_id() self._CLIENTS[self.id] = self self._log_client_list()
def stop(self): """ Stop tornado web server """ ioloop = tornado.ioloop.IOLoop.instance() ioloop.add_callback(ioloop.stop) logger.debug("Exiting tornado...")
def on_open(self, info): # type: (ConnectionInfo) -> None log_data = dict(extra='[transport=%s]' % (self.session.transport_name,)) record_request_start_data(log_data) ioloop = tornado.ioloop.IOLoop.instance() self.authenticated = False self.session.user_profile = None self.close_info = None # type: CloseErrorInfo self.did_close = False try: self.browser_session_id = info.get_cookie(settings.SESSION_COOKIE_NAME).value self.csrf_token = info.get_cookie(settings.CSRF_COOKIE_NAME).value except AttributeError: # The request didn't contain the necessary cookie values. We can't # close immediately because sockjs-tornado doesn't expect a close # inside on_open(), so do it on the next tick. self.close_info = CloseErrorInfo(403, "Initial cookie lacked required values") ioloop.add_callback(self.close) return def auth_timeout(): # type: () -> None self.close_info = CloseErrorInfo(408, "Timeout while waiting for authentication") self.close() self.timeout_handle = ioloop.add_timeout(time.time() + 10, auth_timeout) write_log_line(log_data, path='/socket/open', method='SOCKET', remote_ip=info.ip, email='unknown', client_name='?')
def inner_run(self, *args, **options): quit_command = (platform == "win32") and "CTRL-BREAK" or "CONTROL-C" if (hasattr(settings, "AUTO_SETUP") and settings.AUTO_SETUP) or ( not hasattr(settings, "AUTO_SETUP") and settings.DEBUG): server = self.get_setup_server() loop_thread = threading.Thread( target=tornado.ioloop.IOLoop.current().start) loop_thread.daemon = True loop_thread.start() call_command("setup", force_transpile=False) server.stop() ioloop = tornado.ioloop.IOLoop.current() ioloop.add_callback(ioloop.stop) self.stdout.write( ("%(started_at)s\n" "Fidus Writer version %(version)s, using settings %(settings)r\n" "Fidus Writer server is running at http://%(addr)s:%(port)s/\n" "Quit the server with %(quit_command)s.\n") % { "started_at": datetime.now().strftime("%B %d, %Y - %X"), "version": self.get_version(), "settings": settings.SETTINGS_MODULE, "addr": self.addr, "port": self.port, "quit_command": quit_command, }) # django.core.management.base forces the locale to en-us. We should # set it up correctly for the first request (particularly important # in the "--noreload" case). translation.activate(settings.LANGUAGE_CODE) run_server(self.port)
def init_timers(self): ioloop = tornado.ioloop.IOLoop.instance() # The mongo status monitor. We set up one call immediately, and then # try again every three seconds. ioloop.add_callback(self.monitor_mongo_status) res = tornado.ioloop.PeriodicCallback(self.monitor_mongo_status, 3000) res.start()
def shutdown(self): #self.snapcast_service.stop() #self.snapcast_service.join() self.mopidy_sercice.stop() #self.mopidy_sercice.join() ioloop = tornado.ioloop.IOLoop.current() ioloop.add_callback(ioloop.stop) self.logger.info("Hydraplay Server stopped.")
def read_callback(self, frame): ts = frame.timestamp ioloop.add_callback(lambda:self.publish( 'can.%03x' % frame.id, ts, frame.tojson())) if self.obd2: ioloop.add_callback(lambda: self.obd2.read(ts, frame.tojson()))
def gpio_loop(): ioloop = tornado.ioloop.IOLoop.current() value = True while True: time.sleep(1.0) value = not value ioloop.add_callback(partial(WebSocketHandler.dispatch, value))
def signal_handler(signal, frame): print('Caught %s' % signal) print "Stopping phishing campaign..." ioloop = tornado.ioloop.IOLoop.instance() ioloop.add_callback(ioloop.stop) e.set() print "Asked Tornado to exit" sys.exit(0)
def on_close(self): ioloop = tornado.ioloop.IOLoop.instance() if self._CLIENTS.has_key(self.id): self._CLIENTS.pop(self.id) for name, obj in iteritems(self.__handlers): ioloop.add_callback(obj._onclose) log.info('Client "{0}" disconnected'.format(self.id))
def close(self): super(WebSocketBase, self).close() ioloop = tornado.ioloop.IOLoop.instance() for future in self.store.values(): ioloop.add_callback(partial(future.set_exception, ConnectionClosed)) ioloop.add_callback(lambda: self.on_close() if self.ws_connection else None)
def queue_response(self, response): ioloop = tornado.ioloop.IOLoop.instance() def send_response(*args): self._send_response(response) try: # calling write_message or the socket is not thread safe ioloop.add_callback(send_response) except: logging.error("Error adding callback", exc_info=True)
def send_json_to_web_ui(self, j): """ Send provided Json object to all web clients "param j": Json object to send """ for c in self.web_clients: e = json.dumps(j).encode(encoding="utf-8") ioloop = tornado.ioloop.IOLoop.instance() ioloop.add_callback(c.write_message, e)
def _read_stdin(self): ioloop = tornado.ioloop.IOLoop.instance() try: for line in sys.stdin: line = line.strip() ioloop.add_callback(self._stdin, line) except OSError: pass ioloop.add_callback(self.stop)
def start_server() -> None: """Serve a WSGI application until stopped.""" ioloop.make_current() httpd.listen(port=port, address=address) ioloop.add_callback(started.set) ioloop.start() stopped.set()
def schedule_match(self, match, worker): def send_schedule(): self.send({'$schedule':{ 'match_id': match.match_id, 'game': match.game, 'players': match.players, 'config': match.config }}) ioloop.add_callback(send_schedule) self.matches[match.match_id] = match
def stop(self): """Stop running the server""" logging.debug("Shutting down extension server") self.must_exit = True if self.thread is not None: ioloop = tornado.ioloop.IOLoop.instance() ioloop.add_callback(ioloop.stop) self.thread.join() self.thread = None logging.debug("Extension server stopped")
def async_task(): global times times += 1 print('run async task %s' % times) # functools.partial调用的结果是产生一个偏函数 # ioloop.add_callback中的参数callback只能接异步函数名,没有地方再给异步函数传参数,偏函数整好派上用场, # 原先调用wrapper方式:wrapper(func1) # 转为偏函数:wrapper2 = functools.partial(wrapper,func1) # 偏函数调用方式:wrapper2(),且与原先的调用方式效果一模一样, ioloop.add_callback(callback=functools.partial(wrapper, callback))
def on_close(self): ''' Called when client closes this connection. Cleanup is done here. ''' if self.id in self.funcserver.websocks: self.funcserver.websocks[self.id] = None ioloop = tornado.ioloop.IOLoop.instance() ioloop.add_callback(lambda: self.funcserver.websocks.pop(self.id, None))
def main(): ioloop = tornado.ioloop.IOLoop.current() tornado.log.enable_pretty_logging() tornado.log.app_log.setLevel(logging.DEBUG) app = tornado.web.Application( [(r"/static/(.*)", tornado.web.StaticFileHandler, {"path": "./static"}), (r"/api/puzzle", PuzzleHandler)] ) app.listen(8888) ioloop.add_callback(in_app_worker) ioloop.add_callback(in_app_worker) ioloop.start()
def main(): ioloop = tornado.ioloop.IOLoop.current() app = tornado.web.Application([(r'/api/steam/v1', ApiHandler)]) app.listen(int(sys.argv[1])) ioloop.add_callback(timer) pc = tornado.ioloop.PeriodicCallback(timer, 5 * 60 * 1000) pc.start() ioloop.start()
def on_close(self): ''' Called when client closes this connection. Cleanup is done here. ''' if self.id in self.funcserver.websocks: self.funcserver.websocks[self.id] = None ioloop = tornado.ioloop.IOLoop.instance() ioloop.add_callback( lambda: self.funcserver.websocks.pop(self.id, None))
def restart_tornado(): global restart_server global server # print("checking for file change") # print(restart_server) if (restart_server): print("updating the bigquery client") server.stop() server = None server = start_app() ioloop.add_callback(ioloop.stop)
def send(self, method_name, data): """Sends a messge to the client. Args: method_name: The javascript method name data: A dictionary of data to pass to the client """ j_msg = dict(event=method_name, data=data) message = json.dumps(j_msg) ioloop.add_callback(lambda: self.write_message(message))
def cbMethod( *cargs, **ckwargs ): cb = ckwargs.pop( 'callback' ) method = cargs[0] disetConf = cargs[1] cargs = cargs[2] RESTHandler.__disetConfig.load( disetConf ) ioloop = tornado.ioloop.IOLoop.instance() try: result = method( *cargs, **ckwargs ) ioloop.add_callback( functools.partial( cb, result ) ) except Exception, excp: exc_info = sys.exc_info() ioloop.add_callback( lambda : genTask.runner.handle_exception( *exc_info ) )
def main(): debug = int(os.environ.get("AS_DEV", "0")) logging.basicConfig( format=f"%(asctime)s captain: %(levelname)s: %(message)s", level=logging.DEBUG if debug else logging.INFO, ) ioloop = tornado.ioloop.IOLoop.current() ioloop.add_callback(signal.signal, signal.SIGTERM, handle_sigterm) ioloop.add_future(asyncio.ensure_future(async_main()), lambda _: None) logging.debug("Entering the IOLoop...") ioloop.start()
def main(): tornado.options.options.log_file_prefix = '/tmp/load_test.log' tornado.options.parse_command_line() signal.signal(signal.SIGTERM, sig_handler) signal.signal(signal.SIGINT, sig_handler) ioloop = tornado.ioloop.IOLoop.instance() ioloop.add_callback(init) logger.info("started") ioloop.start() logger.info("Exit...")
def stop_server(*args): global web_server, web_server_thread, modemServer, exit_event log.debug('Server stopping') web_server.stop() ioloop = tornado.ioloop.IOLoop.instance() ioloop.add_callback(ioloop.stop) # web_server_thread.join() log.debug('Server stopped') log.debug('Modem stopping') exit_event.set() log.debug('Modem stopped')
def sighup_handler (server, ioloop, signum, frame): def stop_ioloop (ioloop): logging.info ("Stopping IOloop") ioloop.stop () logging.info ("Done.") def stop_server (server, ioloop): logging.info ("Stopping HTTP server") server.stop () ioloop.add_timeout (time.time () + 5.0, partial (stop_ioloop, ioloop)) logging.info ("Waiting for pending requests") logging.info ("Graceful exit due to SIGHUP") ioloop.add_callback (partial (stop_server, server, ioloop))
def main(config_file=None): parse_configs(config_files=config_file) if options.app is None: log.exception('no frontik application present (`app` option is not specified)') sys.exit(1) log.info('starting application %s', options.app) try: module = importlib.import_module(options.app) except Exception as e: log.exception('failed to import application module "%s": %s', options.app, e) sys.exit(1) if options.app_class is not None and not hasattr(module, options.app_class): log.exception('application class "%s" not found', options.app_class) sys.exit(1) application = getattr(module, options.app_class) if options.app_class is not None else FrontikApplication try: app = application(app_root=os.path.dirname(module.__file__), **options.as_dict()) ioloop = tornado.ioloop.IOLoop.current() def _async_init_cb(): try: init_futures = app.default_init_futures + list(app.init_async()) if init_futures: def await_init(future): if future.exception() is not None: log.error('failed to initialize application, init_async returned: %s', future.exception()) sys.exit(1) run_server(app) ioloop.add_future(gen.multi(init_futures), await_init) else: run_server(app) except Exception: log.exception('failed to initialize application') sys.exit(1) ioloop.add_callback(_async_init_cb) ioloop.start() except BaseException: log.exception('frontik application exited with exception') sys.exit(1)
def start() : application = Application(drop=options.drop) http_server = tornado.httpserver.HTTPServer(application) try : http_server.listen(app_config.port) except : traceback.print_exc() os._exit(1) # since it otherwise hangs Settings.logging.info("Started news_crowdsourcer in %s mode." % app_config.environment) ioloop = tornado.ioloop.IOLoop.instance() try : ioloop.start() except : ioloop.add_callback(lambda : ioloop.stop())
def cbMethod(*cargs, **ckwargs): cb = ckwargs.pop('callback') method = cargs[0] disetConf = cargs[1] cargs = cargs[2] cls.__disetConfig.load(disetConf) ioloop = tornado.ioloop.IOLoop.instance() try: result = method(*cargs, **ckwargs) ioloop.add_callback(functools.partial(cb, result)) except Exception, excp: exc_info = sys.exc_info() ioloop.add_callback( lambda: genTask.runner.handle_exception(*exc_info))
def init_timers(self): """Start the ioloop timers for this module. """ ioloop = tornado.ioloop.IOLoop.instance() # The mongo status monitor. We set up one call immediately, and then # try again every five seconds. ioloop.add_callback(self.monitor_mongo_status) res = tornado.ioloop.PeriodicCallback(self.monitor_mongo_status, 5000) res.start() # The tworld status monitor. Same deal. ioloop.add_callback(self.monitor_tworld_status) res = tornado.ioloop.PeriodicCallback(self.monitor_tworld_status, 5000) res.start()
def on_close(self): ''' Called when client closes this connection. Cleanup is done here. ''' if self.id in self.funcserver.websocks: self.funcserver.websocks[self.id] = None ioloop = tornado.ioloop.IOLoop.instance() ioloop.add_callback(lambda: self.funcserver.websocks.pop(self.id, None)) psession = self.funcserver.pysessions.get(self.pysession_id, None) if psession: psession['socks'].remove(self.id) if not psession['socks']: del self.funcserver.pysessions[self.pysession_id]
def cbMethod(*cargs, **ckwargs): cb = ckwargs.pop('callback') method = cargs[0] disetConf = cargs[1] cargs = cargs[2] self.__disetConfig.reset() self.__disetConfig.load(disetConf) ioloop = tornado.ioloop.IOLoop.instance() try: result = method(*cargs, **ckwargs) ioloop.add_callback(functools.partial(cb, result)) except Exception as excp: gLogger.error("Following exception occured %s" % excp) exc_info = sys.exc_info() genTask.set_exc_info(exc_info) ioloop.add_callback(lambda: genTask.exception())
def cbMethod( *cargs, **ckwargs ): cb = ckwargs.pop( 'callback' ) method = cargs[0] disetConf = cargs[1] cargs = cargs[2] self.__disetConfig.reset() self.__disetConfig.load( disetConf ) ioloop = tornado.ioloop.IOLoop.instance() try: result = method( *cargs, **ckwargs ) ioloop.add_callback( functools.partial( cb, result ) ) except Exception as excp: gLogger.error( "Following exception occured %s" % excp ) exc_info = sys.exc_info() genTask.set_exc_info( exc_info ) ioloop.add_callback( lambda : genTask.exception() )
def start(): application = Application( environment=options.environment, db_name=options.db_name, drop=options.drop, make_payments=options.make_payments ) http_server = tornado.httpserver.HTTPServer(application) try: http_server.listen(options.port) except: traceback.print_exc() os._exit(1) # since it otherwise hangs Settings.logging.info("Started news_crowdsourcer in %s mode." % options.environment) ioloop = tornado.ioloop.IOLoop.instance() try: ioloop.start() except: ioloop.add_callback(lambda: ioloop.stop())
def main(config_file=None): # noinspection PyUnresolvedReferences import frontik.options parse_configs(config_files=config_file) if options.app is None: log.exception('no frontik application present (`app` option is not specified)') sys.exit(1) log.info('starting application %s', options.app) try: module = importlib.import_module(options.app) except Exception as e: log.exception('failed to import application module "%s": %s', options.app, e) sys.exit(1) if options.app_class is not None and not hasattr(module, options.app_class): log.exception('application class "%s" not found', options.app_class) sys.exit(1) application = getattr(module, options.app_class) if options.app_class is not None else FrontikApplication try: tornado_app = application(**options.as_dict()) ioloop = tornado.ioloop.IOLoop.current() def _run_server_cb(future): if future.exception() is not None: log.error('failed to initialize application, init_async returned: %s', future.exception()) sys.exit(1) run_server(tornado_app) def _async_init_cb(): try: ioloop.add_future(tornado_app.init_async(), _run_server_cb) except Exception: log.exception('failed to initialize application') sys.exit(1) ioloop.add_callback(_async_init_cb) ioloop.start() except: log.exception('frontik application exited with exception') sys.exit(1)
def on_close(self): """ Called when client closes this connection. Cleanup is done here. """ if self.id in self.funcserver.websocks: self.funcserver.websocks[self.id] = None ioloop = tornado.ioloop.IOLoop.instance() ioloop.add_callback( lambda: self.funcserver.websocks.pop(self.id, None)) psession = self.funcserver.pysessions.get(self.pysession_id, None) if psession: psession["socks"].remove(self.id) if not psession["socks"]: del self.funcserver.pysessions[self.pysession_id]
def register(handlers=None, subdomain=None, parent_dir=None, urls=None): ''' Register additional handlers to the server. :param handlers: List of handler classes to register. :param subdomain: The desired subdomain :param parent_dir: The directory under which all the handlers should be placed :param urls: List of lists like [['path', Handler]]. Overwrites handlers input. ''' # parse input if subdomain is None: subdomain = "[A-Za-z0-9.]*" else: subdomain = r'{}\.[A-Za-z0-9.]*'.format(subdomain) if parent_dir is None: parent_dir = '' else: parent_dir = '/{}'.format(parent_dir) # create proper URLSpec handlers and callback if not urls: def doc_url(handler): """ reads the url regexp from the handler's docstring. """ docs = handler.__doc__ pieces = docs.strip().split('\n\n')[0].split('\n') return ''.join([piece.strip() for piece in pieces]) handlers = [ tornado.web.URLSpec('{}{}'.format(parent_dir, doc_url(handler)), handler) for handler in handlers ] else: handlers = urls def add_handler_callback(server, subdmn, hndls): """ add handler to server """ server.add_handlers(subdmn, hndls) # schedule handler addition to next IOLoop iteration ioloop = tornado.ioloop.IOLoop.instance() ioloop.add_callback(add_handler_callback, SERVER, subdomain, handlers)
def handle_shoot(self, message): player = message['player'] if not player in self.application.battlefield.players: return shot_player = self.application.battlefield.calculate_shot(player) if shot_player: self.application.battlefield.inc_score(player) self.write_message({'cmd':'kill', 'game':True, 'args' : [shot_player, application.battlefield.get_score()]}) self.broadcast({'cmd':'kill', 'game':True, 'args' : [shot_player, application.battlefield.get_score()]}) score = self.application.battlefield.remove_player(shot_player) def respawn(): self.respawn(shot_player, score) def timeout(): ioloop.add_timeout(timedelta(seconds = 3), respawn) ioloop.add_callback(timeout) return True
def register(handlers=None, subdomain=None, parent_dir=None, urls=None): ''' Register additional handlers to the server. :param handlers: List of handler classes to register. :param subdomain: The desired subdomain :param parent_dir: The directory under which all the handlers should be placed :param urls: List of lists like [['path', Handler]]. Overwrites handlers input. ''' # parse input if subdomain is None: subdomain = "[A-Za-z0-9.]*" else: subdomain = r'{}\.[A-Za-z0-9.]*'.format(subdomain) if parent_dir is None: parent_dir = '' else: parent_dir = '/{}'.format(parent_dir) # create proper URLSpec handlers and callback if not urls: def doc_url(handler): """ reads the url regexp from the handler's docstring. """ docs = handler.__doc__ pieces = docs.strip().split('\n\n')[0].split('\n') return ''.join([piece.strip() for piece in pieces]) handlers = [tornado.web.URLSpec('{}{}'.format(parent_dir, doc_url(handler)), handler) for handler in handlers] else: handlers = urls def add_handler_callback(server, subdmn, hndls): """ add handler to server """ server.add_handlers(subdmn, hndls) # schedule handler addition to next IOLoop iteration ioloop = tornado.ioloop.IOLoop.instance() ioloop.add_callback(add_handler_callback, SERVER, subdomain, handlers)
def main(config_file=None): # noinspection PyUnresolvedReferences import frontik.options parse_configs_and_start(config_files=config_file) if options.app is None: log.exception('no frontik application present (`app` option is not specified)') sys.exit(1) try: module = importlib.import_module(options.app) except Exception as e: log.exception('failed to import application module "%s": %s', options.app, e) sys.exit(1) if options.app_class is not None and not hasattr(module, options.app_class): log.exception('application class "%s" not found', options.app_class) sys.exit(1) application = getattr(module, options.app_class) if options.app_class is not None else FrontikApplication try: tornado_app = application(**options.as_dict()) ioloop = tornado.ioloop.IOLoop.instance() def _async_init_cb(): def _run_server_cb(future): if future.exception() is not None: log.exception('failed to start: %s', future.exception()) sys.exit(1) run_server(tornado_app) ioloop.add_future( tornado_app.init_async(), _run_server_cb ) ioloop.add_callback(_async_init_cb) ioloop.start() except: log.exception('failed to initialize frontik application, quitting') sys.exit(1)
def stop(self): # Let the master process do the printing if self.verbosity > 0 and os.getpid() == self.master_pid: print('\nStopping URL shortener web service', flush=True) # The zero ID process joins back the database process if self.server_process_id == 0: self.database_process.join() self.database_process.close() # Stop server and event loop self.server.stop() ioloop = tornado.ioloop.IOLoop.instance() ioloop.add_callback(ioloop.stop) # In a perfect world, all forked off subprocesses should now # be joined. However, our use of multiprocessing from both # Tornado and Python somehow leaves child processes still # running, which will be wrongly joined at Python exit, # leading to uncatchable exceptions. It is no big deal, # but the large tracebacks are annoying. # As a very hacky solution, we send all processes to sleep # except the master process, i.e. the one originally # responsible for launching the service, and thus a common # ancestor to all other running processes. This process then # gets the process ID of all its descendants (through a hacky # call to the system ps command), and then asks the system to # kill these. if os.getpid() != self.master_pid: time.sleep(1) return # Ought to be killed before reaching here pids = sorted( int(line.strip().split()[0].strip()) for line in subprocess.check_output( f'ps -o pid,cmd -g $(ps -o sid= -p {self.master_pid})', shell=True, ).decode().split('\n') if line.strip() and 'python' in line ) for pid in pids: if pid > self.master_pid: try: os.kill(pid, signal.SIGTERM) os.kill(pid, signal.SIGKILL) except ProcessLookupError: pass
def run(self): try: ioloop = tornado.ioloop.IOLoop.instance() def handler(signum, frame): ioloop.add_callback(ioloop.stop) signal.signal(signal.SIGTERM, handler) from tornado.httpserver import HTTPServer http_server = HTTPServer(self.application) http_server.listen(self.port, address=self.host) self.logger.info('Application Server is Ready: ' + self.home_url) def ready(): self.is_starting_event.set() ioloop.add_callback(ready) ioloop.start() except: self.is_starting_event.set() raise
def call(fn): ioloop = tornado.ioloop.IOLoop.instance() ioloop.add_callback(fn)
def unload(): ''' stops the http server ''' ioloop = tornado.ioloop.IOLoop.instance() ioloop.add_callback(lambda x: x.stop(), ioloop) _LOGGER.info('Unloaded HTTP element')