Exemplo n.º 1
0
 def __init__(self,
              application,
              map=None,
              _start=True,      # test shim
              _sock=None,       # test shim
              _dispatcher=None, # test shim
              adj=None,         # adjustments
              **kw
              ):
     if adj is None:
         adj = Adjustments(**kw)
     self.application = application
     self.adj = adj
     self.trigger = trigger.trigger(map)
     if _dispatcher is None:
         _dispatcher = ThreadedTaskDispatcher()
         _dispatcher.set_thread_count(self.adj.threads)
     self.task_dispatcher = _dispatcher
     self.asyncore.dispatcher.__init__(self, _sock, map=map)
     if _sock is None:
         self.create_socket(self.family, socket.SOCK_STREAM)
     self.set_reuse_addr()
     self.bind_server_socket()
     self.effective_host, self.effective_port = self.getsockname()
     self.server_name = self.get_server_name(self.adj.host)
     self.active_channels = {}
     if _start:
         self.accept_connections()
Exemplo n.º 2
0
def run(argv=sys.argv, _serve=serve):
    """Command line runner."""
    name = os.path.basename(argv[0])

    try:
        kw, args = Adjustments.parse_args(argv[1:])
    except getopt.GetoptError as exc:
        show_help(sys.stderr, name, str(exc))
        return 1

    if kw["help"]:
        show_help(sys.stdout, name)
        return 0

    if len(args) != 1:
        show_help(sys.stderr, name, "Specify one application only")
        return 1

    # set a default level for the logger only if it hasn't been set explicitly
    # note that this level does not override any parent logger levels,
    # handlers, etc but without it no log messages are emitted by default
    if logger.level == logging.NOTSET:
        logger.setLevel(logging.INFO)

    try:
        module, obj_name = match(args[0])
    except ValueError as exc:
        show_help(sys.stderr, name, str(exc))
        show_exception(sys.stderr)
        return 1

    # Add the current directory onto sys.path
    sys.path.append(os.getcwd())

    # Get the WSGI function.
    try:
        app = resolve(module, obj_name)
    except ImportError:
        show_help(sys.stderr, name, f"Bad module '{module}'")
        show_exception(sys.stderr)
        return 1
    except AttributeError:
        show_help(sys.stderr, name, f"Bad object name '{obj_name}'")
        show_exception(sys.stderr)
        return 1
    if kw["call"]:
        app = app()

    # These arguments are specific to the runner, not waitress itself.
    del kw["call"], kw["help"]

    _serve(app, **kw)
    return 0
Exemplo n.º 3
0
    def __init__(self,
                 application,
                 map=None,
                 _start=True,      # test shim
                 _sock=None,       # test shim
                 dispatcher=None,  # dispatcher
                 adj=None,         # adjustments
                 sockinfo=None,    # opaque object
                 bind_socket=True,
                 **kw
                 ):
        if adj is None:
            adj = Adjustments(**kw)
        if map is None:
            # use a nonglobal socket map by default to hopefully prevent
            # conflicts with apps and libs that use the wasyncore global socket
            # map ala https://github.com/Pylons/waitress/issues/63
            map = {}
        if sockinfo is None:
            sockinfo = adj.listen[0]

        self.sockinfo = sockinfo
        self.family = sockinfo[0]
        self.socktype = sockinfo[1]
        self.application = application
        self.adj = adj
        self.trigger = trigger.trigger(map)
        if dispatcher is None:
            dispatcher = ThreadedTaskDispatcher()
            dispatcher.set_thread_count(self.adj.threads)

        self.task_dispatcher = dispatcher
        self.asyncore.dispatcher.__init__(self, _sock, map=map)
        if _sock is None:
            self.create_socket(self.family, self.socktype)
            if self.family == socket.AF_INET6: # pragma: nocover
                self.socket.setsockopt(IPPROTO_IPV6, IPV6_V6ONLY, 1)

        self.set_reuse_addr()

        if bind_socket:
            self.bind_server_socket()

        self.effective_host, self.effective_port = self.getsockname()
        self.server_name = self.get_server_name(self.effective_host)
        self.active_channels = {}
        if _start:
            self.accept_connections()
Exemplo n.º 4
0
def run(argv=sys.argv, _serve=serve):
    """Command line runner."""
    name = os.path.basename(argv[0])

    try:
        kw, args = Adjustments.parse_args(argv[1:])
    except getopt.GetoptError as exc:
        show_help(sys.stderr, name, str(exc))
        return 1

    if kw["help"]:
        show_help(sys.stdout, name)
        return 0

    if len(args) != 1:
        show_help(sys.stderr, name, "Specify one application only")
        return 1

    try:
        module, obj_name = match(args[0])
    except ValueError as exc:
        show_help(sys.stderr, name, str(exc))
        show_exception(sys.stderr)
        return 1

    # Add the current directory onto sys.path
    sys.path.append(os.getcwd())

    # Get the WSGI function.
    try:
        app = resolve(module, obj_name)
    except ImportError:
        show_help(sys.stderr, name, "Bad module '{}'".format(module))
        show_exception(sys.stderr)
        return 1
    except AttributeError:
        show_help(sys.stderr, name, "Bad object name '{}'".format(obj_name))
        show_exception(sys.stderr)
        return 1
    if kw["call"]:
        app = app()

    # These arguments are specific to the runner, not waitress itself.
    del kw["call"], kw["help"]

    _serve(app, **kw)
    return 0
