diff --git a/sentry-android-core/api/sentry-android-core.api b/sentry-android-core/api/sentry-android-core.api index 7c8dcbb151e..821dc124374 100644 --- a/sentry-android-core/api/sentry-android-core.api +++ b/sentry-android-core/api/sentry-android-core.api @@ -213,7 +213,7 @@ public final class io/sentry/android/core/AppStartExtension$ExtendedAppStart { public fun (Lio/sentry/ITransaction;Lio/sentry/ISpan;)V } -public final class io/sentry/android/core/AppState : java/io/Closeable { +public final class io/sentry/android/core/AppState : io/sentry/android/core/AppStateProvider, java/io/Closeable { public fun addAppStateListener (Lio/sentry/android/core/AppState$AppStateListener;)V public fun close ()V public static fun getInstance ()Lio/sentry/android/core/AppState; @@ -444,6 +444,7 @@ public final class io/sentry/android/core/SentryAndroidOptions : io/sentry/Sentr public fun getBeforeViewHierarchyCaptureCallback ()Lio/sentry/android/core/SentryAndroidOptions$BeforeCaptureCallback; public fun getDebugImagesLoader ()Lio/sentry/android/core/IDebugImagesLoader; public fun getFrameMetricsCollector ()Lio/sentry/android/core/internal/util/SentryFrameMetricsCollector; + public fun getHangManager ()Lio/sentry/android/core/hang/HangManager; public fun getMonotonicTicker ()Lio/sentry/time/MonotonicTicker; public fun getNativeSdkName ()Ljava/lang/String; public fun getNdkAppHangTimeoutIntervalMillis ()J @@ -514,6 +515,7 @@ public final class io/sentry/android/core/SentryAndroidOptions : io/sentry/Sentr public fun setEnableSystemEventBreadcrumbs (Z)V public fun setEnableSystemEventBreadcrumbsExtras (Z)V public fun setFrameMetricsCollector (Lio/sentry/android/core/internal/util/SentryFrameMetricsCollector;)V + public fun setHangManager (Lio/sentry/android/core/hang/HangManager;)V public fun setMemoryLimiterEnabled (Z)V public fun setNativeHandlerStrategy (Lio/sentry/android/core/NdkHandlerStrategy;)V public fun setNativeSdkName (Ljava/lang/String;)V @@ -763,6 +765,14 @@ public final class io/sentry/android/core/anr/AnrProfileRotationHelper { public static fun rotate ()V } +public final class io/sentry/android/core/anr/AnrProfileStore : io/sentry/android/core/hang/HangSampleStore { + public fun (Lio/sentry/SentryOptions;)V + public fun add (Lio/sentry/android/core/anr/AnrStackTrace;)V + public synthetic fun add (Ljava/lang/Object;)V + public fun clear ()V + public fun close ()V +} + public final class io/sentry/android/core/anr/AnrProfilingIntegration : io/sentry/Integration, io/sentry/android/core/AppState$AppStateListener, java/io/Closeable, java/lang/Runnable { public static final field POLLING_INTERVAL_MS J public static final field THRESHOLD_ANR_MS J @@ -811,6 +821,12 @@ public final class io/sentry/android/core/cache/AndroidEnvelopeCache : io/sentry public fun storeEnvelope (Lio/sentry/SentryEnvelope;Lio/sentry/Hint;)Z } +public final class io/sentry/android/core/hang/HandlerThreadPoster : io/sentry/android/core/hang/ThreadPoster { + public fun (Landroid/os/Handler;)V + public fun post (Ljava/lang/Runnable;)V + public fun remove (Ljava/lang/Runnable;)V +} + public final class io/sentry/android/core/hang/HangCollectorSetup { public fun (Lio/sentry/android/core/hang/HangDataCollector;Lio/sentry/android/core/hang/HangRecordWriter;Lio/sentry/android/core/hang/HangSampleStore;)V } diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/AndroidOptionsInitializer.java b/sentry-android-core/src/main/java/io/sentry/android/core/AndroidOptionsInitializer.java index 52a54b339dc..9ef7e81cc43 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/AndroidOptionsInitializer.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/AndroidOptionsInitializer.java @@ -9,11 +9,14 @@ import android.content.Context; import android.content.pm.PackageInfo; import android.os.Build; +import android.os.Handler; +import android.os.Looper; import io.sentry.CompositePerformanceCollector; import io.sentry.DeduplicateMultithreadedEventProcessor; import io.sentry.DefaultCompositePerformanceCollector; import io.sentry.DefaultVersionDetector; import io.sentry.IContinuousProfiler; +import io.sentry.IDebugManager; import io.sentry.ILogger; import io.sentry.ISentryLifecycleToken; import io.sentry.ITransactionProfiler; @@ -29,9 +32,17 @@ import io.sentry.SendFireAndForgetOutboxSender; import io.sentry.SentryLevel; import io.sentry.SentryOpenTelemetryMode; +import io.sentry.android.core.anr.AnrProfileManager; import io.sentry.android.core.anr.AnrProfileRotationHelper; +import io.sentry.android.core.anr.AnrProfileStore; import io.sentry.android.core.anr.AnrProfilingIntegration; import io.sentry.android.core.cache.AndroidEnvelopeCache; +import io.sentry.android.core.hang.HandlerThreadPoster; +import io.sentry.android.core.hang.HangCollectorSetup; +import io.sentry.android.core.hang.HangManager; +import io.sentry.android.core.hang.ThreadHangSignal; +import io.sentry.android.core.hang.ThreadPoster; +import io.sentry.android.core.hang.ThreadSampleCollector; import io.sentry.android.core.internal.debugmeta.AssetsDebugMetaLoader; import io.sentry.android.core.internal.gestures.AndroidViewGestureTargetLocator; import io.sentry.android.core.internal.modules.AssetsModulesLoader; @@ -53,6 +64,9 @@ import io.sentry.internal.modules.NoOpModulesLoader; import io.sentry.internal.viewhierarchy.ViewHierarchyExporter; import io.sentry.protocol.SentryId; +import io.sentry.time.EpochClock; +import io.sentry.time.JavaMonotonicTicker; +import io.sentry.time.MonotonicTicker; import io.sentry.transport.CurrentDateProvider; import io.sentry.transport.NoOpEnvelopeCache; import io.sentry.transport.NoOpTransportGate; @@ -61,6 +75,7 @@ import io.sentry.util.thread.NoOpThreadChecker; import java.io.File; import java.util.ArrayList; +import java.util.Collections; import java.util.List; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -258,9 +273,12 @@ static void initializeIntegrationsAndProcessors( if (options.getThreadChecker() instanceof NoOpThreadChecker) { options.setThreadChecker(AndroidThreadChecker.getInstance()); } - if (options.getDebugManager() == null) { - options.setDebugManager(new AndroidDebugManager()); + @Nullable IDebugManager debugManager = options.getDebugManager(); + if (debugManager == null) { + debugManager = new AndroidDebugManager(); + options.setDebugManager(debugManager); } + setupHangManager(options, debugManager); if (options.getSocketTagger() instanceof NoOpSocketTagger) { options.setSocketTagger(AndroidSocketTagger.getInstance()); } @@ -516,6 +534,41 @@ static void installDefaultIntegrations( .setFormHandler(new SentryAndroidOptions.AndroidUserFeedbackFormHandler()); } + private static void setupHangManager( + final @NotNull SentryAndroidOptions options, final @NotNull IDebugManager debugManager) { + if (options.getCacheDirPath() == null || options.getHangManager() != null) { + return; + } + final @NotNull Looper mainLooper = Looper.getMainLooper(); + final @NotNull ThreadPoster mainThreadPoster = new HandlerThreadPoster(new Handler(mainLooper)); + // options.getMonotonicTicker() counts device sleep, which would read as a hang. + final @NotNull MonotonicTicker ticker = JavaMonotonicTicker.getInstance(); + final @NotNull EpochClock epochClock = options.getEpochClock(); + final @NotNull HangManager manager = + new HangManager( + options, + AppState.getInstance(), + ticker, + epochClock, + HangManager.DEFAULT_POLLING_INTERVAL_MS, + HangManager.DEFAULT_MAX_RECORDING_TIME_MS, + AnrProfileManager.MAX_NUM_STACKTRACES, + HangManager.DEFAULT_EXECUTOR_FACTORY, + metronome -> + Collections.singletonList( + new ThreadHangSignal( + metronome, + debugManager, + mainThreadPoster, + HangManager.DEFAULT_SUSPICIOUS_THRESHOLD_MS)), + Collections.singletonList( + new HangCollectorSetup<>( + new ThreadSampleCollector(mainLooper.getThread()), + (stackTrace, record) -> record.addStackTrace(stackTrace), + new AnrProfileStore(options)))); + options.setHangManager(manager); + } + /** * Reads and sets default option values that are Android specific like release and inApp * diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/AppState.java b/sentry-android-core/src/main/java/io/sentry/android/core/AppState.java index 24562e3aa49..08897de9565 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/AppState.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/AppState.java @@ -22,7 +22,7 @@ /** AppState holds the state of the App, e.g. whether the app is in background/foreground, etc. */ @ApiStatus.Internal -public final class AppState implements Closeable { +public final class AppState implements Closeable, AppStateProvider { private static @NotNull AppState instance = new AppState(); private final @NotNull AutoClosableReentrantLock lock = new AutoClosableReentrantLock(); private volatile @Nullable LifecycleObserver lifecycleObserver; @@ -61,6 +61,7 @@ void setInBackground(final boolean inBackground) { this.inBackground = inBackground; } + @Override public void addAppStateListener(final @NotNull AppStateListener listener) { try (final @NotNull ISentryLifecycleToken ignored = lock.acquire()) { ensureLifecycleObserver(NoOpLogger.getInstance()); @@ -71,6 +72,7 @@ public void addAppStateListener(final @NotNull AppStateListener listener) { } } + @Override public void removeAppStateListener(final @NotNull AppStateListener listener) { try (final @NotNull ISentryLifecycleToken ignored = lock.acquire()) { if (lifecycleObserver != null) { diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/SentryAndroidOptions.java b/sentry-android-core/src/main/java/io/sentry/android/core/SentryAndroidOptions.java index 2afb245fe38..d6c6a80f61c 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/SentryAndroidOptions.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/SentryAndroidOptions.java @@ -14,6 +14,7 @@ import io.sentry.SentryLevel; import io.sentry.SentryOptions; import io.sentry.SpanStatus; +import io.sentry.android.core.hang.HangManager; import io.sentry.android.core.internal.time.AndroidMonotonicTicker; import io.sentry.android.core.internal.util.RootChecker; import io.sentry.android.core.internal.util.SentryFrameMetricsCollector; @@ -333,6 +334,8 @@ public interface BeforeCaptureCallback { private boolean enableAnrFingerprinting = true; + private volatile @Nullable HangManager hangManager; + public SentryAndroidOptions() { setSentryClientName(BuildConfig.SENTRY_ANDROID_SDK_NAME + "/" + BuildConfig.VERSION_NAME); setSdkVersion(createSdkVersion()); @@ -977,6 +980,10 @@ public void setEnableSystemEventBreadcrumbsExtras( * Sets the sample rate for capturing main-thread stack profiles when a foreground ANR is * detected. The profile is attached to the ANR event on the next app start. * + *

The sampling decision is made at each hang. Stack sampling starts after the main thread was + * blocked for 300 ms. An unsampled hang captures no stacks, unless another feature, such as + * non-fatal ANR reporting, needs them. + * *

Use {@code null} to disable ANR profiling (default). Values must be between {@code 0.0} and * {@code 1.0}. * @@ -1002,6 +1009,20 @@ public boolean isAnrProfilingEnabled() { return anrProfilingSampleRate != null && anrProfilingSampleRate > 0; } + /** + * The hang manager that the ANR integrations share. Null if {@link #getCacheDirPath()} was null + * at init. + */ + @ApiStatus.Internal + public @Nullable HangManager getHangManager() { + return hangManager; + } + + @ApiStatus.Internal + public void setHangManager(final @Nullable HangManager hangManager) { + this.hangManager = hangManager; + } + /** * Returns whether ANR fingerprinting is enabled. When enabled, the SDK assigns static * fingerprints to ANR events that would otherwise produce noisy grouping. Currently, this applies diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfileRotationHelper.java b/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfileRotationHelper.java index 204d4c5c650..6a79c15cdf6 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfileRotationHelper.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfileRotationHelper.java @@ -6,8 +6,8 @@ import org.jetbrains.annotations.NotNull; /** - * Coordinates file rotation between AnrProfilingIntegration and AnrV2Integration to prevent - * concurrent access to the same QueueFile. + * Coordinates file rotation between AnrProfileStore and AnrV2Integration to prevent concurrent + * access to the same QueueFile. */ @ApiStatus.Internal public final class AnrProfileRotationHelper { diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfileStore.java b/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfileStore.java new file mode 100644 index 00000000000..8a0495fe8d3 --- /dev/null +++ b/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfileStore.java @@ -0,0 +1,62 @@ +package io.sentry.android.core.anr; + +import io.sentry.SentryOptions; +import io.sentry.android.core.hang.HangSampleStore; +import java.io.File; +import java.io.IOException; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +/** + * Writes the main-thread samples of a hang to the ANR profile file, which the fatal ANR path reads + * at the next app start. Opens the file at the first write. Does nothing without a {@link + * SentryOptions#getCacheDirPath()}. + */ +@ApiStatus.Internal +public final class AnrProfileStore implements HangSampleStore { + + private final @NotNull SentryOptions options; + private @Nullable AnrProfileManager profileManager; + + public AnrProfileStore(final @NotNull SentryOptions options) { + this.options = options; + } + + @Override + public void clear() throws IOException { + final @Nullable AnrProfileManager manager = openProfileManager(); + if (manager != null) { + manager.clear(); + } + } + + @Override + public void add(final @NotNull AnrStackTrace sample) throws IOException { + final @Nullable AnrProfileManager manager = openProfileManager(); + if (manager != null) { + manager.add(sample); + } + } + + @Override + public void close() throws IOException { + final @Nullable AnrProfileManager manager = profileManager; + profileManager = null; + if (manager != null) { + manager.close(); + } + } + + private @Nullable AnrProfileManager openProfileManager() { + if (profileManager == null) { + final @Nullable String cacheDirPath = options.getCacheDirPath(); + if (cacheDirPath != null) { + profileManager = + new AnrProfileManager( + options, AnrProfileRotationHelper.getFileForRecording(new File(cacheDirPath))); + } + } + return profileManager; + } +} diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfilingIntegration.java b/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfilingIntegration.java index 018fd49f6fd..61ad01b77a9 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfilingIntegration.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfilingIntegration.java @@ -2,347 +2,125 @@ import static io.sentry.util.IntegrationUtils.addIntegrationToSdkVersion; -import android.os.Handler; -import android.os.Looper; -import io.sentry.IDebugManager; import io.sentry.ILogger; import io.sentry.IScopes; -import io.sentry.ISentryLifecycleToken; import io.sentry.Integration; -import io.sentry.NoOpLogger; import io.sentry.SentryLevel; import io.sentry.SentryOptions; import io.sentry.android.core.AppState; import io.sentry.android.core.SentryAndroidOptions; -import io.sentry.time.MonotonicTicker; -import io.sentry.time.Stopwatch; -import io.sentry.util.AutoClosableReentrantLock; +import io.sentry.android.core.hang.HangManager; +import io.sentry.android.core.hang.HangRecord; +import io.sentry.android.core.hang.HangRecordingListener; +import io.sentry.android.core.hang.HangRecordingRequest; import io.sentry.util.Objects; import io.sentry.util.SentryRandom; import java.io.Closeable; -import java.io.File; import java.io.IOException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; -import org.jetbrains.annotations.ApiStatus; +import java.util.concurrent.atomic.AtomicReference; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.jetbrains.annotations.TestOnly; /** * Captures main-thread stack profiles while the app is unresponsive and attaches them to ANR events * on the next app start. * + *

Subscribes to the {@link HangManager} of the options for the SDK lifetime, and draws the + * sample rate at each hang. The hang manager writes the stacks of a sampled hang to disk. An + * unsampled hang needs nothing from the hang manager. + * *

Enable via {@link SentryAndroidOptions#setAnrProfilingSampleRate(Double)} or the {@code * io.sentry.anr.profiling.sample-rate} manifest metadata. */ public final class AnrProfilingIntegration implements Integration, Closeable, AppState.AppStateListener, Runnable { - public static final long POLLING_INTERVAL_MS = 66; - private static final long THRESHOLD_SUSPICION_MS = 1000; + // StackTraceConverter expects the samples this far apart. + public static final long POLLING_INTERVAL_MS = HangManager.DEFAULT_POLLING_INTERVAL_MS; public static final long THRESHOLD_ANR_MS = 4000; - static final int MAX_NUM_STACKS = (int) (10_000 / POLLING_INTERVAL_MS); - - private final AtomicBoolean enabled = new AtomicBoolean(true); - - private volatile @Nullable MonotonicTicker ticker; - - private final @NotNull Runnable updater = - () -> { - final @Nullable MonotonicTicker currentTicker = ticker; - if (currentTicker != null) { - lastMainThreadExecutionNanos = currentTicker.tickNanos(); - } - }; - - private final @NotNull AutoClosableReentrantLock lifecycleLock = new AutoClosableReentrantLock(); - private final @NotNull AutoClosableReentrantLock profileManagerLock = - new AutoClosableReentrantLock(); - private volatile long lastMainThreadExecutionNanos; - final AtomicInteger numCollectedStacks = new AtomicInteger(); - private volatile MainThreadState mainThreadState = MainThreadState.IDLE; - private volatile @Nullable AnrProfileManager profileManager; - private volatile @NotNull ILogger logger = NoOpLogger.getInstance(); - private volatile @Nullable SentryAndroidOptions options; - private volatile @Nullable IDebugManager debugManager; - private volatile @Nullable Thread thread = null; - private volatile boolean sampled = false; - private volatile boolean inForeground = false; - private volatile @Nullable Handler mainHandler; - private volatile @Nullable Thread mainThread; + private final @NotNull AtomicReference subscribedManager = new AtomicReference<>(); + private final @NotNull AtomicReference subscription = + new AtomicReference<>(); @Override public void register(final @NotNull IScopes scopes, final @NotNull SentryOptions options) { - this.options = + final @NotNull SentryAndroidOptions androidOptions = Objects.requireNonNull( (options instanceof SentryAndroidOptions) ? (SentryAndroidOptions) options : null, "SentryAndroidOptions is required"); - this.logger = options.getLogger(); - final @NotNull MonotonicTicker ticker = options.getMonotonicTicker(); - // A tick's origin is arbitrary, so the default of 0 would read as a stall of unknown length. - this.lastMainThreadExecutionNanos = ticker.tickNanos(); - this.ticker = ticker; - this.debugManager = this.options.getDebugManager(); - - if (this.options.isAnrProfilingEnabled()) { - if (this.options.getCacheDirPath() == null) { - logger.log(SentryLevel.WARNING, "ANR Profiling is enabled but cacheDirPath is not set"); - return; - } - - final Looper mainLooper = Looper.getMainLooper(); - this.mainThread = mainLooper.getThread(); - this.mainHandler = new Handler(mainLooper); - - addIntegrationToSdkVersion("AnrProfiling"); - AppState.getInstance().addAppStateListener(this); - } - } - - @Override - @SuppressWarnings("FutureReturnValueIgnored") - public void close() throws IOException { - enabled.set(false); - AppState.getInstance().removeAppStateListener(this); - - // Remove any pending updater callbacks from the main handler - final @Nullable Handler handler = mainHandler; - if (handler != null) { - handler.removeCallbacks(updater); - } - - // Wake and interrupt the thread so it exits - final @Nullable Thread t = thread; - if (t != null) { - synchronized (this) { - notifyAll(); - } - t.interrupt(); - } - - final @Nullable SentryAndroidOptions opts = options; - final @Nullable AnrProfileManager pm; - try (final @NotNull ISentryLifecycleToken ignored = profileManagerLock.acquire()) { - pm = profileManager; - profileManager = null; + if (!androidOptions.isAnrProfilingEnabled()) { + return; } - if (opts != null) { - try { - opts.getExecutorService() - .submit(() -> { - if (pm == null) { - return; - } - - try { - pm.close(); - } catch (IOException e) { - logger.log(SentryLevel.WARNING, "Failed to close AnrProfileManager"); - } - }); - } catch (Throwable e) { - logger.log(SentryLevel.WARNING, "Failed to submit AnrProfileManager close"); - } + final @NotNull ILogger logger = options.getLogger(); + if (androidOptions.getCacheDirPath() == null) { + logger.log(SentryLevel.WARNING, "ANR Profiling is enabled but cacheDirPath is not set"); + return; } - } - - @Override - public void onForeground() { - if (!enabled.get()) { + final @Nullable HangManager manager = androidOptions.getHangManager(); + if (manager == null) { + logger.log(SentryLevel.WARNING, "ANR Profiling is enabled but there is no hang manager"); return; } - try (final @NotNull ISentryLifecycleToken ignored = lifecycleLock.acquire()) { - if (inForeground) { - return; - } - inForeground = true; - updater.run(); - - final @Nullable Thread existingThread = thread; - if (existingThread != null && existingThread.isAlive()) { - // Wake the existing thread - synchronized (this) { - notifyAll(); - } - } - if (existingThread == null || !existingThread.isAlive()) { - final @NotNull Thread profilingThread = new Thread(this, "AnrProfilingIntegration"); - profilingThread.setDaemon(true); - profilingThread.start(); - thread = profilingThread; - } + if (!subscribedManager.compareAndSet(null, manager)) { + return; } + final @NotNull HangRecordingListener listener = new ProfileSampler(androidOptions); + subscription.set(listener); + manager.subscribe(listener); + addIntegrationToSdkVersion("AnrProfiling"); } @Override - public void onBackground() { - if (!enabled.get()) { - return; - } - try (final @NotNull ISentryLifecycleToken ignored = lifecycleLock.acquire()) { - inForeground = false; + public void close() throws IOException { + final @Nullable HangManager manager = subscribedManager.getAndSet(null); + final @Nullable HangRecordingListener listener = subscription.getAndSet(null); + if (manager != null && listener != null) { + manager.unsubscribe(listener); } } + /** + * @deprecated Not used by the SDK any more. + */ + @Deprecated @Override - public void run() { - final @Nullable Handler handler = mainHandler; - final @Nullable Thread mt = mainThread; - if (handler == null || mt == null) { - return; - } - - try { - while (enabled.get() && !Thread.currentThread().isInterrupted()) { - try { - if (!inForeground) { - // Wait until we're back in the foreground or disabled - synchronized (this) { - while (!inForeground && enabled.get()) { - wait(); - } - } - // Reset the updater timestamp after waking to avoid false suspicion - updater.run(); - continue; - } - - checkMainThread(mt); + public void onForeground() {} - handler.removeCallbacks(updater); - handler.post(updater); + /** + * @deprecated Not used by the SDK any more. + */ + @Deprecated + @Override + public void onBackground() {} - // noinspection BusyWait - Thread.sleep(POLLING_INTERVAL_MS); - } catch (InterruptedException e) { - // Restore interrupt status and exit the polling loop - Thread.currentThread().interrupt(); - return; - } - } - } catch (Throwable t) { - logger.log(SentryLevel.WARNING, "Failed to execute AnrStacktraceIntegration", t); - } - } + /** + * @deprecated Not used by the SDK any more. + */ + @Deprecated + @Override + public void run() {} - @ApiStatus.Internal - void checkMainThread(final @NotNull Thread mainThread) throws IOException { - if (debugManager != null && debugManager.isDebuggerConnected()) { - // The main thread can sit at a breakpoint for a long time, which is not an ANR. Reset the - // timestamp, so the paused time does not count against us after the debugger detaches. - mainThreadState = MainThreadState.IDLE; - sampled = false; - updater.run(); - return; - } + private static final class ProfileSampler implements HangRecordingListener { - final @Nullable MonotonicTicker currentTicker = ticker; - if (currentTicker == null) { - return; - } - final long diff = - TimeUnit.NANOSECONDS.toMillis(currentTicker.tickNanos() - lastMainThreadExecutionNanos); + private final @NotNull SentryAndroidOptions options; - if (diff < THRESHOLD_SUSPICION_MS) { - mainThreadState = MainThreadState.IDLE; - sampled = false; + ProfileSampler(final @NotNull SentryAndroidOptions options) { + this.options = options; } - if (mainThreadState == MainThreadState.IDLE && diff > THRESHOLD_SUSPICION_MS) { - if (logger.isEnabled(SentryLevel.DEBUG)) { - logger.log(SentryLevel.DEBUG, "ANR: main thread is suspicious"); - } - mainThreadState = MainThreadState.SUSPICIOUS; - - final @Nullable SentryAndroidOptions opts = options; - final @Nullable Double sampleRate = opts != null ? opts.getAnrProfilingSampleRate() : null; + @Override + public @Nullable HangRecordingRequest onHangStarted() { + final @Nullable Double sampleRate = options.getAnrProfilingSampleRate(); if (sampleRate != null && SentryRandom.current().nextDouble() < sampleRate) { - sampled = true; - } - - if (sampled) { - clearStacks(); + return new HangRecordingRequest(true, true); } + return null; } - // if we are suspicious and sampled, we need to collect stack traces - if (sampled - && (mainThreadState == MainThreadState.SUSPICIOUS - || mainThreadState == MainThreadState.ANR_DETECTED)) { - if (numCollectedStacks.get() < MAX_NUM_STACKS) { - final @NotNull Stopwatch stopwatch = Stopwatch.started(currentTicker); - final @NotNull AnrStackTrace trace = - new AnrStackTrace(System.currentTimeMillis(), mainThread.getStackTrace()); - if (logger.isEnabled(SentryLevel.DEBUG)) { - logger.log( - SentryLevel.DEBUG, - "AnrWatchdog: capturing main thread stacktrace took " - + stopwatch.elapsed(TimeUnit.MILLISECONDS) - + "ms"); - } - addStackTrace(trace); - } else { - if (logger.isEnabled(SentryLevel.DEBUG)) { - logger.log( - SentryLevel.DEBUG, - "ANR: reached maximum number of collected stack traces, skipping further collection"); - } - } + @Override + public void onHangRecorded(final @NotNull HangRecord record) { + // The fatal path reads the profile from disk at the next launch, it needs no record. } - - if (mainThreadState == MainThreadState.SUSPICIOUS && diff > THRESHOLD_ANR_MS) { - if (logger.isEnabled(SentryLevel.DEBUG)) { - logger.log(SentryLevel.DEBUG, "ANR: main thread ANR threshold reached"); - } - mainThreadState = MainThreadState.ANR_DETECTED; - } - } - - @TestOnly - @NotNull - MainThreadState getState() { - return mainThreadState; - } - - @TestOnly - @NotNull - AnrProfileManager getProfileManager() { - try (final @NotNull ISentryLifecycleToken ignored = profileManagerLock.acquire()) { - if (profileManager == null) { - final @NotNull SentryOptions opts = - Objects.requireNonNull(options, "Options can't be null"); - final @Nullable String cacheDirPath = opts.getCacheDirPath(); - if (cacheDirPath == null) { - throw new IllegalStateException("cacheDirPath is required for ANR profiling"); - } - final @NotNull File currentFile = - AnrProfileRotationHelper.getFileForRecording(new File(cacheDirPath)); - profileManager = new AnrProfileManager(opts, currentFile); - } - - return profileManager; - } - } - - private void clearStacks() throws IOException { - numCollectedStacks.set(0); - getProfileManager().clear(); - } - - private void addStackTrace(@NotNull final AnrStackTrace trace) throws IOException { - if (!enabled.get()) { - return; - } - numCollectedStacks.incrementAndGet(); - getProfileManager().add(trace); - } - - protected enum MainThreadState { - IDLE, - SUSPICIOUS, - ANR_DETECTED, } } diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/hang/HandlerThreadPoster.java b/sentry-android-core/src/main/java/io/sentry/android/core/hang/HandlerThreadPoster.java new file mode 100644 index 00000000000..b9288c80d49 --- /dev/null +++ b/sentry-android-core/src/main/java/io/sentry/android/core/hang/HandlerThreadPoster.java @@ -0,0 +1,25 @@ +package io.sentry.android.core.hang; + +import android.os.Handler; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; + +@ApiStatus.Internal +public final class HandlerThreadPoster implements ThreadPoster { + + private final @NotNull Handler handler; + + public HandlerThreadPoster(final @NotNull Handler handler) { + this.handler = handler; + } + + @Override + public void post(final @NotNull Runnable runnable) { + handler.post(runnable); + } + + @Override + public void remove(final @NotNull Runnable runnable) { + handler.removeCallbacks(runnable); + } +} diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/AndroidOptionsInitializerTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/AndroidOptionsInitializerTest.kt index 226ea753977..de27c32474a 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/AndroidOptionsInitializerTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/AndroidOptionsInitializerTest.kt @@ -4,12 +4,15 @@ import android.content.Context import android.content.res.AssetManager import android.os.Build import android.os.Bundle +import android.os.Looper import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.google.common.truth.Truth.assertThat import io.sentry.CompositePerformanceCollector import io.sentry.DefaultCompositePerformanceCollector import io.sentry.IConnectionStatusProvider import io.sentry.IContinuousProfiler +import io.sentry.IDebugManager import io.sentry.ILogger import io.sentry.ISocketTagger import io.sentry.ITransaction @@ -20,7 +23,18 @@ import io.sentry.NoOpTransactionProfiler import io.sentry.SentryIntegrationPackageStorage import io.sentry.SentryOptions import io.sentry.android.core.SentryAndroidOptions.AndroidUserFeedbackFormHandler +import io.sentry.android.core.anr.AnrProfileManager +import io.sentry.android.core.anr.AnrProfileStore +import io.sentry.android.core.anr.AnrStackTrace import io.sentry.android.core.cache.AndroidEnvelopeCache +import io.sentry.android.core.hang.HangCollectorSetup +import io.sentry.android.core.hang.HangDataCollector +import io.sentry.android.core.hang.HangManager +import io.sentry.android.core.hang.HangRecord +import io.sentry.android.core.hang.HangRecordWriter +import io.sentry.android.core.hang.HangSignal +import io.sentry.android.core.hang.ThreadHangSignal +import io.sentry.android.core.hang.ThreadSampleCollector import io.sentry.android.core.internal.debugmeta.AssetsDebugMetaLoader import io.sentry.android.core.internal.gestures.AndroidViewGestureTargetLocator import io.sentry.android.core.internal.modules.AssetsModulesLoader @@ -38,6 +52,8 @@ import io.sentry.internal.debugmeta.IDebugMetaLoader import io.sentry.internal.modules.IModulesLoader import io.sentry.protocol.SentryId import io.sentry.test.ImmediateExecutorService +import io.sentry.test.getProperty +import io.sentry.time.JavaMonotonicTicker import io.sentry.transport.ITransportGate import io.sentry.util.thread.IThreadChecker import java.io.File @@ -682,6 +698,106 @@ class AndroidOptionsInitializerTest { assertTrue { appLifecycleIndex < anrIndex } } + @Test + fun `HangManager is created and stored in the options`() { + fixture.initSut() + + val manager = fixture.sentryOptions.hangManager + assertThat(manager).isNotNull() + assertThat(manager!!.getProperty("appStateProvider")) + .isSameInstanceAs(AppState.getInstance()) + assertThat(manager.getProperty("ticker")) + .isSameInstanceAs(JavaMonotonicTicker.getInstance()) + assertThat(manager.getProperty("epochClock")) + .isSameInstanceAs(fixture.sentryOptions.epochClock) + assertThat(manager.getProperty("pollingIntervalMs")) + .isEqualTo(HangManager.DEFAULT_POLLING_INTERVAL_MS) + assertThat(manager.getProperty("maxRecordingTimeMs")) + .isEqualTo(HangManager.DEFAULT_MAX_RECORDING_TIME_MS) + assertThat(manager.getProperty("maxSamples")) + .isEqualTo(AnrProfileManager.MAX_NUM_STACKTRACES) + assertThat(manager.getProperty("executorFactory")) + .isSameInstanceAs(HangManager.DEFAULT_EXECUTOR_FACTORY) + } + + @Test + fun `HangManager signal is a ThreadHangSignal with the AndroidDebugManager`() { + fixture.initSut() + + val signal = + fixture.sentryOptions.hangManager!!.getProperty>("signals").single() + assertThat(signal).isInstanceOf(ThreadHangSignal::class.java) + assertThat(signal.getProperty("debugManager")) + .isSameInstanceAs(fixture.sentryOptions.debugManager) + assertThat(fixture.sentryOptions.debugManager).isInstanceOf(AndroidDebugManager::class.java) + assertThat(signal.getProperty("metronome")) + .isSameInstanceAs(fixture.sentryOptions.hangManager) + assertThat(signal.getProperty("suspiciousThresholdMs")) + .isEqualTo(HangManager.DEFAULT_SUSPICIOUS_THRESHOLD_MS) + } + + @Test + fun `HangManager signal uses a debug manager that is already set`() { + val debugManager = IDebugManager { false } + fixture.sentryOptions.debugManager = debugManager + + fixture.initSut() + + val signal = + fixture.sentryOptions.hangManager!!.getProperty>("signals").single() + assertThat(signal.getProperty("debugManager")).isSameInstanceAs(debugManager) + } + + @Test + fun `HangManager collector samples the main thread into the ANR profile store`() { + fixture.initSut() + + val setup = + fixture.sentryOptions.hangManager!! + .getProperty>>("collectors") + .single() + val collector = setup.getProperty>("collector") + assertThat(collector).isInstanceOf(ThreadSampleCollector::class.java) + assertThat(collector.getProperty("thread")) + .isSameInstanceAs(Looper.getMainLooper().thread) + val store = setup.getProperty("store") + assertThat(store).isInstanceOf(AnrProfileStore::class.java) + assertThat(store.getProperty("options")).isSameInstanceAs(fixture.sentryOptions) + } + + @Test + fun `HangManager writes the main thread samples into the record as stack traces`() { + fixture.initSut() + val setup = + fixture.sentryOptions.hangManager!! + .getProperty>>("collectors") + .single() + val writer = setup.getProperty>("writer") + val stackTrace = AnrStackTrace(1, emptyArray()) + val builder = HangRecord.Builder() + + writer.write(stackTrace, builder) + + assertThat(builder.build().stackTraces).containsExactly(stackTrace) + } + + @Test + fun `HangManager that is already set is kept`() { + val existing = mock() + fixture.sentryOptions.hangManager = existing + + fixture.initSut() + + assertThat(fixture.sentryOptions.hangManager).isSameInstanceAs(existing) + } + + @Test + fun `HangManager is not created when cacheDirPath is null`() { + fixture.initSut(configureOptions = { cacheDirPath = null }) + + assertThat(fixture.sentryOptions.hangManager).isNull() + } + @Test fun `EnvelopeFileObserverIntegration added to integration list`() { fixture.initSut() diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidTest.kt index 2717128af95..2b80786f177 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidTest.kt @@ -11,6 +11,7 @@ import android.os.Looper import android.os.SystemClock import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.google.common.truth.Truth.assertThat import io.sentry.Breadcrumb import io.sentry.DateUtils import io.sentry.Hint @@ -31,6 +32,7 @@ import io.sentry.SystemOutLogger import io.sentry.UncaughtExceptionHandlerIntegration import io.sentry.android.core.anr.AnrProfilingIntegration import io.sentry.android.core.cache.AndroidEnvelopeCache +import io.sentry.android.core.hang.HangManager import io.sentry.android.core.performance.AppStartMetrics import io.sentry.android.fragment.FragmentLifecycleIntegration import io.sentry.android.replay.ReplayIntegration @@ -200,6 +202,35 @@ class SentryAndroidTest { assertTrue(Sentry.isEnabled()) } + @Test + fun `close unsubscribes the ANR profiling integration from the hang manager`() { + val manager = mock() + fixture.initSut { + it.hangManager = manager + it.anrProfilingSampleRate = 1.0 + } + verify(manager).subscribe(any()) + + Sentry.close() + + verify(manager).unsubscribe(any()) + } + + @Test + fun `re-init creates a new hang manager`() { + val previous = mock() + fixture.initSut { it.hangManager = previous } + var options: SentryAndroidOptions? = null + + fixture.initSut { + it.cacheDirPath = tmpDir.newFolder().absolutePath + options = it + } + + assertThat(options!!.hangManager).isNotNull() + assertThat(options!!.hangManager).isNotSameInstanceAs(previous) + } + @Test fun `when auto-init is disabled and user calls init manually with configuration handler, options should be set`() { assertFalse(Sentry.isEnabled()) diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/anr/AnrProfileStoreTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/anr/AnrProfileStoreTest.kt new file mode 100644 index 00000000000..c404d54427a --- /dev/null +++ b/sentry-android-core/src/test/java/io/sentry/android/core/anr/AnrProfileStoreTest.kt @@ -0,0 +1,111 @@ +package io.sentry.android.core.anr + +import com.google.common.truth.Truth.assertThat +import io.sentry.SentryOptions +import io.sentry.test.getProperty +import java.io.File +import java.nio.file.Files +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test + +class AnrProfileStoreTest { + + private lateinit var cacheDir: File + private lateinit var options: SentryOptions + private lateinit var store: AnrProfileStore + + @BeforeTest + fun setUp() { + cacheDir = Files.createTempDirectory("anr-profile-store").toFile() + // Rotation moves an existing file once per process, do it before any file is seeded. + AnrProfileRotationHelper.getFileForRecording(cacheDir) + options = SentryOptions() + options.cacheDirPath = cacheDir.absolutePath + store = AnrProfileStore(options) + } + + @AfterTest + fun tearDown() { + store.close() + cacheDir.deleteRecursively() + } + + private fun file() = File(cacheDir, "anr_profile") + + private fun readFile(): List { + // The store keeps the queue open, so release it before reading from a second manager. + store.close() + AnrProfileManager(options, file()).use { + return it.load().stacks + } + } + + @Test + fun `clear and add write the samples to the ANR profile file`() { + store.clear() + store.add(AnrStackTrace(1, emptyArray())) + store.add(AnrStackTrace(2, emptyArray())) + + assertThat(readFile().map { it.timestampMs }).containsExactly(1L, 2L).inOrder() + } + + @Test + fun `clear removes the samples of an earlier hang`() { + AnrProfileManager(options, file()).use { it.add(AnrStackTrace(1, emptyArray())) } + + store.clear() + store.add(AnrStackTrace(2, emptyArray())) + + assertThat(readFile().map { it.timestampMs }).containsExactly(2L) + } + + @Test + fun `the file is opened at the first write`() { + assertThat(file().exists()).isFalse() + + store.clear() + + assertThat(file().exists()).isTrue() + } + + @Test + fun `the file is opened once`() { + store.clear() + val manager = store.getProperty("profileManager") + + store.add(AnrStackTrace(1, emptyArray())) + + assertThat(store.getProperty("profileManager")).isSameInstanceAs(manager) + } + + @Test + fun `writes nothing without cacheDirPath`() { + options.cacheDirPath = null + + store.clear() + store.add(AnrStackTrace(1, emptyArray())) + + assertThat(file().exists()).isFalse() + } + + @Test + fun `close without a write creates no file`() { + store.close() + + assertThat(file().exists()).isFalse() + } + + @Test + fun `close releases the file`() { + store.add(AnrStackTrace(1, emptyArray())) + + store.close() + store.close() + + assertThat(store.getProperty("profileManager")).isNull() + AnrProfileManager(options, file()).use { + assertThat(it.load().stacks.map { stack -> stack.timestampMs }).containsExactly(1L) + } + } +} diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/anr/AnrProfilingIntegrationTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/anr/AnrProfilingIntegrationTest.kt index 6c3d08c76bc..d4dfd86f93a 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/anr/AnrProfilingIntegrationTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/anr/AnrProfilingIntegrationTest.kt @@ -5,358 +5,234 @@ import com.google.common.truth.Truth.assertThat import io.sentry.ILogger import io.sentry.IScopes import io.sentry.SentryIntegrationPackageStorage +import io.sentry.SentryLevel import io.sentry.SentryOptions -import io.sentry.android.core.AppState import io.sentry.android.core.SentryAndroidOptions -import io.sentry.test.getProperty -import io.sentry.time.TestMonotonicTicker -import java.util.concurrent.TimeUnit.HOURS -import java.util.concurrent.TimeUnit.MILLISECONDS -import kotlin.test.AfterTest +import io.sentry.android.core.hang.HangManager +import io.sentry.android.core.hang.HangRecordingListener +import io.sentry.util.Random +import io.sentry.util.SentryRandom import kotlin.test.BeforeTest import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFalse -import kotlin.test.assertNotNull -import kotlin.test.assertSame -import kotlin.test.assertTrue +import kotlin.test.assertFailsWith import org.junit.Rule import org.junit.rules.TemporaryFolder import org.junit.runner.RunWith +import org.mockito.kotlin.any +import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.mock -import org.mockito.kotlin.spy -import org.mockito.kotlin.whenever +import org.mockito.kotlin.never +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.verifyNoMoreInteractions @RunWith(AndroidJUnit4::class) class AnrProfilingIntegrationTest { @get:Rule val tmpDir = TemporaryFolder() - private lateinit var mockScopes: IScopes - private lateinit var mockLogger: ILogger + private val scopes = mock() + private val mockLogger = mock() + private val manager = mock() private lateinit var options: SentryAndroidOptions - private lateinit var ticker: TestMonotonicTicker @BeforeTest fun setup() { - // A tick origin far from zero, as on any device that has been up a while. Starting at zero - // would let a reading taken against a different origin pass unnoticed. - ticker = TestMonotonicTicker(HOURS.toNanos(30)) - mockScopes = mock() - mockLogger = mock() + SentryIntegrationPackageStorage.getInstance().clearStorage() options = SentryAndroidOptions().apply { cacheDirPath = tmpDir.root.absolutePath setLogger(mockLogger) + isDebug = true anrProfilingSampleRate = 1.0 + hangManager = manager } - AppState.getInstance().resetInstance() } - @AfterTest - fun cleanup() { - AppState.getInstance().resetInstance() + private fun subscribed(): HangRecordingListener { + AnrProfilingIntegration().register(scopes, options) + val captor = argumentCaptor() + verify(manager).subscribe(captor.capture()) + return captor.firstValue } - /** `SentryAndroidOptions` is final and has no ticker setter, so a spy supplies [ticker]. */ - private fun withTestTicker(options: SentryAndroidOptions): SentryAndroidOptions = - spy(options).also { whenever(it.monotonicTicker).thenReturn(ticker) } - @Test - fun `onForeground starts monitoring thread`() { + fun `register subscribes to the hang manager when ANR profiling is enabled`() { val integration = AnrProfilingIntegration() - integration.register(mockScopes, options) - integration.onForeground() - Thread.sleep(100) // Allow thread to start + integration.register(scopes, options) - val thread = integration.getProperty("thread") - assertNotNull(thread) - assertTrue(thread.isAlive) - assertEquals("AnrProfilingIntegration", thread.name) + verify(manager, times(1)).subscribe(any()) + assertThat(SentryIntegrationPackageStorage.getInstance().integrations).contains("AnrProfiling") } @Test - fun `onBackground pauses monitoring thread`() { + fun `register subscribes without a draw`() { + // Enabled, but only a draw of exactly 0.0 is below it. + options.anrProfilingSampleRate = Double.MIN_VALUE val integration = AnrProfilingIntegration() - integration.register(mockScopes, options) - integration.onForeground() - Thread.sleep(100) - val thread = integration.getProperty("thread") - assertNotNull(thread) + integration.register(scopes, options) - integration.onBackground() - Thread.sleep(200) // Allow thread to enter wait state + verify(manager, times(1)).subscribe(any()) + assertThat(SentryIntegrationPackageStorage.getInstance().integrations).contains("AnrProfiling") + } - // Thread should still be alive but waiting - assertTrue(thread.isAlive) + @Test + fun `sampled hang asks the hang manager to persist`() { + val listener = subscribed() - integration.close() - thread.join(2000) - assertFalse(thread.isAlive) + assertThat(listener.onHangStarted()!!.shouldPersist()).isTrue() } @Test - fun `close disables integration and interrupts thread`() { - val integration = AnrProfilingIntegration() - integration.register(mockScopes, options) - integration.onForeground() - Thread.sleep(100) + fun `unsampled hang needs nothing from the hang manager`() { + options.anrProfilingSampleRate = Double.MIN_VALUE + val listener = subscribed() - val thread = integration.getProperty("thread") - assertNotNull(thread) - - assertTrue(AppState.getInstance().lifecycleObserver!!.listeners.isNotEmpty()) + assertThat(listener.onHangStarted()).isNull() + } - integration.close() - thread.join(2000) + @Test + fun `a new random number is drawn at each hang`() { + val draws = Random(SEED, 0).let { listOf(it.nextDouble(), it.nextDouble()) } + assertThat(draws[0]).isLessThan(draws[1]) + options.anrProfilingSampleRate = draws[1] + val listener = subscribed() + SentryRandom.current().setSeed(SEED, 0) - assertTrue(!thread.isAlive) - val enabled = integration.getProperty("enabled") - assertTrue(!enabled.get()) - assertTrue(AppState.getInstance().lifecycleObserver!!.listeners.isEmpty()) + assertThat(listener.onHangStarted()!!.shouldPersist()).isTrue() + assertThat(listener.onHangStarted()).isNull() } @Test - fun `lifecycle methods have no influence after close`() { - val integration = AnrProfilingIntegration() - integration.register(mockScopes, options) - integration.close() - integration.onForeground() - integration.onBackground() + fun `sample rate is read again at each hang`() { + val listener = subscribed() + assertThat(listener.onHangStarted()!!.shouldPersist()).isTrue() + + options.anrProfilingSampleRate = Double.MIN_VALUE - val thread = integration.getProperty("thread") - assertTrue(thread == null || !thread.isAlive) + assertThat(listener.onHangStarted()).isNull() } @Test - fun `multiple foreground calls do not create multiple threads`() { - val integration = AnrProfilingIntegration() - integration.register(mockScopes, options) + fun `hang after the sample rate became null needs nothing from the hang manager`() { + val listener = subscribed() - integration.onForeground() - Thread.sleep(100) - val thread1 = integration.getProperty("thread") + options.anrProfilingSampleRate = null - integration.onForeground() - Thread.sleep(100) - val thread2 = integration.getProperty("thread") + assertThat(listener.onHangStarted()).isNull() + } - assertNotNull(thread1) - assertNotNull(thread2) - assertEquals(thread1, thread2, "Should reuse the same thread") + @Test + fun `sampled hang asks for a record`() { + val listener = subscribed() - integration.close() + assertThat(listener.onHangStarted()!!.shouldRecord()).isTrue() } @Test - fun `foreground after background reuses thread`() { + fun `register does not subscribe when ANR profiling is disabled`() { + options.anrProfilingSampleRate = null val integration = AnrProfilingIntegration() - integration.register(mockScopes, options) - - integration.onForeground() - Thread.sleep(100) - val thread1 = integration.getProperty("thread") - - integration.onBackground() - integration.onForeground() - Thread.sleep(100) - val thread2 = integration.getProperty("thread") + integration.register(scopes, options) - assertNotNull(thread1) - assertNotNull(thread2) - assertSame(thread1, thread2, "Should reuse the same thread after background") - assertTrue(thread1.isAlive) - - integration.close() + verify(manager, never()).subscribe(any()) } @Test - fun `properly walks through state transitions and collects stack traces`() { - val mainThread = Thread.currentThread() + fun `register does not subscribe when cacheDirPath is null`() { + options.cacheDirPath = null + val integration = AnrProfilingIntegration() - val androidOptions = - SentryAndroidOptions().apply { - cacheDirPath = tmpDir.root.absolutePath - setLogger(mockLogger) - anrProfilingSampleRate = 1.0 - } + integration.register(scopes, options) - val integration = AnrProfilingIntegration() - integration.register(mockScopes, withTestTicker(androidOptions)) - // Drive the state machine synchronously to avoid racing the background polling thread. - - ticker.advance(900, MILLISECONDS) - integration.checkMainThread(mainThread) - assertEquals(AnrProfilingIntegration.MainThreadState.IDLE, integration.state) - assertTrue(integration.profileManager.load().stacks.isEmpty()) - - ticker.advance(2_000, MILLISECONDS) - integration.checkMainThread(mainThread) - assertEquals(AnrProfilingIntegration.MainThreadState.SUSPICIOUS, integration.state) - - ticker.advance(3_000, MILLISECONDS) - integration.checkMainThread(mainThread) - assertEquals(AnrProfilingIntegration.MainThreadState.ANR_DETECTED, integration.state) - assertEquals(2, integration.profileManager.load().stacks.size) - - for (i in 0 until AnrProfilingIntegration.MAX_NUM_STACKS + 1) { - integration.checkMainThread(mainThread) - } - assertEquals(AnrProfilingIntegration.MAX_NUM_STACKS, integration.numCollectedStacks.get()) + verify(manager, never()).subscribe(any()) + verify(mockLogger) + .log(SentryLevel.WARNING, "ANR Profiling is enabled but cacheDirPath is not set") } @Test - fun `debugger pauses are treated as idle`() { - val mainThread = Thread.currentThread() - var debuggerConnected = true + fun `register does nothing when there is no hang manager`() { + options.hangManager = null + val integration = AnrProfilingIntegration() - val androidOptions = - SentryAndroidOptions().apply { - cacheDirPath = tmpDir.root.absolutePath - setLogger(mockLogger) - anrProfilingSampleRate = 1.0 - debugManager = { debuggerConnected } - } + integration.register(scopes, options) + integration.close() - val integration = AnrProfilingIntegration() - integration.register(mockScopes, withTestTicker(androidOptions)) - - ticker.advance(19_000, MILLISECONDS) - integration.checkMainThread(mainThread) - assertEquals(AnrProfilingIntegration.MainThreadState.IDLE, integration.state) - assertEquals(0, integration.numCollectedStacks.get()) - - // the time spent paused must not count towards an ANR once the debugger detaches - debuggerConnected = false - ticker.advance(100, MILLISECONDS) - integration.checkMainThread(mainThread) - assertEquals(AnrProfilingIntegration.MainThreadState.IDLE, integration.state) + assertThat(SentryIntegrationPackageStorage.getInstance().integrations) + .doesNotContain("AnrProfiling") } @Test - fun `background foreground transitions don't trigger an ANR`() { - val mainThread = Thread.currentThread() + fun `register requires SentryAndroidOptions`() { + val integration = AnrProfilingIntegration() - val androidOptions = - SentryAndroidOptions().apply { - cacheDirPath = tmpDir.root.absolutePath - setLogger(mockLogger) - anrProfilingSampleRate = 1.0 - } + assertFailsWith { integration.register(scopes, SentryOptions()) } + } + @Test + fun `close unsubscribes the listener it subscribed`() { val integration = AnrProfilingIntegration() - integration.register(mockScopes, withTestTicker(androidOptions)) - integration.onBackground() + integration.register(scopes, options) - ticker.advance(19_000, MILLISECONDS) - integration.onForeground() + integration.close() - Thread.sleep(100) - integration.checkMainThread(mainThread) - assertEquals(AnrProfilingIntegration.MainThreadState.IDLE, integration.state) + val subscribed = argumentCaptor() + verify(manager).subscribe(subscribed.capture()) + verify(manager).unsubscribe(subscribed.firstValue) } @Test - fun `does not report a stall when the ticker origin is far from zero`() { + fun `close unsubscribes only once`() { val integration = AnrProfilingIntegration() - integration.register(mockScopes, withTestTicker(options)) + integration.register(scopes, options) - integration.checkMainThread(Thread.currentThread()) + integration.close() + integration.close() - assertThat(integration.state).isEqualTo(AnrProfilingIntegration.MainThreadState.IDLE) - assertThat(integration.profileManager.load().stacks).isEmpty() + verify(manager, times(1)).unsubscribe(any()) } @Test - fun `does not register when options is not SentryAndroidOptions`() { - val plainOptions = - SentryOptions().apply { - cacheDirPath = tmpDir.root.absolutePath - setLogger(mockLogger) - } - + fun `close does not unsubscribe when not subscribed`() { + options.anrProfilingSampleRate = null val integration = AnrProfilingIntegration() + integration.register(scopes, options) - try { - integration.register(mockScopes, plainOptions) - } catch (e: IllegalArgumentException) { - // ignored - } - - // Verify no listeners were added - val lifecycleObserver = AppState.getInstance().lifecycleObserver - if (lifecycleObserver != null) { - assertTrue(lifecycleObserver.listeners.isEmpty()) - } + integration.close() + + verify(manager, never()).unsubscribe(any()) } @Test - fun `does not register when ANR profiling is disabled`() { - val androidOptions = - SentryAndroidOptions().apply { - cacheDirPath = tmpDir.root.absolutePath - setLogger(mockLogger) - anrProfilingSampleRate = null - } + fun `two integrations on one hang manager use distinct subscriptions`() { + val first = AnrProfilingIntegration() + val second = AnrProfilingIntegration() + first.register(scopes, options) + second.register(scopes, options) - val integration = AnrProfilingIntegration() - integration.register(mockScopes, androidOptions) - - // When ANR profiling is disabled, the integration doesn't add itself to AppState - // So the lifecycle observer may be null or have no listeners - val lifecycleObserver = AppState.getInstance().lifecycleObserver - if (lifecycleObserver != null) { - assertTrue(lifecycleObserver.listeners.isEmpty()) - } + val subscribed = argumentCaptor() + verify(manager, times(2)).subscribe(subscribed.capture()) + assertThat(subscribed.firstValue).isNotSameInstanceAs(subscribed.secondValue) } @Test - fun `does not collect stacks when sample rate is zero`() { - val mainThread = Thread.currentThread() - - val androidOptions = - SentryAndroidOptions().apply { - cacheDirPath = tmpDir.root.absolutePath - setLogger(mockLogger) - anrProfilingSampleRate = 0.0 - } - + @Suppress("DEPRECATION") + fun `deprecated lifecycle and run methods do nothing`() { val integration = AnrProfilingIntegration() - integration.register(mockScopes, withTestTicker(androidOptions)) - integration.onForeground() - - // Transition to suspicious - ticker.advance(2_900, MILLISECONDS) - integration.checkMainThread(mainThread) - assertEquals(AnrProfilingIntegration.MainThreadState.SUSPICIOUS, integration.state) + integration.register(scopes, options) + verify(manager).subscribe(any()) - // Transition to ANR - ticker.advance(3_000, MILLISECONDS) - integration.checkMainThread(mainThread) - assertEquals(AnrProfilingIntegration.MainThreadState.ANR_DETECTED, integration.state) + integration.onForeground() + integration.onBackground() + integration.run() - // No stacks should have been collected - assertEquals(0, integration.numCollectedStacks.get()) + verifyNoMoreInteractions(manager) } - @Test - fun `registers when ANR profiling is enabled`() { - val androidOptions = - SentryAndroidOptions().apply { - cacheDirPath = tmpDir.root.absolutePath - setLogger(mockLogger) - anrProfilingSampleRate = 1.0 - } - - val integration = AnrProfilingIntegration() - integration.register(mockScopes, androidOptions) - - assertFalse(AppState.getInstance().lifecycleObserver!!.listeners.isEmpty()) - assertTrue(SentryIntegrationPackageStorage.getInstance().integrations.contains("AnrProfiling")) - - integration.close() + private companion object { + const val SEED = 1L } } diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/hang/HandlerThreadPosterTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/hang/HandlerThreadPosterTest.kt new file mode 100644 index 00000000000..52b5db2ea5f --- /dev/null +++ b/sentry-android-core/src/test/java/io/sentry/android/core/hang/HandlerThreadPosterTest.kt @@ -0,0 +1,39 @@ +package io.sentry.android.core.hang + +import android.os.Handler +import android.os.Looper +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.google.common.truth.Truth.assertThat +import kotlin.test.Test +import org.junit.runner.RunWith +import org.robolectric.Shadows.shadowOf + +@RunWith(AndroidJUnit4::class) +class HandlerThreadPosterTest { + + private val sut = HandlerThreadPoster(Handler(Looper.getMainLooper())) + + @Test + fun `post runs the runnable on the main looper`() { + var ranOn: Thread? = null + + sut.post { ranOn = Thread.currentThread() } + shadowOf(Looper.getMainLooper()).idle() + + assertThat(ranOn).isSameInstanceAs(Looper.getMainLooper().thread) + } + + @Test + fun `remove drops only the given pending runnable`() { + val ran = mutableListOf() + val removed = Runnable { ran.add("removed") } + val kept = Runnable { ran.add("kept") } + sut.post(removed) + sut.post(kept) + + sut.remove(removed) + shadowOf(Looper.getMainLooper()).idle() + + assertThat(ran).containsExactly("kept") + } +}