diff --git a/sentry/api/sentry.api b/sentry/api/sentry.api index dc5c3c2a1c9..94e3127a9d3 100644 --- a/sentry/api/sentry.api +++ b/sentry/api/sentry.api @@ -4992,6 +4992,7 @@ public final class io/sentry/W3CTraceparentHeader { public final class io/sentry/backpressure/BackpressureMonitor : io/sentry/backpressure/IBackpressureMonitor, java/lang/Runnable { public fun (Lio/sentry/SentryOptions;Lio/sentry/IScopes;)V + public fun (Lio/sentry/SentryOptions;Lio/sentry/IScopes;Lio/sentry/ISentryExecutorService;)V public fun close ()V public fun getDownsampleFactor ()I public fun run ()V @@ -5453,6 +5454,7 @@ public abstract interface class io/sentry/internal/InternalIntegration : io/sent public final class io/sentry/internal/InternalServices { public static fun builder ()Lio/sentry/internal/InternalServices$Builder; + public fun close (ZJLio/sentry/ILogger;)V public static fun getCurrent ()Lio/sentry/internal/InternalServices; public fun getEnvelopeDiskCache ()Lio/sentry/cache/IEnvelopeCache; public fun getExecutorService ()Lio/sentry/ISentryExecutorService; @@ -8053,6 +8055,7 @@ public final class io/sentry/util/InitUtil { public fun ()V public static fun initializeProfileConverter (Lio/sentry/SentryOptions;)Lio/sentry/IProfileConverter; public static fun initializeProfiler (Lio/sentry/SentryOptions;)Lio/sentry/IContinuousProfiler; + public static fun initializeProfiler (Lio/sentry/SentryOptions;Lio/sentry/ISentryExecutorService;)Lio/sentry/IContinuousProfiler; public static fun shouldInit (Lio/sentry/SentryOptions;Lio/sentry/SentryOptions;Z)Z } diff --git a/sentry/src/main/java/io/sentry/Scopes.java b/sentry/src/main/java/io/sentry/Scopes.java index 30df2538699..ca4977201d8 100644 --- a/sentry/src/main/java/io/sentry/Scopes.java +++ b/sentry/src/main/java/io/sentry/Scopes.java @@ -3,6 +3,8 @@ import io.sentry.clientreport.DiscardReason; import io.sentry.hints.SessionEndHint; import io.sentry.hints.SessionStartHint; +import io.sentry.internal.InternalServices; +import io.sentry.internal.LegacyOptionsBridge; import io.sentry.logger.ILoggerApi; import io.sentry.logger.LoggerApi; import io.sentry.metrics.IMetricsApi; @@ -15,7 +17,6 @@ import io.sentry.util.TracingUtils; import java.io.Closeable; import java.util.List; -import java.util.concurrent.RejectedExecutionException; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -28,6 +29,8 @@ public final class Scopes implements IScopes { private final @Nullable Scopes parentScopes; + private final @Nullable InternalServices services; + private final @NotNull String creator; private final @NotNull CompositePerformanceCollector compositePerformanceCollector; @@ -41,7 +44,16 @@ public Scopes( final @NotNull IScope isolationScope, final @NotNull IScope globalScope, final @NotNull String creator) { - this(scope, isolationScope, globalScope, null, creator); + this(scope, isolationScope, globalScope, null, null, creator); + } + + Scopes( + final @NotNull IScope scope, + final @NotNull IScope isolationScope, + final @NotNull IScope globalScope, + final @NotNull InternalServices services, + final @NotNull String creator) { + this(scope, isolationScope, globalScope, null, services, creator); } private Scopes( @@ -49,12 +61,14 @@ private Scopes( final @NotNull IScope isolationScope, final @NotNull IScope globalScope, final @Nullable Scopes parentScopes, + final @Nullable InternalServices services, final @NotNull String creator) { this.combinedScope = new CombinedScopeView(globalScope, isolationScope, scope); this.scope = scope; this.isolationScope = isolationScope; this.globalScope = globalScope; this.parentScopes = parentScopes; + this.services = services; this.creator = creator; final @NotNull SentryOptions options = getOptions(); @@ -113,12 +127,12 @@ public boolean isAncestorOf(final @Nullable IScopes otherScopes) { @Override public @NotNull IScopes forkedScopes(final @NotNull String creator) { - return new Scopes(scope.clone(), isolationScope.clone(), globalScope, this, creator); + return new Scopes(scope.clone(), isolationScope.clone(), globalScope, this, services, creator); } @Override public @NotNull IScopes forkedCurrentScope(final @NotNull String creator) { - return new Scopes(scope.clone(), isolationScope, globalScope, this, creator); + return new Scopes(scope.clone(), isolationScope, globalScope, this, services, creator); } @Override @@ -476,23 +490,11 @@ public void close(final boolean isRestarting) { if (!isRestarting) { getOptions().getTimerExecutorService().close(getOptions().getShutdownTimeoutMillis()); } - final @NotNull ISentryExecutorService executorService = getOptions().getExecutorService(); - if (isRestarting) { - try { - executorService.submit( - () -> executorService.close(getOptions().getShutdownTimeoutMillis())); - } catch (RejectedExecutionException e) { - getOptions() - .getLogger() - .log( - SentryLevel.WARNING, - "Failed to submit executor service shutdown task during restart. Shutting down synchronously.", - e); - executorService.close(getOptions().getShutdownTimeoutMillis()); - } - } else { - executorService.close(getOptions().getShutdownTimeoutMillis()); - } + // A Scopes created without internal services gets the ones on its options. + final @NotNull InternalServices services = + this.services != null ? this.services : LegacyOptionsBridge.servicesOf(getOptions()); + services.close( + isRestarting, getOptions().getShutdownTimeoutMillis(), getOptions().getLogger()); // TODO: should we end session before closing client? configureScope(ScopeType.CURRENT, scope -> scope.getClient().close(isRestarting)); diff --git a/sentry/src/main/java/io/sentry/Sentry.java b/sentry/src/main/java/io/sentry/Sentry.java index c43f339b122..d09f4390a8e 100644 --- a/sentry/src/main/java/io/sentry/Sentry.java +++ b/sentry/src/main/java/io/sentry/Sentry.java @@ -372,22 +372,25 @@ private static void init( globalScope.replaceOptions(options); + // Before the internal services, so that what they create logs to the logger the customer + // configured. + initLogger(options); + // Also replaces an executor that a previous init closed, when the options are reused. + final @NotNull InternalServices services = + LegacyOptionsBridge.buildServices(servicesBuilder, options); + InternalServices.setCurrent(services); + final IScope rootScope = new Scope(options); final IScope rootIsolationScope = new Scope(options); - rootScopes = new Scopes(rootScope, rootIsolationScope, globalScope, "Sentry.init"); + rootScopes = + new Scopes(rootScope, rootIsolationScope, globalScope, services, "Sentry.init"); - initLogger(options); initForOpenTelemetryMaybe(options); getScopesStorage().set(rootScopes); - initConfigurations(options); + initConfigurations(options, services); globalScope.bindClient(new SentryClient(options)); - // Also replaces an executor that a previous init closed, when the options are reused. - final @NotNull InternalServices services = - LegacyOptionsBridge.buildServices(servicesBuilder, options); - InternalServices.setCurrent(services); - if (options.getTimerExecutorService().isClosed()) { options.setTimerExecutorService( new SentryExecutorService( @@ -660,7 +663,8 @@ private static boolean preInitConfigurations(final @NotNull SentryOptions option // older AGP versions do not support method references @SuppressWarnings({"FutureReturnValueIgnored", "Convert2MethodRef"}) - private static void initConfigurations(final @NotNull SentryOptions options) { + private static void initConfigurations( + final @NotNull SentryOptions options, final @NotNull InternalServices services) { final @NotNull ILogger logger = options.getLogger(); logger.log(SentryLevel.INFO, "Initializing SDK with DSN: '%s'", options.getDsn()); @@ -690,7 +694,7 @@ private static void initConfigurations(final @NotNull SentryOptions options) { profilingTracesDir.mkdirs(); try { - options + services .getExecutorService() .submit(() -> { final File[] oldTracesDirContent = profilingTracesDir.listFiles(); @@ -746,12 +750,13 @@ private static void initConfigurations(final @NotNull SentryOptions options) { if (options.isEnableBackpressureHandling() && Platform.isJvm()) { if (options.getBackpressureMonitor() instanceof NoOpBackpressureMonitor) { options.setBackpressureMonitor( - new BackpressureMonitor(options, ScopesAdapter.getInstance())); + new BackpressureMonitor( + options, ScopesAdapter.getInstance(), services.getExecutorService())); } options.getBackpressureMonitor().start(); } - initJvmContinuousProfiling(options); + initJvmContinuousProfiling(options, services); options .getLogger() @@ -762,8 +767,9 @@ private static void initConfigurations(final @NotNull SentryOptions options) { options.getProfileLifecycle()); } - private static void initJvmContinuousProfiling(@NotNull SentryOptions options) { - InitUtil.initializeProfiler(options); + private static void initJvmContinuousProfiling( + final @NotNull SentryOptions options, final @NotNull InternalServices services) { + InitUtil.initializeProfiler(options, services.getExecutorService()); InitUtil.initializeProfileConverter(options); } diff --git a/sentry/src/main/java/io/sentry/backpressure/BackpressureMonitor.java b/sentry/src/main/java/io/sentry/backpressure/BackpressureMonitor.java index fdbfea2a3a2..354d083e583 100644 --- a/sentry/src/main/java/io/sentry/backpressure/BackpressureMonitor.java +++ b/sentry/src/main/java/io/sentry/backpressure/BackpressureMonitor.java @@ -5,6 +5,7 @@ import io.sentry.ISentryLifecycleToken; import io.sentry.SentryLevel; import io.sentry.SentryOptions; +import io.sentry.internal.LegacyOptionsBridge; import io.sentry.util.AutoClosableReentrantLock; import java.util.concurrent.Future; import java.util.concurrent.RejectedExecutionException; @@ -18,6 +19,7 @@ public final class BackpressureMonitor implements IBackpressureMonitor, Runnable private final @NotNull SentryOptions sentryOptions; private final @NotNull IScopes scopes; + private final @Nullable ISentryExecutorService executorService; private int downsampleFactor = 0; private volatile @Nullable Future latestScheduledRun = null; private final @NotNull AutoClosableReentrantLock lock = new AutoClosableReentrantLock(); @@ -26,6 +28,16 @@ public BackpressureMonitor( final @NotNull SentryOptions sentryOptions, final @NotNull IScopes scopes) { this.sentryOptions = sentryOptions; this.scopes = scopes; + this.executorService = null; + } + + public BackpressureMonitor( + final @NotNull SentryOptions sentryOptions, + final @NotNull IScopes scopes, + final @NotNull ISentryExecutorService executorService) { + this.sentryOptions = sentryOptions; + this.scopes = scopes; + this.executorService = executorService; } @Override @@ -77,7 +89,10 @@ void checkHealth() { @SuppressWarnings("FutureReturnValueIgnored") private void reschedule(final int delay) { - final @NotNull ISentryExecutorService executorService = sentryOptions.getExecutorService(); + final @NotNull ISentryExecutorService executorService = + this.executorService != null + ? this.executorService + : LegacyOptionsBridge.executorOf(sentryOptions); if (!executorService.isClosed()) { try (final @NotNull ISentryLifecycleToken ignored = lock.acquire()) { try { diff --git a/sentry/src/main/java/io/sentry/internal/InternalServices.java b/sentry/src/main/java/io/sentry/internal/InternalServices.java index 8d1d7480b48..d4b8dc866d1 100644 --- a/sentry/src/main/java/io/sentry/internal/InternalServices.java +++ b/sentry/src/main/java/io/sentry/internal/InternalServices.java @@ -1,14 +1,17 @@ package io.sentry.internal; +import io.sentry.ILogger; import io.sentry.ISentryExecutorService; import io.sentry.ISerializer; import io.sentry.JsonSerializer; import io.sentry.SentryExecutorService; +import io.sentry.SentryLevel; import io.sentry.SentryOptions; import io.sentry.cache.EnvelopeCache; import io.sentry.cache.IEnvelopeCache; import io.sentry.transport.NoOpEnvelopeCache; import io.sentry.util.LazyEvaluator; +import java.util.concurrent.RejectedExecutionException; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -65,6 +68,31 @@ public static void setCurrent(final @Nullable InternalServices services) { return require(envelopeDiskCache, "envelopeDiskCache"); } + /** + * Shuts down the internal services that hold resources. On restart the executor finishes its + * queued work first, because the previous init may still have tasks on it. + */ + @SuppressWarnings("FutureReturnValueIgnored") + public void close( + final boolean isRestarting, final long shutdownTimeoutMillis, final @NotNull ILogger logger) { + if (executorService == null) { + return; + } + if (isRestarting) { + try { + executorService.submit(() -> executorService.close(shutdownTimeoutMillis)); + } catch (RejectedExecutionException e) { + logger.log( + SentryLevel.WARNING, + "Failed to submit executor service shutdown task during restart. Shutting down synchronously.", + e); + executorService.close(shutdownTimeoutMillis); + } + } else { + executorService.close(shutdownTimeoutMillis); + } + } + private static @NotNull T require(final @Nullable T value, final @NotNull String name) { if (value == null) { // Only buildForTest() leaves internal services unset. diff --git a/sentry/src/main/java/io/sentry/util/InitUtil.java b/sentry/src/main/java/io/sentry/util/InitUtil.java index 6c1787474fa..95e683dc37f 100644 --- a/sentry/src/main/java/io/sentry/util/InitUtil.java +++ b/sentry/src/main/java/io/sentry/util/InitUtil.java @@ -2,12 +2,14 @@ import io.sentry.IContinuousProfiler; import io.sentry.IProfileConverter; +import io.sentry.ISentryExecutorService; import io.sentry.ManifestVersionDetector; import io.sentry.NoOpContinuousProfiler; import io.sentry.NoOpProfileConverter; import io.sentry.NoopVersionDetector; import io.sentry.SentryLevel; import io.sentry.SentryOptions; +import io.sentry.internal.LegacyOptionsBridge; import io.sentry.profiling.ProfilingServiceLoader; import java.io.File; import org.jetbrains.annotations.ApiStatus; @@ -56,6 +58,13 @@ public static boolean shouldInit( } public static IContinuousProfiler initializeProfiler(@NotNull SentryOptions options) { + // Spring creates the profiler as a bean before Sentry.init, when no internal services exist + // yet. + return initializeProfiler(options, LegacyOptionsBridge.executorOf(options)); + } + + public static IContinuousProfiler initializeProfiler( + final @NotNull SentryOptions options, final @NotNull ISentryExecutorService executorService) { if (!shouldInitializeProfiler(options)) { return options.getContinuousProfiler(); } @@ -67,7 +76,7 @@ public static IContinuousProfiler initializeProfiler(@NotNull SentryOptions opti options.getLogger(), profilingTracesDirPath, options.getProfilingTracesHz(), - options.getExecutorService()); + executorService); if (profiler instanceof NoOpContinuousProfiler) { options diff --git a/sentry/src/test/java/io/sentry/SentryTest.kt b/sentry/src/test/java/io/sentry/SentryTest.kt index 24406d541ba..4b09bc1a63b 100644 --- a/sentry/src/test/java/io/sentry/SentryTest.kt +++ b/sentry/src/test/java/io/sentry/SentryTest.kt @@ -823,20 +823,22 @@ class SentryTest { } @Test - fun `init does not throw on executor shut down`() { + fun `init replaces a shut down executor before using it`() { val logger = mock() + val closed = SentryExecutorService() + closed.close(0) initForTest { it.dsn = dsn it.profilesSampleRate = 1.0 it.cacheDirPath = getTempPath() it.setLogger(logger) - it.executorService = SentryExecutorService() - it.executorService.close(0) + it.executorService = closed it.isDebug = true } - verify(logger) + assertNotSame(closed, Sentry.getCurrentScopes().options.executorService) + verify(logger, never()) .log( eq(SentryLevel.ERROR), eq( diff --git a/sentry/src/test/java/io/sentry/internal/InternalServicesTest.kt b/sentry/src/test/java/io/sentry/internal/InternalServicesTest.kt index 44a10348734..26e458e7d29 100644 --- a/sentry/src/test/java/io/sentry/internal/InternalServicesTest.kt +++ b/sentry/src/test/java/io/sentry/internal/InternalServicesTest.kt @@ -3,14 +3,20 @@ package io.sentry.internal import com.google.common.truth.Truth.assertThat import io.sentry.ISentryExecutorService import io.sentry.ISerializer +import io.sentry.NoOpLogger import io.sentry.SentryOptions import io.sentry.cache.EnvelopeCache import io.sentry.cache.IEnvelopeCache +import io.sentry.test.ImmediateExecutorService import io.sentry.transport.NoOpEnvelopeCache import java.nio.file.Files import kotlin.test.Test import kotlin.test.assertFailsWith +import org.mockito.kotlin.any +import org.mockito.kotlin.inOrder import org.mockito.kotlin.mock +import org.mockito.kotlin.spy +import org.mockito.kotlin.verify import org.mockito.kotlin.whenever class InternalServicesTest { @@ -51,6 +57,30 @@ class InternalServicesTest { assertThat(created).isEqualTo(1) } + @Test + fun `close shuts the executor down`() { + val executor = mock() + val services = InternalServices.builder().executorService(executor).buildForTest() + + services.close(false, 123, NoOpLogger.getInstance()) + + verify(executor).close(123) + } + + @Test + fun `close on restart lets the executor finish its queued work first`() { + val executor = ImmediateExecutorService() + val closing = spy(executor) + val services = InternalServices.builder().executorService(closing).buildForTest() + + services.close(true, 123, NoOpLogger.getInstance()) + + inOrder(closing) { + verify(closing).submit(any()) + verify(closing).close(123) + } + } + @Test fun `buildForTest fails on an internal service the test didn't set`() { val services = InternalServices.builder().envelopeDiskCache(mock()).buildForTest()