Search in sources :

Example 1 with AutoConfiguredOpenTelemetrySdk

use of io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk in project opentelemetry-java-instrumentation by open-telemetry.

the class AgentInstaller method installBytebuddyAgent.

/**
 * Install the core bytebuddy agent along with all implementations of {@link
 * InstrumentationModule}.
 *
 * @param inst Java Instrumentation used to install bytebuddy
 * @return the agent's class transformer
 */
public static ResettableClassFileTransformer installBytebuddyAgent(Instrumentation inst, Iterable<AgentListener> agentListeners) {
    WeakRefAsyncOperationEndStrategies.initialize();
    Config config = Config.get();
    setBootstrapPackages(config);
    // If noop OpenTelemetry is enabled, autoConfiguredSdk will be null and AgentListeners are not
    // called
    AutoConfiguredOpenTelemetrySdk autoConfiguredSdk = null;
    if (config.getBoolean(JAVAAGENT_NOOP_CONFIG, false)) {
        logger.info("Tracing and metrics are disabled because noop is enabled.");
        GlobalOpenTelemetry.set(NoopOpenTelemetry.getInstance());
    } else {
        autoConfiguredSdk = installOpenTelemetrySdk(config);
    }
    if (autoConfiguredSdk != null) {
        runBeforeAgentListeners(agentListeners, config, autoConfiguredSdk);
    }
    AgentBuilder agentBuilder = new AgentBuilder.Default().disableClassFormatChanges().with(AgentBuilder.RedefinitionStrategy.RETRANSFORMATION).with(new RedefinitionDiscoveryStrategy()).with(AgentBuilder.DescriptionStrategy.Default.POOL_ONLY).with(AgentTooling.poolStrategy()).with(new ClassLoadListener()).with(AgentTooling.locationStrategy(Utils.getBootstrapProxy()));
    if (JavaModule.isSupported()) {
        agentBuilder = agentBuilder.with(new ExposeAgentBootstrapListener(inst));
    }
    agentBuilder = configureIgnoredTypes(config, agentBuilder);
    if (logger.isDebugEnabled()) {
        agentBuilder = agentBuilder.with(AgentBuilder.RedefinitionStrategy.RETRANSFORMATION).with(new RedefinitionDiscoveryStrategy()).with(new RedefinitionLoggingListener()).with(new TransformLoggingListener());
    }
    int numberOfLoadedExtensions = 0;
    for (AgentExtension agentExtension : loadOrdered(AgentExtension.class)) {
        logger.debug("Loading extension {} [class {}]", agentExtension.extensionName(), agentExtension.getClass().getName());
        try {
            agentBuilder = agentExtension.extend(agentBuilder);
            numberOfLoadedExtensions++;
        } catch (Exception | LinkageError e) {
            logger.error("Unable to load extension {} [class {}]", agentExtension.extensionName(), agentExtension.getClass().getName(), e);
        }
    }
    logger.debug("Installed {} extension(s)", numberOfLoadedExtensions);
    ResettableClassFileTransformer resettableClassFileTransformer = agentBuilder.installOn(inst);
    ClassFileTransformerHolder.setClassFileTransformer(resettableClassFileTransformer);
    if (autoConfiguredSdk != null) {
        runAfterAgentListeners(agentListeners, config, autoConfiguredSdk);
    }
    return resettableClassFileTransformer;
}
Also used : Config(io.opentelemetry.instrumentation.api.config.Config) AutoConfiguredOpenTelemetrySdk(io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk) AgentBuilder(net.bytebuddy.agent.builder.AgentBuilder) ResettableClassFileTransformer(net.bytebuddy.agent.builder.ResettableClassFileTransformer)

Example 2 with AutoConfiguredOpenTelemetrySdk

use of io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk in project opentelemetry-java-instrumentation by open-telemetry.

the class OpenTelemetryInstaller method installOpenTelemetrySdk.

