Пример #1
0
    def start(self):
        import strut
        from channels.routing import get_default_application
        from daphne.access import AccessLogGenerator
        from daphne.server import Server

        strut.setup()

        application = get_default_application()

        endpoint = build_endpoint_description_string(self.bind)

        print(f"> listening on {endpoint}...")
        Server(
            application=application,
            signal_handlers=True,
            endpoints=[endpoint],
            action_logger=AccessLogGenerator(sys.stdout),
            ping_interval=20,
            ping_timeout=30,
            websocket_timeout=7200,
            websocket_handshake_timeout=5,
            verbosity=1,
            proxy_forwarded_address_header="X-Forwarded-For",
            proxy_forwarded_port_header="X-Forwarded-Port",
            proxy_forwarded_proto_header="X-Forwarded-Proto",
        ).run()
Пример #2
0
    def inner_run(self, *args, **options):
        # Maybe they want the wsgi one?
        if not options.get(
                "use_asgi",
                True) or DEFAULT_CHANNEL_LAYER not in channel_layers:
            return RunserverCommand.inner_run(self, *args, **options)
        # Check a handler is registered for http reqs; if not, add default one
        self.channel_layer = channel_layers[DEFAULT_CHANNEL_LAYER]
        self.channel_layer.router.check_default(
            http_consumer=self.get_consumer(*args, **options), )
        # Run checks
        self.stdout.write("Performing system checks...\n\n")
        self.check(display_num_errors=True)
        self.check_migrations()
        # Print helpful text
        quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C'
        now = datetime.datetime.now().strftime('%B %d, %Y - %X')
        if six.PY2:
            now = now.decode(get_system_encoding())
        self.stdout.write(now)
        self.stdout.write(
            ("Django version %(version)s, using settings %(settings)r\n"
             "Starting Channels development server at http://%(addr)s:%(port)s/\n"
             "Channel layer %(layer)s\n"
             "Quit the server with %(quit_command)s.\n") % {
                 "version": self.get_version(),
                 "settings": settings.SETTINGS_MODULE,
                 "addr": '[%s]' % self.addr if self._raw_ipv6 else self.addr,
                 "port": self.port,
                 "quit_command": quit_command,
                 "layer": self.channel_layer,
             })

        # Launch workers as subthreads
        if options.get("run_worker", True):
            worker_count = 4 if options.get("use_threading", True) else 1
            for _ in range(worker_count):
                worker = WorkerThread(self.channel_layer, self.logger)
                worker.daemon = True
                worker.start()
        # Launch server in 'main' thread. Signals are disabled as it's still
        # actually a subthread under the autoreloader.
        self.logger.debug("Daphne running, listening on %s:%s", self.addr,
                          self.port)
        try:
            Server(
                channel_layer=self.channel_layer,
                host=self.addr,
                port=int(self.port),
                signal_handlers=not options['use_reloader'],
                action_logger=self.log_action,
                http_timeout=self.http_timeout,
                ws_protocols=getattr(settings, 'CHANNELS_WS_PROTOCOLS', None),
            ).run()
            self.logger.debug("Daphne exited")
        except KeyboardInterrupt:
            shutdown_message = options.get('shutdown_message', '')
            if shutdown_message:
                self.stdout.write(shutdown_message)
            return
Пример #3
0
    def run(self):

        try:
            self.common_setup()
            channel_layers = ChannelLayerManager()
            channel_layer = channel_layers.make_test_backend(
                DEFAULT_CHANNEL_LAYER)
            self.server = Server(
                channel_layer=channel_layer,
                endpoints=['tcp:interface=%s:port=0' % (self.host)],
                signal_handlers=False,
            )
            reactor.callLater(0.5, self.resolve_port)
            self.server.run()
        except Exception:
            self.is_ready.set()
            raise
Пример #4
0
class CodalabDaphneProcess(DaphneProcess):

    # have to set port in this hidden way so we can override it later (Daphne uses
    # fancy multiprocessing shared memory vars we have to work around
    _port = 36475

    def __init__(self,
                 host,
                 application,
                 kwargs=None,
                 setup=None,
                 teardown=None):
        super().__init__(host,
                         application,
                         kwargs=None,
                         setup=None,
                         teardown=None)

        # Move our port into shared memory
        self.port.value = self._port

    def run(self):
        """Overriding this _just_ for the port bit...!"""
        try:
            # Create the server class -- with our fancy multiprocessing variable (note
            # `self.port.value`)
            endpoints = build_endpoint_description_strings(
                host=self.host, port=self.port.value)
            self.server = Server(application=self.application,
                                 endpoints=endpoints,
                                 signal_handlers=False,
                                 **self.kwargs)
            # Set up a poller to look for the port
            reactor.callLater(0.1, self.resolve_port)
            # Run with setup/teardown
            self.setup()
            try:
                self.server.run()
            finally:
                self.teardown()
        except Exception as e:
            # Put the error on our queue so the parent gets it
            self.errors.put((e, traceback.format_exc()))
