Beispiel #1
0
async def discovery_response(
        xds_type: discovery.DiscoveryTypes,
        discovery_request: DiscoveryRequest = Body(None),
        host: str = Header('no_host_provided'),
):
    authenticate(discovery_request)
    response: dict = await discovery.response(discovery_request,
                                              xds_type.value,
                                              host=host)
    extra_headers = {
        'X-Sovereign-Client-Build':
        discovery_request.envoy_version,
        'X-Sovereign-Client-Version':
        discovery_request.version_info,
        'X-Sovereign-Requested-Resources':
        ','.join(discovery_request.resource_names) or 'all',
        'X-Sovereign-Requested-Type':
        xds_type.value,
        'X-Sovereign-Response-Version':
        response['version_info']
    }
    add_log_context(resource_names=discovery_request.resource_names,
                    envoy_ver=discovery_request.envoy_version)
    if response['version_info'] == discovery_request.version_info:
        # Configuration is identical, send a Not Modified response
        return Response(status_code=304, headers=extra_headers)
    elif len(response.get('resources', [])) == 0:
        return json_response_class(content={'detail': 'No resources found'},
                                   status_code=404,
                                   headers=extra_headers)
    elif response['version_info'] != discovery_request.version_info:
        return json_response_class(content=response, headers=extra_headers)
Beispiel #2
0
def generic_error_response(e: Exception) -> JSONResponse:
    """
    Responds with a JSON object containing basic context
    about the exception passed in to this function.

    If the server is in debug mode, it will include a traceback in the response.

    The traceback is **always** emitted in logs.
    """
    tb = [line for line in traceback.format_exc().split("\n")]
    error = {
        "error": e.__class__.__name__,
        "detail": getattr(e, "detail", "-"),
        "request_id": get_request_id(),
    }
    logs.queue_log_fields(
        ERROR=error["error"],
        ERROR_DETAIL=error["detail"],
        TRACEBACK=tb,
    )
    # Don't expose tracebacks in responses, but add it to the logs
    if DEBUG:
        error["traceback"] = tb
    return json_response_class(content=error,
                               status_code=getattr(e, "status_code", 500))
Beispiel #3
0
async def display_config(
        xds_type: DiscoveryTypes = Query(...,
                                         title='xDS type',
                                         description='The type of request',
                                         example='clusters'),
        service_cluster: str = Query(
            '*',
            title='The clients service cluster to emulate in this XDS request'
        ),
        resource_names: str = Query('',
                                    title='Envoy Resource names to request'),
        region: str = Query(
            None, title='The clients region to emulate in this XDS request'),
        version: str = Query(
            '1.11.1',
            title='The clients envoy version to emulate in this XDS request')):
    ret = defaultdict(list)
    mock_request = mock_discovery_request(service_cluster=service_cluster,
                                          resource_names=resource_names,
                                          version=version,
                                          region=region)
    response = await discovery.response(request=mock_request,
                                        xds_type=xds_type.value)
    ret['resources'] += response.get('resources', [])
    safe_response = jsonable_encoder(ret)
    return json_response_class(content=safe_response)
Beispiel #4
0
async def virtual_hosts(
        route_configuration: str = Path(
            ..., title='Name of the route configuration'),
        virtual_host: str = Path(..., title='Name of the resource to view'),
        region: str = Query(
            None, title='The clients region to emulate in this XDS request'),
        service_cluster: str = Cookie(
            '*',
            title='The clients service cluster to emulate in this XDS request'
        ),
        envoy_version: str = Cookie(
            '__any__',
            title='The clients envoy version to emulate in this XDS request')):
    response = await discovery.response(request=mock_discovery_request(
        service_cluster=service_cluster,
        resource_names=[route_configuration],
        version=envoy_version,
        region=region),
                                        xds_type='routes')
    if isinstance(response, dict):
        route_configs = [
            resource_ for resource_ in response.get('resources', [])
            if resource_['name'] == route_configuration
        ]
        for route_config in route_configs:
            for vhost in route_config['virtual_hosts']:
                if vhost['name'] == virtual_host:
                    safe_response = jsonable_encoder(vhost)
                    try:
                        return json_response_class(content=safe_response)
                    except TypeError:
                        return JSONResponse(content=safe_response)
            break