/**
 * Install the {@link OpenTelemetrySdk} using autoconfigure, and return the {@link
 * AutoConfiguredOpenTelemetrySdk}.
 *
 * @return the {@link AutoConfiguredOpenTelemetrySdk}
 */
static AutoConfiguredOpenTelemetrySdk installOpenTelemetrySdk(Config config) {
    System.setProperty("io.opentelemetry.context.contextStorageProvider", "default");
    AutoConfiguredOpenTelemetrySdkBuilder builder = AutoConfiguredOpenTelemetrySdk.builder().setResultAsGlobal(true).addPropertiesSupplier(config::getAllProperties);
    ClassLoader classLoader = AgentInitializer.getExtensionsClassLoader();
    if (classLoader != null) {
        // May be null in unit tests.
        builder.setServiceClassLoader(classLoader);
    }
    AutoConfiguredOpenTelemetrySdk autoConfiguredSdk = builder.build();
    OpenTelemetrySdk sdk = autoConfiguredSdk.getOpenTelemetrySdk();
    OpenTelemetrySdkAccess.internalSetForceFlush((timeout, unit) -> {
        CompletableResultCode traceResult = sdk.getSdkTracerProvider().forceFlush();
        CompletableResultCode metricsResult = sdk.getSdkMeterProvider().forceFlush();
        CompletableResultCode.ofAll(Arrays.asList(traceResult, metricsResult)).join(timeout, unit);
    });
    SdkLogEmitterProvider sdkLogEmitterProvider = autoConfiguredSdk.getOpenTelemetrySdk().getSdkLogEmitterProvider();
    LogEmitterProvider logEmitterProvider = DelegatingLogEmitterProvider.from(sdkLogEmitterProvider);
    AgentLogEmitterProvider.set(logEmitterProvider);
    return autoConfiguredSdk;
}
Also used : AutoConfiguredOpenTelemetrySdkBuilder(io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdkBuilder) AgentLogEmitterProvider(io.opentelemetry.javaagent.instrumentation.api.appender.internal.AgentLogEmitterProvider) DelegatingLogEmitterProvider(io.opentelemetry.instrumentation.sdk.appender.internal.DelegatingLogEmitterProvider) SdkLogEmitterProvider(io.opentelemetry.sdk.logs.SdkLogEmitterProvider) LogEmitterProvider(io.opentelemetry.instrumentation.api.appender.internal.LogEmitterProvider) CompletableResultCode(io.opentelemetry.sdk.common.CompletableResultCode) AutoConfiguredOpenTelemetrySdk(io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk) SdkLogEmitterProvider(io.opentelemetry.sdk.logs.SdkLogEmitterProvider) AutoConfiguredOpenTelemetrySdk(io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk) OpenTelemetrySdk(io.opentelemetry.sdk.OpenTelemetrySdk)

Example 3 with AutoConfiguredOpenTelemetrySdk

use of io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk in project opentelemetry-plugin by jenkinsci.

the class OpenTelemetrySdkProvider method initialize.