Пример #5
0
 def _create_server(self):
     endpoints = build_endpoint_description_strings(host=self.host,
                                                    port=self._port)
     return Server(
         application=self.application,
         endpoints=endpoints,
         signal_handlers=False,
         ws_protocols=getattr(settings, "CHANNELS_WS_PROTOCOLS", None),
         root_path=getattr(settings, "FORCE_SCRIPT_NAME", "") or "",
         ready_callable=lambda: self.is_ready.set(),
     )
Пример #6
0
 def run(self):
     """Overriding this _just_ for the port bit...!"""
     try:
         # Create the server class -- with our fancy multiprocessing variable (note
         # `self.port.value`)
         endpoints = build_endpoint_description_strings(
             host=self.host, port=self.port.value)
         self.server = Server(application=self.application,
                              endpoints=endpoints,
                              signal_handlers=False,
                              **self.kwargs)
         # Set up a poller to look for the port
         reactor.callLater(0.1, self.resolve_port)
         # Run with setup/teardown
         self.setup()
         try:
             self.server.run()
         finally:
             self.teardown()
     except Exception as e:
         # Put the error on our queue so the parent gets it
         self.errors.put((e, traceback.format_exc()))
Пример #7
0
def _run(addr, port, prod):
    # if True or prod:
    #    channel_layer = get_channel_layer()
    # else:
    #    channel_layer = channel_layers[DEFAULT_CHANNEL_LAYER]
    #    channel_layer.router.check_default(
    #        http_consumer=ViewConsumer(),
    #    )
    #    for _ in range(4):
    #        worker = WorkerThread(channel_layer)
    #        worker.daemon = True
    #        worker.start()
    try:
        from daphne.server import Server
        from daphne.endpoints import build_endpoint_description_strings
        from channels.routing import get_default_application

        django.setup()

        # application = django.core.handlers.wsgi.WSGIHandler()

        print(addr, port)
        endpoints = build_endpoint_description_strings(host=addr,
                                                       port=int(port))

        server = Server(
            # channel_layer=channel_layer,
            get_default_application(),
            endpoints=endpoints,
            # host=addr,
            # port=int(port),
            signal_handlers=False,
            action_logger=log_action,
            http_timeout=60,
        )
        server.run()
    except KeyboardInterrupt:
        return
Пример #8
0
class DaphneProcess(ProcessSetup):
    def __init__(self, host, port_storage, is_ready, overridden_settings,
                 modified_settings, databases):

        self.host = host
        self.port_storage = port_storage
        self.is_ready = is_ready
        self.overridden_settings = overridden_settings
        self.modified_settings = modified_settings
        self.databases = databases
        super(DaphneProcess, self).__init__()
        self.daemon = True

    def run(self):

        try:
            self.common_setup()
            channel_layers = ChannelLayerManager()
            channel_layer = channel_layers.make_test_backend(
                DEFAULT_CHANNEL_LAYER)
            self.server = Server(
                channel_layer=channel_layer,
                endpoints=['tcp:interface=%s:port=0' % (self.host)],
                signal_handlers=False,
            )
            reactor.callLater(0.5, self.resolve_port)
            self.server.run()
        except Exception:
            self.is_ready.set()
            raise

    def resolve_port(self):

        port = self.server.listeners[0].result.getHost().port
        self.port_storage.value = port
        self.is_ready.set()
Пример #9
0
class DaphneProcess(ProcessSetup):

    def __init__(self, host, port_storage, is_ready, overridden_settings,
                 modified_settings, databases):

        self.host = host
        self.port_storage = port_storage
        self.is_ready = is_ready
        self.overridden_settings = overridden_settings
        self.modified_settings = modified_settings
        self.databases = databases
        super(DaphneProcess, self).__init__()
        self.daemon = True

    def run(self):

        try:
            self.common_setup()
            channel_layers = ChannelLayerManager()
            channel_layer = channel_layers.make_test_backend(DEFAULT_CHANNEL_LAYER)
            self.server = Server(
                channel_layer=channel_layer,
                endpoints=['tcp:interface=%s:port=0' % (self.host)],
                signal_handlers=False,
            )
            reactor.callLater(0.5, self.resolve_port)
            self.server.run()
        except Exception:
            self.is_ready.set()
            raise

    def resolve_port(self):

        port = self.server.listeners[0].result.getHost().port
        self.port_storage.value = port
        self.is_ready.set()
