Function called by the WSGI server.
14743
def app(environ, start_response):
    """"""
    r = HttpRequestHandler(environ, start_response, Router).dispatch()
    return r
331395
def RunOnce(self):
    """"""
    # pylint: disable=unused-variable,g-import-not-at-top
    from grr_response_server.gui import gui_plugins
    # pylint: enable=unused-variable,g-import-not-at-top

    if config.CONFIG.Get("AdminUI.django_secret_key", None):
      logging.warning(
          "The AdminUI.django_secret_key option has been deprecated, "
          "please use AdminUI.csrf_secret_key instead.")
403006
def wsgi_app(self, environ, start_response):
        

        path = environ['PATH_INFO']

        if re.match(self.path_pattern, path):
            ws = environ['wsgi.websocket']
            address = (environ.get('REMOTE_ADDR'), environ.get('REMOTE_PORT'))
            self._handle_stream(ws, address)
        else:
            if self.merge_wsgi_app:
                return self.merge_wsgi_app(environ, start_response)
            else:
                start_response("400 Bad Request", [])
                return ['400 Bad Request']
521621
def get_response(wsgi_request):
    '''
        
    '''
    service_start_time = datetime.now()
    # Get the view / handler for this request
    view, args, kwargs = resolve(wsgi_request.path_info)

    kwargs.update({"request": wsgi_request})

    # Let the view do his task.
    try:
        resp = view(*args, **kwargs)
    except Exception as exc:
        resp = HttpResponseServerError(content=exc.message)

    headers = dict(resp._headers.values())
    # Convert HTTP response into simple dict type.
    d_resp = {"status_code": resp.status_code, "reason_phrase": resp.reason_phrase,
              "headers": headers}
    try:
        d_resp.update({"body": resp.content})
    except ContentNotRenderedError:
        resp.render()
        d_resp.update({"body": resp.content})

    # Check if we need to send across the duration header.
    if _settings.ADD_DURATION_HEADER:
        d_resp['headers'].update({_settings.DURATION_HEADER_NAME: (datetime.now() - service_start_time).seconds})

    return d_resp
738320
def handle(self):
        
        self.raw_requestline = self.rfile.readline()
        if not self.parse_request(): # An error code has been sent, just exit
            return

        # next line is where we'd have expect a configuration key somehow
        handler = self.WebSocketWSGIHandler(
            self.rfile, self.wfile, self.get_stderr(), self.get_environ()
        )
        handler.request_handler = self      # backpointer for logging
        handler.run(self.server.get_app())
972570
def serve(self, host='127.0.0.1', port=5000):
        """"""
        from meinheld import server, middleware
        # self.app.run(host=host, port=port)
        server.listen((host, port))
        server.run(middleware.WebSocketMiddleware(self.app))
1235310
def _body(self, full_path, environ, file_like):
        """"""
        way_to_send = environ.get('wsgi.file_wrapper', iter_and_close)
        return way_to_send(file_like, self.block_size)
794864
async def request(self):
        '''
        '''
        request_headers = self.request_headers()
        environ = self.environ
        method = environ['REQUEST_METHOD']
        data = None
        if method in ENCODE_BODY_METHODS:
            data = DataIterator(self)
        http = self.wsgi.http_client
        try:
            await http.request(method,
                               environ['RAW_URI'],
                               data=data,
                               headers=request_headers,
                               version=environ['SERVER_PROTOCOL'],
                               pre_request=self.pre_request)
        except Exception as exc:
            self.error(exc)
1215081
def http_call(self, url=None, **kwargs):
        
        if not url:
            url = self.search_url
        http_func, arg_name = self.get_http_method_arg_name()
        # Build the argument dictionary to pass in the http function
        _kwargs = {
            arg_name: kwargs,
        }
        # The actual HTTP call
        response = http_func(
            url=url.format(**kwargs),
            headers=self.get_http_headers(),
            **_kwargs
        )
        # Error handling
        if response.status_code != 200:
            logger.warning('Invalid Request for `%s`', response.url)
            # Raising a "requests" exception
            response.raise_for_status()
        return response.json()
