Skip to content

Commit e886785

Browse files
committed
Merge pull request #44394 from nosan
* pr/44394: Polish "Add support for OTel-specific environment variables" Add support for OTel-specific environment variables Closes gh-44394
2 parents 79ad6b7 + 8f4e051 commit e886785

File tree

5 files changed

+361
-26
lines changed

5 files changed

+361
-26
lines changed

Diff for: spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/otlp/OtlpMetricsPropertiesConfigAdapter.java

+8-9
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2012-2024 the original author or authors.
2+
* Copyright 2012-2025 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -17,7 +17,6 @@
1717
package org.springframework.boot.actuate.autoconfigure.metrics.export.otlp;
1818

1919
import java.util.Collections;
20-
import java.util.HashMap;
2120
import java.util.Map;
2221
import java.util.concurrent.TimeUnit;
2322

@@ -27,8 +26,8 @@
2726

2827
import org.springframework.boot.actuate.autoconfigure.metrics.export.properties.StepRegistryPropertiesConfigAdapter;
2928
import org.springframework.boot.actuate.autoconfigure.opentelemetry.OpenTelemetryProperties;
29+
import org.springframework.boot.actuate.autoconfigure.opentelemetry.OpenTelemetryResourceAttributes;
3030
import org.springframework.core.env.Environment;
31-
import org.springframework.util.CollectionUtils;
3231
import org.springframework.util.StringUtils;
3332

3433
/**
@@ -78,12 +77,12 @@ public AggregationTemporality aggregationTemporality() {
7877

7978
@Override
8079
public Map<String, String> resourceAttributes() {
81-
Map<String, String> resourceAttributes = this.openTelemetryProperties.getResourceAttributes();
82-
Map<String, String> result = new HashMap<>((!CollectionUtils.isEmpty(resourceAttributes)) ? resourceAttributes
83-
: OtlpConfig.super.resourceAttributes());
84-
result.computeIfAbsent("service.name", (key) -> getApplicationName());
85-
result.computeIfAbsent("service.group", (key) -> getApplicationGroup());
86-
return Collections.unmodifiableMap(result);
80+
Map<String, String> attributes = new OpenTelemetryResourceAttributes(
81+
this.openTelemetryProperties.getResourceAttributes())
82+
.asMap();
83+
attributes.computeIfAbsent("service.name", (key) -> getApplicationName());
84+
attributes.computeIfAbsent("service.group", (key) -> getApplicationGroup());
85+
return Collections.unmodifiableMap(attributes);
8786
}
8887

8988
private String getApplicationName() {

Diff for: spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/opentelemetry/OpenTelemetryAutoConfiguration.java

+20-17
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2012-2024 the original author or authors.
2+
* Copyright 2012-2025 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -16,9 +16,9 @@
1616

1717
package org.springframework.boot.actuate.autoconfigure.opentelemetry;
1818

19+
import java.util.Map;
20+
1921
import io.opentelemetry.api.OpenTelemetry;
20-
import io.opentelemetry.api.common.AttributeKey;
21-
import io.opentelemetry.api.common.Attributes;
2222
import io.opentelemetry.context.propagation.ContextPropagators;
2323
import io.opentelemetry.sdk.OpenTelemetrySdk;
2424
import io.opentelemetry.sdk.OpenTelemetrySdkBuilder;
@@ -54,10 +54,6 @@ public class OpenTelemetryAutoConfiguration {
5454
*/
5555
private static final String DEFAULT_APPLICATION_NAME = "unknown_service";
5656

