Skip to content
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
3 changes: 3 additions & 0 deletions agent/agent-tooling/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,13 @@ dependencies {

testImplementation("org.junit.jupiter:junit-jupiter")
testImplementation("org.assertj:assertj-core")
testImplementation("org.awaitility:awaitility")
testImplementation("org.mockito:mockito-core")
testImplementation("uk.org.webcompere:system-stubs-jupiter:1.1.0")
testImplementation("io.github.hakky54:logcaptor")

testImplementation("io.opentelemetry:opentelemetry-sdk-testing")

testImplementation("com.microsoft.jfr:jfr-streaming")
testImplementation("com.azure:azure-storage-blob")
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import com.microsoft.applicationinsights.agent.bootstrap.diagnostics.DiagnosticsHelper;
import com.microsoft.applicationinsights.agent.bootstrap.diagnostics.status.StatusFile;
import com.microsoft.applicationinsights.agent.internal.common.FriendlyException;
import io.opentelemetry.api.common.AttributeKey;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
Expand Down Expand Up @@ -195,11 +196,59 @@ public static class PreviewConfiguration {
public LiveMetrics liveMetrics = new LiveMetrics();
public LegacyRequestIdPropagation legacyRequestIdPropagation = new LegacyRequestIdPropagation();

public List<InheritedAttribute> inheritedAttributes = new ArrayList<>();

public ProfilerConfiguration profiler = new ProfilerConfiguration();
public GcEventConfiguration gcEvents = new GcEventConfiguration();
public AadAuthentication authentication = new AadAuthentication();
}

public static class InheritedAttribute {
public String key;
public SpanAttributeType type;

public AttributeKey<?> getAttributeKey() {
switch (type) {
case STRING:
return AttributeKey.stringKey(key);
case BOOLEAN:
return AttributeKey.booleanKey(key);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i checked out #1743, the way they send extra attributes are through part C. Breeze accepts key/value pair string only. how other datatypes here will get used?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

they are all converted to strings, see Exporter.getStringValue()

case LONG:
return AttributeKey.longKey(key);
case DOUBLE:
return AttributeKey.doubleKey(key);
case STRING_ARRAY:
return AttributeKey.stringArrayKey(key);
case BOOLEAN_ARRAY:
return AttributeKey.booleanArrayKey(key);
case LONG_ARRAY:
return AttributeKey.longArrayKey(key);
case DOUBLE_ARRAY:
return AttributeKey.doubleArrayKey(key);
}
throw new IllegalStateException("Unexpected attribute key type: " + type);
}
}

public enum SpanAttributeType {
@JsonProperty("string")
STRING,
@JsonProperty("boolean")
BOOLEAN,
@JsonProperty("long")
LONG,
@JsonProperty("double")
DOUBLE,
@JsonProperty("string-array")
STRING_ARRAY,
@JsonProperty("boolean-array")
BOOLEAN_ARRAY,
@JsonProperty("long-array")
LONG_ARRAY,
@JsonProperty("double-array")
DOUBLE_ARRAY
}

public static class LegacyRequestIdPropagation {
public boolean enabled;
}
Expand Down Expand Up @@ -904,6 +953,7 @@ public void validate() {
}

public enum AuthenticationType {
// TODO (kyralama) should these use @JsonProperty to bind lowercase like other enums?
UAMI,
SAMI,
VSCODE,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/*
* 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.agent.internal.init;

import com.microsoft.applicationinsights.agent.internal.configuration.Configuration;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.context.Context;
import io.opentelemetry.sdk.trace.ReadWriteSpan;
import io.opentelemetry.sdk.trace.ReadableSpan;
import io.opentelemetry.sdk.trace.SpanProcessor;
import java.util.List;
import java.util.stream.Collectors;

public class InheritedAttributesSpanProcessor implements SpanProcessor {

private final List<AttributeKey<?>> inheritAttributeKeys;

public InheritedAttributesSpanProcessor(
List<Configuration.InheritedAttribute> inheritedAttributes) {
this.inheritAttributeKeys =
inheritedAttributes.stream()
.map(Configuration.InheritedAttribute::getAttributeKey)
.collect(Collectors.toList());
}

@Override
@SuppressWarnings("unchecked")
public void onStart(Context parentContext, ReadWriteSpan span) {
Span parentSpan = Span.fromContextOrNull(parentContext);
if (parentSpan == null) {
return;
}
if (!(parentSpan instanceof ReadableSpan)) {
return;
}
ReadableSpan parentReadableSpan = (ReadableSpan) parentSpan;

for (AttributeKey<?> inheritAttributeKey : inheritAttributeKeys) {
Object value = TempGetAttribute.getAttribute(parentReadableSpan, inheritAttributeKey);
if (value != null) {
span.setAttribute((AttributeKey<Object>) inheritAttributeKey, value);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

are inheritAttributes part of the customDimensions in the payload?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes

}
}
}

@Override
public boolean isStartRequired() {
return true;
}

@Override
public void onEnd(ReadableSpan span) {}

@Override
public boolean isEndRequired() {
return false;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -107,20 +107,23 @@ public void configure(SdkTracerProviderBuilder tracerProvider) {
}
}

// using BatchSpanProcessor in order to get off of the application thread as soon as possible
// using batch size 1 because need to convert to SpanData as soon as possible to grab data for
// live metrics
// real batching is done at a lower level
batchSpanProcessor = BatchSpanProcessor.builder(currExporter).setMaxExportBatchSize(1).build();
tracerProvider.addSpanProcessor(batchSpanProcessor);
// operation name span processor is only applied on span start, so doesn't need to be chained
// with above span processors
// with the batch span processor
tracerProvider.addSpanProcessor(new AiOperationNameSpanProcessor());
// legacy span processor is only applied on span start, so doesn't need to be chained with above
// span processors
// inherited attributes span processor is only applied on span start, so doesn't need to be
// chained with the batch span processor
tracerProvider.addSpanProcessor(
new InheritedAttributesSpanProcessor(config.preview.inheritedAttributes));
// legacy span processor is only applied on span start, so doesn't need to be chained with the
// batch span processor
// it is used to pass legacy attributes from the context (extracted by the AiLegacyPropagator)
// to the span attributes (since there is no way to update attributes on span directly from
// propagator)
tracerProvider.addSpanProcessor(new AiLegacyHeaderSpanProcessor());
// using BatchSpanProcessor in order to get off of the application thread as soon as possible
// using batch size 1 because need to convert to SpanData as soon as possible to grab data for
// live metrics. the real batching is done at a lower level
batchSpanProcessor = BatchSpanProcessor.builder(currExporter).setMaxExportBatchSize(1).build();
tracerProvider.addSpanProcessor(batchSpanProcessor);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
/*
* 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.agent.internal.init;

import static io.opentelemetry.api.trace.SpanKind.INTERNAL;
import static io.opentelemetry.sdk.testing.assertj.TracesAssert.assertThat;
import static org.assertj.core.api.Assertions.entry;
import static org.awaitility.Awaitility.await;

import com.microsoft.applicationinsights.agent.internal.configuration.Configuration;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.Tracer;
import io.opentelemetry.context.Context;
import io.opentelemetry.sdk.OpenTelemetrySdk;
import io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions;
import io.opentelemetry.sdk.testing.exporter.InMemorySpanExporter;
import io.opentelemetry.sdk.trace.SdkTracerProvider;
import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;

public class InheritedAttributesSpanProcessorTest {

private final InMemorySpanExporter exporter = InMemorySpanExporter.create();

private final AttributeKey<String> oneStringKey = AttributeKey.stringKey("one");
private final AttributeKey<Long> oneLongKey = AttributeKey.longKey("one");

@AfterEach
public void afterEach() {
exporter.reset();
}

@Test
public void shouldNotInheritAttribute() {
Tracer tracer = newTracer(Collections.emptyList());
Span span =
tracer.spanBuilder("parent").setNoParent().setAttribute(oneStringKey, "1").startSpan();
Context context = Context.root().with(span);
try {
tracer.spanBuilder("child").setParent(context).startSpan().end();
} finally {
span.end();
}

await().until(() -> exporter.getFinishedSpanItems().size() == 2);

assertThat(Collections.singleton(exporter.getFinishedSpanItems()))
.hasTracesSatisfyingExactly(
trace ->
trace.hasSpansSatisfyingExactly(
childSpan ->
childSpan.hasName("child").hasKind(INTERNAL).hasTotalAttributeCount(0),
parentSpan ->
parentSpan
.hasName("parent")
.hasKind(INTERNAL)
.hasAttributesSatisfying(
attributes ->
OpenTelemetryAssertions.assertThat(attributes)
.containsOnly(entry(oneStringKey, "1")))));
}

@Test
public void shouldInheritAttribute() {
Configuration.InheritedAttribute inheritedAttribute = new Configuration.InheritedAttribute();
inheritedAttribute.key = "one";
inheritedAttribute.type = Configuration.SpanAttributeType.STRING;

Tracer tracer = newTracer(Collections.singletonList(inheritedAttribute));
Span span =
tracer.spanBuilder("parent").setNoParent().setAttribute(oneStringKey, "1").startSpan();
Context context = Context.root().with(span);
try {
tracer.spanBuilder("child").setParent(context).startSpan().end();
} finally {
span.end();
}

await().until(() -> exporter.getFinishedSpanItems().size() == 2);

assertThat(Collections.singleton(exporter.getFinishedSpanItems()))
.hasTracesSatisfyingExactly(
trace ->
trace.hasSpansSatisfyingExactly(
childSpan ->
childSpan
.hasName("child")
.hasKind(INTERNAL)
.hasAttributesSatisfying(
attributes ->
OpenTelemetryAssertions.assertThat(attributes)
.containsOnly(entry(oneStringKey, "1"))),
parentSpan ->
parentSpan
.hasName("parent")
.hasKind(INTERNAL)
.hasAttributesSatisfying(
attributes ->
OpenTelemetryAssertions.assertThat(attributes)
.containsOnly(entry(oneStringKey, "1")))));
}

@Test
public void shouldNotInheritAttributeWithSameNameButDifferentType() {
Configuration.InheritedAttribute inheritedAttribute = new Configuration.InheritedAttribute();
inheritedAttribute.key = "one";
inheritedAttribute.type = Configuration.SpanAttributeType.STRING;

Tracer tracer = newTracer(Collections.singletonList(inheritedAttribute));
Span span = tracer.spanBuilder("parent").setNoParent().setAttribute(oneLongKey, 1L).startSpan();
Context context = Context.root().with(span);
try {
tracer.spanBuilder("child").setParent(context).startSpan().end();
} finally {
span.end();
}

await().until(() -> exporter.getFinishedSpanItems().size() == 2);

assertThat(Collections.singleton(exporter.getFinishedSpanItems()))
.hasTracesSatisfyingExactly(
trace ->
trace.hasSpansSatisfyingExactly(
childSpan ->
childSpan.hasName("child").hasKind(INTERNAL).hasTotalAttributeCount(0),
parentSpan ->
parentSpan
.hasName("parent")
.hasKind(INTERNAL)
.hasAttributesSatisfying(
attributes ->
OpenTelemetryAssertions.assertThat(attributes)
.containsOnly(entry(oneLongKey, 1L)))));
}

private Tracer newTracer(List<Configuration.InheritedAttribute> inheritedAttributes) {
OpenTelemetrySdk sdk =
OpenTelemetrySdk.builder()
.setTracerProvider(
SdkTracerProvider.builder()
.addSpanProcessor(new InheritedAttributesSpanProcessor(inheritedAttributes))
.addSpanProcessor(SimpleSpanProcessor.create(exporter))
.build())
.build();
return sdk.getTracer("test");
}
}
1 change: 1 addition & 0 deletions dependencyManagement/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ val DEPENDENCIES = listOf(
"com.azure:azure-storage-blob:12.13.0",
"com.github.oshi:oshi-core:5.8.0",
"org.assertj:assertj-core:3.19.0",
"org.awaitility:awaitility:4.1.0",
"io.github.hakky54:logcaptor:2.5.0",
"com.microsoft.jfr:jfr-streaming:1.2.0",
"org.checkerframework:checker-qual:3.14.0"
Expand Down
1 change: 1 addition & 0 deletions settings.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ include ':test:smoke:testApps:CustomDimensions'
include ':test:smoke:testApps:gRPC'
include ':test:smoke:testApps:HeartBeat'
include ':test:smoke:testApps:HttpClients'
include ':test:smoke:testApps:InheritedAttributes'
include ':test:smoke:testApps:Jdbc'
include ':test:smoke:testApps:Jedis'
include ':test:smoke:testApps:JettyNativeHandler'
Expand Down
Loading