Search in sources :

Example 1 with TransactionListener

use of com.newrelic.agent.TransactionListener in project newrelic-java-agent by newrelic.

the class TraceAnnotationTest method testCallAsyncAnnotatedThreadInsideOfTxnMultiThreaded.

/* Case 4: @Trace(async = true), multithreaded with a started Transaction */
@Test
public void testCallAsyncAnnotatedThreadInsideOfTxnMultiThreaded() throws InterruptedException {
    Transaction.clearTransaction();
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicBoolean metricsAssertionsPassed = new AtomicBoolean(false);
    // AgentBridge getTransaction call should return null if no Transaction exists in ThreadLocal
    Assert.assertNull(AgentBridge.getAgent().getTransaction(false));
    // Transaction listener which will only countdown the latch when a specific txn finishes
    ServiceFactory.getTransactionService().addTransactionListener(new TransactionListener() {

        @Override
        public void dispatcherTransactionFinished(TransactionData transactionData, TransactionStats transactionStats) {
            PriorityTransactionName ptn = transactionData.getTransaction().getPriorityTransactionName();
            String txnMetric1 = "Java/test.newrelic.test.agent.TraceAnnotationTest$AsyncAnnotatedThreadInsideOfTxn/run";
            String txnMetric2 = "Java/test.newrelic.test.agent.TraceAnnotationTest/callAsyncAnnotatedThreadInsideOfTxnMultiThreaded";
            Map<String, StatsBase> scopedStatsMap = transactionStats.getScopedStats().getStatsMap();
            if (ptn.getPartialName().equals("/MyCategory/TracedAsyncTxn")) {
                try {
                    Assert.assertTrue("The following metric should exist: " + txnMetric1, scopedStatsMap.containsKey(txnMetric1));
                    Assert.assertTrue("The following metric should exist: " + txnMetric2, scopedStatsMap.containsKey(txnMetric2));
                    metricsAssertionsPassed.set(true);
                } catch (Throwable t) {
                    metricsAssertionsPassed.set(false);
                    t.printStackTrace();
                } finally {
                    latch.countDown();
                }
            }
        }
    });
    callAsyncAnnotatedThreadInsideOfTxnMultiThreaded();
    latch.await();
    Assert.assertTrue("Metric assertions didn't pass", metricsAssertionsPassed.get());
}
Also used : TransactionListener(com.newrelic.agent.TransactionListener) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) TransactionStats(com.newrelic.agent.stats.TransactionStats) PriorityTransactionName(com.newrelic.agent.transaction.PriorityTransactionName) TransactionData(com.newrelic.agent.TransactionData) CountDownLatch(java.util.concurrent.CountDownLatch) HashMap(java.util.HashMap) Map(java.util.Map) Test(org.junit.Test)

Example 2 with TransactionListener

use of com.newrelic.agent.TransactionListener in project newrelic-java-agent by newrelic.

the class SpanEventsServiceFactoryTest method testBuildPicksStorageBackend_infiniteTracing.

@Test
public void testBuildPicksStorageBackend_infiniteTracing() throws Exception {
    when(agentConfig.getApplicationName()).thenReturn(APP_NAME);
    when(infiniteTracingConfig.isEnabled()).thenReturn(true);
    when(spanEventsConfig.isEnabled()).thenReturn(true);
    SpanEventsService service = SpanEventsServiceFactory.builder().configService(configService).rpmServiceManager(rpmServiceManager).infiniteTracingConsumer(infTracingConsumer).transactionService(transactionService).build();
    service.storeEvent(event);
    verify(infTracingConsumer).accept(event);
    verify(reservoir, never()).add(event);
    ArgumentCaptor<AgentConfigListener> configListener = ArgumentCaptor.forClass(AgentConfigListener.class);
    ArgumentCaptor<TransactionListener> transactionListener = ArgumentCaptor.forClass(TransactionListener.class);
    verify(configService, times(2)).addIAgentConfigListener(configListener.capture());
    verify(transactionService).addTransactionListener(transactionListener.capture());
    assertSame(configListener.getValue(), service);
    assertSame(transactionListener.getValue(), service);
}
Also used : TransactionListener(com.newrelic.agent.TransactionListener) SpanEventsService(com.newrelic.agent.service.analytics.SpanEventsService) AgentConfigListener(com.newrelic.agent.config.AgentConfigListener) Test(org.junit.Test)

Example 3 with TransactionListener

use of com.newrelic.agent.TransactionListener in project newrelic-java-agent by newrelic.

the class TokenTimeoutTest method testTxnAttrTokenTimeout.

