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

Add custom instrumentation hook #2380

Merged
merged 2 commits into from
Jul 11, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -317,6 +317,8 @@ public static class PreviewConfiguration {
// "% Processor Time Normalized"
public boolean useNormalizedValueForNonNormalizedCpuPercentage = true;

public List<CustomInstrumentation> customInstrumentation = new ArrayList<>();

private static final Set<String> VALID_ADDITIONAL_PROPAGATORS =
new HashSet<>(asList("b3", "b3multi"));

Expand Down Expand Up @@ -493,6 +495,11 @@ public void validate() {
}
}

public static class CustomInstrumentation {
public String className;
public String methodName;
}

public static class EnabledByDefaultInstrumentation {
public boolean enabled = true;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,22 @@ public Map<String, String> defaultProperties() {
// enable log4j 1.x MDC
properties.put("otel.instrumentation.log4j-appender.experimental.capture-mdc-attributes", "*");

// custom instrumentation
if (!config.preview.customInstrumentation.isEmpty()) {
StringBuilder sb = new StringBuilder();
for (Configuration.CustomInstrumentation customInstrumentation :
config.preview.customInstrumentation) {
if (sb.length() > 0) {
sb.append(';');
}
sb.append(customInstrumentation.className);
sb.append('[');
sb.append(customInstrumentation.methodName);
sb.append(']');
}
properties.put("otel.instrumentation.methods.include", sb.toString());
}

properties.put("otel.propagators", DelegatingPropagatorProvider.NAME);

properties.put("otel.traces.sampler", DelegatingSamplerProvider.NAME);
Expand Down Expand Up @@ -143,11 +159,6 @@ private static void enableInstrumentations(Configuration config, Map<String, Str

properties.put("otel.instrumentation.experimental.span-suppression-strategy", "client");

// TODO (trask) remove these two after
// https://github.com/open-telemetry/opentelemetry-java-instrumentation/pull/5989
properties.put("otel.instrumentation.oshi-metrics.enabled", "false");
properties.put("otel.instrumentation.runtime-metrics.enabled", "false");

// instrumentation that cannot be disabled (currently at least)

properties.put("otel.instrumentation.ai-azure-functions.enabled", "true");
Expand All @@ -167,12 +178,6 @@ private static void enableInstrumentations(Configuration config, Map<String, Str
properties.put("otel.instrumentation.jaxrs-client.enabled", "true");
properties.put("otel.instrumentation.jaxws.enabled", "true");

// TODO (trask) remove these three after
// https://github.com/open-telemetry/opentelemetry-java-instrumentation/pull/5980
properties.put("otel.instrumentation.axis2.enabled", "true");
properties.put("otel.instrumentation.cxf.enabled", "true");
properties.put("otel.instrumentation.metro.enabled", "true");

properties.put("otel.instrumentation.jboss-logmanager-appender.enabled", "true");
properties.put("otel.instrumentation.jboss-logmanager-mdc.enabled", "true");
properties.put("otel.instrumentation.jetty.enabled", "true");
Expand All @@ -185,6 +190,7 @@ private static void enableInstrumentations(Configuration config, Map<String, Str
properties.put("otel.instrumentation.log4j-mdc.enabled", "true");
properties.put("otel.instrumentation.log4j-context-data.enabled", "true");
properties.put("otel.instrumentation.logback-mdc.enabled", "true");
properties.put("otel.instrumentation.methods.enabled", "true");

// not supporting netty-3.8 for now
properties.put("otel.instrumentation.netty-4.0.enabled", "true");
Expand All @@ -198,11 +204,6 @@ private static void enableInstrumentations(Configuration config, Map<String, Str
properties.put("otel.instrumentation.reactor-netty.enabled", "true");
properties.put("otel.instrumentation.rxjava.enabled", "true");

// TODO (trask) remove these two after
// https://github.com/open-telemetry/opentelemetry-java-instrumentation/pull/5984
properties.put("otel.instrumentation.rxjava2.enabled", "true");
properties.put("otel.instrumentation.rxjava3.enabled", "true");

properties.put("otel.instrumentation.servlet.enabled", "true");
properties.put("otel.instrumentation.spring-core.enabled", "true");
properties.put("otel.instrumentation.spring-web.enabled", "true");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,8 @@ public TelemetryItem map(SpanData span, float samplingPercentage) {
String instrumentationName = span.getInstrumentationScopeInfo().getName();
TelemetryItem telemetryItem;
if (kind == SpanKind.INTERNAL) {
if (instrumentationName.startsWith("io.opentelemetry.spring-scheduling-")
if ((instrumentationName.startsWith("io.opentelemetry.spring-scheduling-")
|| instrumentationName.equals("io.opentelemetry.methods"))
&& !span.getParentSpanContext().isValid()) {
// TODO (trask) AI mapping: need semantic convention for determining whether to map INTERNAL
// to request or dependency (or need clarification to use SERVER for this)
Expand Down
2 changes: 1 addition & 1 deletion settings.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ include ':smoke-tests:apps:AzureSdk'
include ':smoke-tests:apps:Cassandra'
include ':smoke-tests:apps:CoreAndFilter'
include ':smoke-tests:apps:CustomDimensions'
//include ':smoke-tests:apps:CustomInstrumentation'
include ':smoke-tests:apps:CustomInstrumentation'
include ':smoke-tests:apps:gRPC'
include ':smoke-tests:apps:HeartBeat'
include ':smoke-tests:apps:HttpClients'
Expand Down
7 changes: 7 additions & 0 deletions smoke-tests/apps/CustomInstrumentation/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
plugins {
id("ai.smoke-test-jar")
}

dependencies {
implementation("org.springframework.boot:spring-boot-starter-web:2.1.7.RELEASE")
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
* ApplicationInsights-Java
* Copyright (c) Microsoft Corporation
* All rights reserved.
*
* MIT License
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the ""Software""), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/

package com.microsoft.applicationinsights.smoketestapp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootApp {

public static void main(String[] args) {
SpringApplication.run(SpringBootApp.class, args);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
* ApplicationInsights-Java
* Copyright (c) Microsoft Corporation
* All rights reserved.
*
* MIT License
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the ""Software""), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/

package com.microsoft.applicationinsights.smoketestapp;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

private static final Logger logger = LoggerFactory.getLogger("smoketestapp");

@GetMapping("/")
public String root() {
return "OK";
}

@GetMapping("/test")
public String test() {
// spin off separate thread to simulate a top-level (request) instrumentation captured on the
// run() method
new Thread(this::run).start();
return "OK!";
}

private void run() {
logger.info("hello");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package com.microsoft.applicationinsights.smoketest;

import static com.microsoft.applicationinsights.smoketest.WarEnvironmentValue.JAVA_11;
import static com.microsoft.applicationinsights.smoketest.WarEnvironmentValue.JAVA_17;
import static com.microsoft.applicationinsights.smoketest.WarEnvironmentValue.JAVA_8;
import static org.assertj.core.api.Assertions.assertThat;

import com.microsoft.applicationinsights.smoketest.schemav2.Data;
import com.microsoft.applicationinsights.smoketest.schemav2.Envelope;
import com.microsoft.applicationinsights.smoketest.schemav2.MessageData;
import com.microsoft.applicationinsights.smoketest.schemav2.RequestData;
import com.microsoft.applicationinsights.smoketest.schemav2.SeverityLevel;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

@UseAgent
public abstract class CustomInstrumentationTest {

@RegisterExtension static final SmokeTestExtension testing = new SmokeTestExtension();

@Test
@TargetUri("/test")
void test() throws Exception {
List<Envelope> rdList = testing.mockedIngestion.waitForItems("RequestData", 2);

Envelope rdEnvelope1 = getRequestEnvelope(rdList, "GET /test");
Envelope rdEnvelope2 = getRequestEnvelope(rdList, "TestController.run");

RequestData rd1 = (RequestData) ((Data<?>) rdEnvelope1.getData()).getBaseData();

assertThat(rd1.getName()).isEqualTo("GET /test");
assertThat(rd1.getResponseCode()).isEqualTo("200");
assertThat(rd1.getProperties()).isEmpty();
assertThat(rd1.getSuccess()).isTrue();

RequestData rd2 = (RequestData) ((Data<?>) rdEnvelope2.getData()).getBaseData();

assertThat(rd2.getName()).isEqualTo("TestController.run");
assertThat(rd2.getResponseCode()).isEqualTo("0");
assertThat(rd2.getProperties()).isEmpty();
assertThat(rd2.getSuccess()).isTrue();

String operationId = rdEnvelope2.getTags().get("ai.operation.id");
List<Envelope> mdList = testing.mockedIngestion.waitForMessageItemsInRequest(1, operationId);

Envelope mdEnvelope = mdList.get(0);
MessageData md = (MessageData) ((Data<?>) mdEnvelope.getData()).getBaseData();

assertThat(md.getMessage()).isEqualTo("hello");
assertThat(md.getSeverityLevel()).isEqualTo(SeverityLevel.INFORMATION);
assertThat(md.getProperties()).containsEntry("SourceType", "Logger");
assertThat(md.getProperties()).containsEntry("LoggerName", "smoketestapp");
assertThat(md.getProperties()).containsKey("ThreadName");
assertThat(md.getProperties()).hasSize(3);
}

private static Envelope getRequestEnvelope(List<Envelope> envelopes, String name) {
for (Envelope envelope : envelopes) {
RequestData rd = (RequestData) ((Data<?>) envelope.getData()).getBaseData();
if (rd.getName().equals(name)) {
return envelope;
}
}
throw new IllegalStateException("Could not find request with name: " + name);
}

@Environment(JAVA_8)
static class Java8Test extends CustomInstrumentationTest {}

@Environment(JAVA_11)
static class Java11Test extends CustomInstrumentationTest {}

@Environment(JAVA_17)
static class Java17Test extends CustomInstrumentationTest {}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"preview": {
"customInstrumentation": [
{
"className": "com.microsoft.applicationinsights.smoketestapp.TestController",
"methodName": "run"
}
]
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="warn">
<appender-ref ref="CONSOLE"/>
</root>
</configuration>