Пример #10
0
def main():
    os.environ.setdefault("DJANGO_SETTINGS_MODULE",
                          "stellaru.settings_release")
    django.setup()
    django.core.management.call_command("makemigrations")
    django.core.management.call_command("migrate")

    port = find_port()
    from stellaru import routing as stellaru_app
    application = StaticFilesWrapper(stellaru_app.application)
    endpoints = build_endpoint_description_strings(
        host=DEFAULT_HOST,
        port=port,
        unix_socket=None,
        file_descriptor=None,
    )
    server = Server(application=application,
                    endpoints=endpoints,
                    server_name='Stellaru')

    print('Starting Stellaru')
    thread = threading.Thread(target=open_browser, args=(port, ))
    thread.run()
    server.run()
Пример #11
0
    def run(self):

        try:
            self.common_setup()
            channel_layers = ChannelLayerManager()
            channel_layer = channel_layers.make_test_backend(DEFAULT_CHANNEL_LAYER)
            self.server = Server(
                channel_layer=channel_layer,
                endpoints=['tcp:interface=%s:port=0' % (self.host)],
                signal_handlers=False,
            )
            reactor.callLater(0.5, self.resolve_port)
            self.server.run()
        except Exception:
            self.is_ready.set()
            raise
Пример #12
0
    def run_asgi(self, *args, **options):
        # Launch server in 'main' thread. Signals are disabled as it's still
        # actually a subthread under the autoreloader.
        logger.debug("Daphne running, listening on %s:%s", self.addr,
                     self.port)

        # build the endpoint description string from host/port options
        endpoints = build_endpoint_description_strings(host=self.addr,
                                                       port=self.port)
        Server(
            application=self.get_handler(**options),
            endpoints=endpoints,
            signal_handlers=not options["use_reloader"],
            action_logger=self.log_action,
            http_timeout=self.http_timeout,
            root_path=getattr(settings, "FORCE_SCRIPT_NAME", "") or "",
        ).run()
        logger.debug("Daphne exited")
Пример #13
0
 def inner_run(self, *args, **options):
     # Check a handler is registered for http reqs; if not, add default one
     self.channel_layer = channel_layers[DEFAULT_CHANNEL_LAYER]
     if not self.channel_layer.registry.consumer_for_channel(
             "http.request"):
         self.channel_layer.registry.add_consumer(ViewConsumer(),
                                                  ["http.request"])
     # Note that this is the channel-enabled one on the console
     self.logger.info("Worker thread running, channels enabled")
     # Launch a worker thread
     worker = WorkerThread(self.channel_layer)
     worker.daemon = True
     worker.start()
     # Launch server in main thread
     from daphne.server import Server
     Server(
         channel_layer=self.channel_layer,
         host=self.addr,
         port=int(self.port),
     ).run()
Пример #14
0
    def _create_server(self):
        """
        Create a daphne server with local thread asyncio event loop and twisted reactor.
        """
        # Reset reactor to use local thread's event loop
        from twisted.internet import asyncioreactor
        del sys.modules["twisted.internet.reactor"]

        try:
            event_loop = asyncio.get_event_loop()
        except RuntimeError:
            event_loop = asyncio.new_event_loop()

        asyncioreactor.install(event_loop)
        from twisted.internet import reactor

        # Create hook to check if main thread communicated with us
        reactor.callLater(1, self._on_reactor_hook, reactor)

        application = self.application
        if self.static_handler:
            application = self.static_handler(application)

        endpoints = build_endpoint_description_strings(host=self.host, port=self.port)

        def ready():
            if self.port == 0:
                self.port = self.daphne.listening_addresses[0][1]
            self.is_ready.set()

        return Server(
            application=application,
            endpoints=endpoints,
            signal_handlers=False,
            root_path=getattr(settings, "FORCE_SCRIPT_NAME", "") or "",
            ready_callable=ready,
            reactor=reactor,
        )
Пример #15
0
root.info('TC_DEPLOY: Initialising daphne')

# Same Command
# daphne asgi:application --unix-socket "/tmp/asgi.socket" --http-timeout 29 --proxy-headers --ping-interval 15

# Start Daphne
Server(
    application=asgi.application,
    endpoints=build_endpoint_description_strings(
        unix_socket="/tmp/asgi.socket",
    ),
    http_timeout=29,
    ping_interval=15,
    ping_timeout=30,
    websocket_timeout=10800, # 3 hours maximum length
    websocket_connect_timeout=5,
    application_close_timeout=10,
    action_logger=None,
    ws_protocols=None,
    root_path="",
    verbosity=2,
    proxy_forwarded_address_header="X-Forwarded-For",
    proxy_forwarded_port_header="X-Forwarded-Port",
    # proxy_forwarded_proto_header="X-Forwarded-Proto", # Not enabled on currently released daphne
).run()


# Can re-enable if Uvicorn ever adds keep-alive suport:

# import uvicorn