Java Code Examples for com.dianping.cat.message.Transaction#complete()

The following examples show how to use com.dianping.cat.message.Transaction#complete() . 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: SimpleTest.java    From x-pipe with Apache License 2.0 6 votes vote down vote up
@Test
public void testCat() throws IOException {

	Transaction t1 = Cat.newTransaction("type1", "name1");
	Transaction t21 = Cat.newTransaction("type21", "name2");
	Transaction t31 = Cat.newTransaction("type31", "name3");
	t31.setStatus(Transaction.SUCCESS);
	t31.complete();
	t21.setStatus(Transaction.SUCCESS);
	t21.complete();

	Transaction t22 = Cat.newTransaction("type22", "name2");
	t22.setStatus(Transaction.SUCCESS);
	t22.complete();
	t1.setStatus(Transaction.SUCCESS);
	t1.complete();

	waitForAnyKeyToExit();
}
 
Example 2
Source File: CatFilter.java    From Zebra with Apache License 2.0 6 votes vote down vote up
@Override
public void switchFailOverDataSource(FailOverDataSource source, JdbcFilter chain) {
	Transaction t = Cat.newTransaction(CAT_TYPE, "FailOver");
	try {
		chain.switchFailOverDataSource(source, chain);
		Cat.logEvent("Zebra.FailOver", "Success");
		t.setStatus(Message.SUCCESS);
	} catch (RuntimeException exp) {
		Cat.logEvent("Zebra.FailOver", "Failed");
		Cat.logError(exp);
		t.setStatus("Fail to find any master database");
		throw exp;
	} finally {
		t.complete();
	}
}
 
Example 3
Source File: CatFilter.java    From Zebra with Apache License 2.0 6 votes vote down vote up
@Override
public SingleConnection getSingleConnection(SingleDataSource source, JdbcFilter chain) throws SQLException {
	Transaction t = null;
	try {
		t = Cat.newTransaction("SQL.Conn", source.getConfig().getId());
		SingleConnection conn = chain.getSingleConnection(source, chain);
		t.setStatus(Transaction.SUCCESS);
		return conn;
	} catch (SQLException exp) {
		Transaction sqlTransaction = Cat.newTransaction("SQL", DaoContextHolder.getSqlName());
		try {
			Cat.logEvent("SQL.Database", source.getConfig().getJdbcUrl(), "ERROR", source.getConfig().getId());
			Cat.logError(exp);
			sqlTransaction.setStatus(exp);
		} finally {
			sqlTransaction.complete();
		}
		throw exp;
	} finally {
		if (t != null) {
			t.complete();
		}
	}
}
 
Example 4
Source File: CatUtil.java    From hermes with Apache License 2.0 6 votes vote down vote up
public static void logElapse(String type, String name, long startTimestamp, int count,
      List<Pair<String, String>> datas, String status) {
	if (count > 0) {
		Transaction latencyT = Cat.newTransaction(type, name);
		long delta = System.currentTimeMillis() - startTimestamp;

		if (latencyT instanceof DefaultTransaction) {
			((DefaultTransaction) latencyT).setDurationStart(System.nanoTime() - delta * 1000000L);
		}
		latencyT.addData("*count", count);
		if (datas != null && !datas.isEmpty()) {
			for (Pair<String, String> data : datas) {
				latencyT.addData(data.getKey(), data.getValue());
			}
		}
		latencyT.setStatus(status);
		latencyT.complete();
	}
}
 
Example 5
Source File: CatFilter.java    From Zebra with Apache License 2.0 6 votes vote down vote up
@Override
public void initShardDataSource(com.dianping.zebra.shard.jdbc.ShardDataSource source, JdbcFilter chain) {
	String ruleName = source.getRuleName();
	if (StringUtils.isBlank(ruleName)) {
		ruleName = "localMode";
	}

	Transaction transaction = Cat.newTransaction(CAT_TYPE, "ShardDataSource.Init-" + ruleName);

	try {
		chain.initShardDataSource(source, chain);
		transaction.setStatus(Message.SUCCESS);
	} catch (RuntimeException e) {
		Cat.logError(e);
		transaction.setStatus(e);
		throw e;
	} finally {
		transaction.complete();
	}
}
 
