com.dianping.cat.message.Transaction Java Examples

The following examples show how to use com.dianping.cat.message.Transaction. 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: SendMessageCommandProcessorV3.java    From hermes with Apache License 2.0 6 votes vote down vote up
private void logElapse(SendMessageResultCommand resultCmd) {
	int failCount = 0;
	for (Boolean sendSuccess : resultCmd.getSuccesses().values()) {
		if (!sendSuccess) {
			failCount++;
		}
	}

	int successCount = resultCmd.getSuccesses().size() - failCount;

	if (successCount > 0) {
		CatUtil.logElapse(CatConstants.TYPE_MESSAGE_BROKER_PRODUCE_DB + findDb(m_topic, m_partition), m_topic,
		      m_start, successCount, null, Transaction.SUCCESS);
		CatUtil.logElapse(CatConstants.TYPE_MESSAGE_BROKER_PRODUCE, m_topic, m_start, successCount, null,
		      Transaction.SUCCESS);
	}

	if (failCount > 0) {
		CatUtil.logElapse(CatConstants.TYPE_MESSAGE_BROKER_PRODUCE_DB + findDb(m_topic, m_partition), m_topic,
		      m_start, failCount, null, CatConstants.TRANSACTION_FAIL);
		CatUtil.logElapse(CatConstants.TYPE_MESSAGE_BROKER_PRODUCE, m_topic, m_start, failCount, null,
		      CatConstants.TRANSACTION_FAIL);
	}
}
 
Example #2
Source File: AcemFinancialUIApplication.java    From cat_lab with MIT License 6 votes vote down vote up
@RequestMapping("/readtimeout")
public String timeout() throws InterruptedException {
	Transaction t = Cat.newTransaction(CatConstants.TYPE_URL, "timeout");
	try {
		Thread.sleep(300);
		log.info("Hello from service1. Calling service2 - should end up with read timeout");
		String response = restTemplate.getForObject("http://" + serviceAddress + "/readtimeout", String.class);
		log.info("Got response from service2 [{}]", response);
		return response;
	} catch (Exception e) {
		Cat.getProducer().logError(e);
		t.setStatus(e);
		throw e;
	} finally {
		t.complete();
	}
}
 
Example #3
Source File: AcmeFinancialBackOfficeApplication.java    From cat_lab with MIT License 6 votes vote down vote up
@RequestMapping("/readtimeout")
public String connectionTimeout() throws InterruptedException {
	Transaction t = Cat.newTransaction(CatConstants.TYPE_CALL, "connectionTimeout");
	Thread.sleep(500);
	try {
		log.info("Calling a missing service");
		restTemplate.getForObject("http://localhost:" + MOCK_PORT + "/readtimeout", String.class);
		return "Should blow up";
	} catch(Exception e) {
		t.setStatus(e);
		Cat.getProducer().logError(e);
		throw e;
	} finally {
		t.complete();
	}
}
 
Example #4
Source File: BaseMessageListener.java    From hermes with Apache License 2.0 6 votes vote down vote up
private void setOnMessageStartTime(ConsumerMessage<T> msg) {
	if (msg instanceof BaseConsumerMessageAware) {
		BaseConsumerMessage<?> baseMsg = ((BaseConsumerMessageAware<?>) msg).getBaseConsumerMessage();
		long now = System.currentTimeMillis();
		baseMsg.setOnMessageStartTimeMills(now);

		Transaction latencyT = null;
		if (!msg.isResend()) {
			latencyT = Cat.newTransaction( //
			      CatConstants.TYPE_MESSAGE_CONSUME_LATENCY, msg.getTopic() + ":" + m_groupId);
		} else {
			latencyT = Cat.newTransaction( //
			      CatConstants.TYPE_MESSAGE_CONSUME_RESEND_LATENCY, msg.getTopic() + ":" + m_groupId);
		}
		long delta = System.currentTimeMillis() - baseMsg.getBornTime();

		if (latencyT instanceof DefaultTransaction) {
			((DefaultTransaction) latencyT).setDurationStart(System.nanoTime() - delta * 1000000L);
		}

		latencyT.addData("key", msg.getRefKey());
		latencyT.setStatus(Transaction.SUCCESS);
		latencyT.complete();
	}
}
 
