-
Notifications
You must be signed in to change notification settings - Fork 8
/
AppStartupTraceEmitter.kt
401 lines (357 loc) · 15.2 KB
/
AppStartupTraceEmitter.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
package io.embrace.android.embracesdk.capture.startup
import android.os.Build.VERSION_CODES
import android.os.Process
import io.embrace.android.embracesdk.internal.clock.nanosToMillis
import io.embrace.android.embracesdk.internal.spans.SpanService
import io.embrace.android.embracesdk.internal.utils.Provider
import io.embrace.android.embracesdk.internal.utils.VersionChecker
import io.embrace.android.embracesdk.logging.EmbLogger
import io.embrace.android.embracesdk.spans.EmbraceSpan
import io.embrace.android.embracesdk.spans.PersistableEmbraceSpan
import io.embrace.android.embracesdk.worker.BackgroundWorker
import io.opentelemetry.sdk.common.Clock
import java.util.concurrent.ConcurrentLinkedQueue
import java.util.concurrent.atomic.AtomicBoolean
/**
* Records startup traces based on the data that it is provided. It adjusts what it logs based on what data has been provided and
* and which Android version the app is running.
*
* For the start of cold launch traces, the start time is determined by the following:
*
* - Android 13 onwards, it is determined by when the app process is specialized from the zygote process, which could be some time after the
* the zygote process is created, depending on, perhaps among other things, the manufacturer of the device. If this value is used,
* it value will be captured in an attribute on the root span of the trace.
*
* - Android 7.0 to 12 (inclusive), it is determined by when the app process is created. Some OEMs on some versions of Android are known to
* pre-created a bunch of zygotes in order to speed up startup time, to mixed success. The fact that Pixel devices don't do this should
* tell you how effectively that strategy overall is.
*
* - Older Android version that are supported, if provided, the application object creation time. Otherwise, we fall back to
* SDK startup time (for now)
*
* For the start of warm launch traces, we use the creation time for the first activity that we want to consider for startup
*
*/
internal class AppStartupTraceEmitter(
private val clock: Clock,
private val startupServiceProvider: Provider<StartupService?>,
private val spanService: SpanService,
private val backgroundWorker: BackgroundWorker,
private val versionChecker: VersionChecker,
private val logger: EmbLogger
) : AppStartupDataCollector {
private val processCreateRequestedMs: Long?
private val processCreatedMs: Long?
private val additionalTrackedIntervals = ConcurrentLinkedQueue<TrackedInterval>()
init {
val timestampAtDeviceStart = nowMs() - clock.nanoTime().nanosToMillis()
processCreateRequestedMs = if (versionChecker.isAtLeast(VERSION_CODES.TIRAMISU)) {
timestampAtDeviceStart + Process.getStartRequestedElapsedRealtime()
} else {
null
}
processCreatedMs = if (versionChecker.isAtLeast(VERSION_CODES.N)) {
timestampAtDeviceStart + Process.getStartElapsedRealtime()
} else {
null
}
}
@Volatile
private var applicationInitStartMs: Long? = null
@Volatile
private var applicationInitEndMs: Long? = null
@Volatile
private var startupActivityName: String? = null
@Volatile
private var startupActivityPreCreatedMs: Long? = null
@Volatile
private var startupActivityInitStartMs: Long? = null
@Volatile
private var startupActivityPostCreatedMs: Long? = null
@Volatile
private var startupActivityInitEndMs: Long? = null
@Volatile
private var startupActivityResumedMs: Long? = null
@Volatile
private var firstFrameRenderedMs: Long? = null
private val startupRecorded = AtomicBoolean(false)
private val endWithFrameDraw: Boolean = versionChecker.isAtLeast(VERSION_CODES.Q)
override fun applicationInitStart(timestampMs: Long?) {
applicationInitStartMs = timestampMs ?: nowMs()
}
override fun applicationInitEnd(timestampMs: Long?) {
applicationInitEndMs = timestampMs ?: nowMs()
}
override fun startupActivityPreCreated(timestampMs: Long?) {
startupActivityPreCreatedMs = timestampMs ?: nowMs()
}
override fun startupActivityInitStart(timestampMs: Long?) {
startupActivityInitStartMs = timestampMs ?: nowMs()
}
override fun startupActivityPostCreated(timestampMs: Long?) {
startupActivityPostCreatedMs = timestampMs ?: nowMs()
}
override fun startupActivityInitEnd(timestampMs: Long?) {
startupActivityInitEndMs = timestampMs ?: nowMs()
}
override fun startupActivityResumed(activityName: String, timestampMs: Long?) {
startupActivityName = activityName
startupActivityResumedMs = timestampMs ?: nowMs()
if (!endWithFrameDraw) {
dataCollectionComplete()
}
}
override fun firstFrameRendered(activityName: String, timestampMs: Long?) {
startupActivityName = activityName
firstFrameRenderedMs = timestampMs ?: nowMs()
if (endWithFrameDraw) {
dataCollectionComplete()
}
}
override fun addTrackedInterval(name: String, startTimeMs: Long, endTimeMs: Long) {
additionalTrackedIntervals.add(
TrackedInterval(name = name, startTimeMs = startTimeMs, endTimeMs = endTimeMs)
)
}
/**
* Called when app startup is considered complete, i.e. the data can be used and any additional updates can be ignored
*/
private fun dataCollectionComplete() {
if (!startupRecorded.get()) {
synchronized(startupRecorded) {
if (!startupRecorded.get()) {
backgroundWorker.submit {
recordStartup()
if (!startupRecorded.get()) {
logger.logWarning("App startup trace recording attempted but did not succeed")
}
}
}
}
}
}
@Suppress("CyclomaticComplexMethod", "ComplexMethod")
private fun recordStartup() {
val startupService = startupServiceProvider() ?: return
val sdkInitStartMs = startupService.getSdkInitStartMs()
val sdkInitEndMs = startupService.getSdkInitEndMs()
val sdkStartupDuration = duration(sdkInitStartMs, sdkInitEndMs)
val processStartTimeMs: Long? =
if (versionChecker.isAtLeast(VERSION_CODES.N)) {
processCreatedMs
} else {
applicationInitStartMs ?: sdkInitStartMs
}
val traceEndTimeMs: Long? =
if (versionChecker.isAtLeast(VERSION_CODES.Q)) {
firstFrameRenderedMs
} else {
startupActivityResumedMs
}
if (processStartTimeMs != null && traceEndTimeMs != null) {
val gap = applicationActivityCreationGap() ?: duration(sdkInitEndMs, startupActivityInitStartMs)
if (gap != null) {
val startupTrace: EmbraceSpan? = if (!spanService.initialized()) {
logger.logWarning("Startup trace not recorded because the spans service is not initialized")
null
} else if (gap <= SDK_AND_ACTIVITY_INIT_GAP) {
recordColdTtid(
traceStartTimeMs = processStartTimeMs,
applicationInitEndMs = applicationInitEndMs,
sdkInitStartMs = sdkInitStartMs,
sdkInitEndMs = sdkInitEndMs,
activityInitStartMs = startupActivityInitStartMs,
activityInitEndMs = startupActivityInitEndMs,
traceEndTimeMs = traceEndTimeMs,
)
} else {
startupActivityInitStartMs?.let { startTime ->
recordWarmTtid(
traceStartTimeMs = startTime,
activityInitEndMs = startupActivityInitEndMs,
traceEndTimeMs = traceEndTimeMs,
processToActivityCreateGap = gap,
sdkStartupDuration = sdkStartupDuration,
)
}
}
if (startupTrace != null) {
recordAdditionalIntervals(startupTrace)
}
}
}
}
private fun recordAdditionalIntervals(startupTrace: EmbraceSpan) {
do {
additionalTrackedIntervals.poll()?.let { trackedInterval ->
spanService.recordCompletedSpan(
name = trackedInterval.name,
parent = startupTrace,
startTimeMs = trackedInterval.startTimeMs,
endTimeMs = trackedInterval.endTimeMs,
private = false
)
}
} while (additionalTrackedIntervals.isNotEmpty())
}
@Suppress("CyclomaticComplexMethod", "ComplexMethod")
private fun recordColdTtid(
traceStartTimeMs: Long,
applicationInitEndMs: Long?,
sdkInitStartMs: Long?,
sdkInitEndMs: Long?,
activityInitStartMs: Long?,
activityInitEndMs: Long?,
traceEndTimeMs: Long,
): EmbraceSpan? {
return if (!startupRecorded.get()) {
spanService.startSpan(
name = "cold-time-to-initial-display",
startTimeMs = traceStartTimeMs,
private = false
)?.apply {
addTraceMetadata()
if (stop(endTimeMs = traceEndTimeMs)) {
startupRecorded.set(true)
}
if (applicationInitEndMs != null) {
spanService.recordCompletedSpan(
name = "process-init",
parent = this,
startTimeMs = traceStartTimeMs,
endTimeMs = applicationInitEndMs,
private = false,
)
}
if (sdkInitStartMs != null && sdkInitEndMs != null) {
spanService.recordCompletedSpan(
name = "embrace-init",
parent = this,
startTimeMs = sdkInitStartMs,
endTimeMs = sdkInitEndMs,
private = false,
)
}
val lastEventBeforeActivityInit = applicationInitEndMs ?: sdkInitEndMs
if (lastEventBeforeActivityInit != null && activityInitStartMs != null) {
spanService.recordCompletedSpan(
name = "activity-init-gap",
parent = this,
startTimeMs = lastEventBeforeActivityInit,
endTimeMs = activityInitStartMs,
private = false,
)
}
if (activityInitStartMs != null && activityInitEndMs != null) {
spanService.recordCompletedSpan(
name = "activity-create",
parent = this,
startTimeMs = activityInitStartMs,
endTimeMs = activityInitEndMs,
private = false,
)
}
if (activityInitEndMs != null) {
val uiLoadSpanName = if (endWithFrameDraw) {
"first-frame-render"
} else {
"activity-resume"
}
spanService.recordCompletedSpan(
name = uiLoadSpanName,
parent = this,
startTimeMs = activityInitEndMs,
endTimeMs = traceEndTimeMs,
private = false,
)
}
}
} else {
null
}
}
private fun recordWarmTtid(
traceStartTimeMs: Long,
activityInitEndMs: Long?,
traceEndTimeMs: Long,
processToActivityCreateGap: Long?,
sdkStartupDuration: Long?,
): EmbraceSpan? {
return if (!startupRecorded.get()) {
spanService.startSpan(
name = "warm-time-to-initial-display",
startTimeMs = traceStartTimeMs,
private = false,
)?.apply {
processToActivityCreateGap?.let { gap ->
addAttribute("activity-init-gap-ms", gap.toString())
}
sdkStartupDuration?.let { duration ->
addAttribute("embrace-init-duration-ms", duration.toString())
}
addTraceMetadata()
if (stop(endTimeMs = traceEndTimeMs)) {
startupRecorded.set(true)
}
if (activityInitEndMs != null) {
spanService.recordCompletedSpan(
name = "activity-create",
parent = this,
startTimeMs = traceStartTimeMs,
endTimeMs = activityInitEndMs,
private = false,
)
val uiLoadSpanName = if (endWithFrameDraw) {
"first-frame-render"
} else {
"activity-resume"
}
spanService.recordCompletedSpan(
name = uiLoadSpanName,
parent = this,
startTimeMs = activityInitEndMs,
endTimeMs = traceEndTimeMs,
private = false,
)
}
}
} else {
null
}
}
private fun processCreateDelay(): Long? = duration(processCreateRequestedMs, processCreatedMs)
private fun applicationActivityCreationGap(): Long? = duration(applicationInitEndMs, startupActivityInitStartMs)
private fun nowMs(): Long = clock.now().nanosToMillis()
private fun PersistableEmbraceSpan.addTraceMetadata() {
processCreateDelay()?.let { delay ->
addAttribute("process-create-delay-ms", delay.toString())
}
startupActivityName?.let { name ->
addAttribute("startup-activity-name", name)
}
startupActivityPreCreatedMs?.let { timeMs ->
addAttribute("startup-activity-pre-created-ms", timeMs.toString())
}
startupActivityPostCreatedMs?.let { timeMs ->
addAttribute("startup-activity-post-created-ms", timeMs.toString())
}
}
private data class TrackedInterval(
val name: String,
val startTimeMs: Long,
val endTimeMs: Long,
)
companion object {
/**
* The gap between the end of the Embrace SDK initialization to when the first activity loaded after startup happens.
* If this gap is greater than 1 minute, it's likely that the app process was not created because the user tapped on the app icon,
* so we track this app launch as a warm start.
*/
const val SDK_AND_ACTIVITY_INIT_GAP = 60000L
fun duration(start: Long?, end: Long?): Long? = if (start != null && end != null) {
end - start
} else {
null
}
}
}