Search in sources :

Example 76 with RpcException

use of org.apache.dubbo.rpc.RpcException in project dubbo by alibaba.

the class MetricsFilter method invoke.

@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
    if (exported.compareAndSet(false, true)) {
        this.protocolName = invoker.getUrl().getParameter(METRICS_PROTOCOL) == null ? DEFAULT_PROTOCOL : invoker.getUrl().getParameter(METRICS_PROTOCOL);
        Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getExtension(protocolName);
        this.port = invoker.getUrl().getParameter(METRICS_PORT) == null ? protocol.getDefaultPort() : Integer.parseInt(invoker.getUrl().getParameter(METRICS_PORT));
        Invoker<MetricsService> metricsInvoker = initMetricsInvoker();
        try {
            protocol.export(metricsInvoker);
        } catch (RuntimeException e) {
            logger.error("Metrics Service need to be configured" + " when multiple processes are running on a host" + e.getMessage());
        }
    }
    RpcContext context = RpcContext.getContext();
    boolean isProvider = context.isProviderSide();
    long start = System.currentTimeMillis();
    try {
        // proceed invocation chain
        Result result = invoker.invoke(invocation);
        long duration = System.currentTimeMillis() - start;
        reportMetrics(invoker, invocation, duration, "success", isProvider);
        return result;
    } catch (RpcException e) {
        long duration = System.currentTimeMillis() - start;
        String result = "error";
        if (e.isTimeout()) {
            result = "timeoutError";
        }
        if (e.isBiz()) {
            result = "bisError";
        }
        if (e.isNetwork()) {
            result = "networkError";
        }
        if (e.isSerialization()) {
            result = "serializationError";
        }
        reportMetrics(invoker, invocation, duration, result, isProvider);
        throw e;
    }
}
Also used : RpcContext(org.apache.dubbo.rpc.RpcContext) MetricsService(org.apache.dubbo.monitor.MetricsService) RpcException(org.apache.dubbo.rpc.RpcException) Protocol(org.apache.dubbo.rpc.Protocol) AsyncRpcResult(org.apache.dubbo.rpc.AsyncRpcResult) Result(org.apache.dubbo.rpc.Result)

Example 77 with RpcException

use of org.apache.dubbo.rpc.RpcException in project dubbo by alibaba.

the class DubboHttpProtocolServer method doStart.

@Override
protected void doStart(URL url) {
    // TODO jetty will by default enable keepAlive so the xml config has no effect now
    httpServer = httpBinder.bind(url, new RestHandler());
    ServletContext servletContext = ServletManager.getInstance().getServletContext(url.getPort());
    if (servletContext == null) {
        servletContext = ServletManager.getInstance().getServletContext(ServletManager.EXTERNAL_SERVER_PORT);
    }
    if (servletContext == null) {
        throw new RpcException("No servlet context found. If you are using server='servlet', " + "make sure that you've configured " + BootstrapListener.class.getName() + " in web.xml");
    }
    servletContext.setAttribute(ResteasyDeployment.class.getName(), deployment);
    try {
        dispatcher.init(new SimpleServletConfig(servletContext));
    } catch (ServletException e) {
        throw new RpcException(e);
    }
}
Also used : ServletException(javax.servlet.ServletException) ResteasyDeployment(org.jboss.resteasy.spi.ResteasyDeployment) RpcException(org.apache.dubbo.rpc.RpcException) BootstrapListener(org.apache.dubbo.remoting.http.servlet.BootstrapListener) ServletContext(javax.servlet.ServletContext)

Example 78 with RpcException

use of org.apache.dubbo.rpc.RpcException in project dubbo by alibaba.

the class RestProtocol method doExport.