Example #5
Source File: DefaultPullConsumerHolder.java    From hermes with Apache License 2.0 6 votes vote down vote up
@Override
public PulledBatch<T> poll(int maxMessageCount, int timeout) {
	long startTime = System.currentTimeMillis();
	Transaction t = Cat.newTransaction(CatConstants.TYPE_MESSAGE_CONSUME_POLL_TRIED, m_topic + ":" + m_group);
	try {
		PulledBatch<T> batch = retrive(maxMessageCount, timeout, RetrivePolicy.FAVOUR_FAST_RETURN);
		if (batch.getMessages() != null && !batch.getMessages().isEmpty()) {
			CatUtil.logElapse(CatConstants.TYPE_MESSAGE_CONSUME_POLL_ELAPSE, m_topic + ":" + m_group, startTime, batch
			      .getMessages().size(), null, Transaction.SUCCESS);
		}
		return batch;
	} finally {
		t.setStatus(Transaction.SUCCESS);
		t.complete();
	}
}
 
Example #6
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 #7
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 #8
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 #9
Source File: CatFilter.java    From Zebra with Apache License 2.0 6 votes vote down vote up
@Override
public ResultSet executeShardQuery(ShardStatement source, String sql, JdbcFilter chain) throws SQLException {
	SqlAliasManager.setSqlAlias(sql);
	Transaction t = Cat.newTransaction(SHARD_CAT_TYPE, SqlAliasManager.getSqlAlias());
	ResultSet result = null;
	try {
		result = chain.executeShardQuery(source, sql, chain);
		t.setStatus(Message.SUCCESS);
	} catch (Throwable exp) {
		Cat.logError(exp);
		t.setStatus(exp);
		throw new SQLException(exp);
	} finally {
		t.complete();
	}
	return result;
}
 
Example #10
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 #11
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 #12
Source File: CatInvokeTrace.java    From octo-rpc with Apache License 2.0 6 votes vote down vote up
@Override
protected void serverSendInCodec(TraceParam traceParam, RpcInvocation invocation) {
    TraceTimeline timeline = traceParam.getTraceTimeline();
    Transaction transaction = Cat.newTransactionWithDuration(DORADO_SERVICE, traceParam.getSpanName(),
            System.currentTimeMillis() - traceParam.getStartTimestamp());
    try {
        serverLogEvent(traceParam, invocation);
        transaction.addData(TRACE_ID, traceParam.getTraceId());
        transaction.addData(CatEventType.SERVICE_PHASECOST.type, timeline.genProviderAllPhaseCost());

        if (traceParam.getThrowable() != null) {
            Cat.logErrorWithCategory(DORADO_SERVICE + "." + traceParam.getRemoteAppkey(), traceParam.getThrowable());
            transaction.setStatus(traceParam.getThrowable());
        } else {
            transaction.setStatus(Transaction.SUCCESS);
        }
    } catch (Exception e) {
        Cat.logErrorWithCategory(DORADO_SERVICE + "." + traceParam.getRemoteAppkey(), e);
        transaction.setStatus(e);
    } finally {
        transaction.complete();
    }
}
 
Example #13
Source File: CatInvokeTrace.java    From octo-rpc with Apache License 2.0 6 votes vote down vote up
@Override
protected void serverSendInFilter(TraceParam traceParam, RpcInvocation invocation) {
    Transaction transaction = (Transaction) traceParam.getAttachment(TRANSACTION);
    if (transaction == null) {
        logger.warn("ServerSide: Request {} won't do cat report, cause no start transaction info.", traceParam.getSpanName());
        return;
    }
    try {
        serverLogEvent(traceParam, invocation);
        transaction.addData(TRACE_ID, traceParam.getTraceId());

        if (traceParam.getThrowable() == null) {
            transaction.setStatus(Transaction.SUCCESS);
        } else {
            Cat.logErrorWithCategory(DORADO_SERVICE + "." + traceParam.getRemoteAppkey(), traceParam.getThrowable());
            transaction.setStatus(traceParam.getThrowable());
        }
    } catch (Exception e) {
        Cat.logErrorWithCategory(DORADO_SERVICE + "." + traceParam.getRemoteAppkey(), e);
        transaction.setStatus(e);
    } finally {
        transaction.complete();
    }
}
 
