Java Code Examples for com.alibaba.dubbo.rpc.Invocation#getAttachment()

The following examples show how to use com.alibaba.dubbo.rpc.Invocation#getAttachment() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CompensableSecondaryFilter.java    From ByteTCC with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void afterConsumerInvokeForSVC(Invocation invocation, TransactionRequestImpl request,
		TransactionResponseImpl response) {
	CompensableBeanRegistry beanRegistry = CompensableBeanRegistry.getInstance();
	CompensableBeanFactory beanFactory = beanRegistry.getBeanFactory();
	TransactionInterceptor transactionInterceptor = beanFactory.getTransactionInterceptor();

	RemotingException rpcError = null;
	try {
		if (request.getTransactionContext() != null) {
			String transactionContextContent = invocation.getAttachment(TransactionContext.class.getName());
			byte[] byteArray = ByteUtils.stringToByteArray(transactionContextContent);
			ByteArrayInputStream bais = new ByteArrayInputStream(byteArray);
			HessianInput input = new HessianInput(bais);
			TransactionContext remoteTransactionContext = (TransactionContext) input.readObject();
			response.setTransactionContext(remoteTransactionContext);
		}
	} catch (IOException ex) {
		logger.error("Error occurred in remote call!", ex);
		rpcError = new RemotingException(ex.getMessage());
	}

	try {
		transactionInterceptor.afterReceiveResponse(response);
	} catch (RuntimeException rex) {
		logger.error("Error occurred in remote call!", rex);
		throw new RemotingException(rex.getMessage());
	}

	if (rpcError != null) {
		throw rpcError;
	}

}
 
Example 2
Source File: CompensableSecondaryFilter.java    From ByteTCC with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void beforeProviderInvokeForSVC(Invocation invocation, TransactionRequestImpl request,
		TransactionResponseImpl response) {
	CompensableBeanRegistry beanRegistry = CompensableBeanRegistry.getInstance();
	CompensableBeanFactory beanFactory = beanRegistry.getBeanFactory();
	TransactionInterceptor transactionInterceptor = beanFactory.getTransactionInterceptor();

	RemotingException rpcError = null;
	String transactionContextContent = invocation.getAttachment(TransactionContext.class.getName());
	String propagatedBy = invocation.getAttachment(RemoteCoordinator.class.getName());
	if (StringUtils.isNotBlank(transactionContextContent)) {
		byte[] requestByteArray = ByteUtils.stringToByteArray(transactionContextContent);
		ByteArrayInputStream bais = new ByteArrayInputStream(requestByteArray);
		HessianInput input = new HessianInput(bais);
		try {
			TransactionContext remoteTransactionContext = (TransactionContext) input.readObject();
			remoteTransactionContext.setPropagatedBy(propagatedBy);
			request.setTransactionContext(remoteTransactionContext);
		} catch (IOException ex) {
			logger.error("Error occurred in remote call!", ex);
			rpcError = new RemotingException(ex.getMessage());
		}
	}

	try {
		transactionInterceptor.afterReceiveRequest(request);
	} catch (RuntimeException rex) {
		logger.error("Error occurred in remote call!", rex);
		throw new RemotingException(rex.getMessage());
	}

	if (rpcError != null) {
		throw rpcError;
	}

}
 
Example 3
Source File: CompensablePrimaryFilter.java    From ByteTCC with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void afterConsumerInvokeForSVC(Invocation invocation, TransactionRequestImpl request,
		TransactionResponseImpl response) {
	CompensableBeanRegistry beanRegistry = CompensableBeanRegistry.getInstance();
	CompensableBeanFactory beanFactory = beanRegistry.getBeanFactory();
	TransactionInterceptor transactionInterceptor = beanFactory.getTransactionInterceptor();

	RemotingException rpcError = null;
	try {
		if (request.getTransactionContext() != null) {
			String transactionContextContent = invocation.getAttachment(TransactionContext.class.getName());
			byte[] byteArray = ByteUtils.stringToByteArray(transactionContextContent);
			ByteArrayInputStream bais = new ByteArrayInputStream(byteArray);
			HessianInput input = new HessianInput(bais);
			TransactionContext remoteTransactionContext = (TransactionContext) input.readObject();
			response.setTransactionContext(remoteTransactionContext);
		}
	} catch (IOException ex) {
		logger.error("Error occurred in remote call!", ex);
		rpcError = new RemotingException(ex.getMessage());
	}

	try {
		transactionInterceptor.afterReceiveResponse(response);
	} catch (RuntimeException rex) {
		logger.error("Error occurred in remote call!", rex);
		throw new RemotingException(rex.getMessage());
	}

	if (rpcError != null) {
		throw rpcError;
	}

}
 
