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

Okhttp instrumentation #389

Merged
merged 24 commits into from
Feb 13, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
bb894bb
Creating okhttp instrumentation subprojects
LikeTheSalad Feb 11, 2025
03c56e1
Added http span name test
LikeTheSalad Feb 11, 2025
67bd678
Updating tests
LikeTheSalad Feb 11, 2025
6dc48fe
Creating http span interceptors
LikeTheSalad Feb 11, 2025
bf63ac5
Creating HttpSpanNameInterceptor
LikeTheSalad Feb 11, 2025
a1f0ca9
Renaming http spans
LikeTheSalad Feb 11, 2025
53a66eb
Setting http span interceptor in builder
LikeTheSalad Feb 11, 2025
0454d70
Validating http known methods
LikeTheSalad Feb 11, 2025
ce9cfb2
Adding tests
LikeTheSalad Feb 11, 2025
c7b6f32
Created okhttp test project
LikeTheSalad Feb 12, 2025
dc6ea6b
Added okhttp simple test
LikeTheSalad Feb 12, 2025
d1fcce7
Creating okhttp bytebuddy project
LikeTheSalad Feb 12, 2025
7146d51
Adding okhttp library bytebuddy plugin symbols
LikeTheSalad Feb 12, 2025
bb17b93
Configuring OkHttp3Singletons
LikeTheSalad Feb 12, 2025
3a006f2
Substituting local bytebuddy dependencies
LikeTheSalad Feb 12, 2025
72fe4b3
Moving bytebuddy plugin definitions
LikeTheSalad Feb 12, 2025
2b5e5d4
Flushing spans for androidTests
LikeTheSalad Feb 12, 2025
6a419f6
Validating successful okhttp sync requests
LikeTheSalad Feb 12, 2025
7a340f7
Adding tests
LikeTheSalad Feb 12, 2025
03660a4
Updating notice files
LikeTheSalad Feb 12, 2025
890c7c6
Adding build variant listener
LikeTheSalad Feb 12, 2025
6c004cd
Updating instrumentation plugins
LikeTheSalad Feb 12, 2025
902fd94
Attaching bytebuddy plugins using the ByteBuddyDependencyAttacher
LikeTheSalad Feb 12, 2025
050577a
Updating tests
LikeTheSalad Feb 13, 2025
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
2 changes: 2 additions & 0 deletions NOTICE
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ This product includes software licensed under the 'Apache License Version 2.0' l
- Core (https://developer.android.com/jetpack/androidx/releases/core#1.15.0)
- Kotlin Stdlib (https://kotlinlang.org/)
- Lifecycle Process (https://developer.android.com/jetpack/androidx/releases/lifecycle#2.8.7)
- okhttp (https://square.github.io/okhttp/)
- OpenTelemetry Instrumentation for Java (https://github.com/open-telemetry/opentelemetry-java-instrumentation)
- OpenTelemetry Java (https://github.com/open-telemetry/opentelemetry-java)
- OpenTelemetry Java Contrib (https://github.com/open-telemetry/opentelemetry-java-contrib)
- OpenTelemetry Semantic Conventions Java (https://github.com/open-telemetry/semantic-conventions-java)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package co.elastic.otel.android.api.flusher

import io.opentelemetry.sdk.common.CompletableResultCode

interface SpanFlusher {
fun flushSpans(): CompletableResultCode
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,39 @@ package co.elastic.otel.android.plugin

import co.elastic.otel.android.common.internal.logging.Elog
import co.elastic.otel.android.generated.BuildConfig
import co.elastic.otel.android.plugin.extensions.ElasticApmExtension
import co.elastic.otel.android.plugin.internal.BuildVariantListener
import co.elastic.otel.android.plugin.internal.logging.GradleLoggerFactory
import com.android.build.api.variant.ApplicationAndroidComponentsExtension
import net.bytebuddy.build.gradle.android.ByteBuddyAndroidPlugin
import org.gradle.api.Plugin
import org.gradle.api.Project

internal class ElasticAgentPlugin : Plugin<Project> {
class ElasticAgentPlugin : Plugin<Project> {
private lateinit var project: Project
private val buildVariantListeners = mutableSetOf<BuildVariantListener>()

override fun apply(target: Project) {
this.project = target
Elog.init(GradleLoggerFactory())
addByteBuddyPlugin()
addSdkDependency()
val extension = project.extensions.create("elasticAgent", ElasticApmExtension::class.java)
val androidComponents =
project.extensions.getByType(ApplicationAndroidComponentsExtension::class.java)
androidComponents.finalizeDsl { androidExtension ->
val disableForBuildTypes = extension.bytecodeInstrumentation.disableForBuildTypes.get()
androidExtension.buildTypes.forEach { buildType ->
val name = buildType.name
if (name !in disableForBuildTypes) {
buildVariantListeners.forEach { listener -> listener.onBuildVariant(name) }
}
}
}
}

fun addBuildVariantListener(listener: BuildVariantListener) {
buildVariantListeners.add(listener)
}

private fun addByteBuddyPlugin() {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package co.elastic.otel.android.plugin.extensions

import org.gradle.api.provider.ListProperty

interface BytecodeInstrumentation {
val disableForBuildTypes: ListProperty<String>
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package co.elastic.otel.android.plugin.extensions

import javax.inject.Inject
import org.gradle.api.Action
import org.gradle.api.model.ObjectFactory

abstract class ElasticApmExtension @Inject constructor(objects: ObjectFactory) {
val bytecodeInstrumentation = objects.newInstance(BytecodeInstrumentation::class.java)

fun bytecodeInstrumentation(action: Action<BytecodeInstrumentation>) {
action.execute(bytecodeInstrumentation)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package co.elastic.otel.android.plugin.internal

interface BuildVariantListener {
fun onBuildVariant(name: String)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package co.elastic.otel.android.plugin.internal

import org.gradle.api.Project

class ByteBuddyDependencyAttacher(
private val project: Project,
private val dependencyUri: String
) : BuildVariantListener {

override fun onBuildVariant(name: String) {
project.configurations.maybeCreate("${name}ByteBuddy").dependencies.add(
project.dependencies.create(dependencyUri)
)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ abstract class InstrumentationPlugin : Plugin<Project> {
apply(ElasticAgentPlugin::class.java)
}
}
onApply(target)
onApply(target, target.plugins.getPlugin(ElasticAgentPlugin::class.java))
}

abstract fun onApply(target: Project)
abstract fun onApply(target: Project, agentPlugin: ElasticAgentPlugin)
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import android.app.Application
import co.elastic.otel.android.api.ElasticOtelAgent
import co.elastic.otel.android.api.flusher.LogRecordFlusher
import co.elastic.otel.android.api.flusher.MetricFlusher
import co.elastic.otel.android.api.flusher.SpanFlusher
import co.elastic.otel.android.common.internal.logging.Elog
import co.elastic.otel.android.exporters.ExporterProvider
import co.elastic.otel.android.exporters.configuration.ExportProtocol
Expand All @@ -36,6 +37,8 @@ import co.elastic.otel.android.internal.features.centralconfig.CentralConfigurat
import co.elastic.otel.android.internal.features.centralconfig.CentralConfigurationManager
import co.elastic.otel.android.internal.features.diskbuffering.DiskBufferingConfiguration
import co.elastic.otel.android.internal.features.exportergate.ExporterGateManager
import co.elastic.otel.android.internal.features.httpinterceptor.HttpSpanExporterInterceptor
import co.elastic.otel.android.internal.features.httpinterceptor.HttpSpanNameInterceptor
import co.elastic.otel.android.internal.features.sessionmanager.SessionManager
import co.elastic.otel.android.internal.features.sessionmanager.samplerate.SampleRateManager
import co.elastic.otel.android.internal.services.ServiceManager
Expand All @@ -49,6 +52,7 @@ import io.opentelemetry.api.common.Attributes
import io.opentelemetry.sdk.common.CompletableResultCode
import io.opentelemetry.sdk.logs.export.LogRecordExporter
import io.opentelemetry.sdk.metrics.export.MetricExporter
import io.opentelemetry.sdk.trace.data.SpanData
import io.opentelemetry.sdk.trace.export.SpanExporter

@Suppress("CanBeParameter")
Expand All @@ -57,7 +61,7 @@ class ElasticApmAgent internal constructor(
private val apmServerConnectivityManager: ApmServerConnectivityManager,
private val centralConfigurationManager: CentralConfigurationManager,
private val sampleRateManager: SampleRateManager
) : ElasticOtelAgent, MetricFlusher, LogRecordFlusher {
) : ElasticOtelAgent, MetricFlusher, LogRecordFlusher, SpanFlusher {

init {
centralConfigurationManager.initialize(delegate.openTelemetry)
Expand All @@ -76,6 +80,10 @@ class ElasticApmAgent internal constructor(
return delegate.flushLogRecords()
}

override fun flushSpans(): CompletableResultCode {
return delegate.flushSpans()
}

override fun close() {
delegate.close()
}
Expand Down Expand Up @@ -124,6 +132,7 @@ class ElasticApmAgent internal constructor(
private var sessionIdGenerator: SessionIdGenerator? = null
private var diskBufferingConfiguration: DiskBufferingConfiguration? = null
private var loggingPolicy: LoggingPolicy? = null
private var httpSpanInterceptor: Interceptor<SpanData>? = HttpSpanNameInterceptor()
private val managedAgentBuilder = ManagedElasticOtelAgent.Builder()
internal var internalExporterProviderInterceptor: Interceptor<ExporterProvider> =
Interceptor.noop()
Expand Down Expand Up @@ -193,6 +202,10 @@ class ElasticApmAgent internal constructor(
managedAgentBuilder.setProcessorFactory(value)
}

fun setHttpSpanInterceptor(value: Interceptor<SpanData>?) = apply {
httpSpanInterceptor = value
}

internal fun setDiskBufferingConfiguration(value: DiskBufferingConfiguration) = apply {
diskBufferingConfiguration = value
}
Expand Down Expand Up @@ -246,6 +259,11 @@ class ElasticApmAgent internal constructor(
exporterProvider
)
)

httpSpanInterceptor?.let {
managedAgentBuilder.addSpanExporterInterceptor(HttpSpanExporterInterceptor(it))
}

return ElasticApmAgent(
managedAgentBuilder.build(serviceManager, managedFeatures),
apmServerConnectivityManager,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import android.app.Application
import co.elastic.otel.android.api.ElasticOtelAgent
import co.elastic.otel.android.api.flusher.LogRecordFlusher
import co.elastic.otel.android.api.flusher.MetricFlusher
import co.elastic.otel.android.api.flusher.SpanFlusher
import co.elastic.otel.android.exporters.ExporterProvider
import co.elastic.otel.android.features.session.SessionIdGenerator
import co.elastic.otel.android.interceptor.Interceptor
Expand Down Expand Up @@ -50,7 +51,7 @@ class ManagedElasticOtelAgent private constructor(
private val serviceManager: ServiceManager,
internal val openTelemetry: ElasticOpenTelemetry,
internal val features: ManagedFeatures
) : ElasticOtelAgent, MetricFlusher, LogRecordFlusher {
) : ElasticOtelAgent, MetricFlusher, LogRecordFlusher, SpanFlusher {

init {
features.elasticClockManager.initialize()
Expand Down Expand Up @@ -79,6 +80,10 @@ class ManagedElasticOtelAgent private constructor(
return openTelemetry.sdk.sdkLoggerProvider.forceFlush()
}

override fun flushSpans(): CompletableResultCode {
return openTelemetry.sdk.sdkTracerProvider.forceFlush()
}

internal fun getElasticClockManager(): ElasticClockManager {
return features.elasticClockManager
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,10 @@ internal class ExporterGateManager(
metricGateQueue.openLatch(holder)
}

internal fun spanGateIsOpen(): Boolean {
return spanGateOpen.get()
}

internal fun metricGateIsOpen(): Boolean {
return metricGateOpen.get()
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package co.elastic.otel.android.internal.features.httpinterceptor

import co.elastic.otel.android.interceptor.Interceptor
import io.opentelemetry.sdk.common.CompletableResultCode
import io.opentelemetry.sdk.trace.data.SpanData
import io.opentelemetry.sdk.trace.export.SpanExporter
import io.opentelemetry.semconv.UrlAttributes

internal class HttpSpanExporter(
private val delegate: SpanExporter,
private val httpSpanInterceptor: Interceptor<SpanData>
) : SpanExporter {

override fun export(spans: Collection<SpanData>): CompletableResultCode {
val processedSpans = mutableListOf<SpanData>()

spans.forEach {
processedSpans.add(process(it))
}

return delegate.export(processedSpans)
}

private fun process(spanData: SpanData): SpanData {
if (spanData.attributes.get(UrlAttributes.URL_FULL) != null) {
return httpSpanInterceptor.intercept(spanData)
}
return spanData
}

override fun flush(): CompletableResultCode {
return delegate.flush()
}

override fun shutdown(): CompletableResultCode {
return delegate.shutdown()
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package co.elastic.otel.android.internal.features.httpinterceptor

import co.elastic.otel.android.interceptor.Interceptor
import io.opentelemetry.sdk.trace.data.SpanData
import io.opentelemetry.sdk.trace.export.SpanExporter

internal class HttpSpanExporterInterceptor(private val httpSpanInterceptor: Interceptor<SpanData>) :
Interceptor<SpanExporter> {

override fun intercept(item: SpanExporter): SpanExporter {
return HttpSpanExporter(item, httpSpanInterceptor)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package co.elastic.otel.android.internal.features.httpinterceptor

import co.elastic.otel.android.interceptor.Interceptor
import io.opentelemetry.sdk.trace.data.DelegatingSpanData
import io.opentelemetry.sdk.trace.data.SpanData
import io.opentelemetry.semconv.UrlAttributes

class HttpSpanNameInterceptor : Interceptor<SpanData> {
private companion object {
private val URL_PATTERN = Regex("https?://([^/]+).*")
private val KNOWN_METHODS =
listOf("CONNECT", "DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT", "TRACE")
}

override fun intercept(item: SpanData): SpanData {
if (item.name !in KNOWN_METHODS) {
return item
}

val url = item.attributes.get(UrlAttributes.URL_FULL) ?: return item

return getNewName(item.name, url)?.let { newName ->
NameOverrideDelegatingSpanData(item, newName)
} ?: item
}

private fun getNewName(name: String, url: String): String? {
return URL_PATTERN.matchEntire(url)?.let { match ->
"$name ${match.groupValues[1]}"
}
}

private class NameOverrideDelegatingSpanData(
delegate: SpanData,
private val name: String
) : DelegatingSpanData(delegate) {

override fun getName(): String {
return name
}
}
}
Loading