Search in sources :

Example 86 with SofaRpcException

use of com.alipay.sofa.rpc.core.exception.SofaRpcException in project sofa-rpc by sofastack.

the class BoltInvokerCallback method onException.

@Override
public void onException(Throwable e) {
    if (callback == null) {
        return;
    }
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    try {
        Thread.currentThread().setContextClassLoader(this.classLoader);
        RpcInternalContext.setContext(context);
        if (EventBus.isEnable(ClientAsyncReceiveEvent.class)) {
            EventBus.post(new ClientAsyncReceiveEvent(consumerConfig, providerInfo, request, null, e));
        }
        // do async filter after respond server
        FilterChain chain = consumerConfig.getConsumerBootstrap().getCluster().getFilterChain();
        if (chain != null) {
            chain.onAsyncResponse(consumerConfig, request, null, e);
        }
        recordClientElapseTime();
        if (EventBus.isEnable(ClientEndInvokeEvent.class)) {
            EventBus.post(new ClientEndInvokeEvent(request, null, e));
        }
        // judge is timeout or others
        SofaRpcException sofaRpcException = null;
        if (e instanceof InvokeTimeoutException) {
            sofaRpcException = new SofaTimeOutException(e);
        } else {
            sofaRpcException = new SofaRpcException(RpcErrorType.SERVER_UNDECLARED_ERROR, e.getMessage(), e);
        }
        callback.onSofaException(sofaRpcException, request.getMethodName(), request);
    } finally {
        Thread.currentThread().setContextClassLoader(cl);
        RpcInvokeContext.removeContext();
        RpcInternalContext.removeAllContext();
    }
}
Also used : ClientEndInvokeEvent(com.alipay.sofa.rpc.event.ClientEndInvokeEvent) InvokeTimeoutException(com.alipay.remoting.rpc.exception.InvokeTimeoutException) FilterChain(com.alipay.sofa.rpc.filter.FilterChain) SofaTimeOutException(com.alipay.sofa.rpc.core.exception.SofaTimeOutException) ClientAsyncReceiveEvent(com.alipay.sofa.rpc.event.ClientAsyncReceiveEvent) SofaRpcException(com.alipay.sofa.rpc.core.exception.SofaRpcException)

Example 87 with SofaRpcException

use of com.alipay.sofa.rpc.core.exception.SofaRpcException in project sofa-rpc by sofastack.

the class BoltInvokerCallback method onResponse.

@Override
public void onResponse(Object result) {
    if (callback == null) {
        return;
    }
    ClassLoader oldCl = Thread.currentThread().getContextClassLoader();
    SofaResponse response = (SofaResponse) result;
    Throwable throwable = null;
    try {
        Thread.currentThread().setContextClassLoader(this.classLoader);
        RpcInternalContext.setContext(context);
        if (EventBus.isEnable(ClientAsyncReceiveEvent.class)) {
            EventBus.post(new ClientAsyncReceiveEvent(consumerConfig, providerInfo, request, response, null));
        }
        pickupBaggage(response);
        // do async filter after respond server
        FilterChain chain = consumerConfig.getConsumerBootstrap().getCluster().getFilterChain();
        if (chain != null) {
            chain.onAsyncResponse(consumerConfig, request, response, null);
        }
        recordClientElapseTime();
        if (EventBus.isEnable(ClientEndInvokeEvent.class)) {
            EventBus.post(new ClientEndInvokeEvent(request, response, null));
        }
        Object appResp = response.getAppResponse();
        if (response.isError()) {
            // rpc层异常
            SofaRpcException sofaRpcException = new SofaRpcException(RpcErrorType.SERVER_UNDECLARED_ERROR, response.getErrorMsg());
            callback.onSofaException(sofaRpcException, request.getMethodName(), request);
        } else if (appResp instanceof Throwable) {
            // 业务层异常
            throwable = (Throwable) appResp;
            callback.onAppException(throwable, request.getMethodName(), request);
        } else {
            callback.onAppResponse(appResp, request.getMethodName(), request);
        }
    } finally {
        Thread.currentThread().setContextClassLoader(oldCl);
        RpcInvokeContext.removeContext();
        RpcInternalContext.removeAllContext();
    }
}
Also used : ClientEndInvokeEvent(com.alipay.sofa.rpc.event.ClientEndInvokeEvent) FilterChain(com.alipay.sofa.rpc.filter.FilterChain) ClientAsyncReceiveEvent(com.alipay.sofa.rpc.event.ClientAsyncReceiveEvent) SofaResponse(com.alipay.sofa.rpc.core.response.SofaResponse) SofaRpcException(com.alipay.sofa.rpc.core.exception.SofaRpcException)

Example 88 with SofaRpcException

use of com.alipay.sofa.rpc.core.exception.SofaRpcException in project sofa-rpc by sofastack.

the class CallbackInvokeClientMain method main.