Example 6
Source File: CatFilter.java    From Zebra with Apache License 2.0 6 votes vote down vote up
@Override
public int executeShardUpdate(ShardStatement source, String sql, int autoGeneratedKeys, int[] columnIndexes,
      String[] columnNames, JdbcFilter chain) throws SQLException {
	SqlAliasManager.setSqlAlias(sql);
	Transaction t = Cat.newTransaction(SHARD_CAT_TYPE, SqlAliasManager.getSqlAlias());
	int result;
	try {
		result = chain.executeShardUpdate(source, sql, autoGeneratedKeys, columnIndexes, columnNames, chain);
		t.setStatus(Message.SUCCESS);
	} catch (Throwable exp) {
		Cat.logError(exp);
		t.setStatus(exp);
		throw new SQLException(exp);
	} finally {
		t.complete();
	}
	return result;
}
 
Example 7
Source File: CatTransactionMonitor.java    From x-pipe with Apache License 2.0 5 votes vote down vote up
@Override
public void logTransaction(String type, String name, Task task) throws Exception {

	Transaction transaction = Cat.newTransaction(type, name);
	try{
		task.go();
		transaction.setStatus(Transaction.SUCCESS);
	}catch(Exception th){
		transaction.setStatus(th);
		throw th;
	}finally{
		transaction.complete();
	}
}
 
Example 8
Source File: BrokerMessageSender.java    From hermes with Apache License 2.0 5 votes vote down vote up
private SendMessageCommandV6 createSendMessageCommand(int size) {
	long maxMsgSelectorOffset = Long.MIN_VALUE;
	SendMessageCommandV6 cmd = null;
	List<ProducerWorkerContext> contexts = new ArrayList<ProducerWorkerContext>(size);
	m_queue.drainTo(contexts, size);
	if (!contexts.isEmpty()) {
		cmd = new SendMessageCommandV6(m_topic, m_partition, m_config.getBrokerSenderResultTimeoutMillis());
		for (ProducerWorkerContext context : contexts) {
			int produceTimeoutSeconds = m_config.getProduceTimeoutSeconds(m_topic);

			if (produceTimeoutSeconds > 0
			      && System.currentTimeMillis() - context.m_msg.getBornTime() > produceTimeoutSeconds * 1000) {
				MessageSendException exception = new MessageSendException("Send timeout.", context.m_msg);
				notifySendFail(context.m_future, exception);

				Transaction t = Cat.newTransaction(CatConstants.TYPE_MESSAGE_PRODUCE_TIMEOUT, m_topic);
				t.setStatus(Transaction.SUCCESS);
				t.complete();
			} else {
				cmd.addMessage(context.m_msg, context.m_future);
			}
			maxMsgSelectorOffset = Math.max(maxMsgSelectorOffset, context.m_msg.getSelectorOffset());
		}
		cmd.setSelectorOffset(maxMsgSelectorOffset);
		cmd.setTargetIdc(getTargetIdc().toLowerCase());
	}
	return cmd;
}
 
Example 9
Source File: ZuulCallable.java    From s2g-zuul with MIT License 5 votes vote down vote up
/**
 * executes "pre" filters
 *
 * @throws ZuulException
 */
private void preRoute() throws ZuulException {
	Transaction tran = Cat.getProducer().newTransaction("ZuulCallable", "preRoute");
	try {
		zuulRunner.preRoute();
		tran.setStatus(Transaction.SUCCESS);
	} catch (Throwable e) {
		tran.setStatus(e);
		throw e;
	} finally {
		tran.complete();
	}
}
 
Example 10
Source File: ZuulCallable.java    From s2g-zuul with MIT License 5 votes vote down vote up
/**
 * executes "route" filters
 *
 * @throws ZuulException
 */
private void route() throws ZuulException {
	Transaction tran = Cat.getProducer().newTransaction("ZuulCallable", "route");
	try {
		zuulRunner.route();
		tran.setStatus(Transaction.SUCCESS);
	} catch (Throwable e) {
		tran.setStatus(e);
		throw e;
	} finally {
		tran.complete();
	}
}
 
Example 11
Source File: CatTransactionMonitor.java    From x-pipe with Apache License 2.0 5 votes vote down vote up
@Override
public void logTransactionSwallowException(String type, String name, Task task) {
	
	Transaction transaction = Cat.newTransaction(type, name);
	try{
		task.go();
		transaction.setStatus(Transaction.SUCCESS);
	}catch(Throwable th){
		transaction.setStatus(th);
		logger.error("[logTransaction]" + type + "," + name + "," + task, th);
	}finally{
		transaction.complete();
	}
}
 