Example 4
Source File: DubboSofaTracerFilter.java    From sofa-tracer with Apache License 2.0 5 votes vote down vote up
/**
 * append tag
 * @param invocation
 * @param sofaTracerSpan
 * @param result
 * @param isClient
 */
private static void appendElapsedTimeTags(Invocation invocation, SofaTracerSpan sofaTracerSpan,
                                          Result result, boolean isClient) {
    if (sofaTracerSpan == null) {
        return;
    }
    String reqSize;
    String respSize;
    String elapsed;
    String deElapsed;
    if (isClient) {
        reqSize = invocation.getAttachment(AttachmentKeyConstants.CLIENT_SERIALIZE_SIZE);
        elapsed = invocation.getAttachment(AttachmentKeyConstants.CLIENT_SERIALIZE_TIME);
        respSize = result.getAttachment(AttachmentKeyConstants.CLIENT_DESERIALIZE_SIZE);
        deElapsed = result.getAttachment(AttachmentKeyConstants.CLIENT_DESERIALIZE_TIME);
        sofaTracerSpan.setTag(AttachmentKeyConstants.CLIENT_SERIALIZE_TIME,
            parseAttachment(elapsed, 0));
        sofaTracerSpan.setTag(AttachmentKeyConstants.CLIENT_DESERIALIZE_TIME,
            parseAttachment(deElapsed, 0));
        sofaTracerSpan.setTag(AttachmentKeyConstants.CLIENT_SERIALIZE_SIZE,
            parseAttachment(reqSize, 0));
        sofaTracerSpan.setTag(AttachmentKeyConstants.CLIENT_DESERIALIZE_SIZE,
            parseAttachment(respSize, 0));
    } else {
        reqSize = invocation.getAttachment(AttachmentKeyConstants.SERVER_DESERIALIZE_SIZE);
        deElapsed = invocation.getAttachment(AttachmentKeyConstants.SERVER_DESERIALIZE_TIME);
        respSize = result.getAttachment(AttachmentKeyConstants.SERVER_SERIALIZE_SIZE);
        elapsed = result.getAttachment(AttachmentKeyConstants.SERVER_SERIALIZE_TIME);
        sofaTracerSpan.setTag(AttachmentKeyConstants.SERVER_DESERIALIZE_SIZE,
            parseAttachment(reqSize, 0));
        sofaTracerSpan.setTag(AttachmentKeyConstants.SERVER_DESERIALIZE_TIME,
            parseAttachment(deElapsed, 0));
        sofaTracerSpan.setTag(AttachmentKeyConstants.SERVER_SERIALIZE_SIZE,
            parseAttachment(respSize, 0));
        sofaTracerSpan.setTag(AttachmentKeyConstants.SERVER_SERIALIZE_TIME,
            parseAttachment(elapsed, 0));
    }

}
 
Example 5
Source File: CompensablePrimaryFilter.java    From ByteTCC with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void beforeProviderInvokeForSVC(Invocation invocation, TransactionRequestImpl request,
		TransactionResponseImpl response) {
	CompensableBeanRegistry beanRegistry = CompensableBeanRegistry.getInstance();
	CompensableBeanFactory beanFactory = beanRegistry.getBeanFactory();
	TransactionInterceptor transactionInterceptor = beanFactory.getTransactionInterceptor();

	RemotingException rpcError = null;
	String transactionContextContent = invocation.getAttachment(TransactionContext.class.getName());
	String propagatedBy = invocation.getAttachment(RemoteCoordinator.class.getName());
	if (StringUtils.isNotBlank(transactionContextContent)) {
		byte[] requestByteArray = ByteUtils.stringToByteArray(transactionContextContent);
		ByteArrayInputStream bais = new ByteArrayInputStream(requestByteArray);
		HessianInput input = new HessianInput(bais);
		try {
			TransactionContext remoteTransactionContext = (TransactionContext) input.readObject();
			remoteTransactionContext.setPropagatedBy(propagatedBy);
			request.setTransactionContext(remoteTransactionContext);
		} catch (IOException ex) {
			logger.error("Error occurred in remote call!", ex);
			rpcError = new RemotingException(ex.getMessage());
		}
	}

	try {
		transactionInterceptor.afterReceiveRequest(request);
	} catch (RuntimeException rex) {
		logger.error("Error occurred in remote call!", rex);
		throw new RemotingException(rex.getMessage());
	}

	if (rpcError != null) {
		throw rpcError;
	}

}
 