Beispiel #5
0
async def resource(
        xds_type: DiscoveryTypes = Path('clusters',
                                        title='xDS type',
                                        description='The type of request'),
        resource_name: str = Path(..., title='Name of the resource to view'),
        region: str = Query(
            None, title='The clients region to emulate in this XDS request'),
        service_cluster: str = Cookie(
            '*',
            title='The clients service cluster to emulate in this XDS request'
        ),
        envoy_version: str = Cookie(
            '__any__',
            title='The clients envoy version to emulate in this XDS request')):
    response = await discovery.response(request=mock_discovery_request(
        service_cluster=service_cluster,
        resource_names=[resource_name],
        version=envoy_version,
        region=region),
                                        xds_type=xds_type.value)
    safe_response = jsonable_encoder(response)
    try:
        return json_response_class(content=safe_response)
    except TypeError:
        return JSONResponse(content=safe_response)
Beispiel #6
0
def instances(
        service_cluster: str = Query(
            '*',
            title='The clients service cluster to emulate in this XDS request'
        ),
        modified:
    str = Query(
        'yes',
        title=
        'Whether the sources should run Modifiers/Global Modifiers prior to being returned'
    )):
    node = mock_discovery_request(service_cluster=service_cluster).node
    args = {
        'modify': yaml.safe_load(modified),
        'node_value': extract_node_key(node)
    }
    ret = match_node(**args)
    safe_response = jsonable_encoder(ret)
    return json_response_class(content=safe_response)
Beispiel #7
0
async def virtual_hosts(
    route_configuration: str = Path(...,
                                    title="Name of the route configuration"),
    virtual_host: str = Path(..., title="Name of the resource to view"),
    region: str = Query(
        None, title="The clients region to emulate in this XDS request"),
    api_version: str = Query("v2", title="The desired Envoy API version"),
    service_cluster: str = Cookie(
        "*",
        title="The clients service cluster to emulate in this XDS request"),
    envoy_version: str = Cookie(
        "__any__",
        title="The clients envoy version to emulate in this XDS request"),
) -> Response:
    response = await perform_discovery(
        req=mock_discovery_request(
            service_cluster=service_cluster,
            resource_names=[route_configuration],
            version=envoy_version,
            region=region,
        ),
        api_version=api_version,
        xds=getattr(DiscoveryTypes, "routes", "routes"),
        skip_auth=True,
    )
    route_configs = [
        resource_ for resource_ in response.deserialize_resources()
        if resource_["name"] == route_configuration
    ]
    for route_config in route_configs:
        for vhost in route_config["virtual_hosts"]:
            if vhost["name"] == virtual_host:
                safe_response = jsonable_encoder(vhost)
                try:
                    return json_response_class(content=safe_response)
                except TypeError:
                    return JSONResponse(content=safe_response)
        break
    return JSONResponse(content={})
def generic_error_response(e):
    """
    Responds with a JSON object containing basic context
    about the exception passed in to this function.

    If the server is in debug mode, it will include a traceback in the response.

    The traceback is **always** emitted in logs.
    """
    error = {
        'error': e.__class__.__name__,
        'detail': getattr(e, 'detail', '-'),
        'request_id': get_request_id()
    }
    # Don't expose tracebacks in responses, but add it to the logs
    tb = [line for line in traceback.format_exc().split('\n')]
    add_log_context(**error, traceback=tb)
    if config.debug_enabled:
        error['traceback'] = tb
    return json_response_class(
        content=error,
        status_code=getattr(e, 'status_code', 500)
    )
Beispiel #9
0
async def _decryptable(request: DecryptableRequest = Body(None)):
    decrypt(request.data)
    return json_response_class({})
Beispiel #10
0
def show_stats():
    return json_response_class(content=stats.emitted)
Beispiel #11
0
def show_configuration():
    safe_response = jsonable_encoder(config.show())
    return json_response_class(content=safe_response)
Beispiel #12
0
async def _decryptable(request: DecryptableRequest = Body(
    None)) -> JSONResponse:
    cipher_suite.decrypt(request.data)
    return json_response_class({})