@Test
public void testTxnAttrTokenTimeout() throws InterruptedException {
    Transaction.clearTransaction();
    Transaction tx = Transaction.getTransaction();
    Tracer rootTracer = TransactionAsyncUtility.createDispatcherTracer(this, "hi");
    tx.getTransactionActivity().tracerStarted(rootTracer);
    // Name the transaction so we can identify it in the listener below and create an event
    tx.setTransactionName(TransactionNamePriority.CUSTOM_HIGH, true, "TokenTimeout", "timeout");
    final List<TransactionEvent> events = new ArrayList<>();
    final CountDownLatch latch = new CountDownLatch(1);
    ServiceFactory.getServiceManager().getTransactionService().addTransactionListener(new TransactionListener() {

        @Override
        public void dispatcherTransactionFinished(TransactionData transactionData, TransactionStats transactionStats) {
            if (transactionData.getPriorityTransactionName().getName().equals("WebTransaction/TokenTimeout/timeout")) {
                events.add(ServiceFactory.getTransactionEventsService().createEvent(transactionData, transactionStats, transactionData.getBlameOrRootMetricName()));
                latch.countDown();
            }
        }
    });
    tx.getTransactionActivity().tracerStarted(rootTracer);
    // Let this timeout the transaction
    Token token = tx.getToken();
    rootTracer.finish(Opcodes.RETURN, 0);
    assertFalse(tx.isFinished());
    // Don't start the thread. The timeout is configured to 0 seconds.
    // Allow it to expire and then run the code that implements it.
    busyWait(1000);
    latch.await();
    assertTrue(tx.isFinished());
    assertFalse(events.isEmpty());
    assertEquals("WebTransaction/TokenTimeout/timeout", events.get(0).getName());
    assertEquals(TimeoutCause.TOKEN, events.get(0).getTimeoutCause());
}
Also used : TransactionListener(com.newrelic.agent.TransactionListener) ExtendedTransactionListener(com.newrelic.agent.ExtendedTransactionListener) TransactionEvent(com.newrelic.agent.service.analytics.TransactionEvent) TransactionStats(com.newrelic.agent.stats.TransactionStats) Transaction(com.newrelic.agent.Transaction) Tracer(com.newrelic.agent.tracers.Tracer) ArrayList(java.util.ArrayList) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) Token(com.newrelic.agent.bridge.Token) TransactionData(com.newrelic.agent.TransactionData) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

Example 4 with TransactionListener

use of com.newrelic.agent.TransactionListener in project newrelic-java-agent by newrelic.

the class KafkaTest method produceConsumeTest.

@Test
public void produceConsumeTest() throws Exception {
    EnvironmentHolderSettingsGenerator envHolderSettings = new EnvironmentHolderSettingsGenerator(CONFIG_FILE, "all_enabled_test", CLASS_LOADER);
    EnvironmentHolder holder = new EnvironmentHolder(envHolderSettings);
    holder.setupEnvironment();
    kafkaUnitRule.getKafkaUnit().createTopic(testTopic, 1);
    final KafkaConsumer<String, String> consumer = setupConsumer();
    final CountDownLatch latch = new CountDownLatch(1);
    final ConcurrentLinkedQueue<TransactionData> finishedTransactions = new ConcurrentLinkedQueue<>();
    TransactionListener transactionListener = new TransactionListener() {

        @Override
        public void dispatcherTransactionFinished(TransactionData transactionData, TransactionStats transactionStats) {
            finishedTransactions.add(transactionData);
            latch.countDown();
        }
    };
    ServiceFactory.getTransactionService().addTransactionListener(transactionListener);
    try {
        produceMessage();
        final Future<?> submit = executorService.submit(new Runnable() {

            @Override
            public void run() {
                consumeMessage(consumer);
            }
        });
        submit.get(30, TimeUnit.SECONDS);
        latch.await(30, TimeUnit.SECONDS);
        Assert.assertEquals(2, finishedTransactions.size());
        // Wait for the metrics reporter
        Thread.sleep(1000);
        // Assert on the kafka metrics that we're expecting
        StatsEngine statsEngine = ServiceFactory.getStatsService().getStatsEngineForHarvest(ServiceFactory.getConfigService().getDefaultAgentConfig().getApplicationName());
        Stats messagesConsumed = statsEngine.getStats("MessageBroker/Kafka/Internal/consumer-fetch-manager-metrics/records-consumed-rate");
        Assert.assertNotNull(messagesConsumed);
        Assert.assertTrue(messagesConsumed.getCallCount() > 1);
        Assert.assertTrue(messagesConsumed.getTotal() > 0);
        Stats bytesConsumed = statsEngine.getStats("MessageBroker/Kafka/Internal/consumer-metrics/incoming-byte-rate");
        Assert.assertNotNull(bytesConsumed);
        Assert.assertTrue(bytesConsumed.getCallCount() > 1);
        Assert.assertTrue(bytesConsumed.getTotal() > 0);
        Stats rebalanceAssignedPartition = statsEngine.getStats("MessageBroker/Kafka/Rebalance/Assigned/" + testTopic + "/0");
        Assert.assertNotNull(rebalanceAssignedPartition);
        Assert.assertEquals(1, rebalanceAssignedPartition.getCallCount());
        Stats serializationByTopic = statsEngine.getStats("MessageBroker/Kafka/Serialization/TestTopic");
        Assert.assertNotNull(serializationByTopic);
        // One for the key, one for the value
        Assert.assertEquals(2, serializationByTopic.getCallCount());
        Assert.assertTrue(serializationByTopic.getTotal() > 1);
        Stats deserializationByTopic = statsEngine.getStats("MessageBroker/Kafka/Deserialization/TestTopic");
        Assert.assertNotNull(deserializationByTopic);
        // One for the key, one for the value
        Assert.assertEquals(2, deserializationByTopic.getCallCount());
        Assert.assertTrue(deserializationByTopic.getTotal() > 1);
        // external reporting test
        TransactionData prodTxn = finishedTransactions.poll();
        Collection<Tracer> tracers = prodTxn.getTracers();
        Iterator<Tracer> iterator = tracers.iterator();
        Assert.assertTrue(iterator.hasNext());
        Tracer tracer = iterator.next();
        Assert.assertEquals("MessageBroker/Kafka/Topic/Produce/Named/TestTopic", tracer.getMetricName());
        TransactionData conTxn = finishedTransactions.poll();
        Tracer rootTracer = conTxn.getRootTracer();
        Assert.assertEquals("MessageBroker/Kafka/Topic/Consume/Named/TestTopic", rootTracer.getMetricName());
        Assert.assertNotNull(conTxn.getInboundDistributedTracePayload());
    } finally {
        ServiceFactory.getTransactionService().removeTransactionListener(transactionListener);
        consumer.close();
    }
}
Also used : TransactionListener(com.newrelic.agent.TransactionListener) EnvironmentHolderSettingsGenerator(test.newrelic.EnvironmentHolderSettingsGenerator) EnvironmentHolder(test.newrelic.test.agent.EnvironmentHolder) Tracer(com.newrelic.agent.tracers.Tracer) CountDownLatch(java.util.concurrent.CountDownLatch) StatsEngine(com.newrelic.agent.stats.StatsEngine) TransactionStats(com.newrelic.agent.stats.TransactionStats) TransactionStats(com.newrelic.agent.stats.TransactionStats) Stats(com.newrelic.agent.stats.Stats) TransactionData(com.newrelic.agent.TransactionData) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) Test(org.junit.Test)