public static void main(String[] args) throws InterruptedException {
    ApplicationConfig applicationConfig = new ApplicationConfig().setAppName("future-server");
    ConsumerConfig<HelloService> consumerConfig = new ConsumerConfig<HelloService>().setApplication(applicationConfig).setInterfaceId(HelloService.class.getName()).setInvokeType(RpcConstants.INVOKER_TYPE_CALLBACK).setTimeout(3000).setDirectUrl("bolt://127.0.0.1:22222?appName=future-server");
    HelloService helloService = consumerConfig.refer();
    LOGGER.warn("started at pid {}", RpcRuntimeContext.PID);
    for (int i = 0; i < 100; i++) {
        try {
            RpcInvokeContext.getContext().setResponseCallback(new SofaResponseCallback() {

                @Override
                public void onAppResponse(Object appResponse, String methodName, RequestBase request) {
                    LOGGER.info("Invoke get result: {}", appResponse);
                }

                @Override
                public void onAppException(Throwable throwable, String methodName, RequestBase request) {
                    LOGGER.info("Invoke get app exception: {}", throwable);
                }

                @Override
                public void onSofaException(SofaRpcException sofaException, String methodName, RequestBase request) {
                    LOGGER.info("Invoke get sofa exception: {}", sofaException);
                }
            });
            String s = helloService.sayHello("xxx", 22);
            LOGGER.warn("{}", s);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        try {
            Thread.sleep(2000);
        } catch (Exception e) {
        }
    }
}
Also used : ApplicationConfig(com.alipay.sofa.rpc.config.ApplicationConfig) HelloService(com.alipay.sofa.rpc.test.HelloService) SofaResponseCallback(com.alipay.sofa.rpc.core.invoke.SofaResponseCallback) RequestBase(com.alipay.sofa.rpc.core.request.RequestBase) SofaRpcException(com.alipay.sofa.rpc.core.exception.SofaRpcException) SofaRpcException(com.alipay.sofa.rpc.core.exception.SofaRpcException)

Example 89 with SofaRpcException

use of com.alipay.sofa.rpc.core.exception.SofaRpcException in project sofa-rpc by sofastack.

the class CallbackMethodClientMain method main.

public static void main(String[] args) throws InterruptedException {
    ApplicationConfig applicationConfig = new ApplicationConfig().setAppName("future-server");
    MethodConfig methodConfig = new MethodConfig();
    methodConfig.setName("sayHello").setInvokeType(RpcConstants.INVOKER_TYPE_CALLBACK).setOnReturn(new SofaResponseCallback() {

        @Override
        public void onAppResponse(Object appResponse, String methodName, RequestBase request) {
            LOGGER.info("Method get result: {}", appResponse);
        }

        @Override
        public void onAppException(Throwable throwable, String methodName, RequestBase request) {
            LOGGER.info("Method get app exception: {}", throwable);
        }

        @Override
        public void onSofaException(SofaRpcException sofaException, String methodName, RequestBase request) {
            LOGGER.info("Method get sofa exception: {}", sofaException);
        }
    });
    ConsumerConfig<HelloService> consumerConfig = new ConsumerConfig<HelloService>().setApplication(applicationConfig).setInterfaceId(HelloService.class.getName()).setTimeout(5000).setMethods(Collections.singletonList(methodConfig)).setDirectUrl("bolt://127.0.0.1:22222?appName=future-server");
    HelloService helloService = consumerConfig.refer();
    LOGGER.warn("started at pid {}", RpcRuntimeContext.PID);
    try {
        for (int i = 0; i < 100; i++) {
            try {
                String s = helloService.sayHello("xxx", 22);
                LOGGER.warn("{}", s);
            } catch (Exception e) {
                LOGGER.error(e.getMessage(), e);
            }
            try {
                Thread.sleep(2000);
            } catch (Exception e) {
            }
        }
    } catch (Exception e) {
        LOGGER.error("", e);
    }
    synchronized (CallbackMethodClientMain.class) {
        while (true) {
            CallbackMethodClientMain.class.wait();
        }
    }
}
Also used : SofaResponseCallback(com.alipay.sofa.rpc.core.invoke.SofaResponseCallback) HelloService(com.alipay.sofa.rpc.test.HelloService) RequestBase(com.alipay.sofa.rpc.core.request.RequestBase) SofaRpcException(com.alipay.sofa.rpc.core.exception.SofaRpcException) SofaRpcException(com.alipay.sofa.rpc.core.exception.SofaRpcException) MethodConfig(com.alipay.sofa.rpc.config.MethodConfig) ApplicationConfig(com.alipay.sofa.rpc.config.ApplicationConfig)

Example 90 with SofaRpcException

use of com.alipay.sofa.rpc.core.exception.SofaRpcException in project sofa-rpc by sofastack.

the class Http2ServerChannelHandler method handleRequest.

protected void handleRequest(ChannelHandlerContext ctx, int streamId, Http2Headers http2Headers, ByteBuf data) {
    String uri = StringUtils.defaultString(http2Headers.path());
    // ignore uris
    if (RemotingConstants.IGNORE_WEB_BROWSER.equals(uri)) {
        sendHttp2Response(ctx, streamId, HttpResponseStatus.OK, StringUtils.EMPTY);
        return;
    }
    CharSequence reqMethod = StringUtils.defaultString(http2Headers.method());
    // HEAD for check method exists
    if (reqMethod.equals(HttpMethod.HEAD.name())) {
        String[] iam = HttpTransportUtils.getInterfaceIdAndMethod(uri);
        boolean exists = serverHandler.checkService(iam[0], iam[1]);
        sendHttp2Response(ctx, streamId, exists ? HttpResponseStatus.OK : HttpResponseStatus.NOT_FOUND, null);
        return;
    } else // POST(primary) / GET for invoke
    if (!reqMethod.equals(HttpMethod.POST.name())) {
        sendHttp2Response(ctx, streamId, HttpResponseStatus.BAD_REQUEST, "Only support POST/HEAD");
        return;
    }
    /**
     * https://http2.github.io/http2-spec/#rfc.section.5.1.1 second paragraph
     * only when in upgrade h2c mode, 0x01 cannot be selected as a new stream identifier.
     * some gateway or proxy product, use 0x01 as first normal request's stream id  when
     * in prior knowleadge mode.
     */
    if (this.isUpgradeH2cMode && streamId > 1 || !this.isUpgradeH2cMode && streamId > 0) {
        // 本来这里可以提前检查接口方法是否存在,但是为了日志统一,全部放到serverHandler里去
        SofaRequest sofaRequest = new SofaRequest();
        try {
            String[] iam = HttpTransportUtils.getInterfaceIdAndMethod(uri);
            sofaRequest.setTargetServiceUniqueName(iam[0]);
            sofaRequest.setMethodName(iam[1]);
            sofaRequest.setData(new NettyByteBuffer(data));
            parseHttp2Request(http2Headers, sofaRequest);
        } catch (Exception e) {
            String message = "Failed to parse http2 request for uri " + uri + " form " + NetUtils.channelToString(ctx.channel().remoteAddress(), ctx.channel().localAddress()) + ", cause by: " + e.getMessage();
            if (LOGGER.isWarnEnabled()) {
                LOGGER.warn(message, e);
            }
            sendHttp2Response(ctx, streamId, HttpResponseStatus.BAD_REQUEST, message);
            return;
        }
        try {
            serverHandler.handleHttp2Request(streamId, sofaRequest, ctx, encoder());
        } catch (SofaRpcException e) {
            int type = e.getErrorType();
            if (type == RpcErrorType.SERVER_BUSY) {
                sendHttp2Response(ctx, streamId, HttpResponseStatus.SERVICE_UNAVAILABLE, e.getMessage());
            } else if (type == RpcErrorType.SERVER_NOT_FOUND_INVOKER) {
                sendHttp2Response(ctx, streamId, HttpResponseStatus.NOT_FOUND, e.getMessage());
            } else {
                sendHttp2Response(ctx, streamId, HttpResponseStatus.INTERNAL_SERVER_ERROR, e.getMessage());
            }
        } catch (Exception e) {
            sendHttp2Response(ctx, streamId, HttpResponseStatus.INTERNAL_SERVER_ERROR, e.getMessage());
        }
    }
}
Also used : SofaRequest(com.alipay.sofa.rpc.core.request.SofaRequest) NettyByteBuffer(com.alipay.sofa.rpc.transport.netty.NettyByteBuffer) SofaRpcException(com.alipay.sofa.rpc.core.exception.SofaRpcException) SofaRpcException(com.alipay.sofa.rpc.core.exception.SofaRpcException)

Aggregations

SofaRpcException (com.alipay.sofa.rpc.core.exception.SofaRpcException)91 Test (org.junit.Test)35 RequestBase (com.alipay.sofa.rpc.core.request.RequestBase)28 SofaResponseCallback (com.alipay.sofa.rpc.core.invoke.SofaResponseCallback)27 ServerConfig (com.alipay.sofa.rpc.config.ServerConfig)24 ActivelyDestroyTest (com.alipay.sofa.rpc.test.ActivelyDestroyTest)23 SofaTimeOutException (com.alipay.sofa.rpc.core.exception.SofaTimeOutException)22 ConsumerConfig (com.alipay.sofa.rpc.config.ConsumerConfig)21 CountDownLatch (java.util.concurrent.CountDownLatch)20 SofaResponse (com.alipay.sofa.rpc.core.response.SofaResponse)19 ProviderConfig (com.alipay.sofa.rpc.config.ProviderConfig)16 HelloService (com.alipay.sofa.rpc.test.HelloService)16 RpcInvokeContext (com.alipay.sofa.rpc.context.RpcInvokeContext)15 ApplicationConfig (com.alipay.sofa.rpc.config.ApplicationConfig)14 RpcInternalContext (com.alipay.sofa.rpc.context.RpcInternalContext)14 SofaRequest (com.alipay.sofa.rpc.core.request.SofaRequest)11 HelloServiceImpl (com.alipay.sofa.rpc.test.HelloServiceImpl)11 HashMap (java.util.HashMap)9 Filter (com.alipay.sofa.rpc.filter.Filter)8 InvokeTimeoutException (com.alipay.remoting.rpc.exception.InvokeTimeoutException)7