Example 6
Source File: FlowControlFilter.java    From dubbo-ext with Apache License 2.0 5 votes vote down vote up
/**
 * 根据调用信息统计后端服务状态,定时清除计数器
 */
public void run() {
    while (!Thread.interrupted()) {
        try {
            Thread.sleep(timerPeroid);
            Invocation rpc = rpcs.poll();
            long now = System.currentTimeMillis();
            resetIfExpired(now);
            if (rpc == null)
                continue;
            String endStr = rpc.getAttachment("end");
            boolean hasReturn = (endStr != null);
            long end = hasReturn ? now : Long.valueOf(endStr);
            long start = Long.valueOf(rpc.getAttachment("start"));
            ServerStatus status = statusMap.get(rpc.getAttachment("addr"));
            if ((end - start) > recordRespThreshold) {
                status.slowRespCount.getAndIncrement();
            } else if (hasReturn) {
                /* 没有返回,也没有超时,则重新放到队列 */
                rpcs.add(rpc);
            }
            if (rpc.getAttachments().containsKey("hasError")) {
                status.failCount.getAndIncrement();
            }
            modifyMaxRequest(status);
        } catch (Exception e) {
            logger.error("FlowControl-Timer error", e);
        }
    }
}
 
Example 7
Source File: RouterConsumerFilter.java    From dubbox with Apache License 2.0 5 votes vote down vote up
/**
 * 消费端
 */
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
	try {
		// 接收到调用的时候以传入的为准
		RouterInfo ri = RouterContext.get(RouterConsts.ROUTER_KEY);
		if (ri != null && Scope.REMOTE.equals(ri.getScope())
				&& invocation.getAttachment(RouterConsts.ROUTER_KEY) == null) {
			// 如果路由信息不为空,且作用域为remote,则执行并传递该路由
			invocation.getAttachments().put(RouterConsts.ROUTER_KEY, ri.toString());
		}

		Result result = invoker.invoke(invocation);

		// Map<String, String> attachments = result.getAttachments();
		// 如果远端返回的结果中包含了路由信息,则本地保存。
		// 这里判断,如果调用的远端服务中包含了路由信息 ,则后续的远端请求和本地SQL执行都会依照该路由信息执行 。
		// if (attachments.containsKey(RouterConsts.ROUTER_KEY)) {
		//
		// // 写入上下文
		// if (sqlrouter == null) {
		// RouterContext.put(RouterConsts.ROUTER_KEY,
		// attachments.get(RouterConsts.ROUTER_KEY));
		// }
		// }

		return result;
	} catch (RuntimeException e) {
		logger.error("Got unchecked and undeclared exception which called by "
				+ RpcContext.getContext().getRemoteHost() + ". service: " + invoker.getInterface().getName()
				+ ", method: " + invocation.getMethodName() + ", exception: " + e.getClass().getName() + ": "
				+ e.getMessage(), e);
		throw e;
	} finally {
		// 如果当前span是最前端(当前span没有提供者表明当前位置处在最前端消费者)则清理路由上下文
		// if (!isprovider()) {
		// // RouterContext.cleanup();
		// }
	}
}
 
Example 8
Source File: RpcUtils.java    From dubbox-hystrix with Apache License 2.0 4 votes vote down vote up
public static Long getInvocationId(Invocation inv) {
   	String id = inv.getAttachment(Constants.ID_KEY);
	return id == null ? null : new Long(id);
}
 