Example #14
Source File: AsyncZuulServlet.java    From s2g-zuul with MIT License 6 votes vote down vote up
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	Transaction tran = Cat.getProducer().newTransaction("AsyncZuulServlet", req.getRequestURL().toString());
    req.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);
    AsyncContext asyncContext = req.startAsync();
    asyncContext.setTimeout(asyncTimeout.get());
    asyncContext.addListener(new AsyncZuulListener());
    try {
    	Context ctx = new CatContext();
    	Cat.logRemoteCallClient(ctx);
        poolExecutorRef.get().submit(new ZuulCallable(ctx,asyncContext, zuulRunner,req));            
        tran.setStatus(Transaction.SUCCESS);
    } catch (RuntimeException e) {
        Cat.logError(e);
        tran.setStatus(e);
        rejectedRequests.incrementAndGet();
        throw e;
    }finally{
    	tran.complete();
    }
}
 
Example #15
Source File: CatAop.java    From javabase with Apache License 2.0 6 votes vote down vote up
private Object aroundTransaction(String type, String name, ProceedingJoinPoint joinPoint) throws Throwable {
    Object result = null;
    Transaction transaction = null;
    //不让cat异常导致业务异常
    try {
        transaction = Cat.getProducer().newTransaction(type, name);
    } catch (Exception e) {
        log.error("Cat.getProducer().newTransaction Error", e);
    }
    try {
        log.info("大众点评cat拦截:type="+type+";name="+name);
        result = joinPoint.proceed();
        if (transaction != null) transaction.setStatus(Transaction.SUCCESS);
    } catch (Throwable throwable) {
        if (transaction != null) transaction.setStatus(throwable);
        log.error("aroundTransaction exception", throwable);
        throw throwable;
    } finally {
        if (transaction != null)
            transaction.complete();
    }
    return result;
}
 
Example #16
Source File: BrokerLeaseHolder.java    From hermes with Apache License 2.0 6 votes vote down vote up
private long loadNewLeasesAssignedByOtherMetaservers(long lastRunTime) throws DalException {
	Transaction transaction = Cat.newTransaction(CatConstants.TYPE_LEASE_DIRTY_LOAD, "Broker");
	int count = 0;
	long maxLodedTime = -1L;
	try {
		List<BrokerLease> changes = m_leasesDao.listLatestChanges(new Date(lastRunTime), Networks.forIp()
		      .getLocalHostAddress(), BrokerLeaseEntity.READSET_FULL);
		if (changes != null && !changes.isEmpty()) {
			count = changes.size();
			maxLodedTime = loadExistingLeases(changes);
		}
		transaction.setStatus(Transaction.SUCCESS);
		return maxLodedTime;
	} catch (Exception e) {
		transaction.setStatus(e);
		throw e;
	} finally {
		transaction.addData("count", count);
		transaction.complete();
	}
}
 
Example #17
Source File: LeaseResource.java    From hermes with Apache License 2.0 6 votes vote down vote up
private LeaseAcquireResponse proxyConsumerLeaseRequestIfNecessary(HttpServletRequest req, String topic, String uri,
      Map<String, String> params, Object payload, Transaction tx) {

	Map<String, ClientContext> responsors = m_metaServerAssignmentHolder.getAssignment(topic);

	if (responsors != null && !responsors.isEmpty()) {
		ClientContext responsor = responsors.values().iterator().next();
		if (responsor != null) {
			if (m_config.getMetaServerHost().equals(responsor.getIp())
			      && m_config.getMetaServerPort() == responsor.getPort()) {
				return null;
			} else {
				if (!isFromAnotherMetaServer(req)) {
					tx.addData("dest", responsor.getIp() + ":" + responsor.getPort());
					return proxyPass(responsor.getIp(), responsor.getPort(), uri, params, payload);
				} else {
					return new LeaseAcquireResponse(false, null, m_systemClockService.now()
					      + PROXY_PASS_FAIL_DELAY_TIME_MILLIS);
				}
			}
		}
	}
	return new LeaseAcquireResponse(false, null, m_systemClockService.now() + NO_ASSIGNMENT_DELAY_TIME_MILLIS);

}
 
Example #18
Source File: CatController.java    From javabase with Apache License 2.0 6 votes vote down vote up
/**
 * Cat.newTransaction 与Cat.getProducer().newTransaction 区别在于 一个是重新生成一个transation  和获取当前线程绑定的transaction“
 *
 * @return
 * @throws Exception
 */
