-
-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathSentryTelemetryService.kt
More file actions
366 lines (329 loc) · 13 KB
/
Copy pathSentryTelemetryService.kt
File metadata and controls
366 lines (329 loc) · 13 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
@file:Suppress("UnstableApiUsage")
package io.sentry.android.gradle.telemetry
import com.android.build.api.dsl.CommonExtension
import io.sentry.BuildConfig
import io.sentry.IScopes
import io.sentry.ISpan
import io.sentry.ITransaction
import io.sentry.NoOpScopes
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.SentryPlugin
import io.sentry.android.gradle.SentryPlugin.Companion.logger
import io.sentry.android.gradle.SentryPropertiesFileProvider
import io.sentry.android.gradle.defaultOrgProvider
import io.sentry.android.gradle.extensions.SentryPluginExtension
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.exception.ExceptionMechanismException
import io.sentry.gradle.common.SentryVariant
import io.sentry.protocol.Mechanism
import io.sentry.protocol.User
import java.util.concurrent.atomic.AtomicBoolean
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.internal.tasks.execution.ExecuteTaskBuildOperationDetails
import org.gradle.api.provider.Provider
import org.gradle.api.services.BuildService
import org.gradle.api.services.BuildServiceParameters.None
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.util.GradleVersion
abstract class SentryTelemetryService : BuildService<None>, BuildOperationListener, AutoCloseable {
private var scopes: IScopes = NoOpScopes.getInstance()
private var transaction: ITransaction? = null
private var didAddChildSpans: Boolean = false
private var started: Boolean = false
private var orgProvider: Provider<String>? = null
private val orgAttached = AtomicBoolean(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."
}
scopes = NoOpScopes.getInstance()
} else if (!startParameters.sendTelemetry) {
SentryPlugin.logger.info { "Sentry telemetry has been disabled." }
scopes = NoOpScopes.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) {}
}
}
scopes = Sentry.getCurrentScopes()
startRun("gradle build ${startParameters.buildType}")
scopes.configureScope { scope ->
scope.user =
User().also { user -> startParameters.sentryOrganization?.let { user.id = it } }
}
orgProvider = startParameters.cliOrgProvider
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 }
scopes.captureEvent(event)
}
fun startRun(transactionName: String) {
scopes.startSession()
val options = TransactionOptions()
options.isBindToScope = true
transaction = scopes.startTransaction(transactionName, "build", options)
}
fun endRun() {
if (didAddChildSpans) {
transaction?.finish()
scopes.endSession()
}
}
fun traceCli(): List<String> {
val args = mutableListOf<String>()
scopes.traceparent?.let { header ->
args.add("--header")
args.add("${header.name}:${header.value}")
}
scopes.baggage?.let { header ->
args.add("--header")
args.add("${header.name}:${header.value}")
}
return args
}
fun startTask(operation: String): ISpan? {
didAddChildSpans = true
attachDefaultOrg()
scopes.setTag("step", operation)
return scopes.span?.startChild(operation)
}
// Resolves the default org (via the SentryOrgValueSource provider) on the first tracked task and
// attaches it to the telemetry scope. Querying the provider here, during task execution, keeps
// the underlying sentry-cli process out of the configuration phase so the configuration cache
// stays valid. An explicitly configured org already set on the scope is left untouched.
private fun attachDefaultOrg() {
if (!orgAttached.compareAndSet(false, true)) {
return
}
orgProvider?.orNull?.let { org ->
scopes.configureScope { scope ->
if (scope.user?.id == null) {
scope.user = User().also { it.id = org }
}
}
}
}
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"
fun createParameters(
project: Project,
variant: SentryVariant?,
extension: SentryPluginExtension,
sentryOrg: String?,
buildType: String,
): SentryTelemetryServiceParams {
val tags = extraTagsFromExtension(project, extension)
val org = sentryOrg ?: extension.org.orNull
return SentryTelemetryServiceParams(
extension.telemetry.get(),
extension.telemetryDsn.get(),
org,
buildType,
tags,
extension.debug.get(),
saas = extension.url.orNull == null,
cliVersion = BuildConfig.CliVersion,
cliOrgProvider =
project.defaultOrgProvider(
extension.url.orNull,
extension.authToken.orNull,
variant?.let { SentryPropertiesFileProvider.getPropertiesFilePath(project, it) },
),
)
}
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(
"autoInstallation_verifyOpenTelemetryVersions",
extension.autoInstallation.verifyOpenTelemetryVersions.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) }
try {
val android = project.extensions.findByType(CommonExtension::class.java)
if (android != null) {
tags.put(
"coreLibraryDesugaring_enabled",
android.compileOptions.isCoreLibraryDesugaringEnabled.toString(),
)
android.defaultConfig.minSdk?.let { tags.put("minSdk", it.toString()) }
}
} catch (_: Throwable) {
// Android extensions may not be available (e.g. JVM plugin)
}
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])
}
}
data class SentryTelemetryServiceParams(
val sendTelemetry: Boolean,
val dsn: String,
val sentryOrganization: String?,
val buildType: String,
val extraTags: Map<String, String>,
val isDebug: Boolean,
val saas: Boolean? = null,
val cliVersion: String? = null,
val cliOrgProvider: Provider<String>? = null,
)