Example 9
Source File: MonitorFilter.java    From dubbox with Apache License 2.0 4 votes vote down vote up
private void collect(Invoker<?> invoker, Invocation invocation, Result result, RpcContext context, long start, boolean error) {
    try {
        // ---- 服务信息获取 ----
        long elapsed = System.currentTimeMillis() - start; // 计算调用耗时
        int concurrent = getConcurrent(invoker, invocation).get(); // 当前并发数
        String application = invoker.getUrl().getParameter(Constants.APPLICATION_KEY);
        String service = invoker.getInterface().getName(); // 获取服务名称
        String method = RpcUtils.getMethodName(invocation); // 获取方法名
        URL url = invoker.getUrl().getUrlParameter(Constants.MONITOR_KEY);
        Monitor monitor = monitorFactory.getMonitor(url);
        int localPort;
        String remoteKey;
        String remoteValue;
        if (Constants.CONSUMER_SIDE.equals(invoker.getUrl().getParameter(Constants.SIDE_KEY))) {
            // ---- 服务消费方监控 ----
            context = RpcContext.getContext(); // 消费方必须在invoke()之后获取context信息
            localPort = 0;
            remoteKey = MonitorService.PROVIDER;
            remoteValue = invoker.getUrl().getAddress();
        } else {
            // ---- 服务提供方监控 ----
            localPort = invoker.getUrl().getPort();
            remoteKey = MonitorService.CONSUMER;
            remoteValue = context.getRemoteHost();
        }
        String input = "", output = "";
        if (invocation.getAttachment(Constants.INPUT_KEY) != null) {
            input = invocation.getAttachment(Constants.INPUT_KEY);
        }
        if (result != null && result.getAttachment(Constants.OUTPUT_KEY) != null) {
            output = result.getAttachment(Constants.OUTPUT_KEY);
        }
        monitor.collect(new URL(Constants.COUNT_PROTOCOL,
                            NetUtils.getLocalHost(), localPort,
                            service + "/" + method,
                            MonitorService.APPLICATION, application,
                            MonitorService.INTERFACE, service,
                            MonitorService.METHOD, method,
                            remoteKey, remoteValue,
                            error ? MonitorService.FAILURE : MonitorService.SUCCESS, "1",
                            MonitorService.ELAPSED, String.valueOf(elapsed),
                            MonitorService.CONCURRENT, String.valueOf(concurrent),
                            Constants.INPUT_KEY, input,
                            Constants.OUTPUT_KEY, output));
    } catch (Throwable t) {
        logger.error("Failed to monitor count service " + invoker.getUrl() + ", cause: " + t.getMessage(), t);
    }
}
 
Example 10
Source File: RpcUtils.java    From dubbox with Apache License 2.0 4 votes vote down vote up
public static Long getInvocationId(Invocation inv) {
   	String id = inv.getAttachment(Constants.ID_KEY);
	return id == null ? null : new Long(id);
}
 
Example 11
Source File: RpcUtils.java    From dubbo3 with Apache License 2.0 4 votes vote down vote up
public static Long getInvocationId(Invocation inv) {
    String id = inv.getAttachment(Constants.ID_KEY);
    return id == null ? null : new Long(id);
}
 
Example 12
Source File: MonitorFilter.java    From dubbox-hystrix with Apache License 2.0 4 votes vote down vote up
private void collect(Invoker<?> invoker, Invocation invocation, Result result, RpcContext context, long start, boolean error) {
    try {
        // ---- 服务信息获取 ----
        long elapsed = System.currentTimeMillis() - start; // 计算调用耗时
        int concurrent = getConcurrent(invoker, invocation).get(); // 当前并发数
        String application = invoker.getUrl().getParameter(Constants.APPLICATION_KEY);
        String service = invoker.getInterface().getName(); // 获取服务名称
        String method = RpcUtils.getMethodName(invocation); // 获取方法名
        URL url = invoker.getUrl().getUrlParameter(Constants.MONITOR_KEY);
        Monitor monitor = monitorFactory.getMonitor(url);
        int localPort;
        String remoteKey;
        String remoteValue;
        if (Constants.CONSUMER_SIDE.equals(invoker.getUrl().getParameter(Constants.SIDE_KEY))) {
            // ---- 服务消费方监控 ----
            context = RpcContext.getContext(); // 消费方必须在invoke()之后获取context信息
            localPort = 0;
            remoteKey = MonitorService.PROVIDER;
            remoteValue = invoker.getUrl().getAddress();
        } else {
            // ---- 服务提供方监控 ----
            localPort = invoker.getUrl().getPort();
            remoteKey = MonitorService.CONSUMER;
            remoteValue = context.getRemoteHost();
        }
        String input = "", output = "";
        if (invocation.getAttachment(Constants.INPUT_KEY) != null) {
            input = invocation.getAttachment(Constants.INPUT_KEY);
        }
        if (result != null && result.getAttachment(Constants.OUTPUT_KEY) != null) {
            output = result.getAttachment(Constants.OUTPUT_KEY);
        }
        monitor.collect(new URL(Constants.COUNT_PROTOCOL,
                            NetUtils.getLocalHost(), localPort,
                            service + "/" + method,
                            MonitorService.APPLICATION, application,
                            MonitorService.INTERFACE, service,
                            MonitorService.METHOD, method,
                            remoteKey, remoteValue,
                            error ? MonitorService.FAILURE : MonitorService.SUCCESS, "1",
                            MonitorService.ELAPSED, String.valueOf(elapsed),
                            MonitorService.CONCURRENT, String.valueOf(concurrent),
                            Constants.INPUT_KEY, input,
                            Constants.OUTPUT_KEY, output));
    } catch (Throwable t) {
        logger.error("Failed to monitor count service " + invoker.getUrl() + ", cause: " + t.getMessage(), t);
    }
}
 