public void initialize(@Nonnull OpenTelemetryConfiguration configuration) {
    // shutdown existing SDK
    preDestroy();
    AutoConfiguredOpenTelemetrySdkBuilder sdkBuilder = AutoConfiguredOpenTelemetrySdk.builder();
    // PROPERTIES
    sdkBuilder.addPropertiesSupplier(() -> configuration.toOpenTelemetryProperties());
    // RESOURCE
    sdkBuilder.addResourceCustomizer((resource, configProperties) -> {
        ResourceBuilder resourceBuilder = Resource.builder().putAll(resource).putAll(configuration.toOpenTelemetryResource());
        return resourceBuilder.build();
    });
    sdkBuilder.registerShutdownHook(// SDK closed by io.jenkins.plugins.opentelemetry.OpenTelemetrySdkProvider.preDestroy()
    false).setResultAsGlobal(// ensure GlobalOpenTelemetry.set() is invoked
    true);
    AutoConfiguredOpenTelemetrySdk autoConfiguredOpenTelemetrySdk = sdkBuilder.build();
    this.openTelemetrySdk = autoConfiguredOpenTelemetrySdk.getOpenTelemetrySdk();
    this.resource = autoConfiguredOpenTelemetrySdk.getResource();
    this.config = autoConfiguredOpenTelemetrySdk.getConfig();
    this.openTelemetry = this.openTelemetrySdk;
    this.tracer.setDelegate(openTelemetry.getTracer(GlobalOpenTelemetrySdk.INSTRUMENTATION_NAME, OtelUtils.getOpentelemetryPluginVersion()));
    this.logEmitter = openTelemetrySdk.getSdkLogEmitterProvider().get(GlobalOpenTelemetrySdk.INSTRUMENTATION_NAME);
    this.meter = openTelemetry.getMeterProvider().get(GlobalOpenTelemetrySdk.INSTRUMENTATION_NAME);
    LOGGER.log(Level.INFO, () -> "OpenTelemetry SDK initialized: " + OtelUtils.prettyPrintOtelSdkConfig(autoConfiguredOpenTelemetrySdk));
}
Also used : AutoConfiguredOpenTelemetrySdkBuilder(io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdkBuilder) ResourceBuilder(io.opentelemetry.sdk.resources.ResourceBuilder) AutoConfiguredOpenTelemetrySdk(io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk)

Example 4 with AutoConfiguredOpenTelemetrySdk

use of io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk in project splunk-otel-java by signalfx.

the class TestMicrometerInstaller method beforeAgent.

@Override
public void beforeAgent(Config config, AutoConfiguredOpenTelemetrySdk autoConfiguredOpenTelemetrySdk) {
    Tags globalMetricsTags = config.getMap("splunk.testing.metrics.global-tags", emptyMap()).entrySet().stream().map(e -> Tag.of(e.getKey(), e.getValue())).reduce(Tags.empty(), Tags::and, Tags::concat);
    SimpleMeterRegistry registry = new SimpleMeterRegistry();
    registry.config().meterFilter(MeterFilter.commonTags(globalMetricsTags));
    Metrics.addRegistry(registry);
}
Also used : MeterFilter(io.micrometer.core.instrument.config.MeterFilter) Config(io.opentelemetry.instrumentation.api.config.Config) Collections.emptyMap(java.util.Collections.emptyMap) Tag(io.micrometer.core.instrument.Tag) Tags(io.micrometer.core.instrument.Tags) SimpleMeterRegistry(io.micrometer.core.instrument.simple.SimpleMeterRegistry) AutoConfiguredOpenTelemetrySdk(io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk) AutoService(com.google.auto.service.AutoService) AgentListener(io.opentelemetry.javaagent.extension.AgentListener) Metrics(io.micrometer.core.instrument.Metrics) SimpleMeterRegistry(io.micrometer.core.instrument.simple.SimpleMeterRegistry) Tags(io.micrometer.core.instrument.Tags)

Example 5 with AutoConfiguredOpenTelemetrySdk

use of io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk in project opentelemetry-plugin by jenkinsci.

the class OpenTelemetryLogToElasticsearchIT method test.