484815
def _bind(self, _descriptor):
        

        # If the method has a default code, use it
        self._defcode = getattr(_descriptor.method, '_wsgi_code', 200)

        # Set up content type and serializer
        self.content_type, self.serializer = _descriptor.serializer(self.req)
90530
def start():
    '''
    
    '''
    from wsgiref.simple_server import make_server

    # When started outside of salt-api __opts__ will not be injected
    if '__opts__' not in globals():
        globals()['__opts__'] = get_opts()

        if __virtual__() is False:
            raise SystemExit(1)

    mod_opts = __opts__.get(__virtualname__, {})

    # pylint: disable=C0103
    httpd = make_server('localhost', mod_opts['port'], application)

    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        raise SystemExit(0)
693613
def main():
    """"""
    parser = argparse.ArgumentParser(
        description='Start an instance of the Cheroot WSGI/HTTP server.',
    )
    for arg, spec in _arg_spec.items():
        parser.add_argument(arg, **spec)
    raw_args = parser.parse_args()

    # ensure cwd in sys.path
    '' in sys.path or sys.path.insert(0, '')

    # create a server based on the arguments provided
    raw_args._wsgi_app.server(raw_args).safe_start()
468578
def execute(self, request, *args, **path_args):
        # type: (BaseHttpRequest, tuple, Dict[Any]) -> Any
        
        binding = self.binding
        if binding:
            # Provide binding as decorators are executed prior to binding
            return self.callback(binding, request, *args, **path_args)
        else:
            return self.callback(request, *args, **path_args)
772307
def run(self, handler):
        """"""
        import eventlet.patcher
        if not eventlet.patcher.is_monkey_patched(os):
            msg = ("%s requires eventlet.monkey_patch() (before "
                   "import)" % self.__class__.__name__)
            raise RuntimeError(msg)

        # Separate out wsgi.server arguments
        wsgi_args = {}
        for arg in ('log', 'environ', 'max_size', 'max_http_version',
                    'protocol', 'server_event', 'minimum_chunk_size',
                    'log_x_forwarded_for', 'custom_pool', 'keepalive',
                    'log_output', 'log_format', 'url_length_limit', 'debug',
                    'socket_timeout', 'capitalize_response_headers'):
            try:
                wsgi_args[arg] = self.options.pop(arg)
            except KeyError:
                pass
        if 'log_output' not in wsgi_args:
            wsgi_args['log_output'] = not self.quiet

        import eventlet.wsgi
        sock = self.options.pop('shared_socket', None) or self.get_socket()
        eventlet.wsgi.server(sock, handler, **wsgi_args)
555619
def server(name='proxy-server', headers_middleware=None,
           server_software=None, **kwargs):
    ''''''
    if headers_middleware is None:
        headers_middleware = [x_forwarded_for]
    wsgi_proxy = ProxyServerWsgiHandler(headers_middleware)
    kwargs['server_software'] = server_software or SERVER_SOFTWARE
    return wsgi.WSGIServer(wsgi_proxy, name=name, **kwargs)
1037549
def WSGIHandler(self):
    """"""
    sdm = werkzeug_wsgi.SharedDataMiddleware(self, {
        "/": config.CONFIG["AdminUI.document_root"],
    })
    # Use DispatcherMiddleware to make sure that SharedDataMiddleware is not
    # used at all if the URL path doesn't start with "/static". This is a
    # workaround for cases when unicode URLs are used on systems with
    # non-unicode filesystems (as detected by Werkzeug). In this case
    # SharedDataMiddleware may fail early while trying to convert the
    # URL into the file path and not dispatch the call further to our own
    # WSGI handler.
    return werkzeug_wsgi.DispatcherMiddleware(self, {
        "/static": sdm,
    })
747337
def input(self):
        """"""
        if self._input is None:
            input_file = self.environ['wsgi.input']
            content_length = self.content_length or 0
            self._input = WsgiInput(input_file, self.content_length)
        return self._input