Search in sources :

Example 26 with AsyncResponse

use of org.apache.servicecomb.swagger.invocation.AsyncResponse in project java-chassis by ServiceComb.

the class TestLoadbalanceHandler method send_failed.

@Test
public void send_failed(@Injectable LoadBalancer loadBalancer) {
    MicroserviceInstance instance1 = new MicroserviceInstance();
    instance1.setInstanceId("1234");
    CacheEndpoint cacheEndpoint = new CacheEndpoint("rest://localhost:8080", instance1);
    ServiceCombServer server = new ServiceCombServer(null, restTransport, cacheEndpoint);
    LoadBalancerStats stats = new LoadBalancerStats("test");
    new Expectations(loadBalancer) {

        {
            loadBalancer.chooseServer(invocation);
            result = server;
            loadBalancer.getLoadBalancerStats();
            result = stats;
        }
    };
    sendResponse = Response.consumerFailResp(new SocketException());
    Holder<Throwable> result = new Holder<>();
    Deencapsulation.invoke(handler, "send", invocation, (AsyncResponse) resp -> {
        result.value = (Throwable) resp.getResult();
    }, loadBalancer);
    Assert.assertEquals(1, loadBalancer.getLoadBalancerStats().getSingleServerStat(server).getSuccessiveConnectionFailureCount());
    Assert.assertEquals("InvocationException: code=490;msg=CommonExceptionData [message=Unexpected consumer error, please check logs for details]", result.value.getMessage());
}
Also used : Expectations(mockit.Expectations) SCBEngine(org.apache.servicecomb.core.SCBEngine) MicroserviceInstance(org.apache.servicecomb.registry.api.registry.MicroserviceInstance) Transport(org.apache.servicecomb.core.Transport) Expectations(mockit.Expectations) CacheEndpoint(org.apache.servicecomb.registry.cache.CacheEndpoint) DiscoveryFilter(org.apache.servicecomb.registry.discovery.DiscoveryFilter) SPIServiceUtils(org.apache.servicecomb.foundation.common.utils.SPIServiceUtils) ArchaiusUtils(org.apache.servicecomb.foundation.test.scaffolding.config.ArchaiusUtils) AsyncResponse(org.apache.servicecomb.swagger.invocation.AsyncResponse) ArrayList(java.util.ArrayList) SocketException(java.net.SocketException) Map(java.util.Map) After(org.junit.After) Mock(mockit.Mock) SCBBootstrap(org.apache.servicecomb.core.bootstrap.SCBBootstrap) Status(javax.ws.rs.core.Response.Status) Response(org.apache.servicecomb.swagger.invocation.Response) ExpectedException(org.junit.rules.ExpectedException) ExecutorService(java.util.concurrent.ExecutorService) LoadBalancerStats(com.netflix.loadbalancer.LoadBalancerStats) Before(org.junit.Before) MockUp(mockit.MockUp) InstanceCacheManager(org.apache.servicecomb.registry.cache.InstanceCacheManager) ConfigUtil(org.apache.servicecomb.config.ConfigUtil) Matchers(org.hamcrest.Matchers) Holder(org.apache.servicecomb.foundation.common.Holder) Test(org.junit.Test) Deencapsulation(mockit.Deencapsulation) Invocation(org.apache.servicecomb.core.Invocation) ExecutionException(java.util.concurrent.ExecutionException) List(java.util.List) Rule(org.junit.Rule) TransportManager(org.apache.servicecomb.core.transport.TransportManager) Injectable(mockit.Injectable) Assert(org.junit.Assert) Collections(java.util.Collections) Mocked(mockit.Mocked) SocketException(java.net.SocketException) CacheEndpoint(org.apache.servicecomb.registry.cache.CacheEndpoint) Holder(org.apache.servicecomb.foundation.common.Holder) LoadBalancerStats(com.netflix.loadbalancer.LoadBalancerStats) MicroserviceInstance(org.apache.servicecomb.registry.api.registry.MicroserviceInstance) Test(org.junit.Test)

Example 27 with AsyncResponse

use of org.apache.servicecomb.swagger.invocation.AsyncResponse in project java-chassis by ServiceComb.

the class RestClientInvocation method invoke.

