Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions sentry/api/sentry.api
Original file line number Diff line number Diff line change
Expand Up @@ -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 <init> (Lio/sentry/SentryOptions;Lio/sentry/IScopes;)V
public fun <init> (Lio/sentry/SentryOptions;Lio/sentry/IScopes;Lio/sentry/ISentryExecutorService;)V
public fun close ()V
public fun getDownsampleFactor ()I
public fun run ()V
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -8053,6 +8055,7 @@ public final class io/sentry/util/InitUtil {
public fun <init> ()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
}

Expand Down
44 changes: 23 additions & 21 deletions sentry/src/main/java/io/sentry/Scopes.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand All @@ -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;

Expand All @@ -41,20 +44,31 @@ 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(
final @NotNull IScope scope,
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();
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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));
Expand Down
34 changes: 20 additions & 14 deletions sentry/src/main/java/io/sentry/Sentry.java
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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());

Expand Down Expand Up @@ -690,7 +694,7 @@ private static void initConfigurations(final @NotNull SentryOptions options) {
profilingTracesDir.mkdirs();

try {
options
services
.getExecutorService()
.submit(() -> {
final File[] oldTracesDirContent = profilingTracesDir.listFiles();
Expand Down Expand Up @@ -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()
Expand All @@ -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);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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();
Expand All @@ -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
Expand Down Expand Up @@ -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 {
Expand Down
28 changes: 28 additions & 0 deletions sentry/src/main/java/io/sentry/internal/InternalServices.java
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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 <T> @NotNull T require(final @Nullable T value, final @NotNull String name) {
if (value == null) {
// Only buildForTest() leaves internal services unset.
Expand Down
11 changes: 10 additions & 1 deletion sentry/src/main/java/io/sentry/util/InitUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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();
}
Expand All @@ -67,7 +76,7 @@ public static IContinuousProfiler initializeProfiler(@NotNull SentryOptions opti
options.getLogger(),
profilingTracesDirPath,
options.getProfilingTracesHz(),
options.getExecutorService());
executorService);

if (profiler instanceof NoOpContinuousProfiler) {
options
Expand Down
10 changes: 6 additions & 4 deletions sentry/src/test/java/io/sentry/SentryTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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<ILogger>()
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(
Expand Down
Loading
Loading