Example 13
Source File: RpcUtils.java    From dubbo-2.6.5 with Apache License 2.0 4 votes vote down vote up
public static Long getInvocationId(Invocation inv) {
    String id = inv.getAttachment(Constants.ID_KEY);
    return id == null ? null : new Long(id);
}
 
Example 14
Source File: MonitorFilter.java    From dubbox with Apache License 2.0 4 votes vote down vote up
private void collect(Invoker<?> invoker, Invocation invocation, Result result, RpcContext context, long start, boolean error) {
    try {
        // ---- 服务信息获取 ----
        long elapsed = System.currentTimeMillis() - start; // 计算调用耗时
        int concurrent = getConcurrent(invoker, invocation).get(); // 当前并发数
        String application = invoker.getUrl().getParameter(Constants.APPLICATION_KEY);
        String service = invoker.getInterface().getName(); // 获取服务名称
        String method = RpcUtils.getMethodName(invocation); // 获取方法名
        URL url = invoker.getUrl().getUrlParameter(Constants.MONITOR_KEY);
        Monitor monitor = monitorFactory.getMonitor(url);
        int localPort;
        String remoteKey;
        String remoteValue;
        if (Constants.CONSUMER_SIDE.equals(invoker.getUrl().getParameter(Constants.SIDE_KEY))) {
            // ---- 服务消费方监控 ----
            context = RpcContext.getContext(); // 消费方必须在invoke()之后获取context信息
            localPort = 0;
            remoteKey = MonitorService.PROVIDER;
            remoteValue = invoker.getUrl().getAddress();
        } else {
            // ---- 服务提供方监控 ----
            localPort = invoker.getUrl().getPort();
            remoteKey = MonitorService.CONSUMER;
            remoteValue = context.getRemoteHost();
        }
        String input = "", output = "";
        if (invocation.getAttachment(Constants.INPUT_KEY) != null) {
            input = invocation.getAttachment(Constants.INPUT_KEY);
        }
        if (result != null && result.getAttachment(Constants.OUTPUT_KEY) != null) {
            output = result.getAttachment(Constants.OUTPUT_KEY);
        }
        monitor.collect(new URL(Constants.COUNT_PROTOCOL,
                            NetUtils.getLocalHost(), localPort,
                            service + "/" + method,
                            MonitorService.APPLICATION, application,
                            MonitorService.INTERFACE, service,
                            MonitorService.METHOD, method,
                            remoteKey, remoteValue,
                            error ? MonitorService.FAILURE : MonitorService.SUCCESS, "1",
                            MonitorService.ELAPSED, String.valueOf(elapsed),
                            MonitorService.CONCURRENT, String.valueOf(concurrent),
                            Constants.INPUT_KEY, input,
                            Constants.OUTPUT_KEY, output));
    } catch (Throwable t) {
        logger.error("Failed to monitor count service " + invoker.getUrl() + ", cause: " + t.getMessage(), t);
    }
}
 
