diff --git a/sentry-android-core/api/sentry-android-core.api b/sentry-android-core/api/sentry-android-core.api index 434a79170d..a376df3d1f 100644 --- a/sentry-android-core/api/sentry-android-core.api +++ b/sentry-android-core/api/sentry-android-core.api @@ -141,6 +141,11 @@ public final class io/sentry/android/core/AndroidProfiler$ProfileStartData { public fun (JJLjava/util/Date;)V } +public final class io/sentry/android/core/AndroidRuntimeStatsSource : io/sentry/android/core/hang/RuntimeStatsSource { + public fun (Lio/sentry/ILogger;)V + public fun read ()Lio/sentry/android/core/hang/RuntimeStatsSnapshot; +} + public final class io/sentry/android/core/AndroidSocketTagger : io/sentry/ISocketTagger { public static fun getInstance ()Lio/sentry/android/core/AndroidSocketTagger; public fun tagSockets ()V @@ -861,6 +866,7 @@ public final class io/sentry/android/core/hang/HangInterval { public final class io/sentry/android/core/hang/HangRecord { public fun getDurationMs ()J + public fun getRuntimeStats ()Ljava/util/Map; public fun getSamples ()Ljava/util/List; public fun getStartTimestampMs ()J public fun hasEndedAtMaxRecordingTime ()Z @@ -870,6 +876,7 @@ public final class io/sentry/android/core/hang/HangRecord$Builder { public fun (JJ)V public fun build ()Lio/sentry/android/core/hang/HangRecord; public fun setEndedAtMaxRecordingTime (Z)Lio/sentry/android/core/hang/HangRecord$Builder; + public fun setRuntimeStats (Ljava/util/Map;)Lio/sentry/android/core/hang/HangRecord$Builder; public fun setSamples (Ljava/util/List;)Lio/sentry/android/core/hang/HangRecord$Builder; } @@ -927,6 +934,47 @@ public abstract interface class io/sentry/android/core/hang/Metronome$TickListen public abstract fun onMetronomeTick (J)V } +public final class io/sentry/android/core/hang/RuntimeStatsCollector : io/sentry/android/core/hang/HangDataCollector { + public static final field KEY_BLOCKING_GC_COUNT Ljava/lang/String; + public static final field KEY_BLOCKING_GC_COUNT_DELTA Ljava/lang/String; + public static final field KEY_BLOCKING_GC_TIME_MS Ljava/lang/String; + public static final field KEY_BLOCKING_GC_TIME_MS_DELTA Ljava/lang/String; + public static final field KEY_FREE_MEMORY Ljava/lang/String; + public static final field KEY_FREE_MEMORY_UNTIL_OOME Ljava/lang/String; + public static final field KEY_GC_COUNT Ljava/lang/String; + public static final field KEY_GC_COUNT_DELTA Ljava/lang/String; + public static final field KEY_GC_TIME_MS Ljava/lang/String; + public static final field KEY_GC_TIME_MS_DELTA Ljava/lang/String; + public static final field KEY_GC_WAITING_TIME_MS Ljava/lang/String; + public static final field KEY_MAX_MEMORY Ljava/lang/String; + public static final field KEY_PRE_OOME_GC_COUNT Ljava/lang/String; + public static final field KEY_TOTAL_MEMORY Ljava/lang/String; + public fun (Lio/sentry/android/core/hang/RuntimeStatsSource;)V + public fun close ()V + public fun onRecordingCanceled ()V + public fun onRecordingStarted (Lio/sentry/android/core/hang/HangInterval;)V + public fun onRecordingStopped (Lio/sentry/android/core/hang/HangInterval;Lio/sentry/android/core/hang/HangRecord$Builder;)V + public fun onSample (Lio/sentry/android/core/hang/HangInterval;)V +} + +public final class io/sentry/android/core/hang/RuntimeStatsSnapshot { + public field blockingGcCount Ljava/lang/Long; + public field blockingGcTimeMs Ljava/lang/Double; + public field freeMemory Ljava/lang/Long; + public field freeMemoryUntilOome Ljava/lang/Long; + public field gcCount Ljava/lang/Long; + public field gcTimeMs Ljava/lang/Double; + public field gcWaitingTimeMs Ljava/lang/Double; + public field maxMemory Ljava/lang/Long; + public field preOomeGcCount Ljava/lang/Long; + public field totalMemory Ljava/lang/Long; + public fun ()V +} + +public abstract interface class io/sentry/android/core/hang/RuntimeStatsSource { + public abstract fun read ()Lio/sentry/android/core/hang/RuntimeStatsSnapshot; +} + public final class io/sentry/android/core/hang/ThreadHangSignal : io/sentry/android/core/hang/HangSignal, io/sentry/android/core/hang/Metronome$TickListener { public fun (Lio/sentry/android/core/hang/Metronome;Lio/sentry/time/MonotonicTicker;Lio/sentry/IDebugManager;Lio/sentry/android/core/hang/ThreadPoster;J)V public fun close ()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 d32d2145b1..d23b163e03 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 @@ -36,7 +36,10 @@ 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.HangDataCollector; import io.sentry.android.core.hang.HangRecorder; +import io.sentry.android.core.hang.RuntimeStatsCollector; +import io.sentry.android.core.hang.RuntimeStatsSource; import io.sentry.android.core.hang.ThreadHangSignal; import io.sentry.android.core.hang.ThreadPoster; import io.sentry.android.core.hang.ThreadSampleCollector; @@ -275,7 +278,7 @@ static void initializeIntegrationsAndProcessors( debugManager = new AndroidDebugManager(); options.setDebugManager(debugManager); } - setupHangRecorder(options, debugManager); + setupHangRecorder(options, debugManager, buildInfoProvider); if (options.getSocketTagger() instanceof NoOpSocketTagger) { options.setSocketTagger(AndroidSocketTagger.getInstance()); } @@ -536,7 +539,9 @@ static void installDefaultIntegrations( } private static void setupHangRecorder( - final @NotNull SentryAndroidOptions options, final @NotNull IDebugManager debugManager) { + final @NotNull SentryAndroidOptions options, + final @NotNull IDebugManager debugManager, + final @NotNull BuildInfoProvider buildInfoProvider) { if (options.getCacheDirPath() == null || options.getHangRecorder() != null) { return; } @@ -545,6 +550,13 @@ private static void setupHangRecorder( // 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 List collectors = new ArrayList<>(); + collectors.add(new ThreadSampleCollector(options, epochClock, ticker, mainLooper.getThread())); + final @Nullable RuntimeStatsSource runtimeStatsSource = + createRuntimeStatsSource(buildInfoProvider, options.getLogger()); + if (runtimeStatsSource != null) { + collectors.add(new RuntimeStatsCollector(runtimeStatsSource)); + } final @NotNull HangRecorder recorder = new HangRecorder( options, @@ -562,11 +574,17 @@ private static void setupHangRecorder( debugManager, mainThreadPoster, HangRecorder.DEFAULT_SUSPICIOUS_THRESHOLD_MS)), - Collections.singletonList( - new ThreadSampleCollector(options, epochClock, ticker, mainLooper.getThread()))); + collectors); options.setHangRecorder(recorder); } + static @Nullable RuntimeStatsSource createRuntimeStatsSource( + final @NotNull BuildInfoProvider buildInfoProvider, final @NotNull ILogger logger) { + return buildInfoProvider.getSdkInfoVersion() >= Build.VERSION_CODES.M + ? new AndroidRuntimeStatsSource(logger) + : null; + } + /** * 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/AndroidRuntimeStatsSource.java b/sentry-android-core/src/main/java/io/sentry/android/core/AndroidRuntimeStatsSource.java new file mode 100644 index 0000000000..cb14773a3a --- /dev/null +++ b/sentry-android-core/src/main/java/io/sentry/android/core/AndroidRuntimeStatsSource.java @@ -0,0 +1,104 @@ +package io.sentry.android.core; + +import android.os.Build; +import android.os.Debug; +import androidx.annotation.RequiresApi; +import io.sentry.ILogger; +import io.sentry.SentryLevel; +import io.sentry.android.core.hang.RuntimeStatsSnapshot; +import io.sentry.android.core.hang.RuntimeStatsSource; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +/** + * Reads the ART counters with {@link Debug#getRuntimeStat(String)} per key, which costs about 0.4 + * us. {@link Debug#getRuntimeStats()} is not used because its map has no value for some keys, and + * {@link Debug#getMemoryInfo(Debug.MemoryInfo)} takes milliseconds. + */ +@ApiStatus.Internal +@RequiresApi(api = Build.VERSION_CODES.M) +public final class AndroidRuntimeStatsSource implements RuntimeStatsSource { + + static final @NotNull String GC_COUNT = "art.gc.gc-count"; + static final @NotNull String GC_TIME = "art.gc.gc-time"; + static final @NotNull String BLOCKING_GC_COUNT = "art.gc.blocking-gc-count"; + static final @NotNull String BLOCKING_GC_TIME = "art.gc.blocking-gc-time"; + static final @NotNull String PRE_OOME_GC_COUNT = "art.gc.pre-oome-gc-count"; + static final @NotNull String GC_WAITING_TIME = "art.gc.total-time-waiting-for-gc"; + + private static final double NANOS_PER_MILLI = 1_000_000.0; + + interface StatReader { + @Nullable + String read(@NotNull String key); + } + + private final @NotNull ILogger logger; + private final @NotNull StatReader statReader; + + public AndroidRuntimeStatsSource(final @NotNull ILogger logger) { + this(logger, Debug::getRuntimeStat); + } + + AndroidRuntimeStatsSource(final @NotNull ILogger logger, final @NotNull StatReader statReader) { + this.logger = logger; + this.statReader = statReader; + } + + @Override + public @NotNull RuntimeStatsSnapshot read() { + final @NotNull RuntimeStatsSnapshot snapshot = new RuntimeStatsSnapshot(); + snapshot.gcCount = readLong(GC_COUNT); + snapshot.gcTimeMs = readDouble(GC_TIME); + snapshot.blockingGcCount = readLong(BLOCKING_GC_COUNT); + snapshot.blockingGcTimeMs = readDouble(BLOCKING_GC_TIME); + snapshot.preOomeGcCount = readLong(PRE_OOME_GC_COUNT); + + // Undocumented unit; the values match nanoseconds. + final @Nullable Double waitingNanos = readDouble(GC_WAITING_TIME); + snapshot.gcWaitingTimeMs = waitingNanos == null ? null : waitingNanos / NANOS_PER_MILLI; + + final @NotNull Runtime runtime = Runtime.getRuntime(); + final long total = runtime.totalMemory(); + final long free = runtime.freeMemory(); + final long max = runtime.maxMemory(); + snapshot.freeMemory = free; + snapshot.totalMemory = total; + snapshot.maxMemory = max; + // ART has no counter for this, the heap headroom is the closest value. + snapshot.freeMemoryUntilOome = max - (total - free); + return snapshot; + } + + private @Nullable Long readLong(final @NotNull String key) { + final @Nullable String value = statReader.read(key); + if (value == null) { + return null; + } + try { + return Long.parseLong(value.trim()); + } catch (NumberFormatException e) { + logUnparsable(key, value, e); + return null; + } + } + + private @Nullable Double readDouble(final @NotNull String key) { + final @Nullable String value = statReader.read(key); + if (value == null) { + return null; + } + try { + return Double.parseDouble(value.trim()); + } catch (NumberFormatException e) { + logUnparsable(key, value, e); + return null; + } + } + + private void logUnparsable( + final @NotNull String key, final @NotNull String value, final @NotNull Throwable e) { + logger.log(SentryLevel.WARNING, e, "Could not parse the runtime stat %s: %s", key, value); + } +} diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/NonFatalAnrIntegration.java b/sentry-android-core/src/main/java/io/sentry/android/core/NonFatalAnrIntegration.java index c770ebf8e8..7206801b36 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/NonFatalAnrIntegration.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/NonFatalAnrIntegration.java @@ -22,7 +22,9 @@ import io.sentry.android.core.hang.HangRecord; import io.sentry.android.core.hang.HangRecorder; import io.sentry.android.core.hang.HangRecorderListener; +import io.sentry.android.core.hang.RuntimeStatsCollector; import io.sentry.android.core.internal.util.AndroidThreadChecker; +import io.sentry.protocol.ArtContext; import io.sentry.protocol.Mechanism; import io.sentry.protocol.SentryException; import io.sentry.protocol.SentryThread; @@ -183,6 +185,14 @@ public void onHangRecorded(final @NotNull HangRecord record) { final @NotNull Map context = new HashMap<>(); context.put("duration_ms", record.getDurationMs()); context.put("sample_count", samples.size()); + final @Nullable Map runtimeStats = record.getRuntimeStats(); + if (runtimeStats != null) { + putDelta(context, runtimeStats, RuntimeStatsCollector.KEY_GC_COUNT_DELTA); + putDelta(context, runtimeStats, RuntimeStatsCollector.KEY_GC_TIME_MS_DELTA); + putDelta(context, runtimeStats, RuntimeStatsCollector.KEY_BLOCKING_GC_COUNT_DELTA); + putDelta(context, runtimeStats, RuntimeStatsCollector.KEY_BLOCKING_GC_TIME_MS_DELTA); + event.getContexts().setArt(toArtContext(runtimeStats)); + } event.getContexts().put("non_fatal_anr", context); if (event.getFingerprints() == null) { @@ -196,6 +206,40 @@ public void onHangRecorded(final @NotNull HangRecord record) { return event; } + private static void putDelta( + final @NotNull Map context, + final @NotNull Map runtimeStats, + final @NotNull String key) { + final @Nullable Object value = runtimeStats.get(key); + if (value != null) { + context.put(key, value); + } + } + + private static @NotNull ArtContext toArtContext(final @NotNull Map stats) { + final @NotNull ArtContext art = new ArtContext(); + art.setGcTotalCount(asLong(stats.get(RuntimeStatsCollector.KEY_GC_COUNT))); + art.setGcTotalTime(asDouble(stats.get(RuntimeStatsCollector.KEY_GC_TIME_MS))); + art.setGcBlockingCount(asLong(stats.get(RuntimeStatsCollector.KEY_BLOCKING_GC_COUNT))); + art.setGcBlockingTime(asDouble(stats.get(RuntimeStatsCollector.KEY_BLOCKING_GC_TIME_MS))); + art.setGcPreOomeCount(asLong(stats.get(RuntimeStatsCollector.KEY_PRE_OOME_GC_COUNT))); + art.setGcWaitingTime(asDouble(stats.get(RuntimeStatsCollector.KEY_GC_WAITING_TIME_MS))); + art.setFreeMemory(asLong(stats.get(RuntimeStatsCollector.KEY_FREE_MEMORY))); + art.setFreeMemoryUntilOome( + asLong(stats.get(RuntimeStatsCollector.KEY_FREE_MEMORY_UNTIL_OOME))); + art.setTotalMemory(asLong(stats.get(RuntimeStatsCollector.KEY_TOTAL_MEMORY))); + art.setMaxMemory(asLong(stats.get(RuntimeStatsCollector.KEY_MAX_MEMORY))); + return art; + } + + private static @Nullable Long asLong(final @Nullable Object value) { + return value instanceof Number ? ((Number) value).longValue() : null; + } + + private static @Nullable Double asDouble(final @Nullable Object value) { + return value instanceof Number ? ((Number) value).doubleValue() : null; + } + private static @NotNull SentryThread mainThread( final long mainThreadId, final @NotNull List samples, diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangRecord.java b/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangRecord.java index abed2ee8a4..e18e5ae2c2 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangRecord.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangRecord.java @@ -3,8 +3,10 @@ import io.sentry.android.core.anr.AnrStackTrace; import java.util.Collections; import java.util.List; +import java.util.Map; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; /** The collected data of one hang interval that ended with a record. */ @ApiStatus.Internal @@ -13,12 +15,14 @@ public final class HangRecord { private final long durationMs; private final long startTimestampMs; private final @NotNull List samples; + private final @Nullable Map runtimeStats; private final boolean endedAtMaxRecordingTime; private HangRecord(final @NotNull Builder builder) { this.durationMs = builder.durationMs; this.startTimestampMs = builder.startTimestampMs; this.samples = builder.samples; + this.runtimeStats = builder.runtimeStats; this.endedAtMaxRecordingTime = builder.endedAtMaxRecordingTime; } @@ -35,6 +39,11 @@ public long getStartTimestampMs() { return samples; } + /** Null if no collector recorded runtime stats for this interval. */ + public @Nullable Map getRuntimeStats() { + return runtimeStats; + } + /** * Whether the interval was cut at the maximum recording time. The watched thread is then still * blocked when the record is given to the listeners. @@ -47,6 +56,7 @@ public static final class Builder { private final long durationMs; private final long startTimestampMs; private @NotNull List samples = Collections.emptyList(); + private @Nullable Map runtimeStats; private boolean endedAtMaxRecordingTime; public Builder(final long durationMs, final long startTimestampMs) { @@ -59,6 +69,11 @@ public Builder(final long durationMs, final long startTimestampMs) { return this; } + public @NotNull Builder setRuntimeStats(final @Nullable Map runtimeStats) { + this.runtimeStats = runtimeStats; + return this; + } + public @NotNull Builder setEndedAtMaxRecordingTime(final boolean endedAtMaxRecordingTime) { this.endedAtMaxRecordingTime = endedAtMaxRecordingTime; return this; diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/hang/RuntimeStatsCollector.java b/sentry-android-core/src/main/java/io/sentry/android/core/hang/RuntimeStatsCollector.java new file mode 100644 index 0000000000..9aa31cbc28 --- /dev/null +++ b/sentry-android-core/src/main/java/io/sentry/android/core/hang/RuntimeStatsCollector.java @@ -0,0 +1,107 @@ +package io.sentry.android.core.hang; + +import java.util.HashMap; +import java.util.Map; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +/** + * Records the runtime counters at the first sample and at the end of a hang interval. The record + * gets the final values and the change of the GC counters over the hang, see the {@code KEY_*} + * constants. + * + *

Not thread-safe, {@link HangRecorder} calls it only on its recorder thread. + */ +@ApiStatus.Internal +public final class RuntimeStatsCollector implements HangDataCollector { + + public static final @NotNull String KEY_GC_COUNT = "gc_count"; + public static final @NotNull String KEY_GC_TIME_MS = "gc_time_ms"; + public static final @NotNull String KEY_BLOCKING_GC_COUNT = "blocking_gc_count"; + public static final @NotNull String KEY_BLOCKING_GC_TIME_MS = "blocking_gc_time_ms"; + public static final @NotNull String KEY_PRE_OOME_GC_COUNT = "pre_oome_gc_count"; + public static final @NotNull String KEY_GC_WAITING_TIME_MS = "gc_waiting_time_ms"; + public static final @NotNull String KEY_FREE_MEMORY = "free_memory"; + public static final @NotNull String KEY_FREE_MEMORY_UNTIL_OOME = "free_memory_until_oome"; + public static final @NotNull String KEY_TOTAL_MEMORY = "total_memory"; + public static final @NotNull String KEY_MAX_MEMORY = "max_memory"; + + public static final @NotNull String KEY_GC_COUNT_DELTA = "gc_count_delta"; + public static final @NotNull String KEY_GC_TIME_MS_DELTA = "gc_time_ms_delta"; + public static final @NotNull String KEY_BLOCKING_GC_COUNT_DELTA = "blocking_gc_count_delta"; + public static final @NotNull String KEY_BLOCKING_GC_TIME_MS_DELTA = "blocking_gc_time_ms_delta"; + + private final @NotNull RuntimeStatsSource source; + private @Nullable RuntimeStatsSnapshot baseline; + + public RuntimeStatsCollector(final @NotNull RuntimeStatsSource source) { + this.source = source; + } + + @Override + public void onRecordingStarted(final @NotNull HangInterval interval) { + baseline = null; + } + + @Override + public void onSample(final @NotNull HangInterval interval) { + if (baseline == null) { + baseline = source.read(); + } + } + + @Override + public void onRecordingStopped( + final @NotNull HangInterval interval, final @NotNull HangRecord.Builder out) { + final @Nullable RuntimeStatsSnapshot start = baseline; + if (start == null) { + return; + } + final @NotNull RuntimeStatsSnapshot end = source.read(); + + final @NotNull Map stats = new HashMap<>(); + put(stats, KEY_GC_COUNT, end.gcCount); + put(stats, KEY_GC_TIME_MS, end.gcTimeMs); + put(stats, KEY_BLOCKING_GC_COUNT, end.blockingGcCount); + put(stats, KEY_BLOCKING_GC_TIME_MS, end.blockingGcTimeMs); + put(stats, KEY_PRE_OOME_GC_COUNT, end.preOomeGcCount); + put(stats, KEY_GC_WAITING_TIME_MS, end.gcWaitingTimeMs); + put(stats, KEY_FREE_MEMORY, end.freeMemory); + put(stats, KEY_FREE_MEMORY_UNTIL_OOME, end.freeMemoryUntilOome); + put(stats, KEY_TOTAL_MEMORY, end.totalMemory); + put(stats, KEY_MAX_MEMORY, end.maxMemory); + + if (end.gcCount != null && start.gcCount != null) { + stats.put(KEY_GC_COUNT_DELTA, end.gcCount - start.gcCount); + } + if (end.gcTimeMs != null && start.gcTimeMs != null) { + stats.put(KEY_GC_TIME_MS_DELTA, end.gcTimeMs - start.gcTimeMs); + } + if (end.blockingGcCount != null && start.blockingGcCount != null) { + stats.put(KEY_BLOCKING_GC_COUNT_DELTA, end.blockingGcCount - start.blockingGcCount); + } + if (end.blockingGcTimeMs != null && start.blockingGcTimeMs != null) { + stats.put(KEY_BLOCKING_GC_TIME_MS_DELTA, end.blockingGcTimeMs - start.blockingGcTimeMs); + } + + out.setRuntimeStats(stats); + } + + @Override + public void onRecordingCanceled() { + baseline = null; + } + + @Override + public void close() { + baseline = null; + } + + private static void put( + final @NotNull Map map, final @NotNull String key, final @Nullable Object v) { + if (v != null) { + map.put(key, v); + } + } +} diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/hang/RuntimeStatsSnapshot.java b/sentry-android-core/src/main/java/io/sentry/android/core/hang/RuntimeStatsSnapshot.java new file mode 100644 index 0000000000..7d82a13231 --- /dev/null +++ b/sentry-android-core/src/main/java/io/sentry/android/core/hang/RuntimeStatsSnapshot.java @@ -0,0 +1,23 @@ +package io.sentry.android.core.hang; + +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.Nullable; + +/** + * The runtime counters at one point in time. GC counters are cumulative for the process, times are + * in milliseconds and memory is in bytes. A value the runtime does not provide is {@code null}. + */ +@ApiStatus.Internal +public final class RuntimeStatsSnapshot { + + public @Nullable Long gcCount; + public @Nullable Double gcTimeMs; + public @Nullable Long blockingGcCount; + public @Nullable Double blockingGcTimeMs; + public @Nullable Long preOomeGcCount; + public @Nullable Double gcWaitingTimeMs; + public @Nullable Long freeMemory; + public @Nullable Long freeMemoryUntilOome; + public @Nullable Long totalMemory; + public @Nullable Long maxMemory; +} diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/hang/RuntimeStatsSource.java b/sentry-android-core/src/main/java/io/sentry/android/core/hang/RuntimeStatsSource.java new file mode 100644 index 0000000000..1ce37ee7ba --- /dev/null +++ b/sentry-android-core/src/main/java/io/sentry/android/core/hang/RuntimeStatsSource.java @@ -0,0 +1,13 @@ +package io.sentry.android.core.hang; + +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; + +/** Reads the runtime counters of the process. */ +@ApiStatus.Internal +public interface RuntimeStatsSource { + + /** Must be cheap, callers may read it on a time-critical thread. */ + @NotNull + RuntimeStatsSnapshot read(); +} 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 bb7bad1261..a3e710617c 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 @@ -27,6 +27,7 @@ import io.sentry.android.core.cache.AndroidEnvelopeCache import io.sentry.android.core.hang.HangDataCollector import io.sentry.android.core.hang.HangRecorder import io.sentry.android.core.hang.HangSignal +import io.sentry.android.core.hang.RuntimeStatsCollector import io.sentry.android.core.hang.ThreadHangSignal import io.sentry.android.core.hang.ThreadSampleCollector import io.sentry.android.core.internal.debugmeta.AssetsDebugMetaLoader @@ -87,6 +88,7 @@ class AndroidOptionsInitializerTest { configureOptions: SentryAndroidOptions.() -> Unit = {}, configureContext: Context.() -> Unit = {}, assets: AssetManager? = null, + buildInfoProvider: BuildInfoProvider = BuildInfoProvider(AndroidLogger()), ) { sentryOptions.executorService = ImmediateExecutorService() mockContext = @@ -128,6 +130,7 @@ class AndroidOptionsInitializerTest { AndroidOptionsInitializer.initializeIntegrationsAndProcessors( sentryOptions, if (useRealContext) context else mockContext, + buildInfoProvider, loadClass, activityFramesTracker, false, @@ -712,6 +715,48 @@ class AndroidOptionsInitializerTest { .isSameInstanceAs(HangRecorder.DEFAULT_EXECUTOR_FACTORY) } + @Config(sdk = [Build.VERSION_CODES.N]) + @Test + fun `runtime stats source is created on API 23 and above`() { + val buildInfo = mock() + whenever(buildInfo.sdkInfoVersion).thenReturn(Build.VERSION_CODES.M) + + assertThat(AndroidOptionsInitializer.createRuntimeStatsSource(buildInfo, mock())) + .isInstanceOf(AndroidRuntimeStatsSource::class.java) + } + + @Config(sdk = [Build.VERSION_CODES.N]) + @Test + fun `HangRecorder collects runtime stats on API 23 and above`() { + fixture.initSut() + + val collectors = + fixture.sentryOptions.hangRecorder!!.getProperty>("collectors") + assertThat(collectors.map { it.javaClass }) + .containsExactly(ThreadSampleCollector::class.java, RuntimeStatsCollector::class.java) + .inOrder() + } + + @Test + fun `HangRecorder collects no runtime stats below API 23`() { + val buildInfo = spy(BuildInfoProvider(AndroidLogger())) + whenever(buildInfo.sdkInfoVersion).thenReturn(Build.VERSION_CODES.LOLLIPOP_MR1) + + fixture.initSut(buildInfoProvider = buildInfo) + + val collectors = + fixture.sentryOptions.hangRecorder!!.getProperty>("collectors") + assertThat(collectors.map { it.javaClass }).containsExactly(ThreadSampleCollector::class.java) + } + + @Test + fun `runtime stats source is not created below API 23`() { + val buildInfo = mock() + whenever(buildInfo.sdkInfoVersion).thenReturn(Build.VERSION_CODES.LOLLIPOP_MR1) + + assertThat(AndroidOptionsInitializer.createRuntimeStatsSource(buildInfo, mock())).isNull() + } + @Test fun `HangRecorder signal is a ThreadHangSignal with the AndroidDebugManager`() { fixture.initSut() @@ -747,7 +792,7 @@ class AndroidOptionsInitializerTest { val collector = fixture.sentryOptions.hangRecorder!! .getProperty>("collectors") - .single() + .first() assertThat(collector).isInstanceOf(ThreadSampleCollector::class.java) assertThat(collector.getProperty("epochClock")) .isSameInstanceAs(fixture.sentryOptions.epochClock) diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/AndroidRuntimeStatsSourceTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/AndroidRuntimeStatsSourceTest.kt new file mode 100644 index 0000000000..17d9e93e52 --- /dev/null +++ b/sentry-android-core/src/test/java/io/sentry/android/core/AndroidRuntimeStatsSourceTest.kt @@ -0,0 +1,87 @@ +package io.sentry.android.core + +import android.os.Build +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.google.common.truth.Truth.assertThat +import io.sentry.ILogger +import io.sentry.SentryLevel +import kotlin.test.Test +import org.junit.runner.RunWith +import org.mockito.kotlin.any +import org.mockito.kotlin.eq +import org.mockito.kotlin.mock +import org.mockito.kotlin.verify +import org.robolectric.annotation.Config + +@RunWith(AndroidJUnit4::class) +@Config(sdk = [Build.VERSION_CODES.N]) +class AndroidRuntimeStatsSourceTest { + + private val logger = mock() + + private fun source(values: Map) = + AndroidRuntimeStatsSource(logger, AndroidRuntimeStatsSource.StatReader { values[it] }) + + @Test + fun `reads gc counters and times`() { + val snapshot = + source( + mapOf( + AndroidRuntimeStatsSource.GC_COUNT to "12", + AndroidRuntimeStatsSource.GC_TIME to "340", + AndroidRuntimeStatsSource.BLOCKING_GC_COUNT to "3", + AndroidRuntimeStatsSource.BLOCKING_GC_TIME to "55", + AndroidRuntimeStatsSource.PRE_OOME_GC_COUNT to "1", + ), + ) + .read() + + assertThat(snapshot.gcCount).isEqualTo(12L) + assertThat(snapshot.gcTimeMs).isEqualTo(340.0) + assertThat(snapshot.blockingGcCount).isEqualTo(3L) + assertThat(snapshot.blockingGcTimeMs).isEqualTo(55.0) + assertThat(snapshot.preOomeGcCount).isEqualTo(1L) + } + + @Test + fun `converts the waiting time from nanoseconds to milliseconds`() { + val snapshot = source(mapOf(AndroidRuntimeStatsSource.GC_WAITING_TIME to "2500000")).read() + + assertThat(snapshot.gcWaitingTimeMs).isEqualTo(2.5) + } + + @Test + fun `missing and malformed keys are null`() { + val snapshot = source(mapOf(AndroidRuntimeStatsSource.GC_COUNT to "abc")).read() + + assertThat(snapshot.gcCount).isNull() + assertThat(snapshot.gcTimeMs).isNull() + assertThat(snapshot.gcWaitingTimeMs).isNull() + } + + @Test + fun `a malformed key is logged`() { + source(mapOf(AndroidRuntimeStatsSource.GC_COUNT to "abc")).read() + + verify(logger) + .log( + eq(SentryLevel.WARNING), + any(), + eq("Could not parse the runtime stat %s: %s"), + eq(AndroidRuntimeStatsSource.GC_COUNT), + eq("abc"), + ) + } + + @Test + fun `memory comes from the runtime and free until oome is the heap headroom`() { + val runtime = Runtime.getRuntime() + + val snapshot = source(emptyMap()).read() + + assertThat(snapshot.maxMemory).isEqualTo(runtime.maxMemory()) + assertThat(snapshot.totalMemory).isGreaterThan(0L) + assertThat(snapshot.freeMemoryUntilOome) + .isEqualTo(snapshot.maxMemory!! - (snapshot.totalMemory!! - snapshot.freeMemory!!)) + } +} diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/NonFatalAnrIntegrationTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/NonFatalAnrIntegrationTest.kt index 705f46eb94..0d51d078e4 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/NonFatalAnrIntegrationTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/NonFatalAnrIntegrationTest.kt @@ -14,6 +14,7 @@ import io.sentry.android.core.anr.NonFatalAnrMarker import io.sentry.android.core.hang.HangRecord import io.sentry.android.core.hang.HangRecorder import io.sentry.android.core.hang.HangRecorderListener +import io.sentry.android.core.hang.RuntimeStatsCollector import io.sentry.android.core.internal.util.AndroidThreadChecker import io.sentry.hints.AbnormalExit import io.sentry.protocol.SentryId @@ -74,7 +75,9 @@ class NonFatalAnrIntegrationTest { AnrStackTrace(1_100, systemStack, Thread.State.RUNNABLE), AnrStackTrace(1_200, systemStack, Thread.State.BLOCKED), ), - ) = HangRecord.Builder(durationMs, 1_000).setSamples(samples).build() + runtimeStats: Map? = null, + ) = + HangRecord.Builder(durationMs, 1_000).setSamples(samples).setRuntimeStats(runtimeStats).build() private fun subscribed(): HangRecorderListener { val integration = NonFatalAnrIntegration() @@ -384,6 +387,69 @@ class NonFatalAnrIntegrationTest { assertThat(context["sample_count"]).isEqualTo(2) } + private val runtimeStats = + mapOf( + RuntimeStatsCollector.KEY_GC_COUNT to 14L, + RuntimeStatsCollector.KEY_GC_TIME_MS to 130.5, + RuntimeStatsCollector.KEY_BLOCKING_GC_COUNT to 3L, + RuntimeStatsCollector.KEY_BLOCKING_GC_TIME_MS to 45.0, + RuntimeStatsCollector.KEY_PRE_OOME_GC_COUNT to 1L, + RuntimeStatsCollector.KEY_GC_WAITING_TIME_MS to 2.5, + RuntimeStatsCollector.KEY_FREE_MEMORY to 10L, + RuntimeStatsCollector.KEY_FREE_MEMORY_UNTIL_OOME to 60L, + RuntimeStatsCollector.KEY_TOTAL_MEMORY to 50L, + RuntimeStatsCollector.KEY_MAX_MEMORY to 100L, + RuntimeStatsCollector.KEY_GC_COUNT_DELTA to 4L, + RuntimeStatsCollector.KEY_GC_TIME_MS_DELTA to 30.5, + RuntimeStatsCollector.KEY_BLOCKING_GC_COUNT_DELTA to 1L, + RuntimeStatsCollector.KEY_BLOCKING_GC_TIME_MS_DELTA to 25.0, + ) + + @Test + fun `runtime stats fill the art context`() { + val listener = subscribed() + + listener.onHangRecorded(record(runtimeStats = runtimeStats)) + + val art = capturedEvent().first.contexts.art!! + assertThat(art.gcTotalCount).isEqualTo(14L) + assertThat(art.gcTotalTime).isEqualTo(130.5) + assertThat(art.gcBlockingCount).isEqualTo(3L) + assertThat(art.gcBlockingTime).isEqualTo(45.0) + assertThat(art.gcPreOomeCount).isEqualTo(1L) + assertThat(art.gcWaitingTime).isEqualTo(2.5) + assertThat(art.freeMemory).isEqualTo(10L) + assertThat(art.freeMemoryUntilGc).isNull() + assertThat(art.freeMemoryUntilOome).isEqualTo(60L) + assertThat(art.totalMemory).isEqualTo(50L) + assertThat(art.maxMemory).isEqualTo(100L) + } + + @Test + fun `runtime stats add the gc deltas to the context`() { + val listener = subscribed() + + listener.onHangRecorded(record(runtimeStats = runtimeStats)) + + val context = capturedEvent().first.contexts["non_fatal_anr"] as Map<*, *> + assertThat(context["gc_count_delta"]).isEqualTo(4L) + assertThat(context["gc_time_ms_delta"]).isEqualTo(30.5) + assertThat(context["blocking_gc_count_delta"]).isEqualTo(1L) + assertThat(context["blocking_gc_time_ms_delta"]).isEqualTo(25.0) + } + + @Test + fun `no runtime stats sets no art context and no deltas`() { + val listener = subscribed() + + listener.onHangRecorded(record()) + + val event = capturedEvent().first + assertThat(event.contexts.art).isNull() + val context = event.contexts["non_fatal_anr"] as Map<*, *> + assertThat(context.keys).containsExactly("duration_ms", "sample_count") + } + @Test fun `adds breadcrumb`() { val listener = subscribed() diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/hang/HangRecorderTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/hang/HangRecorderTest.kt index 12835000b2..251d35322e 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/hang/HangRecorderTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/hang/HangRecorderTest.kt @@ -63,7 +63,10 @@ class HangRecorderTest { createRecorder() } - private fun createRecorder(signalCount: Int = 1) { + private fun createRecorder( + signalCount: Int = 1, + collectors: List = listOf(collector), + ) { recorder = HangRecorder( options, @@ -78,7 +81,7 @@ class HangRecorderTest { repeat(signalCount) { signals.add(FakeSignal(metronome)) } signals }, - listOf(collector), + collectors, ) signal = signals.first() } @@ -170,6 +173,32 @@ class HangRecorderTest { assertThat(record.samples).isSameInstanceAs(samples) } + @Test + fun `record carries the runtime stats of a runtime stats collector`() { + var gcCount = 10L + val source = RuntimeStatsSource { + RuntimeStatsSnapshot().also { + it.gcCount = gcCount + it.totalMemory = 50 + } + } + createRecorder(collectors = listOf(RuntimeStatsCollector(source))) + startInForeground() + openIntervalInTick(300) + gcCount = 13 + + signal.report(HangSignal.State.IDLE, 0) + sdkExecutor.runAll() + + assertThat(records.single().runtimeStats) + .containsAtLeast( + RuntimeStatsCollector.KEY_TOTAL_MEMORY, + 50L, + RuntimeStatsCollector.KEY_GC_COUNT_DELTA, + 3L, + ) + } + @Test fun `no sample after idle`() { startInForeground() diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/hang/RuntimeStatsCollectorTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/hang/RuntimeStatsCollectorTest.kt new file mode 100644 index 0000000000..539f5baec0 --- /dev/null +++ b/sentry-android-core/src/test/java/io/sentry/android/core/hang/RuntimeStatsCollectorTest.kt @@ -0,0 +1,131 @@ +package io.sentry.android.core.hang + +import com.google.common.truth.Truth.assertThat +import kotlin.test.Test + +class RuntimeStatsCollectorTest { + + private class FakeSource : RuntimeStatsSource { + var next = RuntimeStatsSnapshot() + var reads = 0 + + override fun read(): RuntimeStatsSnapshot { + reads++ + return next + } + } + + private val source = FakeSource() + private val collector = RuntimeStatsCollector(source) + private val interval = HangInterval(0) + + private fun snapshot(gcCount: Long, gcTimeMs: Double, blocking: Long, blockingTimeMs: Double) = + RuntimeStatsSnapshot().also { + it.gcCount = gcCount + it.gcTimeMs = gcTimeMs + it.blockingGcCount = blocking + it.blockingGcTimeMs = blockingTimeMs + it.preOomeGcCount = 0 + it.gcWaitingTimeMs = 2.5 + it.freeMemory = 10 + it.freeMemoryUntilOome = 60 + it.totalMemory = 50 + it.maxMemory = 100 + } + + private fun stop(): Map? { + val builder = HangRecord.Builder(1_000, 1) + collector.onRecordingStopped(interval, builder) + return builder.build().runtimeStats + } + + @Test + fun `records the final values and the deltas over the hang`() { + source.next = snapshot(10, 100.0, 2, 20.0) + collector.onSample(interval) + source.next = snapshot(14, 130.5, 3, 45.0) + + val stats = stop()!! + + assertThat(stats[RuntimeStatsCollector.KEY_GC_COUNT]).isEqualTo(14L) + assertThat(stats[RuntimeStatsCollector.KEY_GC_TIME_MS]).isEqualTo(130.5) + assertThat(stats[RuntimeStatsCollector.KEY_BLOCKING_GC_COUNT]).isEqualTo(3L) + assertThat(stats[RuntimeStatsCollector.KEY_BLOCKING_GC_TIME_MS]).isEqualTo(45.0) + assertThat(stats[RuntimeStatsCollector.KEY_PRE_OOME_GC_COUNT]).isEqualTo(0L) + assertThat(stats[RuntimeStatsCollector.KEY_GC_WAITING_TIME_MS]).isEqualTo(2.5) + assertThat(stats[RuntimeStatsCollector.KEY_FREE_MEMORY]).isEqualTo(10L) + assertThat(stats[RuntimeStatsCollector.KEY_FREE_MEMORY_UNTIL_OOME]).isEqualTo(60L) + assertThat(stats[RuntimeStatsCollector.KEY_TOTAL_MEMORY]).isEqualTo(50L) + assertThat(stats[RuntimeStatsCollector.KEY_MAX_MEMORY]).isEqualTo(100L) + assertThat(stats[RuntimeStatsCollector.KEY_GC_COUNT_DELTA]).isEqualTo(4L) + assertThat(stats[RuntimeStatsCollector.KEY_GC_TIME_MS_DELTA]).isEqualTo(30.5) + assertThat(stats[RuntimeStatsCollector.KEY_BLOCKING_GC_COUNT_DELTA]).isEqualTo(1L) + assertThat(stats[RuntimeStatsCollector.KEY_BLOCKING_GC_TIME_MS_DELTA]).isEqualTo(25.0) + } + + @Test + fun `only the first sample takes the baseline`() { + source.next = snapshot(10, 100.0, 2, 20.0) + collector.onSample(interval) + source.next = snapshot(12, 100.0, 2, 20.0) + collector.onSample(interval) + source.next = snapshot(15, 100.0, 2, 20.0) + + assertThat(stop()!![RuntimeStatsCollector.KEY_GC_COUNT_DELTA]).isEqualTo(5L) + assertThat(source.reads).isEqualTo(2) + } + + @Test + fun `stop without a sample adds nothing`() { + assertThat(stop()).isNull() + assertThat(source.reads).isEqualTo(0) + } + + @Test + fun `onRecordingCanceled drops the baseline`() { + collector.onSample(interval) + collector.onRecordingCanceled() + + assertThat(stop()).isNull() + } + + @Test + fun `a new interval after onRecordingCanceled gets a new baseline`() { + source.next = snapshot(10, 100.0, 2, 20.0) + collector.onSample(interval) + collector.onRecordingCanceled() + source.next = snapshot(20, 100.0, 2, 20.0) + collector.onSample(interval) + source.next = snapshot(21, 100.0, 2, 20.0) + + assertThat(stop()!![RuntimeStatsCollector.KEY_GC_COUNT_DELTA]).isEqualTo(1L) + } + + @Test + fun `onRecordingStarted drops the baseline of the previous interval`() { + collector.onSample(interval) + + collector.onRecordingStarted(HangInterval(1_000)) + + assertThat(stop()).isNull() + } + + @Test + fun `close drops the baseline`() { + collector.onSample(interval) + + collector.close() + + assertThat(stop()).isNull() + } + + @Test + fun `values the source does not provide are left out`() { + source.next = RuntimeStatsSnapshot().also { it.totalMemory = 50 } + collector.onSample(interval) + + val stats = stop()!! + + assertThat(stats).containsExactly(RuntimeStatsCollector.KEY_TOTAL_MEMORY, 50L) + } +}