Exemplo n.º 5
0
def run(argv=sys.argv, _serve=serve):
    """Command line runner."""
    name = os.path.basename(argv[0])

    try:
        kw, args = Adjustments.parse_args(argv[1:])
    except getopt.GetoptError as exc:
        show_help(sys.stderr, name, str(exc))
        return 1

    if kw['help']:
        show_help(sys.stdout, name)
        return 0

    if len(args) != 1:
        show_help(sys.stderr, name, 'Specify one application only')
        return 1

    try:
        module, obj_name = match(args[0])
    except ValueError as exc:
        show_help(sys.stderr, name, str(exc))
        show_exception(sys.stderr)
        return 1

    # Add the current directory onto sys.path
    sys.path.append(os.getcwd())

    # Get the WSGI function.
    try:
        app = resolve(module, obj_name)
    except ImportError:
        show_help(sys.stderr, name, "Bad module '{0}'".format(module))
        show_exception(sys.stderr)
        return 1
    except AttributeError:
        show_help(sys.stderr, name, "Bad object name '{0}'".format(obj_name))
        show_exception(sys.stderr)
        return 1
    if kw['call']:
        app = app()

    # These arguments are specific to the runner, not waitress itself.
    del kw['call'], kw['help']

    _serve(app, **kw)
    return 0
Exemplo n.º 6
0
def create_server(application,
                  map=None,
                  _start=True,      # test shim
                  _sock=None,       # test shim
                  _dispatcher=None, # test shim
                  **kw              # adjustments
                  ):
    """
    if __name__ == '__main__':
        server = create_server(app)
        server.run()
    """
    adj = Adjustments(**kw)
    if adj.unix_socket:
        cls = UnixWSGIServer
    else:
        cls = TcpWSGIServer
    return cls(application, map, _start, _sock, _dispatcher, adj)
Exemplo n.º 7
0
def create_server(
        application,
        map=None,
        _start=True,  # test shim
        _sock=None,  # test shim
        _dispatcher=None,  # test shim
        **kw  # adjustments
):
    """
    if __name__ == '__main__':
        server = create_server(app)
        server.run()
    """
    if application is None:
        raise ValueError(
            'The "app" passed to ``create_server`` was ``None``.  You forgot '
            'to return a WSGI app within your application.')
    adj = Adjustments(**kw)
    if adj.unix_socket and hasattr(socket, 'AF_UNIX'):
        cls = UnixWSGIServer
    else:
        cls = TcpWSGIServer
    return cls(application, map, _start, _sock, _dispatcher, adj)
Exemplo n.º 8
0
    def __init__(
            self,
            application,
            map=None,
            _start=True,  # test shim
            _sock=None,  # test shim
            _dispatcher=None,  # test shim
            **kw  # adjustments
    ):

        self.application = application
        self.adj = Adjustments(**kw)
        self.trigger = trigger.trigger(map)
        if _dispatcher is None:
            _dispatcher = ThreadedTaskDispatcher()
            _dispatcher.set_thread_count(self.adj.threads)
        self.task_dispatcher = _dispatcher
        self.asyncore.dispatcher.__init__(self, _sock, map=map)
        if _sock is None:
            try:
                info = socket.getaddrinfo(self.adj.host, self.adj.port,
                                          socket.AF_UNSPEC, socket.SOCK_STREAM,
                                          0, socket.AI_PASSIVE)
                if info:
                    self.create_socket(info[0][0], socket.SOCK_STREAM)
            except socket.gaierror:
                self.create_socket(socket.AF_INET, socket.SOCK_STREAM)

        self.set_reuse_addr()
        self.bind((self.adj.host, self.adj.port))
        # Ignore scope & flow ID if returned for IPv6 sockets
        self.effective_host, self.effective_port = self.getsockname()[:2]
        self.server_name = self.get_server_name(self.adj.host)
        self.active_channels = {}
        if _start:
            self.accept_connections()
Exemplo n.º 9
0
 def setUp(self):
     from waitress.parser import HTTPRequestParser
     from waitress.adjustments import Adjustments
     my_adj = Adjustments()
     self.parser = HTTPRequestParser(my_adj)
