Search in sources :

Example 1 with AppResponse

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

the class MetricsFilterTest method testConsumerSuccess.

public void testConsumerSuccess() throws Exception {
    IMetricManager metricManager = MetricManager.getIMetricManager();
    metricManager.clear();
    MetricsFilter metricsFilter = new MetricsFilter();
    Invocation invocation = new RpcInvocation("sayName", DemoService.class.getName(), "", new Class<?>[] { Integer.class }, new Object[0]);
    RpcContext.getContext().setRemoteAddress(host, url.getPort()).setLocalAddress(host, NetUtils.getAvailablePort());
    RpcContext.getContext().setUrl(serviceInvoker.getUrl().addParameter(SIDE_KEY, CONSUMER_SIDE));
    AppResponse response = AppResponseBuilder.create().build();
    onInvokeReturns(response);
    for (int i = 0; i < 100; i++) {
        metricsFilter.invoke(serviceInvoker, invocation);
    }
    FastCompass dubboClient = metricManager.getFastCompass(DUBBO_GROUP, new MetricName(DUBBO_CONSUMER, MetricLevel.MAJOR));
    FastCompass dubboMethod = metricManager.getFastCompass(DUBBO_GROUP, new MetricName(DUBBO_CONSUMER_METHOD, new HashMap<String, String>(4) {

        {
            put(SERVICE, "org.apache.dubbo.monitor.dubbo.service.DemoService");
            put(METHOD, "void sayName(Integer)");
        }
    }, MetricLevel.NORMAL));
    long timestamp = System.currentTimeMillis() / 5000 * 5000;
    Assertions.assertEquals(100, dubboClient.getMethodCountPerCategory(0).get("success").get(timestamp));
    timestamp = timestamp / 15000 * 15000;
    Assertions.assertEquals(100, dubboMethod.getMethodCountPerCategory(0).get("success").get(timestamp));
}
Also used : RpcInvocation(org.apache.dubbo.rpc.RpcInvocation) MetricName(com.alibaba.metrics.MetricName) Invocation(org.apache.dubbo.rpc.Invocation) RpcInvocation(org.apache.dubbo.rpc.RpcInvocation) FastCompass(com.alibaba.metrics.FastCompass) HashMap(java.util.HashMap) AppResponse(org.apache.dubbo.rpc.AppResponse) DemoService(org.apache.dubbo.monitor.dubbo.service.DemoService) IMetricManager(com.alibaba.metrics.IMetricManager)

Example 2 with AppResponse

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

the class MetricsFilterTest method testInvokeMetricsMethodService.

