Skip to content

Commit

Permalink
Add resource providers (open-telemetry#6574)
Browse files Browse the repository at this point in the history
* Add resource providers

* Use autoservice annotation
  • Loading branch information
jack-berg authored and LironKS committed Dec 4, 2022
1 parent 56ce32a commit cb6bf90
Show file tree
Hide file tree
Showing 24 changed files with 1,166 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ testing {
implementation("org.junit.jupiter:junit-jupiter-params")
runtimeOnly("org.junit.jupiter:junit-jupiter-engine")
runtimeOnly("org.junit.vintage:junit-vintage-engine")
implementation("org.junit-pioneer:junit-pioneer")


implementation("org.assertj:assertj-core")
Expand Down
1 change: 1 addition & 0 deletions dependencyManagement/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ val DEPENDENCIES = listOf(
"com.google.code.findbugs:jsr305:3.0.2",
"org.apache.groovy:groovy:${groovyVersion}",
"org.apache.groovy:groovy-json:${groovyVersion}",
"org.codehaus.mojo:animal-sniffer-annotations:1.22",
"org.junit-pioneer:junit-pioneer:1.7.1",
"org.objenesis:objenesis:3.2",
"org.spockframework:spock-core:2.2-groovy-4.0",
Expand Down
62 changes: 62 additions & 0 deletions instrumentation/resources/library/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# OpenTelemetry Resource Providers

This package includes some standard `ResourceProvider`s for filling in attributes related to
common environments. Currently, the resources provide the following semantic conventions:

## Populated attributes

### Container

Provider: `io.opentelemetry.instrumentation.resources.ContainerResource`

Specification: https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/resource/semantic_conventions/container.md

Implemented attributes:
- `container.id`

### Host

Provider: `io.opentelemetry.instrumentation.resources.HostResource`

Specification: https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/resource/semantic_conventions/host.md

Implemented attributes:
- `host.name`
- `host.arch`

### Operating System

Provider: `io.opentelemetry.instrumentation.resources.OsResource`

Specification: https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/resource/semantic_conventions/os.md

Implemented attributes:
- `os.type`
- `os.description`

### Process

Implementation: `io.opentelemetry.instrumentation.resources.ProcessResource`

Specification: https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/resource/semantic_conventions/process.md#process

Implemented attributes:
- `process.pid`
- `process.executable.path` (note, we assume the `java` binary is located in the `bin` subfolder of `JAVA_HOME`)
- `process.command_line` (note this includes all system properties and arguments when running)

### Java Runtime

Implementation: `io.opentelemetry.instrumentation.resources.ProcessRuntimeResource`

Specification: https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/resource/semantic_conventions/process.md#process-runtimes

Implemented attributes:
- `process.runtime.name`
- `process.runtime.version`
- `process.runtime.description`

## Platforms

This package currently does not run on Android. It has been verified on OpenJDK and should work on
other server JVM distributions but if you find any issues please let us know.
64 changes: 64 additions & 0 deletions instrumentation/resources/library/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
plugins {
id("otel.library-instrumentation")
id("otel.animalsniffer-conventions")
}

val mrJarVersions = listOf(11)

dependencies {
implementation("io.opentelemetry:opentelemetry-sdk-common")
implementation("io.opentelemetry:opentelemetry-semconv")
implementation("io.opentelemetry:opentelemetry-sdk-extension-autoconfigure-spi")

compileOnly("org.codehaus.mojo:animal-sniffer-annotations")

annotationProcessor("com.google.auto.service:auto-service")
compileOnly("com.google.auto.service:auto-service-annotations")

testImplementation("org.junit.jupiter:junit-jupiter-api")
}

for (version in mrJarVersions) {
sourceSets {
create("java$version") {
java {
setSrcDirs(listOf("src/main/java$version"))
}
}
}

tasks {
named<JavaCompile>("compileJava${version}Java") {
sourceCompatibility = "$version"
targetCompatibility = "$version"
options.release.set(version)
}
}

configurations {
named("java${version}Implementation") {
extendsFrom(configurations["implementation"])
}
named("java${version}CompileOnly") {
extendsFrom(configurations["compileOnly"])
}
}

dependencies {
// Common to reference classes in main sourceset from Java 9 one (e.g., to return a common interface)
add("java${version}Implementation", files(sourceSets.main.get().output.classesDirs))
}
}

tasks {
withType(Jar::class) {
for (version in mrJarVersions) {
into("META-INF/versions/$version") {
from(sourceSets["java$version"].output)
}
}
manifest.attributes(
"Multi-Release" to "true"
)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/

package io.opentelemetry.instrumentation.resources;

import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.internal.OtelEncodingUtils;
import io.opentelemetry.sdk.resources.Resource;
import io.opentelemetry.semconv.resource.attributes.ResourceAttributes;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;
import java.util.Optional;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement;

/** Factory for {@link Resource} retrieving Container ID information. */
public final class ContainerResource {

private static final Logger logger = Logger.getLogger(ContainerResource.class.getName());
private static final String UNIQUE_HOST_NAME_FILE_NAME = "/proc/self/cgroup";
private static final Resource INSTANCE = buildSingleton(UNIQUE_HOST_NAME_FILE_NAME);

@IgnoreJRERequirement
private static Resource buildSingleton(String uniqueHostNameFileName) {
// can't initialize this statically without running afoul of animalSniffer on paths
return buildResource(Paths.get(uniqueHostNameFileName));
}

// package private for testing
static Resource buildResource(Path path) {
String containerId = extractContainerId(path);

if (containerId == null || containerId.isEmpty()) {
return Resource.empty();
} else {
return Resource.create(Attributes.of(ResourceAttributes.CONTAINER_ID, containerId));
}
}

/** Returns resource with container information. */
public static Resource get() {
return INSTANCE;
}

/**
* Each line of cgroup file looks like "14:name=systemd:/docker/.../... A hex string is expected
* inside the last section separated by '/' Each segment of the '/' can contain metadata separated
* by either '.' (at beginning) or '-' (at end)
*
* @return containerId
*/
@IgnoreJRERequirement
@Nullable
private static String extractContainerId(Path cgroupFilePath) {
if (!Files.exists(cgroupFilePath) || !Files.isReadable(cgroupFilePath)) {
return null;
}
try (Stream<String> lines = Files.lines(cgroupFilePath)) {
Optional<String> value =
lines
.filter(line -> !line.isEmpty())
.map(ContainerResource::getIdFromLine)
.filter(Objects::nonNull)
.findFirst();
if (value.isPresent()) {
return value.get();
}
} catch (Exception e) {
logger.log(Level.WARNING, "Unable to read file", e);
}
return null;
}

@Nullable
private static String getIdFromLine(String line) {
// This cgroup output line should have the container id in it
int lastSlashIdx = line.lastIndexOf('/');
if (lastSlashIdx < 0) {
return null;
}

String containerId;

String lastSection = line.substring(lastSlashIdx + 1);
int colonIdx = lastSection.lastIndexOf(':');

if (colonIdx != -1) {
// since containerd v1.5.0+, containerId is divided by the last colon when the cgroupDriver is
// systemd:
// https://github.com/containerd/containerd/blob/release/1.5/pkg/cri/server/helpers_linux.go#L64
containerId = lastSection.substring(colonIdx + 1);
} else {
int startIdx = lastSection.lastIndexOf('-');
int endIdx = lastSection.lastIndexOf('.');

startIdx = startIdx == -1 ? 0 : startIdx + 1;
if (endIdx == -1) {
endIdx = lastSection.length();
}
if (startIdx > endIdx) {
return null;
}

containerId = lastSection.substring(startIdx, endIdx);
}

if (OtelEncodingUtils.isValidBase16String(containerId) && !containerId.isEmpty()) {
return containerId;
} else {
return null;
}
}

private ContainerResource() {}
}
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 com.google.auto.service.AutoService;
import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties;
import io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider;
import io.opentelemetry.sdk.resources.Resource;

/** {@link ResourceProvider} for automatically configuring {@link ResourceProvider}. */
@AutoService(ResourceProvider.class)
public class ContainerResourceProvider implements ResourceProvider {
@Override
public Resource createResource(ConfigProperties config) {
return ContainerResource.get();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/

package io.opentelemetry.instrumentation.resources;

import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.common.AttributesBuilder;
import io.opentelemetry.sdk.resources.Resource;
import io.opentelemetry.semconv.resource.attributes.ResourceAttributes;
import java.net.InetAddress;
import java.net.UnknownHostException;

/** Factory for a {@link Resource} which provides information about the host info. */
public final class HostResource {

private static final Resource INSTANCE = buildResource();

/** Returns a {@link Resource} which provides information about host. */
public static Resource get() {
return INSTANCE;
}

// Visible for testing
static Resource buildResource() {
AttributesBuilder attributes = Attributes.builder();
try {
attributes.put(ResourceAttributes.HOST_NAME, InetAddress.getLocalHost().getHostName());
} catch (UnknownHostException e) {
// Ignore
}
String hostArch = null;
try {
hostArch = System.getProperty("os.arch");
} catch (SecurityException t) {
// Ignore
}
if (hostArch != null) {
attributes.put(ResourceAttributes.HOST_ARCH, hostArch);
}

return Resource.create(attributes.build(), ResourceAttributes.SCHEMA_URL);
}

private HostResource() {}
}
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 com.google.auto.service.AutoService;
import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties;
import io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider;
import io.opentelemetry.sdk.resources.Resource;

/** {@link ResourceProvider} for automatically configuring {@link HostResource}. */
@AutoService(ResourceProvider.class)
public final class HostResourceProvider implements ResourceProvider {
@Override
public Resource createResource(ConfigProperties config) {
return HostResource.get();
}
}
Loading

0 comments on commit cb6bf90

Please sign in to comment.