@Override
protected <T> Runnable doExport(T impl, Class<T> type, URL url) throws RpcException {
    String addr = getAddr(url);
    Class implClass = ApplicationModel.getProviderModel(url.getServiceKey()).getServiceInstance().getClass();
    RestProtocolServer server = (RestProtocolServer) serverMap.computeIfAbsent(addr, restServer -> {
        RestProtocolServer s = serverFactory.createServer(url.getParameter(SERVER_KEY, DEFAULT_SERVER));
        s.setAddress(url.getAddress());
        s.start(url);
        return s;
    });
    String contextPath = getContextPath(url);
    if ("servlet".equalsIgnoreCase(url.getParameter(SERVER_KEY, DEFAULT_SERVER))) {
        ServletContext servletContext = ServletManager.getInstance().getServletContext(ServletManager.EXTERNAL_SERVER_PORT);
        if (servletContext == null) {
            throw new RpcException("No servlet context found. Since you are using server='servlet', " + "make sure that you've configured " + BootstrapListener.class.getName() + " in web.xml");
        }
        String webappPath = servletContext.getContextPath();
        if (StringUtils.isNotEmpty(webappPath)) {
            webappPath = webappPath.substring(1);
            if (!contextPath.startsWith(webappPath)) {
                throw new RpcException("Since you are using server='servlet', " + "make sure that the 'contextpath' property starts with the path of external webapp");
            }
            contextPath = contextPath.substring(webappPath.length());
            if (contextPath.startsWith("/")) {
                contextPath = contextPath.substring(1);
            }
        }
    }
    final Class resourceDef = GetRestful.getRootResourceClass(implClass) != null ? implClass : type;
    server.deploy(resourceDef, impl, contextPath);
    final RestProtocolServer s = server;
    return () -> {
        // TODO due to dubbo's current architecture,
        // it will be called from registry protocol in the shutdown process and won't appear in logs
        s.undeploy(resourceDef);
    };
}
Also used : TIMEOUT_KEY(org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY) DEFAULT_CONNECT_TIMEOUT(org.apache.dubbo.remoting.Constants.DEFAULT_CONNECT_TIMEOUT) AbstractProxyProtocol(org.apache.dubbo.rpc.protocol.AbstractProxyProtocol) INTERFACE_KEY(org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY) BasicHeaderElementIterator(org.apache.http.message.BasicHeaderElementIterator) SERVER_KEY(org.apache.dubbo.remoting.Constants.SERVER_KEY) SocketConfig(org.apache.http.config.SocketConfig) RequestConfig(org.apache.http.client.config.RequestConfig) COMMA_SPLIT_PATTERN(org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN) BootstrapListener(org.apache.dubbo.remoting.http.servlet.BootstrapListener) ResteasyClientBuilder(org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder) ResteasyWebTarget(org.jboss.resteasy.client.jaxrs.ResteasyWebTarget) ProtocolServer(org.apache.dubbo.rpc.ProtocolServer) StringUtils(org.apache.dubbo.common.utils.StringUtils) URL(org.apache.dubbo.common.URL) Map(java.util.Map) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) ApacheHttpClient4Engine(org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine) GetRestful(org.jboss.resteasy.util.GetRestful) LinkedList(java.util.LinkedList) HttpBinder(org.apache.dubbo.remoting.http.HttpBinder) HTTP(org.apache.http.protocol.HTTP) HeaderElementIterator(org.apache.http.HeaderElementIterator) DEFAULT_TIMEOUT(org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) EXTENSION_KEY(org.apache.dubbo.rpc.protocol.rest.Constants.EXTENSION_KEY) ApplicationModel(org.apache.dubbo.rpc.model.ApplicationModel) CONNECTIONS_KEY(org.apache.dubbo.remoting.Constants.CONNECTIONS_KEY) RpcException(org.apache.dubbo.rpc.RpcException) HeaderElement(org.apache.http.HeaderElement) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) CONNECT_TIMEOUT_KEY(org.apache.dubbo.remoting.Constants.CONNECT_TIMEOUT_KEY) ResteasyClient(org.jboss.resteasy.client.jaxrs.ResteasyClient) ServletManager(org.apache.dubbo.remoting.http.servlet.ServletManager) ProcessingException(javax.ws.rs.ProcessingException) WebApplicationException(javax.ws.rs.WebApplicationException) ServletContext(javax.servlet.ServletContext) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) Collections(java.util.Collections) RpcException(org.apache.dubbo.rpc.RpcException) BootstrapListener(org.apache.dubbo.remoting.http.servlet.BootstrapListener) ServletContext(javax.servlet.ServletContext)

Example 79 with RpcException

use of org.apache.dubbo.rpc.RpcException in project dubbo by alibaba.

the class ThriftCodec method encodeRequest.