@RequestMapping(value = "/cycletransation", method = RequestMethod.GET)
public String newtransation() throws Exception {
	Transaction t = Cat.getProducer().newTransaction("TransactionTest", "Cat.getProducer()");
	Cat.getProducer().logEvent("eventType1", "1", Message.SUCCESS, "");
	Cat.getProducer().logEvent("eventType1", "2", Message.SUCCESS, "");
	Transaction t2 = Cat.getProducer().newTransaction("TransactionTest-1", "child transaction 1");
	Cat.getProducer().logEvent("eventType2-1", "2-1", Message.SUCCESS, "");
	Cat.getProducer().logEvent("eventType2-2", "2-2", Message.SUCCESS, "");
	t2.addData("tChild transaction-1");
	t2.setStatus(Message.SUCCESS);
	t2.complete();
	Transaction t3 = Cat.getProducer().newTransaction("TransactionTest-2", "child transaction 2");
	Cat.getProducer().logEvent("eventType3-1", "3-1", Message.SUCCESS, "");
	Cat.getProducer().logEvent("eventType3-2", "3-2", Message.SUCCESS, "");
	t3.addData("Child transaction-2");
	t3.setStatus(Message.SUCCESS);
	// 休眠3s 验证时间
	Thread.sleep(4000);
	t3.complete();
	t.addData(" Parent transaction");
	t.setStatus(Message.SUCCESS);
	t.complete();
	return "";
}
 
Example #19
Source File: LeaseResource.java    From hermes with Apache License 2.0 6 votes vote down vote up
private LeaseAcquireResponse proxyBrokerLeaseRequestIfNecessary(HttpServletRequest req, String uri,
      Map<String, String> params, Object payload, Transaction tx) {
	if (m_clusterStateHolder.getRole() == Role.LEADER) {
		return null;
	} else {
		if (!isFromAnotherMetaServer(req)) {
			HostPort leader = m_clusterStateHolder.getLeader();
			if (leader != null) {
				tx.addData("dest", leader.getHost() + ":" + leader.getPort());
				return proxyPass(leader.getHost(), leader.getPort(), uri, params, payload);
			} else {
				return new LeaseAcquireResponse(false, null, m_systemClockService.now()
				      + PROXY_PASS_FAIL_DELAY_TIME_MILLIS);
			}
		} else {
			return new LeaseAcquireResponse(false, null, m_systemClockService.now() + PROXY_PASS_FAIL_DELAY_TIME_MILLIS);
		}
	}
}
 
Example #20
Source File: ConsumerLeaseHolder.java    From hermes with Apache License 2.0 6 votes vote down vote up
private long loadNewLeasesAssignedByOtherMetaservers(long lastRunTime) throws DalException {
	Transaction transaction = Cat.newTransaction(CatConstants.TYPE_LEASE_DIRTY_LOAD, "Consumer");
	int count = 0;
	long maxLodedTime = -1L;
	try {
		List<ConsumerLease> changes = m_leasesDao.listLatestChanges(new Date(lastRunTime), Networks.forIp()
		      .getLocalHostAddress(), ConsumerLeaseEntity.READSET_FULL);
		if (changes != null && !changes.isEmpty()) {
			count = changes.size();
			maxLodedTime = loadExistingLeases(changes);
		}
		transaction.setStatus(Transaction.SUCCESS);
		return maxLodedTime;
	} catch (Exception e) {
		transaction.setStatus(e);
		throw e;
	} finally {
		transaction.addData("count", count);
		transaction.complete();
	}
}
 
Example #21
Source File: CatAopService.java    From piggymetrics with MIT License 6 votes vote down vote up
@Around("@annotation(CatAnnotation)")
public Object aroundMethod(ProceedingJoinPoint pjp) {
	MethodSignature joinPointObject = (MethodSignature) pjp.getSignature();
	Method method = joinPointObject.getMethod();

	Transaction t = Cat.newTransaction("method", method.getName());

	try {
		Object obj = pjp.proceed();

		t.setSuccessStatus();
		return obj;
	} catch (Throwable e) {
		t.setStatus(e);
		Cat.logError(e);
		throw new RuntimeException("Exception thrown by CAT aop", e);
	} finally {
		t.complete();
	}
}
 
Example #22
Source File: DefaultPullConsumerHolder.java    From hermes with Apache License 2.0 6 votes vote down vote up
@Override
public PulledBatch<T> collect(int maxMessageCount, int timeout) {
	long startTime = System.currentTimeMillis();
	Transaction t = Cat.newTransaction(CatConstants.TYPE_MESSAGE_CONSUME_COLLECT_TRIED, m_topic + ":" + m_group);
	try {
		PulledBatch<T> batch = retrive(maxMessageCount, timeout, RetrivePolicy.FAVOUR_MORE_MESSAGE);
		if (batch.getMessages() != null && !batch.getMessages().isEmpty()) {
			CatUtil.logElapse(CatConstants.TYPE_MESSAGE_CONSUME_COLLECT_ELAPSE, m_topic + ":" + m_group, startTime,
			      batch.getMessages().size(), null, Transaction.SUCCESS);
		}
		return batch;
	} finally {
		t.setStatus(Transaction.SUCCESS);
		t.complete();
	}
}
 