Example 15
Source File: CicadaDubboFilter.java    From cicada with MIT License 4 votes vote down vote up
@SuppressWarnings({"PMD.OnlyOneReturn", "PMD.OnlyOneReturn"})
public Result invoke(final Invoker<?> invoker, final Invocation invocation) throws RpcException {
  if (tracer == null) {
    return invoker.invoke(invocation);
  }
  final long startTime = System.currentTimeMillis();
  final RpcContext context = RpcContext.getContext();

  // 传入参数,暂不做处理
  // Object[] arguments = context.getArguments();
  // for (Object argument : arguments) {
  // LOGGER.error("arg:" + argument);
  // }

  final String localIp = IpUtils.getRealIpWithStaticCache();
  final int localPort = context.getLocalPort();
  final Endpoint endpoint = new Endpoint(localIp, localPort);

  final URL url = context.getUrl();
  final String appName = url.getParameter("application");
  final String serviceName = url.getServiceInterface();
  final String methodName = context.getMethodName();

  final boolean isConsumerSide = context.isConsumerSide();
  Span span = null;
  try {
    if (isConsumerSide) { // 是否是消费者
      final Span parentSpan = tracer.getParentSpan();
      if (parentSpan == null) { // 为rootSpan
        // 生成root Span
        span = tracer.newSpan(appName, serviceName, methodName);
      } else {
        span = tracer.newSpan(appName, serviceName, methodName, parentSpan);
      }
    } else if (context.isProviderSide()) {
      final String traceId = invocation.getAttachment(TracerUtils.TRACE_ID);
      final String parentId = invocation.getAttachment(TracerUtils.PARENT_SPAN_ID);
      final String spanId = invocation.getAttachment(TracerUtils.SPAN_ID);
      final boolean sample = traceId != null;
      span = tracer.genSpan(appName, serviceName, methodName, traceId, parentId, spanId, sample);
    } else {
      LOGGER.error("[" + url + "] [notConsumerNorProvider]");
      return invoker.invoke(invocation);
    }

    invokerBefore(invocation, span, endpoint, startTime);
    final Result result = invoker.invoke(invocation);
    final Throwable throwable = result.getException();
    if (throwable != null && !isConsumerSide) {
      span.addException(serviceName, methodName, throwable, endpoint);
    }

    // 返回值
    // Object resultValue = result.getValue();
    // LOGGER.error("return:" + JSON.toJSONString(resultValue));
    return result;
  } catch (final RpcException ex) {
    if (span != null) {
      span.addException(serviceName, methodName, ex, endpoint);
    }
    throw ex;
  } finally {
    if (span != null) {
      final long end = System.currentTimeMillis();
      invokerAfter(endpoint, span, end, isConsumerSide);// 调用后记录annotation
    }
  }
}
 
Example 16
Source File: RpcUtils.java    From dubbox with Apache License 2.0 4 votes vote down vote up
public static Long getInvocationId(Invocation inv) {
   	String id = inv.getAttachment(Constants.ID_KEY);
	return id == null ? null : new Long(id);
}
 
Example 17
Source File: DubboUtils.java    From Sentinel with Apache License 2.0 4 votes vote down vote up
public static String getApplication(Invocation invocation, String defaultValue) {
    if (invocation == null || invocation.getAttachments() == null) {
        throw new IllegalArgumentException("Bad invocation instance");
    }
    return invocation.getAttachment(DUBBO_APPLICATION_KEY, defaultValue);
}
 
Example 18
Source File: AlibabaDubboAttachmentHelperImpl.java    From apm-agent-java with Apache License 2.0 4 votes vote down vote up
@Nullable
@Override
public String getFirstHeader(String headerName, Invocation invocation) {
    return invocation.getAttachment(headerName);
}
 