public void invoke(Invocation invocation, AsyncResponse asyncResp) throws Exception {
    this.invocation = invocation;
    this.asyncResp = asyncResp;
    OperationMeta operationMeta = invocation.getOperationMeta();
    restOperationMeta = operationMeta.getExtData(RestConst.SWAGGER_REST_OPERATION);
    String path = this.createRequestPath(restOperationMeta);
    IpPort ipPort = (IpPort) invocation.getEndpoint().getAddress();
    Future<HttpClientRequest> requestFuture = createRequest(ipPort, path);
    invocation.getInvocationStageTrace().startGetConnection();
    requestFuture.compose(clientRequest -> {
        invocation.getInvocationStageTrace().finishGetConnection();
        this.clientRequest = clientRequest;
        clientRequest.putHeader(org.apache.servicecomb.core.Const.TARGET_MICROSERVICE, invocation.getMicroserviceName());
        RestClientRequestImpl restClientRequest = new RestClientRequestImpl(clientRequest, httpClientWithContext.context(), asyncResp, throwableHandler);
        invocation.getHandlerContext().put(RestConst.INVOCATION_HANDLER_REQUESTCLIENT, restClientRequest);
        Buffer requestBodyBuffer;
        try {
            requestBodyBuffer = restClientRequest.getBodyBuffer();
        } catch (Exception e) {
            return Future.failedFuture(e);
        }
        HttpServletRequestEx requestEx = new VertxClientRequestToHttpServletRequest(clientRequest, requestBodyBuffer);
        invocation.getInvocationStageTrace().startClientFiltersRequest();
        for (HttpClientFilter filter : httpClientFilters) {
            if (filter.enabled()) {
                filter.beforeSendRequest(invocation, requestEx);
            }
        }
        // 从业务线程转移到网络线程中去发送
        invocation.onStartSendRequest();
        httpClientWithContext.runOnContext(httpClient -> {
            clientRequest.setTimeout(operationMeta.getConfig().getMsRequestTimeout());
            clientRequest.response().onComplete(asyncResult -> {
                if (asyncResult.failed()) {
                    fail(asyncResult.cause());
                    return;
                }
                handleResponse(asyncResult.result());
            });
            processServiceCombHeaders(invocation, operationMeta);
            restClientRequest.end().onComplete((t) -> invocation.getInvocationStageTrace().finishWriteToBuffer(System.nanoTime()));
        });
        return Future.succeededFuture();
    }).onFailure(failure -> {
        invocation.getTraceIdLogger().error(LOGGER, "Failed to send request, alreadyFailed:{}, local:{}, remote:{}, message={}.", alreadyFailed, getLocalAddress(), ipPort.getSocketAddress(), ExceptionUtils.getExceptionMessageWithoutTrace(failure));
        throwableHandler.handle(failure);
    });
}
Also used : CommonExceptionData(org.apache.servicecomb.swagger.invocation.exception.CommonExceptionData) InvocationException(org.apache.servicecomb.swagger.invocation.exception.InvocationException) RestClientRequestImpl(org.apache.servicecomb.common.rest.codec.param.RestClientRequestImpl) OperationConfig(org.apache.servicecomb.core.definition.OperationConfig) VertxClientRequestToHttpServletRequest(org.apache.servicecomb.foundation.vertx.http.VertxClientRequestToHttpServletRequest) LoggerFactory(org.slf4j.LoggerFactory) TimeoutException(java.util.concurrent.TimeoutException) RequestOptions(io.vertx.core.http.RequestOptions) DefinitionConst(org.apache.servicecomb.registry.definition.DefinitionConst) AsyncResponse(org.apache.servicecomb.swagger.invocation.AsyncResponse) StringUtils(org.apache.commons.lang3.StringUtils) IpPort(org.apache.servicecomb.foundation.common.net.IpPort) ExceptionUtils(org.apache.servicecomb.foundation.common.utils.ExceptionUtils) JsonUtils(org.apache.servicecomb.foundation.common.utils.JsonUtils) ReadStreamPart(org.apache.servicecomb.foundation.vertx.http.ReadStreamPart) HttpClientRequest(io.vertx.core.http.HttpClientRequest) HttpClientResponse(io.vertx.core.http.HttpClientResponse) RestConst(org.apache.servicecomb.common.rest.RestConst) HttpClientFilter(org.apache.servicecomb.common.rest.filter.HttpClientFilter) Status(javax.ws.rs.core.Response.Status) Response(org.apache.servicecomb.swagger.invocation.Response) OperationMeta(org.apache.servicecomb.core.definition.OperationMeta) HttpServletResponseEx(org.apache.servicecomb.foundation.vertx.http.HttpServletResponseEx) RestOperationMeta(org.apache.servicecomb.common.rest.definition.RestOperationMeta) InvocationStageTrace(org.apache.servicecomb.core.invocation.InvocationStageTrace) HttpStatus(org.apache.servicecomb.foundation.common.http.HttpStatus) Logger(org.slf4j.Logger) HttpClientWithContext(org.apache.servicecomb.foundation.vertx.client.http.HttpClientWithContext) VertxClientResponseToHttpServletResponse(org.apache.servicecomb.foundation.vertx.http.VertxClientResponseToHttpServletResponse) Const(org.apache.servicecomb.core.Const) Future(io.vertx.core.Future) Invocation(org.apache.servicecomb.core.Invocation) HttpServletRequestEx(org.apache.servicecomb.foundation.vertx.http.HttpServletRequestEx) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) HttpMethod(io.vertx.core.http.HttpMethod) URIEndpointObject(org.apache.servicecomb.foundation.common.net.URIEndpointObject) Handler(io.vertx.core.Handler) Buffer(io.vertx.core.buffer.Buffer) HttpClientRequest(io.vertx.core.http.HttpClientRequest) HttpClientFilter(org.apache.servicecomb.common.rest.filter.HttpClientFilter) RestClientRequestImpl(org.apache.servicecomb.common.rest.codec.param.RestClientRequestImpl) VertxClientRequestToHttpServletRequest(org.apache.servicecomb.foundation.vertx.http.VertxClientRequestToHttpServletRequest) IpPort(org.apache.servicecomb.foundation.common.net.IpPort) OperationMeta(org.apache.servicecomb.core.definition.OperationMeta) RestOperationMeta(org.apache.servicecomb.common.rest.definition.RestOperationMeta) InvocationException(org.apache.servicecomb.swagger.invocation.exception.InvocationException) TimeoutException(java.util.concurrent.TimeoutException) HttpServletRequestEx(org.apache.servicecomb.foundation.vertx.http.HttpServletRequestEx)

