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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions sentry-android-core/api/sentry-android-core.api
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,11 @@ public final class io/sentry/android/core/AndroidProfiler$ProfileStartData {
public fun <init> (JJLjava/util/Date;)V
}

public final class io/sentry/android/core/AndroidRuntimeStatsSource : io/sentry/android/core/hang/RuntimeStatsSource {
public fun <init> (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
Expand Down Expand Up @@ -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
Expand All @@ -870,6 +876,7 @@ public final class io/sentry/android/core/hang/HangRecord$Builder {
public fun <init> (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;
}

Expand Down Expand Up @@ -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 <init> (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 <init> ()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 <init> (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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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());
}
Expand Down Expand Up @@ -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;
}
Expand All @@ -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<HangDataCollector> 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,
Expand All @@ -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
*
Expand Down
Original file line number Diff line number Diff line change
@@ -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);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -183,6 +185,14 @@ public void onHangRecorded(final @NotNull HangRecord record) {
final @NotNull Map<String, Object> context = new HashMap<>();
context.put("duration_ms", record.getDurationMs());
context.put("sample_count", samples.size());
final @Nullable Map<String, Object> 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) {
Expand All @@ -196,6 +206,40 @@ public void onHangRecorded(final @NotNull HangRecord record) {
return event;
}

private static void putDelta(
final @NotNull Map<String, Object> context,
final @NotNull Map<String, Object> 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<String, Object> 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<AnrStackTrace> samples,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -13,12 +15,14 @@ public final class HangRecord {
private final long durationMs;
private final long startTimestampMs;
private final @NotNull List<AnrStackTrace> samples;
private final @Nullable Map<String, Object> 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;
}

Expand All @@ -35,6 +39,11 @@ public long getStartTimestampMs() {
return samples;
}

/** Null if no collector recorded runtime stats for this interval. */
public @Nullable Map<String, Object> 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.
Expand All @@ -47,6 +56,7 @@ public static final class Builder {
private final long durationMs;
private final long startTimestampMs;
private @NotNull List<AnrStackTrace> samples = Collections.emptyList();
private @Nullable Map<String, Object> runtimeStats;
private boolean endedAtMaxRecordingTime;

public Builder(final long durationMs, final long startTimestampMs) {
Expand All @@ -59,6 +69,11 @@ public Builder(final long durationMs, final long startTimestampMs) {
return this;
}

public @NotNull Builder setRuntimeStats(final @Nullable Map<String, Object> runtimeStats) {
this.runtimeStats = runtimeStats;
return this;
}

public @NotNull Builder setEndedAtMaxRecordingTime(final boolean endedAtMaxRecordingTime) {
this.endedAtMaxRecordingTime = endedAtMaxRecordingTime;
return this;
Expand Down
Loading
Loading