Repository navigation
Expand file tree
/
Copy pathReaperInternal.kt
More file actions
396 lines (350 loc) · 11.6 KB
/
Copy pathReaperInternal.kt
File metadata and controls
396 lines (350 loc) · 11.6 KB
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
// We catch very generic exceptions on purpose. We need to avoid
// crashing the host app.
@file:Suppress("MagicNumber", "TooGenericExceptionCaught", "TooManyFunctions", "UnusedParameter")
package com.emergetools.reaper
import android.app.Application
import android.content.Context
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.os.Build
import android.os.Handler
import android.os.HandlerThread
import android.os.Looper
import android.system.ErrnoException
import android.util.Log
import androidx.annotation.MainThread
import androidx.lifecycle.ProcessLifecycleOwner
import androidx.work.Constraints
import androidx.work.NetworkType
import androidx.work.OneTimeWorkRequest
import androidx.work.WorkManager
import androidx.work.workDataOf
import java.io.File
import java.io.FileNotFoundException
import java.io.IOException
private const val DEFERRED_START_MS = 5L * 1000L
private const val FLUSH_PERIOD_MS = 60L * 1000L
/**
* Internal counterpart to [com.emergetools.reaper.Reaper]
*/
internal object ReaperInternal {
// The tracker has to be statically initialized to avoid needing to check in every call to
// logMethodEntry if it exists.
private var tracker: HashTracker = ThreadLocalSetHashTracker()
// impl should only be accessed while holding the lock for this object. Set by init().
private var impl: ReaperImpl? = null
// Set if the Reaper fuse
private var fused = false
/**
* The fast path where we see new hashes. This is called directly by the instrumentation bytecode.
*/
@JvmStatic
fun logMethodEntry(methodHash: Long) {
tracker.logMethodEntry(methodHash)
}
/**
* There are two methods for initializing Reaper:
* 1. Manually via [Reaper.init]
* 2. Automatically via [ReaperInitializer]
* Either way this method is invoked.
* The startup flow is as follows,
* - This method creates [ReaperImpl]
* - then schedules the remaining startup to happen in [DEFERRED_START_MS] via [Handler.postDelayed].
* - The deferred startup ([mainThreadStart]) runs on the main thread and:
* - Creates a thread with a [Looper] named `ReaperWorker`
* - Sets up an [OnStopLifecycleObserver] to call [ReaperImpl.finalizeReport]
* - And finally posts a message to `ReaperWorker` ([workerThreadStart])
* - [workerThreadStart] calls
* - [ReaperImpl.sweepReports] to action reports left from previous sessions
* - [ReaperImpl.startReport] to start the current report
* - Sets up a recurring call to [ReaperImpl.flush] every [FLUSH_PERIOD_MS]
*/
fun init(context: Context, options: ReaperOptions) {
synchronized(this) {
androidTrace("Reaper#init") {
initSynchronized(context, options)
}
}
}
/**
* Flush all pending hashes to the report on disk.
*/
fun flush(context: Context) {
wrap(context) { it.flush() }
}
/**
* Flush all pending hashes to the report on disk.
*/
fun fuseOff(context: Context) {
synchronized(this) {
androidTrace("Reaper#fuseOff") {
if (impl != null) {
Log.e(TAG, "Reaper already initialized, ignoring Reaper.fuseOff()")
return@androidTrace
}
if (fused) {
return@androidTrace
}
fused = true
val oldTracker = tracker
tracker = NullHashTracker()
oldTracker.flush {}
}
}
}
/**
* Helper for common logic that should exist on most public methods. Takes a lambda and:
* 1. aborts with log message if not initialized
* 2. takes the lock
* 3. otherwise runs the lambda (passing impl)
* 4. catching and reporting any errors
*/
private fun wrap(context: Context, lambda: (impl: ReaperImpl) -> Unit) {
try {
synchronized(this) {
val theImpl = impl
if (theImpl == null) {
Log.e(TAG, "Reaper not initialized")
return
}
lambda(theImpl)
}
} catch (e: Exception) {
sendError(context, e.toString())
}
}
private fun initSynchronized(context: Context, options: ReaperOptions) {
if (impl != null) {
Log.e(TAG, "Reaper already initialized, ignoring Reaper.init().")
return
}
if (fused) {
Log.e(TAG, "Reaper fuse blown, ignoring Reaper.init().")
return
}
val metaData = context.packageManager.getApplicationInfo(
context.packageName,
PackageManager.GET_META_DATA
).metaData
if (!isInstrumented(metaData)) {
// Explicitly don't use fatalError to ensure we don't crash other variants
Log.w(
TAG,
"Reaper is not enabled, ensure this variant is specified in the reaper.enabledVariants" +
" list in the Emerge gradle plugin configuration block." +
" See https://docs.emergetools.com/docs/reaper-setup-android#configure-the-sdk."
)
return
}
val apiKey = getApiKey(metaData)
if (apiKey == "") {
fatalError(context, "Manifest com.emergetools.PUBLISHABLE_API_KEY must be set and non-empty.")
}
val isDebug = isDebug(metaData)
val baseUrl = getBaseUrl(metaData)
// If user provides a OkHttpClient stash that in WorkerResources so Workers use it when doing
// networking.
if (options.okHttpClient != null) {
WorkerResources.setOkHttpClient(options.okHttpClient)
}
val delegate = ReaperImplDelegate(context.applicationContext, options)
val theImpl = ReaperImpl(
tracker = tracker,
delegate = delegate,
apiKey = apiKey,
isDebug = isDebug,
baseUrl = baseUrl,
)
impl = theImpl
// Defer remaining main thread startup work (starting the worker thread
// and creating the lifecycle observer) till some time later - hopefully
// after startup is done. This must happen on the main thread since we
// add ProcessLifecycleOwner which must be done from the main thread.
Handler(Looper.getMainLooper()).postDelayed({
mainThreadStart(context.applicationContext, theImpl)
}, DEFERRED_START_MS)
}
}
private class ReaperImplDelegate(private val context: Context, options: ReaperOptions) : ReaperImpl.Delegate {
val logLevel = options.logLevel
override fun startReport(id: String): File? {
ensureDirectories(context)
val name = getReportName(id)
val file = File(getCurrentDir(context), name)
try {
file.delete()
file.createNewFile()
} catch (e: IOException) {
e("Failed to create report $e")
return null
} catch (e: FileNotFoundException) {
e("Failed to create report $e")
return null
} catch (e: ErrnoException) {
e("Failed to create report $e")
return null
}
return file
}
override fun deleteReport(id: String) {
ensureDirectories(context)
val name = getReportName(id)
// Try to delete from both directories:
File(getCurrentDir(context), name).delete()
File(getPendingDir(context), name).delete()
}
override fun markReportPending(id: String) {
ensureDirectories(context)
val name = getReportName(id)
val current = File(getCurrentDir(context), name)
val pending = File(getPendingDir(context), name)
current.renameTo(pending)
}
override fun listCurrentReports(): Collection<String> {
ensureDirectories(context)
return listReports(getCurrentDir(context))
}
override fun listPendingReports(): Collection<String> {
ensureDirectories(context)
return listReports(getPendingDir(context))
}
private fun listReports(dir: File): Collection<String> {
val files = dir.listFiles() ?: emptyArray<File>()
val prefix = getReportPrefix()
val reports = mutableListOf<String>()
for (file in files) {
if (file.name.startsWith(prefix)) {
val id = getIdFromName(file.name)
if (id != null) {
reports.add(id)
}
}
}
return reports
}
override fun requestUpload(apiKey: String, baseUrl: String, isDebug: Boolean) {
// Schedule upload job:
val data = workDataOf(
ReaperReportUploadWorker.EXTRA_API_KEY to apiKey,
ReaperReportUploadWorker.EXTRA_BASE_URL to baseUrl,
ReaperReportUploadWorker.EXTRA_DEBUG to isDebug,
)
val uploadWorkRequest =
OneTimeWorkRequest.Builder(ReaperReportUploadWorker::class.java).apply {
setInputData(data)
setConstraints(
Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
)
}.build()
WorkManager.getInstance(context).enqueue(uploadWorkRequest)
}
override fun sendError(message: String) {
sendError(context, message)
}
override fun d(message: String) {
when (logLevel) {
ReaperLogLevel.ALL -> Log.d(TAG, message)
ReaperLogLevel.NONE, ReaperLogLevel.ERRORS -> {}
}
}
override fun e(message: String) {
when (logLevel) {
ReaperLogLevel.ALL, ReaperLogLevel.ERRORS -> Log.e(TAG, message)
ReaperLogLevel.NONE -> {}
}
}
override fun <T> trace(name: String, block: () -> T): T {
return androidTrace(name, block)
}
private fun getReportPrefix(): String {
var name = context.packageName
if (Build.VERSION.SDK_INT >= 28) {
// This will normally be:
// com.example.foo
// and sometimes be:
// com.example.foo:bar
// for secondary processes. We use this where possible to reduce stomping on secondary
// process reports.
name = Application.getProcessName()
}
name = name.replace(":", "_")
name = name.replace(".", "_")
return "report_$name"
}
private fun getReportName(id: String): String {
return "${getReportPrefix()}_$id"
}
private fun getIdFromName(name: String): String? {
return name.split("_").lastOrNull()
}
}
private fun fatalError(context: Context, message: String) {
val isRelease = 0 == context.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE
if (isRelease) {
Log.e(TAG, message)
} else {
error(message)
}
}
@MainThread
private fun mainThreadStart(context: Context, impl: ReaperImpl) {
impl.delegate.d("Reaper#mainThreadStart")
impl.delegate.trace("Reaper#mainThreadStart") {
val thread = HandlerThread("ReaperWorker")
thread.start()
val looper = thread.looper
if (looper == null) {
fatalError(context, "Could not initialize Reaper worker")
return@trace
}
val handler = Handler(looper)
// Finalize on onStop:
// This observer has to be added from the main thread.
val observer = OnStopLifecycleObserver {
handler.post {
impl.finalizeReport()
}
}
ProcessLifecycleOwner.get().lifecycle.addObserver(observer)
Handler(looper).post {
workerThreadStart(context, looper, impl)
}
}
}
private fun wrap(context: Context, lambda: () -> Unit) {
try {
lambda()
} catch (e: Exception) {
sendError(context, e.toString())
}
}
private fun workerThreadStart(context: Context, looper: Looper, impl: ReaperImpl) {
impl.delegate.d("Reaper#workerThreadStart")
impl.delegate.trace("Reaper#workerThreadStart") {
// If Reaper was running previously but we did not get a chance to finalize the report we may
// end up with reports 'stuck' in current which will never be finalized. Schedule those for
// upload.
wrap(context) {
impl.sweepReports()
}
wrap(context) {
val path = impl.startReport()
if (path == null) {
impl.delegate.e("Failed to start report")
} else {
// Schedule flushes every FLUSH_PERIOD_MS
scheduleFlush(context, Handler(looper), impl)
}
}
}
}
private fun scheduleFlush(context: Context, handler: Handler, impl: ReaperImpl) {
handler.postDelayed({
wrap(context) {
impl.flush()
scheduleFlush(context, handler, impl)
}
}, FLUSH_PERIOD_MS)
}