public void testInvokeMetricsMethodService() {
    IMetricManager metricManager = MetricManager.getIMetricManager();
    metricManager.clear();
    MetricsFilter metricsFilter = new MetricsFilter();
    Invocation sayNameInvocation = new RpcInvocation("sayName", DemoService.class.getName(), "", new Class<?>[0], new Object[0]);
    Invocation echoInvocation = new RpcInvocation("echo", DemoService.class.getName(), "", new Class<?>[] { Integer.class }, new Integer[] { 1 });
    RpcContext.getContext().setRemoteAddress(host, url.getPort()).setLocalAddress(host, NetUtils.getAvailablePort());
    RpcContext.getContext().setUrl(serviceInvoker.getUrl().addParameter(SIDE_KEY, PROVIDER_SIDE).addParameter(TIMEOUT_KEY, 300));
    AppResponse response = AppResponseBuilder.create().build();
    onInvokeReturns(response);
    for (int i = 0; i < 50; i++) {
        metricsFilter.invoke(serviceInvoker, sayNameInvocation);
        metricsFilter.invoke(serviceInvoker, echoInvocation);
        try {
            metricsFilter.invoke(timeoutInvoker, sayNameInvocation);
        } catch (RpcException e) {
        // ignore
        }
        try {
            metricsFilter.invoke(timeoutInvoker, echoInvocation);
        } catch (RpcException e) {
        // ignore
        }
    }
    Protocol protocol = DubboProtocol.getDubboProtocol();
    URL metricUrl = URL.valueOf("dubbo://" + url.getHost() + ":" + url.getPort() + "/" + MetricsService.class.getName() + "?" + METRICS_PORT + "=" + port);
    Invoker<MetricsService> invoker = protocol.refer(MetricsService.class, metricUrl);
    Invocation invocation = new RpcInvocation("getMetricsByGroup", DemoService.class.getName(), "", new Class<?>[] { String.class }, new Object[] { DUBBO_GROUP });
    try {
        Thread.sleep(15000);
    } catch (Exception e) {
    // ignore
    }
    String resStr = invoker.invoke(invocation).getValue().toString();
    List<MetricObject> metricObjectList = new Gson().fromJson(resStr, new TypeToken<List<MetricObject>>() {
    }.getType());
    Map<String, Map<String, Object>> methodMetricMap = new HashMap<>();
    for (int i = 0; i < metricObjectList.size(); i++) {
        MetricObject object = metricObjectList.get(i);
        String service = object.getTags().get("service");
        String method = service + "." + object.getTags().get("method");
        String metric = object.getMetric().substring(object.getMetric().lastIndexOf(".") + 1);
        Map map = methodMetricMap.get(method);
        if (map == null) {
            map = new HashMap();
            methodMetricMap.put(method, map);
        }
        map.put(metric, object.getValue());
    }
    Assertions.assertEquals(50.0, methodMetricMap.get("org.apache.dubbo.monitor.dubbo.service.DemoService.void sayName()").get("success_bucket_count"));
    Assertions.assertEquals(50.0, methodMetricMap.get("org.apache.dubbo.monitor.dubbo.service.DemoService.void echo(Integer)").get("success_bucket_count"));
    Assertions.assertEquals(50.0, methodMetricMap.get("org.apache.dubbo.monitor.dubbo.service.DemoService.void sayName()").get("timeoutError_bucket_count"));
    Assertions.assertEquals(50.0, methodMetricMap.get("org.apache.dubbo.monitor.dubbo.service.DemoService.void echo(Integer)").get("timeoutError_bucket_count"));
    Assertions.assertEquals(100.0 / 15, methodMetricMap.get("org.apache.dubbo.monitor.dubbo.service.DemoService.void sayName()").get("qps"));
    Assertions.assertEquals(100.0 / 15, methodMetricMap.get("org.apache.dubbo.monitor.dubbo.service.DemoService.void echo(Integer)").get("qps"));
    Assertions.assertEquals(50.0 / 100.0, methodMetricMap.get("org.apache.dubbo.monitor.dubbo.service.DemoService.void sayName()").get("success_rate"));
    Assertions.assertEquals(50.0 / 100.0, methodMetricMap.get("org.apache.dubbo.monitor.dubbo.service.DemoService.void echo(Integer)").get("success_rate"));
    invoker.destroy();
}
Also used : RpcInvocation(org.apache.dubbo.rpc.RpcInvocation) Invocation(org.apache.dubbo.rpc.Invocation) RpcInvocation(org.apache.dubbo.rpc.RpcInvocation) MetricsService(org.apache.dubbo.monitor.MetricsService) HashMap(java.util.HashMap) DemoService(org.apache.dubbo.monitor.dubbo.service.DemoService) Gson(com.google.gson.Gson) IMetricManager(com.alibaba.metrics.IMetricManager) URL(org.apache.dubbo.common.URL) RpcException(org.apache.dubbo.rpc.RpcException) AppResponse(org.apache.dubbo.rpc.AppResponse) TypeToken(com.google.gson.reflect.TypeToken) RpcException(org.apache.dubbo.rpc.RpcException) Protocol(org.apache.dubbo.rpc.Protocol) DubboProtocol(org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol) MetricObject(com.alibaba.metrics.common.MetricObject) HashMap(java.util.HashMap) Map(java.util.Map)

Example 3 with AppResponse

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

the class InvokeTelnetHandler method telnet.