@Test
public void test() throws Exception {
    InputStream envAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(".env");
    Assert.assertNotNull(".env file not found in classpath", envAsStream);
    Properties env = new Properties();
    env.load(envAsStream);
    Map<String, String> configuration = new HashMap<>();
    env.forEach((k, v) -> configuration.put(k.toString(), v.toString()));
    configuration.put("otel.traces.exporter", "otlp");
    configuration.put("otel.metrics.exporter", "otlp");
    configuration.put("otel.logs.exporter", "otlp");
    final int LOG_MESSAGE_COUNT = 100;
    String traceId;
    // PRODUCE OPEN TELEMETRY LOG MESSAGES
    {
        AutoConfiguredOpenTelemetrySdk autoConfiguredOpenTelemetrySdk = AutoConfiguredOpenTelemetrySdk.builder().addPropertiesSupplier(() -> configuration).build();
        try {
            OpenTelemetrySdk sdk = autoConfiguredOpenTelemetrySdk.getOpenTelemetrySdk();
            Tracer tracer = sdk.getTracer("test");
            LogEmitter logEmitter = sdk.getSdkLogEmitterProvider().get("test");
            Span span = tracer.spanBuilder("my-test-pipeline").startSpan();
            try (Scope scope = span.makeCurrent()) {
                for (int i = 0; i < LOG_MESSAGE_COUNT; i++) {
                    logEmitter.logBuilder().setContext(Context.current()).setBody("Log Message " + i).setAttributes(Attributes.of(AttributeKey.stringKey("myStringAttribute"), "Value " + i, AttributeKey.longKey("myNumericAttribute"), (long) i)).emit();
                    Thread.sleep(RANDOM.nextInt(100));
                }
            } finally {
                span.end();
            }
            traceId = span.getSpanContext().getTraceId();
        } finally {
            autoConfiguredOpenTelemetrySdk.getOpenTelemetrySdk().getSdkLogEmitterProvider().close();
            autoConfiguredOpenTelemetrySdk.getOpenTelemetrySdk().getSdkTracerProvider().close();
        }
    }
    Thread.sleep(3_000);
    // VERIFY LOG MESSAGES IN ELASTICSEARCH
    {
        String elasticsearchUrl = configuration.get("elasticsearch.url");
        String elasticsearchUsername = configuration.get("elasticsearch.username");
        String elasticsearchPassword = configuration.get("elasticsearch.password");
        BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(elasticsearchUsername, elasticsearchPassword));
        RestClient restClient = RestClient.builder(HttpHost.create(elasticsearchUrl)).setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)).build();
        RestClientTransport elasticsearchTransport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient elasticsearchClient = new ElasticsearchClient(elasticsearchTransport);
        SearchRequest searchRequest = new SearchRequest.Builder().index("logs-apm.app-*").size(500).sort(s -> s.field(f -> f.field("@timestamp").order(SortOrder.Asc))).query(q -> q.match(m -> m.field("trace.id").query(FieldValue.of(traceId)))).build();
        SearchResponse<ObjectNode> searchResponse = elasticsearchClient.search(searchRequest, ObjectNode.class);
        List<Hit<ObjectNode>> hits = searchResponse.hits().hits();
        if (hits.size() != LOG_MESSAGE_COUNT) {
            System.err.println("Invalid number of log messages: actual: " + hits.size() + ", expected: " + LOG_MESSAGE_COUNT);
        }
        for (Hit<ObjectNode> hit : hits) {
            ObjectNode source = hit.source();
            ObjectNode labels = (ObjectNode) source.findValue("labels");
            ObjectNode numericLabels = (ObjectNode) source.findValue("numeric_labels");
            try {
                String message = source.findValue("message").asText();
                String myStringAttribute = labels.findValue("myStringAttribute").asText();
                long myNumericAttribute = numericLabels.findValue("myNumericAttribute").longValue();
                System.out.println(hit.id() + "\tmessage:'" + message + "', \tmyStringAttribute: '" + myStringAttribute + "', myNumericAttribute: " + myNumericAttribute);
            } catch (Exception e) {
                System.err.println("Error parsing " + source);
            }
        }
    }
}
Also used : RestClientTransport(co.elastic.clients.transport.rest_client.RestClientTransport) RestClient(org.elasticsearch.client.RestClient) SearchRequest(co.elastic.clients.elasticsearch.core.SearchRequest) SearchResponse(co.elastic.clients.elasticsearch.core.SearchResponse) OpenTelemetrySdk(io.opentelemetry.sdk.OpenTelemetrySdk) Attributes(io.opentelemetry.api.common.Attributes) HashMap(java.util.HashMap) Random(java.util.Random) Tracer(io.opentelemetry.api.trace.Tracer) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) AutoConfiguredOpenTelemetrySdk(io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk) Map(java.util.Map) FieldValue(co.elastic.clients.elasticsearch._types.FieldValue) Context(io.opentelemetry.context.Context) Properties(java.util.Properties) SortOrder(co.elastic.clients.elasticsearch._types.SortOrder) Span(io.opentelemetry.api.trace.Span) Scope(io.opentelemetry.context.Scope) Test(org.junit.Test) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) Hit(co.elastic.clients.elasticsearch.core.search.Hit) List(java.util.List) AuthScope(org.apache.http.auth.AuthScope) AttributeKey(io.opentelemetry.api.common.AttributeKey) ElasticsearchClient(co.elastic.clients.elasticsearch.ElasticsearchClient) LogEmitter(io.opentelemetry.sdk.logs.LogEmitter) Assert(org.junit.Assert) HttpHost(org.apache.http.HttpHost) JacksonJsonpMapper(co.elastic.clients.json.jackson.JacksonJsonpMapper) InputStream(java.io.InputStream) SearchRequest(co.elastic.clients.elasticsearch.core.SearchRequest) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HashMap(java.util.HashMap) Properties(java.util.Properties) Span(io.opentelemetry.api.trace.Span) RestClientTransport(co.elastic.clients.transport.rest_client.RestClientTransport) List(java.util.List) ElasticsearchClient(co.elastic.clients.elasticsearch.ElasticsearchClient) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) InputStream(java.io.InputStream) Tracer(io.opentelemetry.api.trace.Tracer) RestClient(org.elasticsearch.client.RestClient) JacksonJsonpMapper(co.elastic.clients.json.jackson.JacksonJsonpMapper) AutoConfiguredOpenTelemetrySdk(io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) SearchResponse(co.elastic.clients.elasticsearch.core.SearchResponse) Hit(co.elastic.clients.elasticsearch.core.search.Hit) Scope(io.opentelemetry.context.Scope) AuthScope(org.apache.http.auth.AuthScope) LogEmitter(io.opentelemetry.sdk.logs.LogEmitter) OpenTelemetrySdk(io.opentelemetry.sdk.OpenTelemetrySdk) AutoConfiguredOpenTelemetrySdk(io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk) Test(org.junit.Test)

