Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat: Measure app start time #1487

Merged
merged 23 commits into from
Jun 11, 2021
Merged
Show file tree
Hide file tree
Changes from 5 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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
* Feat: OkHttp callback for Customising the Span (#1478)
* Feat: Add breadcrumb in Spring RestTemplate integration (#1481)
* Fix: Cloning Stack (#1483)
* Feat: App start up metrics (#1487)

# 5.0.0-beta.4

Expand Down
11 changes: 11 additions & 0 deletions sentry-android-core/api/sentry-android-core.api
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,17 @@ public final class io/sentry/android/core/SentryInitProvider : android/content/C
public fun update (Landroid/net/Uri;Landroid/content/ContentValues;Ljava/lang/String;[Ljava/lang/String;)I
}

public final class io/sentry/android/core/SentryPerformanceProvider : android/content/ContentProvider {
public fun <init> ()V
public fun attachInfo (Landroid/content/Context;Landroid/content/pm/ProviderInfo;)V
public fun delete (Landroid/net/Uri;Ljava/lang/String;[Ljava/lang/String;)I
public fun getType (Landroid/net/Uri;)Ljava/lang/String;
public fun insert (Landroid/net/Uri;Landroid/content/ContentValues;)Landroid/net/Uri;
public fun onCreate ()Z
public fun query (Landroid/net/Uri;[Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)Landroid/database/Cursor;
public fun update (Landroid/net/Uri;Landroid/content/ContentValues;Ljava/lang/String;[Ljava/lang/String;)I
}

public final class io/sentry/android/core/SystemEventsBreadcrumbsIntegration : io/sentry/Integration, java/io/Closeable {
public fun <init> (Landroid/content/Context;)V
public fun <init> (Landroid/content/Context;Ljava/util/List;)V
Expand Down
6 changes: 6 additions & 0 deletions sentry-android-core/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,11 @@
android:name=".SentryInitProvider"
android:authorities="${applicationId}.SentryInitProvider"
android:exported="false"/>

<provider
android:name=".SentryPerformanceProvider"
android:authorities="${applicationId}.SentryPerformanceProvider"
android:initOrder="200"
android:exported="false"/>
</application>
</manifest>
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@ public final class ActivityLifecycleIntegration

private boolean isAllActivityCallbacksAvailable;

/** if the very first Activity has been already created */
private boolean firstActivityCreated = false;
/** if the very first Activity has been already resumed */
private boolean firstActivityResumed = false;

// WeakHashMap isn't thread safe but ActivityLifecycleCallbacks is only called from the
// main-thread
private final @NotNull WeakHashMap<Activity, ITransaction> activitiesWithOngoingTransactions =
Expand Down Expand Up @@ -186,6 +191,12 @@ public synchronized void onActivityPreCreated(
@Override
public synchronized void onActivityCreated(
final @NonNull Activity activity, final @Nullable Bundle savedInstanceState) {
if (!firstActivityCreated && performanceEnabled) {
// if Activity has savedInstanceState then its a warm start
AppStartState.getInstance().setColdStart(savedInstanceState == null);
firstActivityCreated = true;
}

addBreadcrumb(activity, "created");

// fallback call for API < 29 compatibility, otherwise it happens on onActivityPreCreated
Expand All @@ -201,6 +212,12 @@ public synchronized void onActivityStarted(final @NonNull Activity activity) {

@Override
public synchronized void onActivityResumed(final @NonNull Activity activity) {
if (!firstActivityResumed && performanceEnabled) {
// sets App start as finished when the very first activity calls onResume
AppStartState.getInstance().setAppStartEnd();
firstActivityResumed = true;
}

addBreadcrumb(activity, "resumed");

// fallback call for API < 29 compatibility, otherwise it happens on onActivityPostResumed
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ static void init(
readDefaultOptionValues(options, context);

options.addEventProcessor(new DefaultAndroidEventProcessor(context, logger, buildInfoProvider));
options.addEventProcessor(new PerformanceAndroidEventProcessor(options));

options.setTransportGate(new AndroidTransportGate(context, options.getLogger()));
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package io.sentry.android.core;

import android.os.SystemClock;
import java.util.Date;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;

/** AppStartState holds the state of the App Start metric and appStartTime */
final class AppStartState {

private static @NotNull AppStartState instance = new AppStartState();

/** appStart in milliseconds */
private @Nullable Long appStart;

/** appStartEnd in milliseconds */
private @Nullable Long appStartEnd;

/** The type of App start coldStart=true -> Cold start, coldStart=false -> Warm start */
private boolean coldStart;

/** appStart as a Date used in the App's Context */
private @Nullable Date appStartTime;

private AppStartState() {}

static @NotNull AppStartState getInstance() {
return instance;
}

@TestOnly
void resetInstance() {
instance = new AppStartState();
}

void setAppStartEnd() {
appStartEnd = SystemClock.uptimeMillis();
}

@Nullable
Long getAppStartInterval() {
if (appStart == null || appStartEnd == null) {
return null;
}
return appStartEnd - appStart;
}

boolean getColdStart() {
return coldStart;
}

void setColdStart(final boolean coldStart) {
this.coldStart = coldStart;
}

@Nullable
Date getAppStartTime() {
return appStartTime;
}

synchronized void setAppStartTime(final long appStart, final @NotNull Date appStartTime) {
// method is synchronized because the SDK may by init. on a background thread.
if (this.appStartTime != null && this.appStart != null) {
return;
}
this.appStartTime = appStartTime;
this.appStart = appStart;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,6 @@ final class DefaultAndroidEventProcessor implements EventProcessor {
@TestOnly static final String EMULATOR = "emulator";
@TestOnly static final String SIDE_LOADED = "sideLoaded";

// it could also be a parameter and get from Sentry.init(...)
private static final @Nullable Date appStartTime = DateUtils.getCurrentDateTime();

@TestOnly final Context context;

@TestOnly final Future<Map<String, Object>> contextData;
Expand Down Expand Up @@ -299,7 +296,7 @@ private void mergeDebugImages(final @NotNull SentryEvent event) {

private void setAppExtras(final @NotNull App app) {
app.setAppName(getApplicationName());
app.setAppStartTime(appStartTime);
app.setAppStartTime(AppStartState.getInstance().getAppStartTime());
}

@SuppressWarnings("deprecation")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package io.sentry.android.core;

import io.sentry.EventProcessor;
import io.sentry.protocol.MeasurementValue;
import io.sentry.protocol.SentryTransaction;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/** Event Processor responsable for adding Android metrics to transactions */
final class PerformanceAndroidEventProcessor implements EventProcessor {

final @NotNull SentryAndroidOptions options;

PerformanceAndroidEventProcessor(final @NotNull SentryAndroidOptions options) {
this.options = options;
}

// transactions may be started in parallel, making this field volatile instead of a lock
// to avoid contention.
private volatile boolean sentStartMeasurement = false;

@Override
public @NotNull SentryTransaction process(
@NotNull SentryTransaction transaction, @Nullable Object hint) {
// the app start metric is sent only once when the 1st transaction happens
// after the app start is collected.
if (!sentStartMeasurement && options.isTracingEnabled()) {
final Long appStartUpInterval = AppStartState.getInstance().getAppStartInterval();
// if appStartUpInterval is null, metrics are not ready to be sent
if (appStartUpInterval != null) {
final MeasurementValue value = new MeasurementValue((float) appStartUpInterval);

final String appStartKey =
AppStartState.getInstance().getColdStart() ? "app_start_cold" : "app_start_warm";

transaction.getMeasurements().put(appStartKey, value);
sentStartMeasurement = true;
}
}

return transaction;
}
}
Original file line number Diff line number Diff line change
@@ -1,16 +1,24 @@
package io.sentry.android.core;

import android.content.Context;
import android.os.SystemClock;
import io.sentry.DateUtils;
import io.sentry.ILogger;
import io.sentry.OptionsContainer;
import io.sentry.Sentry;
import io.sentry.SentryLevel;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import org.jetbrains.annotations.NotNull;

/** Sentry initialization class */
public final class SentryAndroid {

// static to rely on Class load init.
private static final @NotNull Date appStartTime = DateUtils.getCurrentDateTime();
// SystemClock.uptimeMillis() isn't affected by phone provider or clock changes.
private static final long appStart = SystemClock.uptimeMillis();

private SentryAndroid() {}

/**
Expand Down Expand Up @@ -51,10 +59,14 @@ public static void init(
* @param logger your custom logger that implements ILogger
* @param configuration Sentry.OptionsConfiguration configuration handler
*/
public static void init(
public static synchronized void init(
@NotNull final Context context,
@NotNull ILogger logger,
@NotNull Sentry.OptionsConfiguration<SentryAndroidOptions> configuration) {
// if SentryPerformanceProvider was disabled or removed, we set the App Start when
// the SDK is called.
AppStartState.getInstance().setAppStartTime(appStart, appStartTime);

try {
Sentry.init(
OptionsContainer.create(SentryAndroidOptions.class),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package io.sentry.android.core;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.ProviderInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.SystemClock;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.sentry.DateUtils;
import java.util.Date;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;

/**
* SentryPerformanceProvider is responsible for collecting data (eg appStart) as early as possible
* as ContentProvider is the only reliable hook for libraries that works across all the supported
* SDK versions. When minSDK is >= 24, we could use Process.getStartUptimeMillis()
*/
@ApiStatus.Internal
public final class SentryPerformanceProvider extends ContentProvider {

// static to rely on Class load
private static final @NotNull Date appStartTime = DateUtils.getCurrentDateTime();
// SystemClock.uptimeMillis() isn't affected by phone provider or clock changes.
private static final long appStart = SystemClock.uptimeMillis();

public SentryPerformanceProvider() {
AppStartState.getInstance().setAppStartTime(appStart, appStartTime);
}

@Override
public boolean onCreate() {
return true;
}

@Override
public void attachInfo(Context context, ProviderInfo info) {
// applicationId is expected to be prepended. See AndroidManifest.xml
if (SentryPerformanceProvider.class.getName().equals(info.authority)) {
throw new IllegalStateException(
"An applicationId is required to fulfill the manifest placeholder.");
}
super.attachInfo(context, info);
}

@Nullable
@Override
public Cursor query(
@NonNull Uri uri,
@Nullable String[] projection,
@Nullable String selection,
@Nullable String[] selectionArgs,
@Nullable String sortOrder) {
return null;
}

@Nullable
@Override
public String getType(@NonNull Uri uri) {
return null;
}

@Nullable
@Override
public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
return null;
}

@Override
public int delete(
@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
return 0;
}

@Override
public int update(
@NonNull Uri uri,
@Nullable ContentValues values,
@Nullable String selection,
@Nullable String[] selectionArgs) {
return 0;
}
}
Loading