private void encodeRequest(Channel channel, ChannelBuffer buffer, Request request) throws IOException {
    RpcInvocation inv = (RpcInvocation) request.getData();
    int seqId = nextSeqId();
    String serviceName = inv.getAttachment(INTERFACE_KEY);
    if (StringUtils.isEmpty(serviceName)) {
        throw new IllegalArgumentException("Could not find service name in attachment with key " + INTERFACE_KEY);
    }
    TMessage message = new TMessage(inv.getMethodName(), TMessageType.CALL, seqId);
    String methodArgs = ExtensionLoader.getExtensionLoader(ClassNameGenerator.class).getExtension(channel.getUrl().getParameter(ThriftConstants.CLASS_NAME_GENERATOR_KEY, ThriftClassNameGenerator.NAME)).generateArgsClassName(serviceName, inv.getMethodName());
    if (StringUtils.isEmpty(methodArgs)) {
        throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, "Could not encode request, the specified interface may be incorrect.");
    }
    Class<?> clazz = CACHED_CLASS.get(methodArgs);
    if (clazz == null) {
        try {
            clazz = ClassUtils.forNameWithThreadContextClassLoader(methodArgs);
            CACHED_CLASS.putIfAbsent(methodArgs, clazz);
        } catch (ClassNotFoundException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        }
    }
    TBase args;
    try {
        args = (TBase) clazz.newInstance();
    } catch (InstantiationException | IllegalAccessException e) {
        throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
    }
    for (int i = 0; i < inv.getArguments().length; i++) {
        Object obj = inv.getArguments()[i];
        if (obj == null) {
            continue;
        }
        TFieldIdEnum field = args.fieldForId(i + 1);
        String setMethodName = ThriftUtils.generateSetMethodName(field.getFieldName());
        Method method;
        try {
            method = clazz.getMethod(setMethodName, inv.getParameterTypes()[i]);
        } catch (NoSuchMethodException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        }
        try {
            method.invoke(args, obj);
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        }
    }
    RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream(1024);
    TIOStreamTransport transport = new TIOStreamTransport(bos);
    TBinaryProtocol protocol = new TBinaryProtocol(transport);
    int headerLength, messageLength;
    byte[] bytes = new byte[4];
    try {
        // magic
        protocol.writeI16(MAGIC);
        // message length placeholder
        protocol.writeI32(Integer.MAX_VALUE);
        // message header length placeholder
        protocol.writeI16(Short.MAX_VALUE);
        // version
        protocol.writeByte(VERSION);
        // service name
        protocol.writeString(serviceName);
        // path
        protocol.writeString(inv.getAttachment(PATH_KEY));
        // dubbo request id
        protocol.writeI64(request.getId());
        protocol.getTransport().flush();
        // header size
        headerLength = bos.size();
        // message body
        protocol.writeMessageBegin(message);
        args.write(protocol);
        protocol.writeMessageEnd();
        protocol.getTransport().flush();
        int oldIndex = messageLength = bos.size();
        // fill in message length and header length
        try {
            TFramedTransport.encodeFrameSize(messageLength, bytes);
            bos.setWriteIndex(MESSAGE_LENGTH_INDEX);
            protocol.writeI32(messageLength);
            bos.setWriteIndex(MESSAGE_HEADER_LENGTH_INDEX);
            protocol.writeI16((short) (0xffff & headerLength));
        } finally {
            bos.setWriteIndex(oldIndex);
        }
    } catch (TException e) {
        throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
    }
    buffer.writeBytes(bytes);
    buffer.writeBytes(bos.toByteArray());
}
Also used : RpcInvocation(org.apache.dubbo.rpc.RpcInvocation) TException(org.apache.thrift.TException) TIOStreamTransport(org.apache.thrift.transport.TIOStreamTransport) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException) RandomAccessByteArrayOutputStream(org.apache.dubbo.rpc.protocol.thrift.io.RandomAccessByteArrayOutputStream) TBinaryProtocol(org.apache.thrift.protocol.TBinaryProtocol) TMessage(org.apache.thrift.protocol.TMessage) TFieldIdEnum(org.apache.thrift.TFieldIdEnum) RpcException(org.apache.dubbo.rpc.RpcException) TBase(org.apache.thrift.TBase)

Example 80 with RpcException

use of org.apache.dubbo.rpc.RpcException in project dubbo by alibaba.

the class RmiProtocol method createExporter.

private <T> RmiServiceExporter createExporter(T impl, Class<?> type, URL url, boolean isGeneric) {
    final RmiServiceExporter rmiServiceExporter = new RmiServiceExporter();
    rmiServiceExporter.setRegistryPort(url.getPort());
    if (isGeneric) {
        rmiServiceExporter.setServiceName(url.getPath() + "/" + GENERIC_KEY);
    } else {
        rmiServiceExporter.setServiceName(url.getPath());
    }
    rmiServiceExporter.setServiceInterface(type);
    rmiServiceExporter.setService(impl);
    try {
        rmiServiceExporter.afterPropertiesSet();
    } catch (RemoteException e) {
        throw new RpcException(e.getMessage(), e);
    }
    return rmiServiceExporter;
}
Also used : RpcException(org.apache.dubbo.rpc.RpcException) RmiServiceExporter(org.springframework.remoting.rmi.RmiServiceExporter) RemoteException(java.rmi.RemoteException)

Aggregations

RpcException (org.apache.dubbo.rpc.RpcException)102 URL (org.apache.dubbo.common.URL)37 Test (org.junit.jupiter.api.Test)29 RpcInvocation (org.apache.dubbo.rpc.RpcInvocation)28 Result (org.apache.dubbo.rpc.Result)21 Invocation (org.apache.dubbo.rpc.Invocation)17 ArrayList (java.util.ArrayList)15 AppResponse (org.apache.dubbo.rpc.AppResponse)13 AsyncRpcResult (org.apache.dubbo.rpc.AsyncRpcResult)13 Invoker (org.apache.dubbo.rpc.Invoker)13 IOException (java.io.IOException)9 List (java.util.List)9 Method (java.lang.reflect.Method)8 Gson (com.google.gson.Gson)6 InvocationTargetException (java.lang.reflect.InvocationTargetException)6 HashMap (java.util.HashMap)5 RemotingException (org.apache.dubbo.remoting.RemotingException)5 TException (org.apache.thrift.TException)5 SocketTimeoutException (java.net.SocketTimeoutException)4 CountDownLatch (java.util.concurrent.CountDownLatch)4