Aggregations

AutoConfiguredOpenTelemetrySdk (io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk)7 Config (io.opentelemetry.instrumentation.api.config.Config)2 OpenTelemetrySdk (io.opentelemetry.sdk.OpenTelemetrySdk)2 AutoConfiguredOpenTelemetrySdkBuilder (io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdkBuilder)2 ElasticsearchClient (co.elastic.clients.elasticsearch.ElasticsearchClient)1 FieldValue (co.elastic.clients.elasticsearch._types.FieldValue)1 SortOrder (co.elastic.clients.elasticsearch._types.SortOrder)1 SearchRequest (co.elastic.clients.elasticsearch.core.SearchRequest)1 SearchResponse (co.elastic.clients.elasticsearch.core.SearchResponse)1 Hit (co.elastic.clients.elasticsearch.core.search.Hit)1 JacksonJsonpMapper (co.elastic.clients.json.jackson.JacksonJsonpMapper)1 RestClientTransport (co.elastic.clients.transport.rest_client.RestClientTransport)1 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)1 AutoService (com.google.auto.service.AutoService)1 Metrics (io.micrometer.core.instrument.Metrics)1 Tag (io.micrometer.core.instrument.Tag)1 Tags (io.micrometer.core.instrument.Tags)1 MeterFilter (io.micrometer.core.instrument.config.MeterFilter)1 SimpleMeterRegistry (io.micrometer.core.instrument.simple.SimpleMeterRegistry)1 AttributeKey (io.opentelemetry.api.common.AttributeKey)1