Example 28 with AsyncResponse

use of org.apache.servicecomb.swagger.invocation.AsyncResponse in project java-chassis by ServiceComb.

the class InvokerUtils method reactiveInvoke.

/**
 * This is an internal API, caller make sure already invoked SCBEngine.ensureStatusUp
 */
public static void reactiveInvoke(Invocation invocation, AsyncResponse asyncResp) {
    invocation.setSync(false);
    Supplier<CompletionStage<Response>> next = reactiveInvokeImpl(invocation);
    DecorateCompletionStage<Response> dcs = Decorators.ofCompletionStage(next);
    GovernanceRequest request = MatchType.createGovHttpRequest(invocation);
    try {
        ServiceCombInvocationContext.setInvocationContext(invocation);
        decorateReactiveRetry(invocation, dcs, request);
    } finally {
        ServiceCombInvocationContext.removeInvocationContext();
    }
    dcs.get().whenComplete((r, e) -> {
        if (e == null) {
            asyncResp.complete(r);
            return;
        }
        String message = String.format("invoke failed, operation %s, trace id %s", invocation.getMicroserviceQualifiedName(), invocation.getTraceId());
        LOGGER.error(message, e);
        Response response = Response.createConsumerFail(e, message);
        invocation.onFinish(response);
        asyncResp.complete(response);
    });
}
Also used : AsyncResponse(org.apache.servicecomb.swagger.invocation.AsyncResponse) Response(org.apache.servicecomb.swagger.invocation.Response) Exceptions.toConsumerResponse(org.apache.servicecomb.core.exception.Exceptions.toConsumerResponse) GovernanceRequest(org.apache.servicecomb.governance.marker.GovernanceRequest) DecorateCompletionStage(io.github.resilience4j.decorators.Decorators.DecorateCompletionStage) CompletionStage(java.util.concurrent.CompletionStage)

Example 29 with AsyncResponse

use of org.apache.servicecomb.swagger.invocation.AsyncResponse in project java-chassis by ServiceComb.

the class LoadbalanceHandler method handle.

@Override
public void handle(Invocation invocation, AsyncResponse asyncResp) throws Exception {
    AsyncResponse response = asyncResp;
    asyncResp = async -> {
        ServiceCombServerStats.checkAndReleaseTryingChance(invocation);
        response.handle(async);
    };
    if (handleSuppliedEndpoint(invocation, asyncResp)) {
        invocation.addLocalContext(RetryContext.RETRY_LOAD_BALANCE, false);
        return;
    }
    invocation.addLocalContext(RetryContext.RETRY_LOAD_BALANCE, true);
    String strategy = Configuration.INSTANCE.getRuleStrategyName(invocation.getMicroserviceName());
    if (!Objects.equals(strategy, this.strategy)) {
        // 配置变化,需要重新生成所有的lb实例
        synchronized (lock) {
            clearLoadBalancer();
        }
    }
    this.strategy = strategy;
    LoadBalancer loadBalancer = getOrCreateLoadBalancer(invocation);
    send(invocation, asyncResp, loadBalancer);
}
Also used : AsyncResponse(org.apache.servicecomb.swagger.invocation.AsyncResponse)

Aggregations

AsyncResponse (org.apache.servicecomb.swagger.invocation.AsyncResponse)29 Invocation (org.apache.servicecomb.core.Invocation)20 Test (org.junit.Test)20 Response (org.apache.servicecomb.swagger.invocation.Response)16 MockUp (mockit.MockUp)10 ArrayList (java.util.ArrayList)9 Mock (mockit.Mock)8 List (java.util.List)7 Map (java.util.Map)6 Status (javax.ws.rs.core.Response.Status)6 Expectations (mockit.Expectations)6 Transport (org.apache.servicecomb.core.Transport)6 TransportManager (org.apache.servicecomb.core.transport.TransportManager)6 OperationMeta (org.apache.servicecomb.core.definition.OperationMeta)5 HashMap (java.util.HashMap)4 Holder (javax.xml.ws.Holder)4 Deencapsulation (mockit.Deencapsulation)4 Injectable (mockit.Injectable)4 Mocked (mockit.Mocked)4 RestOperationMeta (org.apache.servicecomb.common.rest.definition.RestOperationMeta)4