@Override
@SuppressWarnings("unchecked")
public String telnet(Channel channel, String message) {
    if (StringUtils.isEmpty(message)) {
        return "Please input method name, eg: \r\ninvoke xxxMethod(1234, \"abcd\", {\"prop\" : \"value\"})\r\n" + "invoke XxxService.xxxMethod(1234, \"abcd\", {\"prop\" : \"value\"})\r\n" + "invoke com.xxx.XxxService.xxxMethod(1234, \"abcd\", {\"prop\" : \"value\"})";
    }
    String service = (String) channel.getAttribute(ChangeTelnetHandler.SERVICE_KEY);
    int i = message.indexOf("(");
    if (i < 0 || !message.endsWith(")")) {
        return "Invalid parameters, format: service.method(args)";
    }
    String method = message.substring(0, i).trim();
    String args = message.substring(i + 1, message.length() - 1).trim();
    i = method.lastIndexOf(".");
    if (i >= 0) {
        service = method.substring(0, i).trim();
        method = method.substring(i + 1).trim();
    }
    List<Object> list;
    try {
        list = JSON.parseArray("[" + args + "]", Object.class);
    } catch (Throwable t) {
        return "Invalid json argument, cause: " + t.getMessage();
    }
    StringBuilder buf = new StringBuilder();
    Method invokeMethod = null;
    ProviderModel selectedProvider = null;
    if (isInvokedSelectCommand(channel)) {
        selectedProvider = (ProviderModel) channel.getAttribute(INVOKE_METHOD_PROVIDER_KEY);
        invokeMethod = (Method) channel.getAttribute(SelectTelnetHandler.SELECT_METHOD_KEY);
    } else {
        for (ProviderModel provider : ApplicationModel.allProviderModels()) {
            if (!isServiceMatch(service, provider)) {
                continue;
            }
            selectedProvider = provider;
            List<Method> methodList = findSameSignatureMethod(provider.getAllMethods(), method, list);
            if (CollectionUtils.isEmpty(methodList)) {
                break;
            }
            if (methodList.size() == 1) {
                invokeMethod = methodList.get(0);
            } else {
                List<Method> matchMethods = findMatchMethods(methodList, list);
                if (CollectionUtils.isEmpty(matchMethods)) {
                    break;
                }
                if (matchMethods.size() == 1) {
                    invokeMethod = matchMethods.get(0);
                } else {
                    // exist overridden method
                    channel.setAttribute(INVOKE_METHOD_PROVIDER_KEY, provider);
                    channel.setAttribute(INVOKE_METHOD_LIST_KEY, matchMethods);
                    channel.setAttribute(INVOKE_MESSAGE_KEY, message);
                    printSelectMessage(buf, matchMethods);
                    return buf.toString();
                }
            }
            break;
        }
    }
    if (!StringUtils.isEmpty(service)) {
        buf.append("Use default service ").append(service).append(".");
    }
    if (selectedProvider == null) {
        buf.append("\r\nNo such service ").append(service);
        return buf.toString();
    }
    if (invokeMethod == null) {
        buf.append("\r\nNo such method ").append(method).append(" in service ").append(service);
        return buf.toString();
    }
    try {
        Object[] array = realize(list.toArray(), invokeMethod.getParameterTypes(), invokeMethod.getGenericParameterTypes());
        long start = System.currentTimeMillis();
        AppResponse result = new AppResponse();
        try {
            Object o = invokeMethod.invoke(selectedProvider.getServiceInstance(), array);
            result.setValue(o);
        } catch (Throwable t) {
            result.setException(t);
        }
        long end = System.currentTimeMillis();
        buf.append("\r\nresult: ");
        buf.append(JSON.toJSONString(result.recreate()));
        buf.append("\r\nelapsed: ");
        buf.append(end - start);
        buf.append(" ms.");
    } catch (Throwable t) {
        return "Failed to invoke method " + invokeMethod.getName() + ", cause: " + StringUtils.toString(t);
    }
    return buf.toString();
}
Also used : AppResponse(org.apache.dubbo.rpc.AppResponse) Method(java.lang.reflect.Method) ProviderModel(org.apache.dubbo.rpc.model.ProviderModel)

Example 4 with AppResponse

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

the class ChannelWrappedInvoker method doInvoke.

