-
-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathSentryTelemetryService.kt
More file actions
516 lines (451 loc) · 17.2 KB
/
SentryTelemetryService.kt
File metadata and controls
516 lines (451 loc) · 17.2 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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
@file:Suppress("UnstableApiUsage")
package io.sentry.android.gradle.telemetry
import io.sentry.BuildConfig
import io.sentry.IHub
import io.sentry.ISpan
import io.sentry.ITransaction
import io.sentry.NoOpHub
import io.sentry.Sentry
import io.sentry.SentryEvent
import io.sentry.SentryLevel
import io.sentry.SpanStatus
import io.sentry.TransactionOptions
import io.sentry.android.gradle.SentryCliProvider
import io.sentry.android.gradle.SentryPlugin
import io.sentry.android.gradle.SentryPlugin.Companion.logger
import io.sentry.android.gradle.SentryPropertiesFileProvider
import io.sentry.android.gradle.extensions.SentryPluginExtension
import io.sentry.android.gradle.telemetry.SentryCliInfoValueSource.InfoParams
import io.sentry.android.gradle.telemetry.SentryCliVersionValueSource.VersionParams
import io.sentry.android.gradle.util.AgpVersions
import io.sentry.android.gradle.util.SentryCliException
import io.sentry.android.gradle.util.error
import io.sentry.android.gradle.util.getBuildServiceName
import io.sentry.android.gradle.util.info
import io.sentry.android.gradle.util.setSentryPipelineEnv
import io.sentry.exception.ExceptionMechanismException
import io.sentry.gradle.common.SentryVariant
import io.sentry.protocol.Mechanism
import io.sentry.protocol.User
import java.io.ByteArrayOutputStream
import java.io.File
import java.nio.charset.Charset
import javax.inject.Inject
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.internal.tasks.execution.ExecuteTaskBuildOperationDetails
import org.gradle.api.provider.Property
import org.gradle.api.provider.Provider
import org.gradle.api.provider.ValueSource
import org.gradle.api.provider.ValueSourceParameters
import org.gradle.api.services.BuildService
import org.gradle.api.services.BuildServiceParameters.None
import org.gradle.api.tasks.Input
import org.gradle.execution.RunRootBuildWorkBuildOperationType
import org.gradle.internal.operations.BuildOperationDescriptor
import org.gradle.internal.operations.BuildOperationListener
import org.gradle.internal.operations.OperationFinishEvent
import org.gradle.internal.operations.OperationIdentifier
import org.gradle.internal.operations.OperationProgressEvent
import org.gradle.internal.operations.OperationStartEvent
import org.gradle.process.ExecOperations
import org.gradle.util.GradleVersion
abstract class SentryTelemetryService : BuildService<None>, BuildOperationListener, AutoCloseable {
private var hub: IHub = NoOpHub.getInstance()
private var transaction: ITransaction? = null
private var didAddChildSpans: Boolean = false
private var started: Boolean = false
@Synchronized
fun start(paramsCallback: () -> SentryTelemetryServiceParams) {
if (started) {
return
}
val startParameters = paramsCallback()
try {
if (startParameters.saas == false) {
SentryPlugin.logger.info {
"Sentry is running against a self hosted instance. " + "Telemetry has been disabled."
}
hub = NoOpHub.getInstance()
} else if (!startParameters.sendTelemetry) {
SentryPlugin.logger.info { "Sentry telemetry has been disabled." }
hub = NoOpHub.getInstance()
} else {
if (!Sentry.isEnabled()) {
SentryPlugin.logger.info {
"Sentry telemetry is enabled. To disable set `telemetry=false` " +
"in the sentry config block."
}
Sentry.init { options ->
options.dsn = startParameters.dsn
options.isDebug = startParameters.isDebug
options.isEnablePrettySerializationOutput = false
options.tracesSampleRate = 1.0
options.release = BuildConfig.Version
options.isSendModules = false
options.environment = startParameters.buildType
options.setTag("SDK_VERSION", BuildConfig.SdkVersion)
options.setTag("BUILD_SYSTEM", "gradle")
options.setTag("GRADLE_VERSION", GradleVersion.current().version)
startParameters.cliVersion?.let { options.setTag("SENTRY_CLI_VERSION", it) }
startParameters.extraTags.forEach { (key, value) -> options.setTag(key, value) }
try {
options.setTag("AGP_VERSION", AgpVersions.CURRENT.toString())
} catch (t: Throwable) {}
}
}
hub = Sentry.getCurrentHub()
startRun("gradle build ${startParameters.buildType}")
hub.configureScope { scope ->
scope.user =
User().also { user ->
startParameters.defaultSentryOrganization?.let { org ->
if (org != "-") {
user.id = org
}
}
startParameters.sentryOrganization?.let { user.id = it }
}
}
started = true
}
} catch (t: Throwable) {
SentryPlugin.logger.error(t) { "Sentry failed to initialize." }
}
}
override fun started(descriptor: BuildOperationDescriptor, event: OperationStartEvent) {}
override fun progress(identifier: OperationIdentifier, event: OperationProgressEvent) {}
override fun finished(
buildOperationDescriptor: BuildOperationDescriptor,
operationFinishEvent: OperationFinishEvent,
) {
val details = buildOperationDescriptor.details
operationFinishEvent.failure?.let { error ->
if (isSentryError(error, details)) {
captureError(error, "build")
transaction?.status = SpanStatus.UNKNOWN_ERROR
}
}
if (details is RunRootBuildWorkBuildOperationType.Details) {
endRun()
}
}
private fun isSentryError(throwable: Throwable, details: Any?): Boolean {
val isSentryTaskName =
(details as? ExecuteTaskBuildOperationDetails)?.let {
it.task.name.substringAfterLast(":").contains("sentry", ignoreCase = true)
} ?: false
return isSentryTaskName ||
throwable.stackTrace.any {
it.className.startsWith("io.sentry") &&
!(it.className.contains("test", ignoreCase = true) ||
it.className.contains("rule", ignoreCase = true))
}
}
fun captureError(exception: Throwable, operation: String?) {
val message =
if (exception is SentryCliException) {
"$operation failed with SentryCliException and reason ${exception.reason}"
} else {
"$operation failed with ${exception.javaClass}"
}
val mechanism =
Mechanism().also {
it.type = MECHANISM_TYPE
it.isHandled = false
}
val mechanismException: Throwable =
ExceptionMechanismException(
mechanism,
SentryMinimalException(message),
Thread.currentThread(),
)
val event = SentryEvent(mechanismException).also { it.level = SentryLevel.FATAL }
hub.captureEvent(event)
}
fun startRun(transactionName: String) {
hub.startSession()
val options = TransactionOptions()
options.isBindToScope = true
transaction = hub.startTransaction(transactionName, "build", options)
}
fun endRun() {
if (didAddChildSpans) {
transaction?.finish()
hub.endSession()
}
}
fun traceCli(): List<String> {
val args = mutableListOf<String>()
hub.traceparent?.let { header ->
args.add("--header")
args.add("${header.name}:${header.value}")
}
hub.baggage?.let { header ->
args.add("--header")
args.add("${header.name}:${header.value}")
}
return args
}
fun startTask(operation: String): ISpan? {
didAddChildSpans = true
hub.setTag("step", operation)
return hub.span?.startChild(operation)
}
fun endTask(span: ISpan?, task: Task) {
span?.let { span ->
task.state.failure?.let { throwable ->
captureError(throwable, span.operation)
span.status = SpanStatus.UNKNOWN_ERROR
}
span.finish()
}
}
override fun close() {
if (transaction?.isFinished == false) {
endRun()
}
Sentry.close()
}
companion object {
val SENTRY_SAAS_DSN: String =
"https://000e5dea9770b4537055f8a6d28c021e@o1.ingest.sentry.io/4506241308295168"
val MECHANISM_TYPE: String = "GradleTelemetry"
private val orgRegex = Regex("""(?m)Default Organization: (.*)$""")
private val versionRegex = Regex("""(?m)sentry-cli (.*)$""")
fun createParameters(
project: Project,
variant: SentryVariant?,
extension: SentryPluginExtension,
cliExecutable: Provider<String>,
sentryOrg: String?,
buildType: String,
): SentryTelemetryServiceParams {
val tags = extraTagsFromExtension(project, extension)
val org = sentryOrg ?: extension.org.orNull
val isTelemetryEnabled = extension.telemetry.get()
// if telemetry is disabled we don't even need to exec sentry-cli as telemetry service
// will be no-op
if (isTelemetryEnabled) {
paramsWithExecAvailable(project, cliExecutable, extension, variant, org, buildType, tags)
?.let {
return it
}
}
// fallback: sentry-cli is not available or e.g. auth token is not configured
return SentryTelemetryServiceParams(
isTelemetryEnabled,
extension.telemetryDsn.get(),
org,
buildType,
tags,
extension.debug.get(),
saas = extension.url.orNull == null,
cliVersion = BuildConfig.CliVersion,
)
}
private fun paramsWithExecAvailable(
project: Project,
cliExecutable: Provider<String>,
extension: SentryPluginExtension,
variant: SentryVariant?,
sentryOrg: String?,
buildType: String,
tags: Map<String, String>,
): SentryTelemetryServiceParams? {
var cliVersion: String? = BuildConfig.CliVersion
var defaultSentryOrganization: String? = null
val infoOutput =
project.providers
.of(SentryCliInfoValueSource::class.java) { cliVS ->
cliVS.parameters.buildDirectory.set(project.buildDir)
cliVS.parameters.cliExecutable.set(cliExecutable)
cliVS.parameters.authToken.set(extension.authToken)
cliVS.parameters.url.set(extension.url)
variant?.let { v ->
cliVS.parameters.propertiesFilePath.set(
SentryPropertiesFileProvider.getPropertiesFilePath(project, v)
)
}
}
.get()
if (infoOutput.isEmpty()) {
return null
}
val isSaas = infoOutput.contains("(?m)Sentry Server: .*sentry.io$".toRegex())
orgRegex.find(infoOutput)?.let { matchResult ->
val groupValues = matchResult.groupValues
if (groupValues.size > 1) {
defaultSentryOrganization = groupValues[1]
}
}
val versionOutput =
project.providers
.of(SentryCliVersionValueSource::class.java) { cliVS ->
cliVS.parameters.buildDirectory.set(project.buildDir)
cliVS.parameters.cliExecutable.set(cliExecutable)
cliVS.parameters.url.set(extension.url)
}
.get()
versionRegex.find(versionOutput)?.let { matchResult ->
val groupValues = matchResult.groupValues
if (groupValues.size > 1) {
cliVersion = groupValues[1]
}
}
return SentryTelemetryServiceParams(
extension.telemetry.get(),
extension.telemetryDsn.get(),
sentryOrg,
buildType,
tags,
extension.debug.get(),
defaultSentryOrganization,
isSaas,
cliVersion = cliVersion,
)
}
fun register(project: Project): Provider<SentryTelemetryService> {
return project.gradle.sharedServices.registerIfAbsent(
getBuildServiceName(SentryTelemetryService::class.java),
SentryTelemetryService::class.java,
) {}
}
private fun extraTagsFromExtension(
project: Project,
extension: SentryPluginExtension,
): Map<String, String> {
val tags = mutableMapOf<String, String>()
tags.put("debug", extension.debug.get().toString())
tags.put("includeProguardMapping", extension.includeProguardMapping.get().toString())
tags.put("autoUploadProguardMapping", extension.autoUploadProguardMapping.get().toString())
tags.put("autoUpload", extension.autoUpload.get().toString())
tags.put("uploadNativeSymbols", extension.uploadNativeSymbols.get().toString())
tags.put("autoUploadNativeSymbols", extension.autoUploadNativeSymbols.get().toString())
tags.put("includeNativeSources", extension.includeNativeSources.get().toString())
tags.put("ignoredVariants_set", extension.ignoredVariants.get().isNotEmpty().toString())
tags.put("ignoredBuildTypes_set", extension.ignoredBuildTypes.get().isNotEmpty().toString())
tags.put("ignoredFlavors_set", extension.ignoredFlavors.get().isNotEmpty().toString())
tags.put("dexguardEnabled", extension.dexguardEnabled.get().toString())
tags.put("tracing_enabled", extension.tracingInstrumentation.enabled.get().toString())
tags.put("tracing_debug", extension.tracingInstrumentation.debug.get().toString())
tags.put(
"tracing_forceInstrumentDependencies",
extension.tracingInstrumentation.forceInstrumentDependencies.get().toString(),
)
tags.put("tracing_features", extension.tracingInstrumentation.features.get().toString())
tags.put(
"tracing_logcat_enabled",
extension.tracingInstrumentation.logcat.enabled.get().toString(),
)
tags.put(
"tracing_logcat_minLevel",
extension.tracingInstrumentation.logcat.minLevel.get().toString(),
)
tags.put("autoInstallation_enabled", extension.autoInstallation.enabled.get().toString())
tags.put(
"autoInstallation_sentryVersion",
extension.autoInstallation.sentryVersion.get().toString(),
)
tags.put("includeDependenciesReport", extension.includeDependenciesReport.get().toString())
tags.put("includeSourceContext", extension.includeSourceContext.get().toString())
tags.put(
"additionalSourceDirsForSourceContext_set",
extension.additionalSourceDirsForSourceContext.get().isNotEmpty().toString(),
)
// TODO PII?
// extension.projectName.orNull?.let { tags.put("projectName", it) }
return tags
}
}
}
class SentryMinimalException(message: String) : RuntimeException(message) {
override fun getStackTrace(): Array<StackTraceElement> {
val superStackTrace = super.getStackTrace()
return if (superStackTrace.isEmpty()) superStackTrace else arrayOf(superStackTrace[0])
}
}
abstract class SentryCliInfoValueSource : ValueSource<String, InfoParams> {
interface InfoParams : ValueSourceParameters {
@get:Input val buildDirectory: Property<File>
@get:Input val cliExecutable: Property<String>
@get:Input val propertiesFilePath: Property<String>
@get:Input val url: Property<String>
@get:Input val authToken: Property<String>
}
@get:Inject abstract val execOperations: ExecOperations
override fun obtain(): String? {
val stdOutput = ByteArrayOutputStream()
val errOutput = ByteArrayOutputStream()
val execResult =
execOperations.exec {
it.isIgnoreExitValue = true
SentryCliProvider.maybeExtractFromResources(
parameters.buildDirectory.get(),
parameters.cliExecutable.get(),
)
val args = mutableListOf(parameters.cliExecutable.get())
parameters.url.orNull?.let { url ->
args.add("--url")
args.add(url)
}
args.add("--log-level=error")
args.add("info")
parameters.propertiesFilePath.orNull?.let { path ->
it.environment("SENTRY_PROPERTIES", path)
}
parameters.authToken.orNull?.let { authToken ->
it.environment("SENTRY_AUTH_TOKEN", authToken)
}
it.setSentryPipelineEnv()
it.commandLine(args)
it.standardOutput = stdOutput
it.errorOutput = errOutput
}
if (execResult.exitValue == 0) {
return String(stdOutput.toByteArray(), Charset.defaultCharset())
} else {
logger.info {
"Failed to execute sentry-cli info. Error Output: " +
String(errOutput.toByteArray(), Charset.defaultCharset())
}
return ""
}
}
}
abstract class SentryCliVersionValueSource : ValueSource<String, VersionParams> {
interface VersionParams : ValueSourceParameters {
@get:Input val buildDirectory: Property<File>
@get:Input val cliExecutable: Property<String>
@get:Input val url: Property<String>
}
@get:Inject abstract val execOperations: ExecOperations
override fun obtain(): String {
val output = ByteArrayOutputStream()
execOperations.exec {
it.isIgnoreExitValue = true
SentryCliProvider.maybeExtractFromResources(
parameters.buildDirectory.get(),
parameters.cliExecutable.get(),
)
val args = mutableListOf(parameters.cliExecutable.get())
args.add("--log-level=error")
args.add("--version")
it.setSentryPipelineEnv()
it.commandLine(args)
it.standardOutput = output
}
return String(output.toByteArray(), Charset.defaultCharset())
}
}
data class SentryTelemetryServiceParams(
val sendTelemetry: Boolean,
val dsn: String,
val sentryOrganization: String?,
val buildType: String,
val extraTags: Map<String, String>,
val isDebug: Boolean,
val defaultSentryOrganization: String? = null,
val saas: Boolean? = null,
val cliVersion: String? = null,
)