Exemplo n.º 10
0
def create_server(
    application,
    map=None,
    _start=True,  # test shim
    _sock=None,  # test shim
    _dispatcher=None,  # test shim
    **kw  # adjustments
):
    """
    if __name__ == '__main__':
        server = create_server(app)
        server.run()
    """
    if application is None:
        raise ValueError(
            'The "app" passed to ``create_server`` was ``None``.  You forgot '
            "to return a WSGI app within your application."
        )
    adj = Adjustments(**kw)

    if map is None:  # pragma: nocover
        map = {}

    dispatcher = _dispatcher
    if dispatcher is None:
        dispatcher = ThreadedTaskDispatcher()
        dispatcher.set_thread_count(adj.threads)

    if adj.unix_socket and hasattr(socket, "AF_UNIX"):
        sockinfo = (socket.AF_UNIX, socket.SOCK_STREAM, None, None)
        return UnixWSGIServer(
            application,
            map,
            _start,
            _sock,
            dispatcher=dispatcher,
            adj=adj,
            sockinfo=sockinfo,
        )

    effective_listen = []
    last_serv = None
    if not adj.sockets:
        for sockinfo in adj.listen:
            # When TcpWSGIServer is called, it registers itself in the map. This
            # side-effect is all we need it for, so we don't store a reference to
            # or return it to the user.
            last_serv = TcpWSGIServer(
                application,
                map,
                _start,
                _sock,
                dispatcher=dispatcher,
                adj=adj,
                sockinfo=sockinfo,
            )
            effective_listen.append(
                (last_serv.effective_host, last_serv.effective_port)
            )

    for sock in adj.sockets:
        sockinfo = (sock.family, sock.type, sock.proto, sock.getsockname())
        if sock.family == socket.AF_INET or sock.family == socket.AF_INET6:
            last_serv = TcpWSGIServer(
                application,
                map,
                _start,
                sock,
                dispatcher=dispatcher,
                adj=adj,
                bind_socket=False,
                sockinfo=sockinfo,
            )
            effective_listen.append(
                (last_serv.effective_host, last_serv.effective_port)
            )
        elif hasattr(socket, "AF_UNIX") and sock.family == socket.AF_UNIX:
            last_serv = UnixWSGIServer(
                application,
                map,
                _start,
                sock,
                dispatcher=dispatcher,
                adj=adj,
                bind_socket=False,
                sockinfo=sockinfo,
            )
            effective_listen.append(
                (last_serv.effective_host, last_serv.effective_port)
            )

    # We are running a single server, so we can just return the last server,
    # saves us from having to create one more object
    if len(effective_listen) == 1:
        # In this case we have no need to use a MultiSocketServer
        return last_serv

    # Return a class that has a utility function to print out the sockets it's
    # listening on, and has a .run() function. All of the TcpWSGIServers
    # registered themselves in the map above.
    return MultiSocketServer(map, adj, effective_listen, dispatcher)
Exemplo n.º 11
0
    def __init__(
        self,
        application,
        map=None,
        _start=True,  # test shim
        _sock=None,  # test shim
        dispatcher=None,  # dispatcher
        adj=None,  # adjustments
        sockinfo=None,  # opaque object
        bind_socket=True,
        **kw
    ):
        if adj is None:
            adj = Adjustments(**kw)

        if adj.trusted_proxy or adj.clear_untrusted_proxy_headers:
            # wrap the application to deal with proxy headers
            # we wrap it here because webtest subclasses the TcpWSGIServer
            # directly and thus doesn't run any code that's in create_server
            application = proxy_headers_middleware(
                application,
                trusted_proxy=adj.trusted_proxy,
                trusted_proxy_count=adj.trusted_proxy_count,
                trusted_proxy_headers=adj.trusted_proxy_headers,
                clear_untrusted=adj.clear_untrusted_proxy_headers,
                log_untrusted=adj.log_untrusted_proxy_headers,
                logger=self.logger,
            )

        if map is None:
            # use a nonglobal socket map by default to hopefully prevent
            # conflicts with apps and libs that use the wasyncore global socket
            # map ala https://github.com/Pylons/waitress/issues/63
            map = {}
        if sockinfo is None:
            sockinfo = adj.listen[0]

        self.sockinfo = sockinfo
        self.family = sockinfo[0]
        self.socktype = sockinfo[1]
        self.application = application
        self.adj = adj
        self.trigger = trigger.trigger(map)
        if dispatcher is None:
            dispatcher = ThreadedTaskDispatcher()
            dispatcher.set_thread_count(self.adj.threads)

        self.task_dispatcher = dispatcher
        self.asyncore.dispatcher.__init__(self, _sock, map=map)
        if _sock is None:
            self.create_socket(self.family, self.socktype)
            if self.family == socket.AF_INET6:  # pragma: nocover
                self.socket.setsockopt(IPPROTO_IPV6, IPV6_V6ONLY, 1)

        self.set_reuse_addr()

        if bind_socket:
            self.bind_server_socket()

        self.effective_host, self.effective_port = self.getsockname()
        self.server_name = self.get_server_name(self.effective_host)
        self.active_channels = {}
        if _start:
            self.accept_connections()
Exemplo n.º 12
0
        def _makeOne(self, **kw):
            from waitress.adjustments import Adjustments

            return Adjustments(**kw)
Exemplo n.º 13
0
    def parse(self, argv):
        from waitress.adjustments import Adjustments

        return Adjustments.parse_args(argv)
Exemplo n.º 14
0
 def setUp(self):
     my_adj = Adjustments()
     self.parser = HTTPRequestParser(my_adj)
Exemplo n.º 15
0
 def parse(self, argv):
     from waitress.adjustments import Adjustments
     return Adjustments.parse_args(argv)