Example 12
Source File: CatServletFilter.java    From s2g-zuul with MIT License 5 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) servletRequest;

    String url = request.getRequestURL().toString();
    for (String urlPattern : urlPatterns) {
        if (url.startsWith(urlPattern)) {
            url = urlPattern;
        }
    }

   Transaction t = Cat.newTransaction("Service", url);

    try {

        PropertyContext propertyContext = new PropertyContext();
        propertyContext.addProperty(Cat.Context.ROOT, request.getHeader(Constants.CAT_ROOT_MESSAGE_ID));
        propertyContext.addProperty(Cat.Context.PARENT, request.getHeader(Constants.CAT_PARENT_MESSAGE_ID));
        propertyContext.addProperty(Cat.Context.CHILD, request.getHeader(Constants.CAT_CHILD_MESSAGE_ID));
        Cat.logRemoteCallServer(propertyContext);

        Cat.logEvent("Service.method", request.getMethod(), Message.SUCCESS, request.getRequestURL().toString());
        Cat.logEvent("Service.client", request.getRemoteHost());

        filterChain.doFilter(servletRequest, servletResponse);

        t.setStatus(Transaction.SUCCESS);
    } catch (Exception ex) {
        t.setStatus(ex);
        Cat.logError(ex);
        throw ex;
    } finally {
        t.complete();
    }
}
 
Example 13
Source File: CatServletFilter.java    From piggymetrics with MIT License 5 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) servletRequest;

    String url = request.getRequestURL().toString();
    for (String urlPattern : urlPatterns) {
        if (url.startsWith(urlPattern)) {
            url = urlPattern;
        }
    }

    CatContext catContext = new CatContext();
    catContext.addProperty(Cat.Context.ROOT, request.getHeader(CatHttpConstants.CAT_HTTP_HEADER_ROOT_MESSAGE_ID));
    catContext.addProperty(Cat.Context.PARENT, request.getHeader(CatHttpConstants.CAT_HTTP_HEADER_PARENT_MESSAGE_ID));
    catContext.addProperty(Cat.Context.CHILD, request.getHeader(CatHttpConstants.CAT_HTTP_HEADER_CHILD_MESSAGE_ID));
    Cat.logRemoteCallServer(catContext);
    
    Transaction t = Cat.newTransaction("Service", url);

    try {

        Cat.logEvent("Service.method", request.getMethod(), Message.SUCCESS, request.getRequestURL().toString());
        Cat.logEvent("Service.client", request.getRemoteHost());

        filterChain.doFilter(servletRequest, servletResponse);

        t.setStatus(Transaction.SUCCESS);
    } catch (Exception ex) {
        t.setStatus(ex);
        Cat.logError(ex);
        throw ex;
    } finally {
        t.complete();
    }
}
 
Example 14
Source File: CatRestInterceptor.java    From piggymetrics with MIT License 5 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
		throws IOException {

	Transaction t = Cat.newTransaction(CatConstants.TYPE_REMOTE_CALL, request.getURI().toString());

	try {
		HttpHeaders headers = request.getHeaders();

		// 保存和传递CAT调用链上下文
		Context ctx = new CatContext();
		Cat.logRemoteCallClient(ctx);
		headers.add(CatHttpConstants.CAT_HTTP_HEADER_ROOT_MESSAGE_ID, ctx.getProperty(Cat.Context.ROOT));
		headers.add(CatHttpConstants.CAT_HTTP_HEADER_PARENT_MESSAGE_ID, ctx.getProperty(Cat.Context.PARENT));
		headers.add(CatHttpConstants.CAT_HTTP_HEADER_CHILD_MESSAGE_ID, ctx.getProperty(Cat.Context.CHILD));

		// 保证请求继续被执行
		ClientHttpResponse response =  execution.execute(request, body);
		t.setStatus(Transaction.SUCCESS);
		return response;
	} catch (Exception e) {
		Cat.getProducer().logError(e);
		t.setStatus(e);
		throw e;
	} finally {
		t.complete();
	}
}
 