Example 5 with TransactionListener

use of com.newrelic.agent.TransactionListener in project newrelic-java-agent by newrelic.

the class SpanEventsServiceFactoryTest method testBuildPicksStorageBackend_collector.

@Test
public void testBuildPicksStorageBackend_collector() throws Exception {
    when(agentConfig.getApplicationName()).thenReturn(APP_NAME);
    when(infiniteTracingConfig.isEnabled()).thenReturn(false);
    when(spanEventsConfig.isEnabled()).thenReturn(true);
    when(reservoirManager.getOrCreateReservoir(any())).thenReturn(reservoir);
    SpanEventsService service = SpanEventsServiceFactory.builder().configService(configService).rpmServiceManager(rpmServiceManager).infiniteTracingConsumer(infTracingConsumer).transactionService(transactionService).reservoirManager(reservoirManager).build();
    service.storeEvent(event);
    verify(reservoir).add(event);
    verify(infTracingConsumer, never()).accept(event);
    ArgumentCaptor<AgentConfigListener> configListener = ArgumentCaptor.forClass(AgentConfigListener.class);
    ArgumentCaptor<TransactionListener> transactionListener = ArgumentCaptor.forClass(TransactionListener.class);
    verify(configService, times(2)).addIAgentConfigListener(configListener.capture());
    verify(transactionService).addTransactionListener(transactionListener.capture());
    assertSame(configListener.getValue(), service);
    assertSame(transactionListener.getValue(), service);
}
Also used : TransactionListener(com.newrelic.agent.TransactionListener) SpanEventsService(com.newrelic.agent.service.analytics.SpanEventsService) AgentConfigListener(com.newrelic.agent.config.AgentConfigListener) Test(org.junit.Test)

Aggregations

TransactionListener (com.newrelic.agent.TransactionListener)5 Test (org.junit.Test)5 TransactionData (com.newrelic.agent.TransactionData)3 TransactionStats (com.newrelic.agent.stats.TransactionStats)3 CountDownLatch (java.util.concurrent.CountDownLatch)3 AgentConfigListener (com.newrelic.agent.config.AgentConfigListener)2 SpanEventsService (com.newrelic.agent.service.analytics.SpanEventsService)2 Tracer (com.newrelic.agent.tracers.Tracer)2 ExtendedTransactionListener (com.newrelic.agent.ExtendedTransactionListener)1 Transaction (com.newrelic.agent.Transaction)1 Token (com.newrelic.agent.bridge.Token)1 TransactionEvent (com.newrelic.agent.service.analytics.TransactionEvent)1 Stats (com.newrelic.agent.stats.Stats)1 StatsEngine (com.newrelic.agent.stats.StatsEngine)1 PriorityTransactionName (com.newrelic.agent.transaction.PriorityTransactionName)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 ConcurrentLinkedQueue (java.util.concurrent.ConcurrentLinkedQueue)1 CopyOnWriteArrayList (java.util.concurrent.CopyOnWriteArrayList)1