def run_server(self): try: host = "127.0.0.1" port = int(self.config["WEBSERVER_HTTP_PORT"]) self.log.info("Starting the webserver on %s:%i", host, port) self.server = ThreadedWSGIServer(host, port, flask_app) self.server.serve_forever() self.log.debug("Webserver stopped") except KeyboardInterrupt: self.log.info("Keyboard interrupt, request a global shutdown.") self.server.shutdown() except Exception: self.log.exception("The webserver exploded.")
def serve_forever(self): if self.__config.GEVENT: from gevent.wsgi import WSGIServer WSGIServer( (self.__config.HOST, self.__config.PORT), self, log='default' if self.__debug else None, ).serve_forever() else: from werkzeug.serving import ThreadedWSGIServer ThreadedWSGIServer(self.__config.HOST, self.__config.PORT, self).serve_forever()
def serving_app(request): """Create a Flask app and serve it over 8080. This will be used to pretend to be GitHub, so we can see test what happens when GitHub returns unexpected responses. When the test ends, the server is destroyed. """ host = '127.0.0.1' port = randint(8000, 8999) app = Flask(__name__) app.url = 'http://{0}:{1}'.format(host, port) server = ThreadedWSGIServer(host, port, app) thread = threading.Thread(target=server.serve_forever) thread.start() request.addfinalizer(server.shutdown) return app
def serve_forever(self): if self._gevent: from gevent.wsgi import WSGIServer WSGIServer( (self.__host, self.__port), self, log='default' if self.__debug else None, ).serve_forever() if self._threading: from werkzeug.serving import ThreadedWSGIServer ThreadedWSGIServer(self.__host, self.__port, self).serve_forever() if self._multiprocessing: from werkzeug.serving import ForkingWSGIServer ForkingWSGIServer(self.__host, self.__port, self).serve_forever() else: self.run()
def run_server(self): try: host = self.config['HOST'] port = self.config['PORT'] ssl = self.config['SSL'] self.log.info('Starting the webserver on %s:%i', host, port) ssl_context = (ssl['certificate'], ssl['key']) if ssl['enabled'] else None self.server = ThreadedWSGIServer( host, ssl['port'] if ssl_context else port, flask_app, ssl_context=ssl_context) self.server.serve_forever() self.log.debug('Webserver stopped') except KeyboardInterrupt: self.log.info('Keyboard interrupt, request a global shutdown.') self.server.shutdown() except Exception: self.log.exception('The webserver exploded.')
def run_server(self): try: host = self.config["HOST"] port = self.config["PORT"] ssl = self.config["SSL"] self.log.info("Starting the webserver on %s:%i", host, port) ssl_context = (ssl["certificate"], ssl["key"]) if ssl["enabled"] else None self.server = ThreadedWSGIServer( host, ssl["port"] if ssl_context else port, flask_app, ssl_context=ssl_context, ) self.server.serve_forever() self.log.debug("Webserver stopped") except KeyboardInterrupt: self.log.info("Keyboard interrupt, request a global shutdown.") self.server.shutdown() except Exception: self.log.exception("The webserver exploded.")
threading.Thread(target=sleep_and_browse).start() browser_watchdog = None if config.BROWSER_WD_SECONDS: browser_watchdog = WatchDog(callback=close, sleep=config.BROWSER_WD_SECONDS) # Iniciamos el watchdog por más que aún no esté levantado el browser ya que # el tiempo del watchdog es mucho mayor que el que se tarda en levantar el server # y el browser. browser_watchdog.start() if options.verbose: print "Levantando el server..." app = create_app(browser_watchdog, verbose=options.verbose) server = ThreadedWSGIServer(config.HOSTNAME, config.PORT, app, handler=None, passthrough_errors=False) server_up.set() server.serve_forever() if options.verbose: print "Terminado, saliendo." cd_wd_timer.cancel() else: app = create_app(watchdog=None, verbose=options.verbose) server = ThreadedWSGIServer(config.HOSTNAME, port, app, handler=None, passthrough_errors=False) server.serve_forever()
def run_webserver(self): try: host = self.config['HOST'] port = self.config['PORT'] logging.info('Starting the webserver on %s:%i' % (host, port)) if self.webchat_mode: # EVERYTHING NEEDS TO BE IN THE SAME THREAD OTHERWISE Socket.IO barfs try: from socketio import socketio_manage from socketio.namespace import BaseNamespace from socketio.mixins import RoomsMixin, BroadcastMixin except ImportError: logging.exception("Could not start the webchat view") logging.error(""" If you intend to use the webchat view please install gevent-socketio: pip install gevent-socketio """) class ChatNamespace(BaseNamespace, RoomsMixin, BroadcastMixin): def on_nickname(self, nickname): self.environ.setdefault('nicknames', []).append(nickname) self.socket.session['nickname'] = nickname self.broadcast_event('announcement', '%s has connected' % nickname) self.broadcast_event('nicknames', self.environ['nicknames']) # Just have them join a default-named room self.join('main_room') def on_user_message(self, msg): self.emit_to_room('main_room', 'msg_to_room', self.socket.session['nickname'], msg) message = holder.bot.build_message(msg) message.setType( 'groupchat' ) # really important for security reasons message.setFrom(self.socket.session['nickname'] + '@' + host) message.setTo(holder.bot.jid) holder.bot.callback_message(holder.bot.conn, message) def recv_message(self, message): print "PING!!!", message @holder.flask_app.route('/') def index(): return redirect('/chat.html') @holder.flask_app.route("/socket.io/<path:path>") def run_socketio(path): socketio_manage(request.environ, {'': ChatNamespace}) encapsulating_middleware = SharedDataMiddleware( holder.flask_app, { '/': os.path.join(os.path.dirname(__file__), 'web-static') }) from socketio.server import SocketIOServer self.server = SocketIOServer((host, port), encapsulating_middleware, namespace="socket.io", policy_server=False) else: self.server = ThreadedWSGIServer(host, port, holder.flask_app) self.server.serve_forever() logging.debug('Webserver stopped') except KeyboardInterrupt as ki: logging.exception('Keyboard interrupt, request a global shutdown.') if isinstance(self.server, ThreadedWSGIServer): logging.info('webserver is ThreadedWSGIServer') self.server.shutdown() else: logging.info('webserver is SocketIOServer') self.server.kill() self.server = None holder.bot.shutdown() except Exception as e: logging.exception('The webserver exploded.')
def __init__( self, running_args: argparse.Namespace, immutable_args: Iterable[str], dashboard_host: str, dashboard_port: int, **kwargs, ): threading.Thread.__init__(self) self.app = dash.Dash(__name__, url_base_pathname='/radiotracking-config/', meta_tags=[{ "name": "viewport", "content": "width=device-width, initial-scale=1" }]) config_columns = html.Div(children=[], style={ "columns": "2 359px", "padding": "20pt" }) config_tab = dcc.Tab(label="tRackIT Configuration", children=[config_columns]) config_columns.children.append( html.Div( "Reconfiguration requires restarting of pyradiotracking. Please keep in mind, that a broken configuration might lead to failing starts." )) self.running_args = running_args self.immutable_args = immutable_args self.config_states: List[State] = [] for group in Runner.parser._action_groups: # skip untitled groups if not isinstance(group.title, str): continue # skip groups not used in the config file if len(group._group_actions) == 0: continue group_div = html.Div(children=[], style={"break-inside": "avoid-column"}) config_columns.children.append(group_div) group_div.children.append(html.H3(f"[{group.title}]")) # iterate actions and extract values for action in group._group_actions: if action.dest not in vars(running_args): continue value = vars(running_args)[action.dest] group_div.children.append( html.P(children=[ html.B(action.dest), f" - {action.help}", html.Br(), dcc.Input(id=action.dest, value=repr(value)), ])) if action.type == int or isinstance(action, argparse._CountAction): if not isinstance(value, list): group_div.children[-1].children[-1].type = "number" group_div.children[-1].children[-1].step = 1 elif action.type == float: if not isinstance(value, list): group_div.children[-1].children[-1].type = "number" elif action.type == str: group_div.children[-1].children[-1].type = "text" if isinstance(value, list): group_div.children[-1].children[-1].value = repr(value) else: group_div.children[-1].children[-1].value = value elif isinstance(action, argparse._StoreTrueAction): group_div.children[-1].children[-1] = dcc.Checklist( id=action.dest, options=[ { "value": action.dest, "disabled": action.dest in self.immutable_args }, ], value=[action.dest] if value else [], ) if action.dest in self.immutable_args: group_div.children[-1].children[-1].disabled = True self.config_states.append(State(action.dest, "value")) config_columns.children.append(html.Button('Save', id="submit-config")) self.app.callback(Output('config-msg', 'children'), [ Input("submit-config", "n_clicks"), ], self.config_states)(self.submit_config) config_columns.children.append( html.Button('Restart', id="submit-restart")) self.app.callback(Output('submit-restart', 'children'), [ Input("submit-restart", "n_clicks"), ])(self.submit_restart) config_columns.children.append( html.H4("", id="config-msg", style={ "text-align": "center", "padding": "10px" })) tabs = dcc.Tabs(children=[]) tabs.children.append(config_tab) self.app.layout = html.Div([tabs]) self.app.layout.style = {"font-family": "sans-serif"} self.server = ThreadedWSGIServer(dashboard_host, dashboard_port + 1, self.app.server) self.calibrations: Dict[float, Dict[str, float]] = {}
def __init__( self, device: List[str], calibrate: bool, calibration: List[float], dashboard_host: str, dashboard_port: int, dashboard_signals: int, signal_min_duration_ms: int, signal_max_duration_ms: int, signal_threshold_dbw: float, snr_threshold_db: float, sample_rate: int, center_freq: int, signal_threshold_dbw_max: float = -20, snr_threshold_db_max: float = 50, **kwargs, ): threading.Thread.__init__(self) self.device = device self.calibrate = calibrate self.calibration = calibration self.signal_queue: Deque[Signal] = collections.deque( maxlen=dashboard_signals) self.matched_queue: Deque[MatchingSignal] = collections.deque( maxlen=dashboard_signals) # compute boundaries for sliders and initialize filters frequency_min = center_freq - sample_rate / 2 frequency_max = center_freq + sample_rate / 2 self.app = dash.Dash(__name__, url_base_pathname='/radiotracking/', meta_tags=[{ "name": "viewport", "content": "width=device-width, initial-scale=1" }]) graph_columns = html.Div(children=[], style={"columns": "2 359px"}) graph_columns.children.append( dcc.Graph(id="signal-noise", style={"break-inside": "avoid-column"})) self.app.callback(Output("signal-noise", "figure"), [ Input("update", "n_intervals"), Input("power-slider", "value"), Input("snr-slider", "value"), Input("frequency-slider", "value"), Input("duration-slider", "value"), ])(self.update_signal_noise) graph_columns.children.append( dcc.Graph(id="frequency-histogram", style={"break-inside": "avoid-column"})) self.app.callback(Output("frequency-histogram", "figure"), [ Input("update", "n_intervals"), Input("power-slider", "value"), Input("snr-slider", "value"), Input("frequency-slider", "value"), Input("duration-slider", "value"), ])(self.update_frequency_histogram) graph_columns.children.append( dcc.Graph(id="signal-match", style={"break-inside": "avoid-column"})) self.app.callback(Output("signal-match", "figure"), [ Input("update", "n_intervals"), ])(self.update_signal_match) graph_columns.children.append( dcc.Graph(id="signal-variance", style={"break-inside": "avoid-column"})) self.app.callback(Output("signal-variance", "figure"), [ Input("update", "n_intervals"), Input("power-slider", "value"), Input("snr-slider", "value"), Input("frequency-slider", "value"), Input("duration-slider", "value"), ])(self.update_signal_variance) graph_tab = dcc.Tab(label="tRackIT Signals", children=[]) graph_tab.children.append( html.H4("Running in calibration mode.", hidden=not calibrate, id="calibration-banner", style={ "text-align": "center", "width": "100%", "background-color": "#ffcccb", "padding": "20px", })) self.app.callback(Output("calibration-banner", "hidden"), [ Input("update", "n_intervals"), ])(self.update_calibration_banner) graph_tab.children.append(dcc.Interval(id="update", interval=1000)) self.app.callback(Output("update", "interval"), [Input("interval-slider", "value")])( self.update_interval) graph_tab.children.append(html.Div([ dcc.Graph(id="signal-time"), ])) self.app.callback(Output("signal-time", "figure"), [ Input("update", "n_intervals"), Input("power-slider", "value"), Input("snr-slider", "value"), Input("frequency-slider", "value"), Input("duration-slider", "value"), ])(self.update_signal_time) graph_columns.children.append( html.Div(children=[], id="calibration_output")) self.app.callback(Output("calibration_output", "children"), [ Input("update", "n_intervals"), ])(self.update_calibration) graph_columns.children.append( html.Div( id="settings", style={"break-inside": "avoid-column"}, children=[ html.H2("Vizualization Filters"), html.H3("Signal Power"), dcc.RangeSlider( id="power-slider", min=signal_threshold_dbw, max=signal_threshold_dbw_max, step=0.1, value=[signal_threshold_dbw, signal_threshold_dbw_max], marks={ int(signal_threshold_dbw): f"{signal_threshold_dbw} dBW", int(signal_threshold_dbw_max): f"{signal_threshold_dbw_max} dBW", }, ), html.H3("SNR"), dcc.RangeSlider( id="snr-slider", min=snr_threshold_db, max=snr_threshold_db_max, step=0.1, value=[snr_threshold_db, snr_threshold_db_max], marks={ int(snr_threshold_db): f"{snr_threshold_db} dBW", int(snr_threshold_db_max): f"{snr_threshold_db_max} dBW", }, ), html.H3("Frequency Range"), dcc.RangeSlider( id="frequency-slider", min=frequency_min, max=frequency_max, step=1, marks={ int(frequency_min): f"{frequency_min/1000/1000:.2f} MHz", int(center_freq): f"{center_freq/1000/1000:.2f} MHz", int(frequency_max): f"{frequency_max/1000/1000:.2f} MHz", }, value=[frequency_min, frequency_max], allowCross=False, ), html.H3("Signal Duration"), dcc.RangeSlider( id="duration-slider", min=signal_min_duration_ms, max=signal_max_duration_ms, step=0.1, marks={ int(signal_min_duration_ms): f"{signal_min_duration_ms} ms", int(signal_max_duration_ms): f"{signal_max_duration_ms} ms", }, value=[signal_min_duration_ms, signal_max_duration_ms], allowCross=False, ), html.H2("Dashboard Update Interval"), dcc.Slider( id="interval-slider", min=0.1, max=10, step=0.1, value=1.0, marks={ 0.1: "0.1 s", 1: "1 s", 5: "5 s", 10: "10 s", }, ), ])) graph_tab.children.append(graph_columns) tabs = dcc.Tabs(children=[]) tabs.children.append(graph_tab) self.app.layout = html.Div([tabs]) self.app.layout.style = {"font-family": "sans-serif"} self.server = ThreadedWSGIServer(dashboard_host, dashboard_port, self.app.server) self.calibrations: Dict[float, Dict[str, float]] = {}