Skip to content

Commit

Permalink
fix and improve manifest resource provider (#10857)
Browse files Browse the repository at this point in the history
Co-authored-by: Lauri Tulmin <ltulmin@splunk.com>
  • Loading branch information
zeitlinger and laurit committed Mar 14, 2024
1 parent 3a508d9 commit 17b6cad
Show file tree
Hide file tree
Showing 7 changed files with 98 additions and 87 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,16 @@
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
* An easier alternative to {@link io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider}, which
* avoids some common pitfalls and boilerplate.
*
* <p>An example of how to use this interface can be found in {@link ManifestResourceProvider}.
*/
@SuppressWarnings({"unchecked", "rawtypes"})
public abstract class AttributeResourceProvider<D> implements ConditionalResourceProvider {

private final AttributeProvider<D> attributeProvider;
Expand All @@ -36,29 +37,31 @@ private AttributeBuilder() {}

@CanIgnoreReturnValue
@Override
@SuppressWarnings({"unchecked", "rawtypes"})
public <T> AttributeBuilder add(AttributeKey<T> key, Function<D, Optional<T>> getter) {
attributeGetters.put((AttributeKey) key, Objects.requireNonNull((Function) getter));
return this;
}
}

private static final ThreadLocal<Resource> existingResource = new ThreadLocal<>();
private Set<AttributeKey<?>> filteredKeys;

private final Map<AttributeKey<Object>, Function<D, Optional<?>>> attributeGetters =
new HashMap<>();

public AttributeResourceProvider(AttributeProvider<D> attributeProvider) {
AttributeResourceProvider(AttributeProvider<D> attributeProvider) {
this.attributeProvider = attributeProvider;
attributeProvider.registerAttributes(new AttributeBuilder());
}

@Override
public final boolean shouldApply(ConfigProperties config, Resource existing) {
existingResource.set(existing);

Map<String, String> resourceAttributes = getResourceAttributes(config);
return attributeGetters.keySet().stream()
.allMatch(key -> shouldUpdate(config, existing, key, resourceAttributes));
Map<String, String> resourceAttributes = config.getMap("otel.resource.attributes");
filteredKeys =
attributeGetters.keySet().stream()
.filter(key -> shouldUpdate(config, existing, key, resourceAttributes))
.collect(Collectors.toSet());
return !filteredKeys.isEmpty();
}

@Override
Expand All @@ -67,17 +70,12 @@ public final Resource createResource(ConfigProperties config) {
.readData()
.map(
data -> {
// what should we do here?
// we don't have access to the existing resource
// if the resource provider produces a single key, we can rely on shouldApply
// i.e. this method won't be called if the key is already present
// the thread local is a hack to work around this
Resource existing =
Objects.requireNonNull(existingResource.get(), "call shouldApply first");
Map<String, String> resourceAttributes = getResourceAttributes(config);
if (filteredKeys == null) {
throw new IllegalStateException("shouldApply should be called first");
}
AttributesBuilder builder = Attributes.builder();
attributeGetters.entrySet().stream()
.filter(e -> shouldUpdate(config, existing, e.getKey(), resourceAttributes))
.filter(e -> filteredKeys.contains(e.getKey()))
.forEach(
e ->
e.getValue()
Expand All @@ -92,10 +90,6 @@ private static <T> void putAttribute(AttributesBuilder builder, AttributeKey<T>
builder.put(key, value);
}

private static Map<String, String> getResourceAttributes(ConfigProperties config) {
return config.getMap("otel.resource.attributes");
}

private static boolean shouldUpdate(
ConfigProperties config,
Resource existing,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
import io.opentelemetry.semconv.ResourceAttributes;
import java.nio.file.Path;
import java.util.Map;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.logging.Logger;

/**
Expand All @@ -26,22 +28,26 @@ public final class JarServiceNameDetector implements ConditionalResourceProvider

private static final Logger logger = Logger.getLogger(JarServiceNameDetector.class.getName());

private final JarPathFinder jarPathFinder;
private final Supplier<Optional<Path>> jarPathSupplier;

@SuppressWarnings("unused") // SPI
public JarServiceNameDetector() {
this(new JarPathFinder());
this(MainJarPathHolder::getJarPath);
}

private JarServiceNameDetector(Supplier<Optional<Path>> jarPathSupplier) {
this.jarPathSupplier = jarPathSupplier;
}

// visible for tests
JarServiceNameDetector(JarPathFinder jarPathFinder) {
this.jarPathFinder = jarPathFinder;
JarServiceNameDetector(MainJarPathFinder jarPathFinder) {
this(() -> Optional.ofNullable(jarPathFinder.detectJarPath()));
}

@Override
public Resource createResource(ConfigProperties config) {
return jarPathFinder
.getJarPath()
return jarPathSupplier
.get()
.map(
jarPath -> {
String serviceName = getServiceName(jarPath);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,33 +9,22 @@
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import javax.annotation.Nullable;

class JarPathFinder {
class MainJarPathFinder {
private final Supplier<String[]> getProcessHandleArguments;
private final Function<String, String> getSystemProperty;
private final Predicate<Path> fileExists;

private static class DetectionResult {
private final Optional<Path> jarPath;

private DetectionResult(Optional<Path> jarPath) {
this.jarPath = jarPath;
}
}

private static Optional<DetectionResult> detectionResult = Optional.empty();

public JarPathFinder() {
public MainJarPathFinder() {
this(ProcessArguments::getProcessArguments, System::getProperty, Files::isRegularFile);
}

// visible for tests
JarPathFinder(
MainJarPathFinder(
Supplier<String[]> getProcessHandleArguments,
Function<String, String> getSystemProperty,
Predicate<Path> fileExists) {
Expand All @@ -44,19 +33,7 @@ public JarPathFinder() {
this.fileExists = fileExists;
}

// visible for testing
static void resetForTest() {
detectionResult = Optional.empty();
}

Optional<Path> getJarPath() {
if (!detectionResult.isPresent()) {
detectionResult = Optional.of(new DetectionResult(Optional.ofNullable(detectJarPath())));
}
return detectionResult.get().jarPath;
}

private Path detectJarPath() {
Path detectJarPath() {
Path jarPath = getJarPathFromProcessHandle();
if (jarPath != null) {
return jarPath;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/

package io.opentelemetry.instrumentation.resources;

import java.nio.file.Path;
import java.util.Optional;

class MainJarPathHolder {
private static final Optional<Path> jarPath =
Optional.ofNullable(new MainJarPathFinder().detectJarPath());

static Optional<Path> getJarPath() {
return jarPath;
}

private MainJarPathHolder() {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,12 @@
import com.google.auto.service.AutoService;
import io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider;
import io.opentelemetry.semconv.ResourceAttributes;
import java.io.InputStream;
import java.net.URL;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.logging.Logger;

Expand All @@ -29,17 +30,16 @@ public final class ManifestResourceProvider extends AttributeResourceProvider<Ma

@SuppressWarnings("unused") // SPI
public ManifestResourceProvider() {
this(new JarPathFinder(), ManifestResourceProvider::readManifest);
this(MainJarPathHolder::getJarPath, ManifestResourceProvider::readManifest);
}

// Visible for testing
ManifestResourceProvider(
JarPathFinder jarPathFinder, Function<Path, Optional<Manifest>> manifestReader) {
private ManifestResourceProvider(
Supplier<Optional<Path>> jarPathSupplier, Function<Path, Optional<Manifest>> manifestReader) {
super(
new AttributeProvider<Manifest>() {
@Override
public Optional<Manifest> readData() {
return jarPathFinder.getJarPath().flatMap(manifestReader);
return jarPathSupplier.get().flatMap(manifestReader);
}

@Override
Expand All @@ -63,14 +63,17 @@ public void registerAttributes(Builder<Manifest> builder) {
});
}

// Visible for testing
ManifestResourceProvider(
MainJarPathFinder jarPathFinder, Function<Path, Optional<Manifest>> manifestReader) {
this(() -> Optional.ofNullable(jarPathFinder.detectJarPath()), manifestReader);
}

private static Optional<Manifest> readManifest(Path jarPath) {
try (InputStream s =
new URL(String.format("jar:%s!/META-INF/MANIFEST.MF", jarPath.toUri())).openStream()) {
Manifest manifest = new Manifest();
manifest.read(s);
return Optional.of(manifest);
} catch (Exception e) {
logger.log(WARNING, "Error reading manifest", e);
try (JarFile jarFile = new JarFile(jarPath.toFile(), false)) {
return Optional.of(jarFile.getManifest());
} catch (IOException exception) {
logger.log(WARNING, "Error reading manifest", exception);
return Optional.empty();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.ExtensionContext;
Expand All @@ -33,11 +32,6 @@ class JarServiceNameDetectorTest {

@Mock ConfigProperties config;

@BeforeEach
void setUp() {
JarPathFinder.resetForTest();
}

@Test
void createResource_empty() {
String[] processArgs = new String[0];
Expand All @@ -53,7 +47,7 @@ void createResource_empty() {
private static JarServiceNameDetector getDetector(
String[] processArgs, Function<String, String> getProperty, Predicate<Path> fileExists) {
return new JarServiceNameDetector(
new JarPathFinder(() -> processArgs, getProperty, fileExists));
new MainJarPathFinder(() -> processArgs, getProperty, fileExists));
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import static io.opentelemetry.semconv.ResourceAttributes.SERVICE_VERSION;
import static org.assertj.core.api.Assertions.assertThat;

import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties;
import io.opentelemetry.sdk.autoconfigure.spi.internal.DefaultConfigProperties;
import io.opentelemetry.sdk.resources.Resource;
Expand All @@ -19,28 +20,29 @@
import java.util.jar.Manifest;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.TestFactory;

class ManifestResourceProviderTest {

@BeforeEach
void setUp() {
JarPathFinder.resetForTest();
}

private static class TestCase {
private final String name;
private final String expectedName;
private final String expectedVersion;
private final InputStream input;
private final Resource existing;

public TestCase(String name, String expectedName, String expectedVersion, InputStream input) {
public TestCase(
String name,
String expectedName,
String expectedVersion,
InputStream input,
Resource existing) {
this.name = name;
this.expectedName = expectedName;
this.expectedVersion = expectedVersion;
this.input = input;
this.existing = existing;
}
}

Expand All @@ -49,18 +51,33 @@ Collection<DynamicTest> createResource() {
ConfigProperties config = DefaultConfigProperties.createFromMap(Collections.emptyMap());

return Stream.of(
new TestCase("name ok", "demo", "0.0.1-SNAPSHOT", openClasspathResource("MANIFEST.MF")),
new TestCase("name - no resource", null, null, null),
new TestCase(
"name - empty resource", null, null, openClasspathResource("empty-MANIFEST.MF")))
"name ok",
"demo",
"0.0.1-SNAPSHOT",
openClasspathResource("MANIFEST.MF"),
Resource.getDefault()),
new TestCase("name - no resource", null, null, null, Resource.getDefault()),
new TestCase(
"name - empty resource",
null,
null,
openClasspathResource("empty-MANIFEST.MF"),
Resource.getDefault()),
new TestCase(
"name already detected",
null,
"0.0.1-SNAPSHOT",
openClasspathResource("MANIFEST.MF"),
Resource.create(Attributes.of(SERVICE_NAME, "old"))))
.map(
t ->
DynamicTest.dynamicTest(
t.name,
() -> {
ManifestResourceProvider provider =
new ManifestResourceProvider(
new JarPathFinder(
new MainJarPathFinder(
() -> JarServiceNameDetectorTest.getArgs("app.jar"),
prop -> null,
JarServiceNameDetectorTest::failPath),
Expand All @@ -73,7 +90,7 @@ Collection<DynamicTest> createResource() {
return Optional.empty();
}
});
provider.shouldApply(config, Resource.getDefault());
provider.shouldApply(config, t.existing);

Resource resource = provider.createResource(config);
assertThat(resource.getAttribute(SERVICE_NAME)).isEqualTo(t.expectedName);
Expand Down

0 comments on commit 17b6cad

Please sign in to comment.