@Override
protected Result doInvoke(Invocation invocation) throws Throwable {
    RpcInvocation inv = (RpcInvocation) invocation;
    // use interface's name as service path to export if it's not found on client side
    inv.setAttachment(PATH_KEY, getInterface().getName());
    inv.setAttachment(CALLBACK_SERVICE_KEY, serviceKey);
    try {
        if (RpcUtils.isOneway(getUrl(), inv)) {
            // may have concurrency issue
            currentClient.send(inv, getUrl().getMethodParameter(invocation.getMethodName(), SENT_KEY, false));
            return AsyncRpcResult.newDefaultAsyncResult(invocation);
        } else {
            final String methodName = RpcUtils.getMethodName(invocation);
            final int timeout = (int) RpcUtils.getTimeout(getUrl(), methodName, RpcContext.getContext(), DEFAULT_TIMEOUT);
            CompletableFuture<AppResponse> appResponseFuture = currentClient.request(inv, timeout, null).thenApply(obj -> (AppResponse) obj);
            return new AsyncRpcResult(appResponseFuture, inv);
        }
    } catch (RpcException e) {
        throw e;
    } catch (TimeoutException e) {
        throw new RpcException(RpcException.TIMEOUT_EXCEPTION, e.getMessage(), e);
    } catch (RemotingException e) {
        throw new RpcException(RpcException.NETWORK_EXCEPTION, e.getMessage(), e);
    } catch (Throwable e) {
        // here is non-biz exception, wrap it.
        throw new RpcException(e.getMessage(), e);
    }
}
Also used : RpcInvocation(org.apache.dubbo.rpc.RpcInvocation) AppResponse(org.apache.dubbo.rpc.AppResponse) RpcException(org.apache.dubbo.rpc.RpcException) RemotingException(org.apache.dubbo.remoting.RemotingException) AsyncRpcResult(org.apache.dubbo.rpc.AsyncRpcResult) TimeoutException(org.apache.dubbo.remoting.TimeoutException)

Example 5 with AppResponse

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

the class FutureFilterTest method testSyncCallbackHasException.

@Test
public void testSyncCallbackHasException() throws RpcException, Throwable {
    Assertions.assertThrows(RuntimeException.class, () -> {
        @SuppressWarnings("unchecked") Invoker<DemoService> invoker = mock(Invoker.class);
        given(invoker.isAvailable()).willReturn(true);
        given(invoker.getInterface()).willReturn(DemoService.class);
        AppResponse result = new AppResponse();
        result.setException(new RuntimeException());
        given(invoker.invoke(invocation)).willReturn(result);
        URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1&onthrow.method=echo");
        given(invoker.getUrl()).willReturn(url);
        eventFilter.invoke(invoker, invocation).recreate();
    });
}
Also used : AppResponse(org.apache.dubbo.rpc.AppResponse) DemoService(org.apache.dubbo.rpc.protocol.dubbo.support.DemoService) URL(org.apache.dubbo.common.URL) Test(org.junit.jupiter.api.Test)

Aggregations

AppResponse (org.apache.dubbo.rpc.AppResponse)54 Test (org.junit.jupiter.api.Test)37 URL (org.apache.dubbo.common.URL)33 Invocation (org.apache.dubbo.rpc.Invocation)27 Result (org.apache.dubbo.rpc.Result)27 AsyncRpcResult (org.apache.dubbo.rpc.AsyncRpcResult)20 Invoker (org.apache.dubbo.rpc.Invoker)20 RpcInvocation (org.apache.dubbo.rpc.RpcInvocation)20 HashMap (java.util.HashMap)13 RpcException (org.apache.dubbo.rpc.RpcException)12 Method (java.lang.reflect.Method)8 Person (org.apache.dubbo.rpc.support.Person)7 TMessage (org.apache.thrift.protocol.TMessage)6 IMetricManager (com.alibaba.metrics.IMetricManager)5 DemoService (org.apache.dubbo.monitor.dubbo.service.DemoService)5 Request (org.apache.dubbo.remoting.exchange.Request)5 Response (org.apache.dubbo.remoting.exchange.Response)5 DemoService (org.apache.dubbo.rpc.support.DemoService)5 TBinaryProtocol (org.apache.thrift.protocol.TBinaryProtocol)5 TIOStreamTransport (org.apache.thrift.transport.TIOStreamTransport)5