Example 15
Source File: CatRestInterceptor.java    From cat_lab with MIT License 5 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
		throws IOException {

	Transaction t = Cat.newTransaction(CatConstants.TYPE_CALL, request.getURI().toString());

	try {
		HttpHeaders headers = request.getHeaders();

		// 保存和传递CAT调用链上下文
		Context ctx = new CatContext();
		Cat.logRemoteCallClient(ctx);
		headers.add(CatHttpConstants.CAT_HTTP_HEADER_ROOT_MESSAGE_ID, ctx.getProperty(Cat.Context.ROOT));
		headers.add(CatHttpConstants.CAT_HTTP_HEADER_PARENT_MESSAGE_ID, ctx.getProperty(Cat.Context.PARENT));
		headers.add(CatHttpConstants.CAT_HTTP_HEADER_CHILD_MESSAGE_ID, ctx.getProperty(Cat.Context.CHILD));

		// 保证请求继续被执行
		ClientHttpResponse response =  execution.execute(request, body);
		t.setStatus(Transaction.SUCCESS);
		return response;
	} catch (Exception e) {
		Cat.getProducer().logError(e);
		t.setStatus(e);
		throw e;
	} finally {
		t.complete();
	}
}
 
Example 16
Source File: CatServletFilter.java    From cat_lab with MIT License 5 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) servletRequest;

    String url = request.getRequestURL().toString();
    for (String urlPattern : urlPatterns) {
        if (url.startsWith(urlPattern)) {
            url = urlPattern;
        }
    }

    CatContext catContext = new CatContext();
    catContext.addProperty(Cat.Context.ROOT, request.getHeader(CatHttpConstants.CAT_HTTP_HEADER_ROOT_MESSAGE_ID));
    catContext.addProperty(Cat.Context.PARENT, request.getHeader(CatHttpConstants.CAT_HTTP_HEADER_PARENT_MESSAGE_ID));
    catContext.addProperty(Cat.Context.CHILD, request.getHeader(CatHttpConstants.CAT_HTTP_HEADER_CHILD_MESSAGE_ID));
    Cat.logRemoteCallServer(catContext);
    
    Transaction t = Cat.newTransaction(CatConstants.TYPE_URL, url);

    try {

        Cat.logEvent("Service.method", request.getMethod(), Message.SUCCESS, request.getRequestURL().toString());
        Cat.logEvent("Service.client", request.getRemoteHost());

        filterChain.doFilter(servletRequest, servletResponse);

        t.setStatus(Transaction.SUCCESS);
    } catch (Exception ex) {
        t.setStatus(ex);
        Cat.logError(ex);
        throw ex;
    } finally {
        t.complete();
    }
}
 
Example 17
Source File: ExchangeRatesServiceImpl.java    From piggymetrics with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
@CatAnnotation
public Map<Currency, BigDecimal> getCurrentRates() {

	if (container == null || !container.getDate().equals(LocalDate.now())) {
		
		Transaction dbTransaction = Cat.newTransaction(CatConstants.TYPE_REMOTE_CALL, "get_current_rates");

		try {
			container = client.getRates(Currency.getBase());
			log.info("exchange rates has been updated: {}", container);
			dbTransaction.setStatus(Transaction.SUCCESS);
		} catch (Exception e) {
			Cat.getProducer().logError(e);
			dbTransaction.setStatus(e);
			throw e;
		} finally {
			dbTransaction.complete();
		}
	}

	return ImmutableMap.of(
			Currency.EUR, container.getRates().get(Currency.EUR.name()),
			Currency.RUB, container.getRates().get(Currency.RUB.name()),
			Currency.USD, BigDecimal.ONE
	);
}
 
Example 18
Source File: DefaultMessageQueueFlusher.java    From hermes with Apache License 2.0 5 votes vote down vote up
@Override
public long flush(int maxMsgCount) {
	long maxPurgedSelectorOffset = purgeExpiredMsgs();
	long maxSavedSelectorOffset = Long.MIN_VALUE;

	int msgCount = 0;

	List<PendingMessageWrapper> todos = new ArrayList<>();
	if (!m_pendingMessages.isEmpty()) {
		PendingMessageWrapper msg = m_pendingMessages.poll();
		todos.add(msg);
		msgCount = msg.getBatch().getMsgSeqs().size();

		PendingMessageWrapper nextMsg = null;
		while ((nextMsg = m_pendingMessages.peek()) != null) {
			int nextPendingMsgCount = nextMsg.getBatch().getMsgSeqs().size();
			if (msgCount + nextPendingMsgCount > maxMsgCount) {
				break;
			}
			todos.add(m_pendingMessages.poll());
			msgCount += nextPendingMsgCount;
		}
	}

	if (!todos.isEmpty()) {
		Transaction catTx = Cat.newTransaction(CatConstants.TYPE_MESSAGE_BROKER_FLUSH, m_topic + "-" + m_partition);
		catTx.addData("count", msgCount);

		maxSavedSelectorOffset = appendMessageSync(todos);

		catTx.setStatus(Transaction.SUCCESS);
		catTx.complete();
	}

	return Math.max(maxPurgedSelectorOffset, maxSavedSelectorOffset);
}
 
