diff --git a/sentry/src/main/java/io/sentry/DefaultCompositePerformanceCollector.java b/sentry/src/main/java/io/sentry/DefaultCompositePerformanceCollector.java index 89373516e2c..c4f0297a135 100644 --- a/sentry/src/main/java/io/sentry/DefaultCompositePerformanceCollector.java +++ b/sentry/src/main/java/io/sentry/DefaultCompositePerformanceCollector.java @@ -5,9 +5,9 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; -import java.util.Timer; -import java.util.TimerTask; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Future; +import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.jetbrains.annotations.ApiStatus; @@ -19,7 +19,14 @@ public final class DefaultCompositePerformanceCollector implements CompositePerf private static final long TRANSACTION_COLLECTION_INTERVAL_MILLIS = 100; private static final long TRANSACTION_COLLECTION_TIMEOUT_MILLIS = 30000; private final @NotNull AutoClosableReentrantLock timerLock = new AutoClosableReentrantLock(); - private volatile @Nullable Timer timer = null; + private volatile @Nullable Future collectFuture = null; + + /** + * Incremented on close() so an in-flight setup or collect run doesn't schedule the next collect + * after its chain was cancelled. Guarded by timerLock. + */ + private long generation = 0; + private final @NotNull Map compositeDataMap = new ConcurrentHashMap<>(); private final @NotNull List snapshotCollectors; private final @NotNull List continuousCollectors; @@ -88,62 +95,72 @@ public void start(final @NotNull String id) { } if (!isStarted.getAndSet(true)) { try (final @NotNull ISentryLifecycleToken ignored = timerLock.acquire()) { - if (timer == null) { - timer = new Timer(true); + final long currentGeneration = generation; + collectFuture = + options + .getTimerExecutorService() + .schedule(() -> setupAndScheduleCollect(currentGeneration), 0L); + } catch (RejectedExecutionException e) { + options + .getLogger() + .log(SentryLevel.WARNING, "Failed to schedule performance collection.", e); + } + } + } + + private void setupAndScheduleCollect(final long scheduledGeneration) { + for (IPerformanceSnapshotCollector collector : snapshotCollectors) { + collector.setup(); + } + // The first collect() is scheduled only after setup() ran, not alongside it: if the shared + // timer thread was busy, both would be due at once and run back to back, leaving collectors + // that average over the time since the previous call, like AndroidCpuCollector, no interval. + scheduleCollect(scheduledGeneration); + } + + private void collectAndReschedule(final long scheduledGeneration) { + final @NotNull PerformanceCollectionData tempData = + new PerformanceCollectionData(options.getDateProvider().now().nanoTimestamp()); + + // Enrich tempData using collectors + for (IPerformanceSnapshotCollector collector : snapshotCollectors) { + collector.collect(tempData); + } + + // Add the enriched tempData to all transactions/profiles/objects that collect data. + // Then Check if that object timed out. + final @NotNull List timedOutTransactions = new ArrayList<>(); + for (CompositeData data : compositeDataMap.values()) { + if (data.addDataAndCheckTimeout(tempData, tempData.getNanoTimestamp())) { + // timed out + if (data.transaction != null) { + timedOutTransactions.add(data.transaction); } - // We schedule the timer to call setup() on collectors immediately in the background. - timer.schedule( - new TimerTask() { - @Override - public void run() { - for (IPerformanceSnapshotCollector collector : snapshotCollectors) { - collector.setup(); - } - } - }, - 0L); - // We schedule the timer to start after a delay, so we let some time pass between setup() - // and collect() calls. - // This way ICollectors that collect average stats based on time intervals, like - // AndroidCpuCollector, can have an actual time interval to evaluate. - final @NotNull List timedOutTransactions = new ArrayList<>(); - TimerTask timerTask = - new TimerTask() { - @Override - public void run() { - timedOutTransactions.clear(); - - final @NotNull PerformanceCollectionData tempData = - new PerformanceCollectionData(options.getDateProvider().now().nanoTimestamp()); - - // Enrich tempData using collectors - for (IPerformanceSnapshotCollector collector : snapshotCollectors) { - collector.collect(tempData); - } - - // Add the enriched tempData to all transactions/profiles/objects that collect data. - // Then Check if that object timed out. - for (CompositeData data : compositeDataMap.values()) { - if (data.addDataAndCheckTimeout(tempData, tempData.getNanoTimestamp())) { - // timed out - if (data.transaction != null) { - timedOutTransactions.add(data.transaction); - } - } - } - // Stop timed out transactions outside compositeDataMap loop, as stop() modifies the - // map - for (final @NotNull ITransaction t : timedOutTransactions) { - stop(t); - } - } - }; - timer.schedule( - timerTask, - TRANSACTION_COLLECTION_INTERVAL_MILLIS, - TRANSACTION_COLLECTION_INTERVAL_MILLIS); } } + // Stop timed out transactions outside compositeDataMap loop, as stop() modifies the map + for (final @NotNull ITransaction t : timedOutTransactions) { + stop(t); + } + + scheduleCollect(scheduledGeneration); + } + + private void scheduleCollect(final long scheduledGeneration) { + try (final @NotNull ISentryLifecycleToken ignored = timerLock.acquire()) { + // close() may have run since this chain was scheduled, even from the calling run by stopping + // a timed out transaction; only continue if the chain is still the current one + if (scheduledGeneration == generation) { + collectFuture = + options + .getTimerExecutorService() + .schedule( + () -> collectAndReschedule(scheduledGeneration), + TRANSACTION_COLLECTION_INTERVAL_MILLIS); + } + } catch (RejectedExecutionException e) { + options.getLogger().log(SentryLevel.WARNING, "Failed to schedule performance collection.", e); + } } @Override @@ -201,9 +218,10 @@ public void close() { } if (isStarted.getAndSet(false)) { try (final @NotNull ISentryLifecycleToken ignored = timerLock.acquire()) { - if (timer != null) { - timer.cancel(); - timer = null; + generation++; + if (collectFuture != null) { + collectFuture.cancel(false); + collectFuture = null; } } } diff --git a/sentry/src/test/java/io/sentry/DefaultCompositePerformanceCollectorTest.kt b/sentry/src/test/java/io/sentry/DefaultCompositePerformanceCollectorTest.kt index 5726b6ca25c..06a8faf545d 100644 --- a/sentry/src/test/java/io/sentry/DefaultCompositePerformanceCollectorTest.kt +++ b/sentry/src/test/java/io/sentry/DefaultCompositePerformanceCollectorTest.kt @@ -2,9 +2,10 @@ package io.sentry import io.sentry.test.getCtor import io.sentry.test.getProperty -import io.sentry.test.injectForField import io.sentry.util.thread.ThreadChecker -import java.util.Timer +import java.util.concurrent.Callable +import java.util.concurrent.Future +import java.util.concurrent.FutureTask import java.util.concurrent.TimeUnit import kotlin.test.Test import kotlin.test.assertEquals @@ -34,7 +35,7 @@ class DefaultCompositePerformanceCollectorTest { val id1 = "id1" val scopes: IScopes = mock() val options = SentryOptions() - var mockTimer: Timer? = null + val executorService = FakeTimerExecutorService() val mockCpuCollector: IPerformanceSnapshotCollector = object : IPerformanceSnapshotCollector { @@ -47,6 +48,7 @@ class DefaultCompositePerformanceCollectorTest { init { whenever(scopes.options).thenReturn(options) + options.setTimerExecutorService(executorService) } fun getSut( @@ -65,14 +67,65 @@ class DefaultCompositePerformanceCollectorTest { optionsConfiguration.configure(options) transaction1 = SentryTracer(TransactionContext("", ""), scopes) transaction2 = SentryTracer(TransactionContext("", ""), scopes) - val collector = DefaultCompositePerformanceCollector(options) - val timer: Timer = collector.getProperty("timer") ?: Timer(true) - mockTimer = spy(timer) - collector.injectForField("timer", mockTimer) - return collector + return DefaultCompositePerformanceCollector(options) } } + /** + * Runs scheduled tasks on the calling thread, only when the test advances its clock, so tests can + * step through each collection and nothing keeps running after a test ends. + */ + private class FakeTimerExecutorService : ISentryExecutorService { + private class ScheduledTask(val runAtMillis: Long, runnable: Runnable) : + FutureTask(runnable, Unit) + + var nowMillis = 0L + private set + + private val tasks = mutableListOf() + val scheduledDelays = mutableListOf() + + override fun schedule(runnable: Runnable, delayMillis: Long): Future<*> { + scheduledDelays.add(delayMillis) + return ScheduledTask(nowMillis + delayMillis, runnable).also { tasks.add(it) } + } + + /** Runs, in order, every task due within [millis], including tasks those tasks schedule. */ + fun advanceBy(millis: Long) { + val targetMillis = nowMillis + millis + while (true) { + val next = + tasks + .filterNot { it.isCancelled } + .minByOrNull { it.runAtMillis } + ?.takeIf { + it.runAtMillis <= targetMillis + } ?: break + tasks.remove(next) + nowMillis = maxOf(nowMillis, next.runAtMillis) + next.run() + } + nowMillis = maxOf(nowMillis, targetMillis) + } + + /** Called from a running task to simulate it holding the timer thread for [millis]. */ + fun busyFor(millis: Long) { + nowMillis += millis + } + + override fun submit(runnable: Runnable): Future<*> = throw UnsupportedOperationException() + + override fun submit(callable: Callable): Future = + throw UnsupportedOperationException() + + override fun close(timeoutMillis: Long) {} + + override fun isClosed(): Boolean = false + } + + private fun CompositePerformanceCollector.collectFuture(): Future<*>? = + getProperty?>("collectFuture") + @Test fun `when null param is provided, invalid argument is thrown`() { val ctor = className.getCtor(ctorTypes) @@ -85,7 +138,7 @@ class DefaultCompositePerformanceCollectorTest { val collector = fixture.getSut(null, null) assertTrue(fixture.options.performanceCollectors.isEmpty()) collector.start(fixture.transaction1) - verify(fixture.mockTimer, never())!!.schedule(any(), any(), any()) + assertTrue(fixture.executorService.scheduledDelays.isEmpty()) } @Test @@ -94,49 +147,72 @@ class DefaultCompositePerformanceCollectorTest { val cpuCollector = mock() val collector = fixture.getSut(memoryCollector, cpuCollector) collector.start(fixture.transaction1) - Thread.sleep(300) + fixture.executorService.advanceBy(0) verify(memoryCollector).setup() verify(cpuCollector).setup() } @Test - fun `when start, timer is scheduled every 100 milliseconds`() { - val collector = fixture.getSut() + fun `when start, collection runs every 100 milliseconds`() { + val collector = fixture.getSut(memoryCollector = null, cpuCollector = countingCollector) collector.start(fixture.transaction1) - verify(fixture.mockTimer)!!.schedule(any(), any(), eq(100)) + + assertCollectsEvery100Millis() } @Test - fun `when start with a string, timer is scheduled every 100 milliseconds`() { - val collector = fixture.getSut() + fun `when start with a string, collection runs every 100 milliseconds`() { + val collector = fixture.getSut(memoryCollector = null, cpuCollector = countingCollector) collector.start(fixture.id1) - verify(fixture.mockTimer)!!.schedule(any(), any(), eq(100)) + + assertCollectsEvery100Millis() + } + + private var collectCount = 0 + private val countingCollector = + object : IPerformanceSnapshotCollector { + override fun setup() {} + + override fun collect(performanceCollectionData: PerformanceCollectionData) { + collectCount++ + } + } + + private fun assertCollectsEvery100Millis() { + fixture.executorService.advanceBy(99) + assertEquals(0, collectCount) + fixture.executorService.advanceBy(1) + assertEquals(1, collectCount) + fixture.executorService.advanceBy(100) + assertEquals(2, collectCount) + fixture.executorService.advanceBy(100) + assertEquals(3, collectCount) } @Test - fun `when stop, timer is stopped`() { + fun `when stop, collection is stopped`() { val collector = fixture.getSut() collector.start(fixture.transaction1) + assertNotNull(collector.collectFuture()) collector.stop(fixture.transaction1) - verify(fixture.mockTimer)!!.schedule(any(), any(), eq(100)) - verify(fixture.mockTimer)!!.cancel() + assertNull(collector.collectFuture()) } @Test - fun `when stop with a string, timer is stopped`() { + fun `when stop with a string, collection is stopped`() { val collector = fixture.getSut() collector.start(fixture.id1) + assertNotNull(collector.collectFuture()) collector.stop(fixture.id1) - verify(fixture.mockTimer)!!.schedule(any(), any(), eq(100)) - verify(fixture.mockTimer)!!.cancel() + assertNull(collector.collectFuture()) } @Test fun `stopping a not collected transaction return null`() { val collector = fixture.getSut() val data = collector.stop(fixture.transaction1) - verify(fixture.mockTimer, never())!!.schedule(any(), any(), eq(100)) - verify(fixture.mockTimer, never())!!.cancel() + assertTrue(fixture.executorService.scheduledDelays.isEmpty()) + assertNull(collector.collectFuture()) assertNull(data) } @@ -144,8 +220,8 @@ class DefaultCompositePerformanceCollectorTest { fun `stopping a not collected id return null`() { val collector = fixture.getSut() val data = collector.stop(fixture.id1) - verify(fixture.mockTimer, never())!!.schedule(any(), any(), eq(100)) - verify(fixture.mockTimer, never())!!.cancel() + assertTrue(fixture.executorService.scheduledDelays.isEmpty()) + assertNull(collector.collectFuture()) assertNull(data) } @@ -155,20 +231,19 @@ class DefaultCompositePerformanceCollectorTest { collector.start(fixture.transaction1) collector.start(fixture.transaction2) collector.start(fixture.id1) - // Let's sleep to make the collector get values - Thread.sleep(300) + fixture.executorService.advanceBy(300) val data1 = collector.stop(fixture.transaction1) - // There is still a transaction and an id running: the timer shouldn't stop now - verify(fixture.mockTimer, never())!!.cancel() + // There is still a transaction and an id running: the collection shouldn't stop now + assertNotNull(collector.collectFuture()) val data2 = collector.stop(fixture.transaction2) - // There is still an id running: the timer shouldn't stop now - verify(fixture.mockTimer, never())!!.cancel() + // There is still an id running: the collection shouldn't stop now + assertNotNull(collector.collectFuture()) val data3 = collector.stop(fixture.id1) - // There are no more transactions or ids running: the time should stop now - verify(fixture.mockTimer)!!.cancel() + // There are no more transactions or ids running: the collection should stop now + assertNull(collector.collectFuture()) assertNotNull(data1) assertNotNull(data2) @@ -196,14 +271,13 @@ class DefaultCompositePerformanceCollectorTest { it.addPerformanceCollector(mockCollector) } collector.start(fixture.transaction1) - verify(fixture.mockTimer, never())!!.cancel() + assertNotNull(collector.collectFuture()) - // Let's sleep to make the collector get values - Thread.sleep(300) + fixture.executorService.advanceBy(300) // When the collector gets the values, it checks the current date, set 31 seconds after the // begin. This means it should stop itself - verify(fixture.mockTimer)!!.cancel() + assertNull(collector.collectFuture()) // When the collector times out, the data collection for spans is stopped, too verify(mockCollector).onSpanFinished(eq(fixture.transaction1)) @@ -224,14 +298,13 @@ class DefaultCompositePerformanceCollectorTest { whenever(mockDateProvider.now()).thenReturn(dates[0], dates[0], dates[0], dates[1]) val collector = fixture.getSut { it.dateProvider = mockDateProvider } collector.start(fixture.transaction1) - verify(fixture.mockTimer, never())!!.cancel() + assertNotNull(collector.collectFuture()) - // Let's sleep to make the collector get values - Thread.sleep(300) + fixture.executorService.advanceBy(300) // When the collector gets the values, it checks the current date, set 30 seconds after the // begin. This means it should continue without being cancelled - verify(fixture.mockTimer, never())!!.cancel() + assertNotNull(collector.collectFuture()) // Data is deleted after the collector times out val data1 = collector.stop(fixture.transaction1) @@ -264,8 +337,7 @@ class DefaultCompositePerformanceCollectorTest { assertEquals(3, fixture.options.performanceCollectors.size) collector.start(fixture.transaction1) - // Let's sleep to make the collector get values - Thread.sleep(300) + fixture.executorService.advanceBy(300) val data1 = collector.stop(fixture.transaction1) assertNotNull(data1) val memoryData = data1.filter { it.hasUsedHeapMemory() } @@ -280,8 +352,36 @@ class DefaultCompositePerformanceCollectorTest { assertEquals(memoryData.size, cpuData.size) } + @Test + fun `first collect runs a full interval after setup even when the timer thread was busy`() { + var setupMillis = -1L + var firstCollectMillis = -1L + val timingCollector = + object : IPerformanceSnapshotCollector { + override fun setup() { + setupMillis = fixture.executorService.nowMillis + } + + override fun collect(performanceCollectionData: PerformanceCollectionData) { + if (firstCollectMillis == -1L) { + firstCollectMillis = fixture.executorService.nowMillis + } + } + } + val collector = fixture.getSut(memoryCollector = null, cpuCollector = timingCollector) + fixture.executorService.schedule({ fixture.executorService.busyFor(200) }, 0L) + + collector.start(fixture.transaction1) + fixture.executorService.advanceBy(300) + + assertEquals(200, setupMillis) + assertEquals(300, firstCollectMillis) + } + @Test fun `setup and collect happen on background thread`() { + val executorService = SentryExecutorService(fixture.options) + fixture.options.setTimerExecutorService(executorService) val threadCheckerCollector = spy(ThreadCheckerCollector()) fixture.options.addPerformanceCollector(threadCheckerCollector) val collector = fixture.getSut() @@ -292,20 +392,21 @@ class DefaultCompositePerformanceCollectorTest { // Let's sleep to make the collector get values Thread.sleep(300) collector.stop(fixture.transaction1) + executorService.close(0) verify(threadCheckerCollector).setup() verify(threadCheckerCollector, atLeast(1)).collect(any()) } @Test - fun `when close, timer is stopped and data is cleared`() { + fun `when close, collection is stopped and data is cleared`() { val collector = fixture.getSut() collector.start(fixture.transaction1) collector.close() - // Timer was canceled - verify(fixture.mockTimer)!!.schedule(any(), any(), eq(100)) - verify(fixture.mockTimer)!!.cancel() + // Collection was canceled + assertTrue(fixture.executorService.scheduledDelays.isNotEmpty()) + assertNull(collector.collectFuture()) // Data was cleared assertNull(collector.stop(fixture.transaction1))