Example 19
Source File: MonitorFilter.java    From dubbox with Apache License 2.0 4 votes vote down vote up
private void collect(Invoker<?> invoker, Invocation invocation, Result result, RpcContext context, long start, boolean error) {
    try {
        // ---- 服务信息获取 ----
        long elapsed = System.currentTimeMillis() - start; // 计算调用耗时
        int concurrent = getConcurrent(invoker, invocation).get(); // 当前并发数
        String application = invoker.getUrl().getParameter(Constants.APPLICATION_KEY);
        String service = invoker.getInterface().getName(); // 获取服务名称
        String method = RpcUtils.getMethodName(invocation); // 获取方法名
        URL url = invoker.getUrl().getUrlParameter(Constants.MONITOR_KEY);
        Monitor monitor = monitorFactory.getMonitor(url);
        int localPort;
        String remoteKey;
        String remoteValue;
        if (Constants.CONSUMER_SIDE.equals(invoker.getUrl().getParameter(Constants.SIDE_KEY))) {
            // ---- 服务消费方监控 ----
            context = RpcContext.getContext(); // 消费方必须在invoke()之后获取context信息
            localPort = 0;
            remoteKey = MonitorService.PROVIDER;
            remoteValue = invoker.getUrl().getAddress();
        } else {
            // ---- 服务提供方监控 ----
            localPort = invoker.getUrl().getPort();
            remoteKey = MonitorService.CONSUMER;
            remoteValue = context.getRemoteHost();
        }
        String input = "", output = "";
        if (invocation.getAttachment(Constants.INPUT_KEY) != null) {
            input = invocation.getAttachment(Constants.INPUT_KEY);
        }
        if (result != null && result.getAttachment(Constants.OUTPUT_KEY) != null) {
            output = result.getAttachment(Constants.OUTPUT_KEY);
        }
        monitor.collect(new URL(Constants.COUNT_PROTOCOL,
                            NetUtils.getLocalHost(), localPort,
                            service + "/" + method,
                            MonitorService.APPLICATION, application,
                            MonitorService.INTERFACE, service,
                            MonitorService.METHOD, method,
                            remoteKey, remoteValue,
                            error ? MonitorService.FAILURE : MonitorService.SUCCESS, "1",
                            MonitorService.ELAPSED, String.valueOf(elapsed),
                            MonitorService.CONCURRENT, String.valueOf(concurrent),
                            Constants.INPUT_KEY, input,
                            Constants.OUTPUT_KEY, output));
    } catch (Throwable t) {
        logger.error("Failed to monitor count service " + invoker.getUrl() + ", cause: " + t.getMessage(), t);
    }
}
 
Example 20
Source File: MonitorFilter.java    From dubbo-2.6.5 with Apache License 2.0 4 votes vote down vote up
private void collect(Invoker<?> invoker, Invocation invocation, Result result, String remoteHost, long start, boolean error) {
    try {
        // ---- service statistics ----
        long elapsed = System.currentTimeMillis() - start; // invocation cost
        int concurrent = getConcurrent(invoker, invocation).get(); // current concurrent count
        String application = invoker.getUrl().getParameter(Constants.APPLICATION_KEY);
        String service = invoker.getInterface().getName(); // service name
        String method = RpcUtils.getMethodName(invocation); // method name
        String group = invoker.getUrl().getParameter(Constants.GROUP_KEY);
        String version = invoker.getUrl().getParameter(Constants.VERSION_KEY);
        URL url = invoker.getUrl().getUrlParameter(Constants.MONITOR_KEY);
        Monitor monitor = monitorFactory.getMonitor(url);
        if (monitor == null) {
            return;
        }
        int localPort;
        String remoteKey;
        String remoteValue;
        if (Constants.CONSUMER_SIDE.equals(invoker.getUrl().getParameter(Constants.SIDE_KEY))) {
            // ---- for service consumer ----
            localPort = 0;
            remoteKey = MonitorService.PROVIDER;
            remoteValue = invoker.getUrl().getAddress();
        } else {
            // ---- for service provider ----
            localPort = invoker.getUrl().getPort();
            remoteKey = MonitorService.CONSUMER;
            remoteValue = remoteHost;
        }
        String input = "", output = "";
        if (invocation.getAttachment(Constants.INPUT_KEY) != null) {
            input = invocation.getAttachment(Constants.INPUT_KEY);
        }
        if (result != null && result.getAttachment(Constants.OUTPUT_KEY) != null) {
            output = result.getAttachment(Constants.OUTPUT_KEY);
        }
        monitor.collect(new URL(Constants.COUNT_PROTOCOL,
                NetUtils.getLocalHost(), localPort,
                service + "/" + method,
                MonitorService.APPLICATION, application,
                MonitorService.INTERFACE, service,
                MonitorService.METHOD, method,
                remoteKey, remoteValue,
                error ? MonitorService.FAILURE : MonitorService.SUCCESS, "1",
                MonitorService.ELAPSED, String.valueOf(elapsed),
                MonitorService.CONCURRENT, String.valueOf(concurrent),
                Constants.INPUT_KEY, input,
                Constants.OUTPUT_KEY, output,
                Constants.GROUP_KEY, group,
                Constants.VERSION_KEY, version));
    } catch (Throwable t) {
        logger.error("Failed to monitor count service " + invoker.getUrl() + ", cause: " + t.getMessage(), t);
    }
}