Example 19
Source File: CatInvokeTrace.java    From octo-rpc with Apache License 2.0 5 votes vote down vote up
@Override
protected void syncClientRecv(TraceParam traceParam, RpcInvocation invocation) {
    Transaction transaction = (Transaction) traceParam.getAttachment(TRANSACTION);
    if (transaction == null) {
        logger.warn("ClientSide: Request {} won't do cat report, cause no start transaction info.", traceParam.getSpanName());
        return;
    }
    try {
        clientLogEvent(traceParam, invocation);
        if (traceParam.getThrowable() != null) {
            Cat.logErrorWithCategory(DORADO_CALL + "." + traceParam.getRemoteAppkey(), traceParam.getThrowable());
            transaction.setStatus(traceParam.getThrowable());
        } else {
            transaction.setStatus(Transaction.SUCCESS);
        }

        transaction.addData(TRACE_ID, traceParam.getTraceId());
        TraceTimeline timeline = traceParam.getTraceTimeline();
        if (timeline.isEnable()) {
            transaction.addData(CatEventType.INVOKER_PHASECOST.type, timeline.genInvokerAllPhaseCost());
        }
    } catch (Exception e) {
        Cat.logErrorWithCategory(DORADO_CALL + "." + traceParam.getRemoteAppkey(), e);
        transaction.setStatus(e);
    } finally {
        transaction.complete();
    }
}
 
Example 20
Source File: BrokerMessageSender.java    From hermes with Apache License 2.0 4 votes vote down vote up
public void send() {
	boolean selectorSendSuccess = false;
	long cmdSelectorOffset = 0;
	SendMessageCommandV6 cmd = null;
	int batchSize = m_config.getBrokerSenderBatchSize();

	try {
		TaskQueue taskQueue = m_taskQueues.get(taskQueueKey);
		cmd = taskQueue.pop(batchSize);

		if (cmd != null) {
			selectorSendSuccess = true;
			cmdSelectorOffset = cmd.getSelectorOffset();

			if (!cmd.getProducerMessages().isEmpty()) {

				int produceTimeoutSeconds = m_config.getProduceTimeoutSeconds(cmd.getTopic());

				if (produceTimeoutSeconds > 0
				      && System.currentTimeMillis() - cmd.getBornTime() > produceTimeoutSeconds * 1000) {
					for (Pair<SettableFuture<SendResult>, ProducerMessage<?>> pair : cmd.getFutureAndMessagePair()) {
						MessageSendException exception = new MessageSendException("Send timeout.", pair.getValue());
						notifySendFail(pair.getKey(), exception);
					}

					Transaction t = Cat.newTransaction(CatConstants.TYPE_MESSAGE_PRODUCE_TIMEOUT, cmd.getTopic());
					t.addData("*count", cmd.getMessageCount());
					t.setStatus(Transaction.SUCCESS);
					t.complete();
				} else {
					SendMessageResult sendResult = sendMessagesToBroker(cmd);

					if (!sendResult.isSuccess() && !sendResult.isShouldSkip()) {
						selectorSendSuccess = false;
						taskQueue.push(cmd);
					}
					tracking(cmd, sendResult);
				}
			}
		}
	} catch (Exception e) {
		log.error("Unexpected exception when send cmd to broker", e);
		selectorSendSuccess = false;
	} finally {

		State state;
		if (selectorSendSuccess) {
			state = State.GotAndSuccessfullyProcessed;
		} else {
			if (cmd == null) {
				state = State.GotNothing;
			} else {
				state = State.GotButErrorInProcessing;
			}
		}
		TriggerResult triggerResult = new TriggerResult(state, new long[] { cmdSelectorOffset });

		m_selectorManager.reRegister(taskQueueKey, callbackContext, triggerResult, new FixedExpireTimeHolder(
		      Long.MAX_VALUE), new SelectorCallback() {

			@Override
			public void onReady(CallbackContext innerCtx) {
				new SendTask(taskQueueKey, innerCtx).send();
			}
		});
	}
}