Example #23
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 #24
Source File: SendMessageCommandProcessor.java    From hermes with Apache License 2.0 6 votes vote down vote up
private void logElapse(SendMessageResultCommand resultCmd) {
	int failCount = 0;
	for (Boolean sendSuccess : resultCmd.getSuccesses().values()) {
		if (!sendSuccess) {
			failCount++;
		}
	}

	int successCount = m_result.getSuccesses().size() - failCount;

	if (successCount > 0) {
		CatUtil.logElapse(CatConstants.TYPE_MESSAGE_BROKER_PRODUCE_DB + findDb(m_topic, m_partition), m_topic,
		      m_start, successCount, null, Transaction.SUCCESS);
		CatUtil.logElapse(CatConstants.TYPE_MESSAGE_BROKER_PRODUCE, m_topic, m_start, successCount, null,
		      Transaction.SUCCESS);
	}

	if (failCount > 0) {
		CatUtil.logElapse(CatConstants.TYPE_MESSAGE_BROKER_PRODUCE_DB + findDb(m_topic, m_partition), m_topic,
		      m_start, failCount, null, CatConstants.TRANSACTION_FAIL);
		CatUtil.logElapse(CatConstants.TYPE_MESSAGE_BROKER_PRODUCE, m_topic, m_start, failCount, null,
		      CatConstants.TRANSACTION_FAIL);
	}
}
 
Example #25
Source File: CatAopService.java    From piggymetrics with MIT License 6 votes vote down vote up
@Around("@annotation(CatAnnotation)")
public Object aroundMethod(ProceedingJoinPoint pjp) {
	MethodSignature joinPointObject = (MethodSignature) pjp.getSignature();
	Method method = joinPointObject.getMethod();

	Transaction t = Cat.newTransaction("method", method.getName());

	try {
		Object obj = pjp.proceed();

		t.setSuccessStatus();
		return obj;
	} catch (Throwable e) {
		t.setStatus(e);
		Cat.logError(e);
		throw new RuntimeException("Exception thrown by CAT aop", e);
	} finally {
		t.complete();
	}
}
 
Example #26
Source File: CatAopService.java    From piggymetrics with MIT License 6 votes vote down vote up
@Around("@annotation(CatAnnotation)")
public Object aroundMethod(ProceedingJoinPoint pjp) {
	MethodSignature joinPointObject = (MethodSignature) pjp.getSignature();
	Method method = joinPointObject.getMethod();

	Transaction t = Cat.newTransaction("method", method.getName());

	try {
		Object obj = pjp.proceed();

		t.setSuccessStatus();
		return obj;
	} catch (Throwable e) {
		t.setStatus(e);
		Cat.logError(e);
		throw new RuntimeException("Exception thrown by CAT aop", e);
	} finally {
		t.complete();
	}
}
 
Example #27
Source File: SendMessageCommandProcessorV5.java    From hermes with Apache License 2.0 6 votes vote down vote up
private void logElapse(SendMessageResultCommand resultCmd) {
	int failCount = 0;
	for (Boolean sendSuccess : resultCmd.getSuccesses().values()) {
		if (!sendSuccess) {
			failCount++;
		}
	}

	int successCount = m_result.getSuccesses().size() - failCount;

	if (successCount > 0) {
		CatUtil.logElapse(CatConstants.TYPE_MESSAGE_BROKER_PRODUCE_DB + findDb(m_topic, m_partition), m_topic,
		      m_start, successCount, null, Transaction.SUCCESS);
		CatUtil.logElapse(CatConstants.TYPE_MESSAGE_BROKER_PRODUCE, m_topic, m_start, successCount, null,
		      Transaction.SUCCESS);
	}

	if (failCount > 0) {
		CatUtil.logElapse(CatConstants.TYPE_MESSAGE_BROKER_PRODUCE_DB + findDb(m_topic, m_partition), m_topic,
		      m_start, failCount, null, CatConstants.TRANSACTION_FAIL);
		CatUtil.logElapse(CatConstants.TYPE_MESSAGE_BROKER_PRODUCE, m_topic, m_start, failCount, null,
		      CatConstants.TRANSACTION_FAIL);
	}
}
 