57-
private static final AttributeKey<String> ATTRIBUTE_KEY_SERVICE_NAME = AttributeKey.stringKey("service.name");
58-
59-
private static final AttributeKey<String> ATTRIBUTE_KEY_SERVICE_GROUP = AttributeKey.stringKey("service.group");
60-
6157
@Bean
6258
@ConditionalOnMissingBean(OpenTelemetry.class)
6359
OpenTelemetrySdk openTelemetry(ObjectProvider<SdkTracerProvider> tracerProvider,
@@ -74,20 +70,27 @@ OpenTelemetrySdk openTelemetry(ObjectProvider<SdkTracerProvider> tracerProvider,
7470
@Bean
7571
@ConditionalOnMissingBean
7672
Resource openTelemetryResource(Environment environment, OpenTelemetryProperties properties) {
77-
String applicationName = environment.getProperty("spring.application.name", DEFAULT_APPLICATION_NAME);
78-
String applicationGroup = environment.getProperty("spring.application.group");
79-
Resource resource = Resource.getDefault()
80-
.merge(Resource.create(Attributes.of(ATTRIBUTE_KEY_SERVICE_NAME, applicationName)));
81-
if (StringUtils.hasLength(applicationGroup)) {
82-
resource = resource.merge(Resource.create(Attributes.of(ATTRIBUTE_KEY_SERVICE_GROUP, applicationGroup)));
83-
}
84-
return resource.merge(toResource(properties));
73+
Resource resource = Resource.getDefault();
74+
return resource.merge(toResource(environment, properties));
8575
}
8676

87-
private static Resource toResource(OpenTelemetryProperties properties) {
77+
private Resource toResource(Environment environment, OpenTelemetryProperties properties) {
8878
ResourceBuilder builder = Resource.builder();
89-
properties.getResourceAttributes().forEach(builder::put);
79+
Map<String, String> attributes = new OpenTelemetryResourceAttributes(properties.getResourceAttributes())
80+
.asMap();
81+
attributes.computeIfAbsent("service.name", (key) -> getApplicationName(environment));
82+
attributes.computeIfAbsent("service.group", (key) -> getApplicationGroup(environment));
83+
attributes.forEach(builder::put);
9084
return builder.build();
9185
}
9286

87+
private String getApplicationName(Environment environment) {
88+
return environment.getProperty("spring.application.name", DEFAULT_APPLICATION_NAME);
89+
}
90+
91+
private String getApplicationGroup(Environment environment) {
92+
String applicationGroup = environment.getProperty("spring.application.group");
93+
return (StringUtils.hasLength(applicationGroup)) ? applicationGroup : null;
94+
}
95+
9396
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
1+
/*
2+
* Copyright 2012-2025 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package org.springframework.boot.actuate.autoconfigure.opentelemetry;
18+
19+
import java.io.ByteArrayOutputStream;
20+
import java.nio.charset.StandardCharsets;
21+
import java.util.Collections;
22+
import java.util.LinkedHashMap;
23+
import java.util.Map;
24+
import java.util.function.Function;
25+
26+
import org.springframework.util.StringUtils;
27+
28+
/**
29+
* OpenTelemetryResourceAttributes retrieves information from the
30+
* {@code OTEL_RESOURCE_ATTRIBUTES} and {@code OTEL_SERVICE_NAME} environment variables
31+
* and merges it with the resource attributes provided by the user.
32+
* <p>
33+
* <b>User-provided resource attributes take precedence.</b>
34+
* <p>
35+
* <a href= "https://opentelemetry.io/docs/specs/otel/resource/sdk/">OpenTelemetry
36+
* Resource Specification</a>
37+
*
38+
* @author Dmytro Nosan
39+
* @since 3.5.0
40+
*/
41+
public final class OpenTelemetryResourceAttributes {
42+
43+
private final Map<String, String> resourceAttributes;
44+
45+
private final Function<String, String> getEnv;
46+
47+
/**
48+
* Creates a new instance of {@link OpenTelemetryResourceAttributes}.
49+
* @param resourceAttributes user provided resource attributes to be used
50+
*/
51+
public OpenTelemetryResourceAttributes(Map<String, String> resourceAttributes) {
52+
this(resourceAttributes, null);
53+
}
54+
55+
/**
56+
* Creates a new {@link OpenTelemetryResourceAttributes} instance.
57+
* @param resourceAttributes user provided resource attributes to be used
58+
* @param getEnv a function to retrieve environment variables by name
59+
*/
60+
OpenTelemetryResourceAttributes(Map<String, String> resourceAttributes, Function<String, String> getEnv) {
61+
this.resourceAttributes = (resourceAttributes != null) ? resourceAttributes : Collections.emptyMap();
62+
this.getEnv = (getEnv != null) ? getEnv : System::getenv;
63+
}
64+
65+
/**
66+
* Returns resource attributes by combining attributes from environment variables and
67+
* user-defined resource attributes. The final resource contains all attributes from
68+
* both sources.
69+
* <p>
70+
* If a key exists in both environment variables and user-defined resources, the value
71+
* from the user-defined resource takes precedence, even if it is empty.
72+
* <p>
73+
* <b>Null keys and values are ignored.</b>
74+
* @return the resource attributes
75+
*/
76+
public Map<String, String> asMap() {
77+
Map<String, String> attributes = getResourceAttributesFromEnv();
78+
this.resourceAttributes.forEach((name, value) -> {
79+
if (name != null && value != null) {
80+
attributes.put(name, value);
81+
}
82+
});
83+
return attributes;
84+
}
85+
86+
/**
87+
* Parses resource attributes from the {@link System#getenv()}. This method fetches
88+
* attributes defined in the {@code OTEL_RESOURCE_ATTRIBUTES} and
89+
* {@code OTEL_SERVICE_NAME} environment variables and provides them as key-value
90+
* pairs.
91+
* <p>
92+
* If {@code service.name} is also provided in {@code OTEL_RESOURCE_ATTRIBUTES}, then
93+
* {@code OTEL_SERVICE_NAME} takes precedence.
94+
* @return resource attributes
95+
*/
96+
private Map<String, String> getResourceAttributesFromEnv() {
97+
Map<String, String> attributes = new LinkedHashMap<>();
98+
for (String attribute : StringUtils.tokenizeToStringArray(getEnv("OTEL_RESOURCE_ATTRIBUTES"), ",")) {
99+
int index = attribute.indexOf('=');
100+
if (index > 0) {
101+
String key = attribute.substring(0, index);
102+
String value = attribute.substring(index + 1);
103+
attributes.put(key.trim(), decode(value.trim()));
104+
}
105+
}
106+
String otelServiceName = getEnv("OTEL_SERVICE_NAME");
107+
if (otelServiceName != null) {
108+
attributes.put("service.name", otelServiceName);
109+
}
110+
return attributes;
111+
}
112+
113+
private String getEnv(String name) {
114+
return this.getEnv.apply(name);
115+
}
116+
117+
/**
118+
* Decodes a percent-encoded string. Converts sequences like '%HH' (where HH
119+
* represents hexadecimal digits) back into their literal representations.
120+
* <p>
121+
* Inspired by {@code org.apache.commons.codec.net.PercentCodec}.
122+
* @param value value to decode
123+
* @return the decoded string
124+
*/
125+
public static String decode(String value) {
126+
if (value.indexOf('%') < 0) {
127+
return value;
128+
}
129+
byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
130+
ByteArrayOutputStream bos = new ByteArrayOutputStream(bytes.length);
131+
for (int i = 0; i < bytes.length; i++) {
132+
byte b = bytes[i];
133+
if (b != '%') {
134+
bos.write(b);
135+
continue;
136+
}
137+
int u = decodeHex(bytes, i + 1);
138+
int l = decodeHex(bytes, i + 2);
139+
if (u >= 0 && l >= 0) {
140+
bos.write((u << 4) + l);
141+
}
142+
else {
143+
throw new IllegalArgumentException(
144+
"Failed to decode percent-encoded characters at index %d in the value: '%s'".formatted(i,
145+
value));
146+
}
147+
i += 2;
148+
}
149+
return bos.toString(StandardCharsets.UTF_8);
150+
}
151+
152+
private static int decodeHex(byte[] bytes, int index) {
153+
return (index < bytes.length) ? Character.digit(bytes[index], 16) : -1;
154+
}
155+
156+
}

0 commit comments

Comments
 (0)