Example #28
Source File: SendMessageCommandProcessorV6.java    From hermes with Apache License 2.0 6 votes vote down vote up
private void logElapse(SendMessageResultCommandV6 resultCmd) {
	int failCount = 0;
	for (SendMessageResult result : resultCmd.getResults().values()) {
		if (!result.isSuccess()) {
			failCount++;
		}
	}

	int successCount = m_result.getResults().size() - failCount;

	if (successCount > 0) {
		CatUtil.logElapse(CatConstants.TYPE_MESSAGE_BROKER_PRODUCE_DB + findDb(m_topic, m_partition), m_topic,
		      m_start, successCount, null, Transaction.SUCCESS);
		CatUtil.logElapse(CatConstants.TYPE_MESSAGE_BROKER_PRODUCE, m_topic, m_start, successCount, null,
		      Transaction.SUCCESS);
	}

	if (failCount > 0) {
		CatUtil.logElapse(CatConstants.TYPE_MESSAGE_BROKER_PRODUCE_DB + findDb(m_topic, m_partition), m_topic,
		      m_start, failCount, null, CatConstants.TRANSACTION_FAIL);
		CatUtil.logElapse(CatConstants.TYPE_MESSAGE_BROKER_PRODUCE, m_topic, m_start, failCount, null,
		      CatConstants.TRANSACTION_FAIL);

	}
}
 
Example #29
Source File: ZuulRequestCommandForSemaphoreIsolation.java    From s2g-zuul with MIT License 6 votes vote down vote up
@Override
protected HttpResponse run() throws Exception {
	
	Transaction t = Cat.newTransaction(CatConstants.TYPE_REMOTE_CALL, httpUriRequest.getURI().toString());
	
    try {
    	HttpResponse response = forward();
        t.setStatus(Transaction.SUCCESS);
        return response;
    } catch (IOException e) {
        t.setStatus(e);
        Cat.logError(e);
    	throw e;
    } finally {
    	t.complete();
    }
}
 
Example #30
Source File: ConfigSubscriber.java    From AsuraFramework with Apache License 2.0 5 votes vote down vote up
/**
 * 初始化zk连接
 *
 * @author zhangshaobin
 * @created 2013-6-26 上午10:21:34
 */
private void init() {
    applicationName = DynamicPropertyFactory.getInstance().getStringProperty(CommonConstant.CONFIG_APPLICATION_NAME_KEY, null).get();
    String zkConfigEnsemble = DynamicPropertyFactory.getInstance().getStringProperty(CommonConstant.ZK_ENSEMABLE_KEY, null).get();
    Integer zkConfigSessionTimeout = DynamicPropertyFactory.getInstance().getIntProperty(CommonConstant.ZK_SESSION_TIMEOUT_KEY, 15000).get();
    Integer zkConfigConnTimeout = DynamicPropertyFactory.getInstance().getIntProperty(CommonConstant.ZK_CONN_TIMEOUT_KEY, 5000).get();

    Transaction tran = Cat.newTransaction("Asura Configuration init", applicationName + "_" + zkConfigEnsemble);

    try {

        if (Check.NuNStr(zkConfigEnsemble)) {
            logger.warn("ZooKeeper configuration running in file mode, zk is not enabled since not configured");
            Cat.logError("zk is not enabled since not configured", new RuntimeException("ZooKeeper located at " + zkConfigEnsemble + " is not started."));
            return;
        }

        client = createAndStartZKClient(zkConfigEnsemble, zkConfigSessionTimeout, zkConfigConnTimeout);

        if (client.getState() != CuratorFrameworkState.STARTED) {
            throw new RuntimeException("ZooKeeper located at " + zkConfigEnsemble + " is not started.");
        }

        tran.setStatus(Transaction.SUCCESS);
    } catch (Exception e) {
        logger.error("连接配置中心服务器超时,时间5000毫秒。", e);
        Cat.logError("asura configuration init exception", e);
        tran.setStatus(e);
        System.exit(1);
    } finally {
        tran.complete();
    }
    logger.info(new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss] ").format(new Date()) + applicationName + " connected to cofnig server(" + zkConfigEnsemble + ").");
    logger.info(applicationName + " connected to cofnig server(" + zkConfigEnsemble + ").");
}