Skip to content
Closed
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
4 changes: 4 additions & 0 deletions custom/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,10 @@ dependencies {
compileOnly("io.opentelemetry.semconv:opentelemetry-semconv")
compileOnly("io.opentelemetry.semconv:opentelemetry-semconv-incubating")
compileOnly("io.opentelemetry.instrumentation:opentelemetry-instrumentation-api")
compileOnly("io.opentelemetry.instrumentation:opentelemetry-instrumentation-api-incubator")
compileOnly("io.opentelemetry.instrumentation:opentelemetry-resources")
compileOnly("io.opentelemetry.instrumentation:opentelemetry-declarative-config-bridge")
compileOnly("io.opentelemetry.instrumentation:opentelemetry-jmx-metrics")
compileOnly("io.opentelemetry.javaagent:opentelemetry-javaagent-extension-api")
compileOnly("io.opentelemetry.javaagent:opentelemetry-javaagent-tooling")
compileOnly("io.opentelemetry.javaagent:opentelemetry-javaagent-internal-logging-simple")
Expand All @@ -31,7 +33,9 @@ dependencies {
testImplementation("io.opentelemetry:opentelemetry-sdk-extension-declarative-config")
testImplementation("io.opentelemetry.semconv:opentelemetry-semconv")
testImplementation("io.opentelemetry.instrumentation:opentelemetry-instrumentation-api")
testImplementation("io.opentelemetry.instrumentation:opentelemetry-instrumentation-api-incubator")
testImplementation("io.opentelemetry.instrumentation:opentelemetry-resources")
testImplementation("io.opentelemetry.instrumentation:opentelemetry-jmx-metrics")
testImplementation("io.opentelemetry.javaagent:opentelemetry-javaagent-extension-api")
testImplementation("io.opentelemetry.javaagent:opentelemetry-javaagent-tooling")
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
/*
* Copyright Splunk Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.splunk.opentelemetry.jmx;

import static java.util.Objects.requireNonNull;

import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.incubator.config.DeclarativeConfigProperties;
import io.opentelemetry.sdk.autoconfigure.declarativeconfig.DeclarativeConfiguration;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import javax.annotation.Nullable;

/** Owns distribution JMX collection across startup and synchronous remote configuration updates. */
public class JmxMetricInsightSupervisor implements AutoCloseable {
private static final AtomicReference<JmxMetricInsightSupervisor> agentInstance =
new AtomicReference<>();

private final JmxMetricsService metricsService;
@Nullable private Map<String, Object> configuration;
private boolean running;
private boolean closed;

/**
* Creates an independent supervisor. A null startup configuration leaves JMX unmanaged and
* rejects remote updates, preserving startup disablement and upstream ownership.
*/
public JmxMetricInsightSupervisor(
OpenTelemetry openTelemetry, @Nullable DeclarativeConfigProperties startupConfiguration) {
this(new JmxMetricsService(openTelemetry), startupConfiguration);
}

JmxMetricInsightSupervisor(
JmxMetricsService metricsService,
@Nullable DeclarativeConfigProperties startupConfiguration) {
this.metricsService = requireNonNull(metricsService, "metricsService");
configuration =
startupConfiguration == null
? null
: DeclarativeConfigProperties.toMap(startupConfiguration);
}

static JmxMetricInsightSupervisor initialize(
OpenTelemetry openTelemetry, @Nullable DeclarativeConfigProperties startupConfiguration) {
JmxMetricInsightSupervisor supervisor =
new JmxMetricInsightSupervisor(openTelemetry, startupConfiguration);
if (!agentInstance.compareAndSet(null, supervisor)) {
throw new IllegalStateException("JMX supervisor is already initialized");
}
return supervisor;
}

/** Returns the supervisor published by the JMX startup listener before OpAMP starts. */
public static JmxMetricInsightSupervisor getInstance() {
JmxMetricInsightSupervisor supervisor = agentInstance.get();
if (supervisor == null) {
throw new IllegalStateException("JMX supervisor is not initialized");
}
return supervisor;
}

/** Starts the configured collection, if distribution-owned JMX was enabled at startup. */
public synchronized void start() {
checkOpen();
if (configuration != null) {
running = metricsService.start(DeclarativeConfiguration.toConfigProperties(configuration));
}
}

/**
* Replaces the current configuration with a complete {@code distribution.splunk.java.jmx} node.
* Omitted settings use their defaults; an empty node resets collection to defaults. Identical
* configurations leave the running collection alone. Invalid rules leave the previous collection
* active and propagate to the remote processor so it can report failure.
*/
public synchronized void applyConfiguration(DeclarativeConfigProperties update) throws Exception {
checkOpen();
if (configuration == null) {
throw new IllegalStateException(
"Remote JMX updates require distribution.splunk.java.jmx to be enabled at agent startup");
}

Map<String, Object> updated =
DeclarativeConfigProperties.toMap(requireNonNull(update, "update"));
if (running && configuration.equals(updated)) {
return;
}

try {
metricsService.reconfigure(DeclarativeConfiguration.toConfigProperties(updated));
} catch (Exception e) {
// Validation failures keep the old collection; a failure after stopping it does not.
// Track the actual state so a later retry is not mistaken for an unchanged active config.
running = metricsService.isRunning();
throw e;
}
configuration = updated;
running = true;
}

@Override
public synchronized void close() throws Exception {
if (closed) {
return;
}
try {
metricsService.close();
} finally {
running = false;
closed = true;
agentInstance.compareAndSet(this, null);
}
}

private void checkOpen() {
if (closed) {
throw new IllegalStateException("JMX supervisor is closed");
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
/*
* Copyright Splunk Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.splunk.opentelemetry.jmx;

import com.google.auto.service.AutoService;
import io.opentelemetry.api.incubator.config.DeclarativeConfigProperties;
import io.opentelemetry.sdk.autoconfigure.declarativeconfig.DeclarativeConfiguration;
import io.opentelemetry.sdk.autoconfigure.declarativeconfig.DeclarativeConfigurationCustomizer;
import io.opentelemetry.sdk.autoconfigure.declarativeconfig.DeclarativeConfigurationCustomizerProvider;
import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalInstrumentationModel;
import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalLanguageSpecificInstrumentationPropertyModel;
import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.OpenTelemetryConfigurationModelAccessor;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.logging.Logger;
import javax.annotation.Nullable;

/**
* Merges and captures JMX settings after other model customizations.
*
* <p>{@link JmxUpstreamDisablingCustomizerProvider} handles upstream disablement earlier because
* upstream snapshots enablement before the model is fully customized. Keeping the merge here
* preserves subsequent changes to either JMX node, including replacement of the model itself. The
* instrumentation node stays intact; upstream disablement prevents duplicate collection. Both
* providers are temporary until upstream supports inline JMX rules.
*/
@AutoService(DeclarativeConfigurationCustomizerProvider.class)
public class JmxMetricsConfigurationCustomizerProvider
implements DeclarativeConfigurationCustomizerProvider {
private static final Logger logger =
Logger.getLogger(JmxMetricsConfigurationCustomizerProvider.class.getName());

// Null means there is no enabled distribution-owned collection to start.
@Nullable private static volatile DeclarativeConfigProperties jmxConfig;

@Override
public void customize(DeclarativeConfigurationCustomizer customizer) {
customizer.addModelCustomizer(model -> {
jmxConfig = null;
// Only take ownership if the early provider disabled upstream before its snapshot.
// In particular, a distribution JMX node added too late must not start a second collector.
Boolean enabled = JmxUpstreamDisablingCustomizerProvider.getOriginalJmxEnabled();
if (enabled == null || model.getDistribution() == null) {
return model;
}
DeclarativeConfigProperties distribution =
DeclarativeConfiguration.toConfigProperties(model.getDistribution());
DeclarativeConfigProperties splunkJava = distribution.get("splunk").get("java");
if (!splunkJava.getPropertyKeys().contains("jmx")) {
return model;
}

Map<String, Object> upstreamConfig = Collections.emptyMap();
ExperimentalInstrumentationModel instrumentationModel =
OpenTelemetryConfigurationModelAccessor.getInstrumentation(model);
if (instrumentationModel != null
&& instrumentationModel.getJava() != null
&& instrumentationModel.getJava().getAdditionalProperties().containsKey("jmx")) {
ExperimentalLanguageSpecificInstrumentationPropertyModel upstream =
instrumentationModel.getJava().getAdditionalProperties().get("jmx");
if (upstream != null) {
upstreamConfig = upstream.getAdditionalProperties();
}
logger.fine(
"Merging instrumentation/development.java.jmx into distribution.splunk.java.jmx");
}

Map<String, Object> merged =
merge(upstreamConfig, DeclarativeConfigProperties.toMap(splunkJava.get("jmx")));
Map<String, Object> javaConfig = DeclarativeConfigProperties.toMap(splunkJava);
javaConfig.put("jmx", merged);
Map<String, Object> splunkConfig =
DeclarativeConfigProperties.toMap(distribution.get("splunk"));
splunkConfig.put("java", javaConfig);
model.getDistribution().setExtensionProperty("splunk", splunkConfig);

// Use the original decision, not the disabled: [jmx] injected for the upstream collector.
if (enabled) {
jmxConfig = DeclarativeConfiguration.toConfigProperties(merged);
}
return model;
});
}

@Override
public int order() {
// Merge after ordinary customizations. Reserve Integer.MAX_VALUE for final model capture,
// including the OpAMP DeclarativeConfigurationInterceptor.
return Integer.MAX_VALUE - 1;
}

@Nullable
static DeclarativeConfigProperties getJmxConfig() {
return jmxConfig;
}

@SuppressWarnings("unchecked")
private static Map<String, Object> merge(
Map<String, Object> defaults, Map<String, Object> overrides) {
Map<String, Object> result = new LinkedHashMap<>(defaults);
overrides.forEach((key, value) -> {
result.compute(
key,
(k, previous) -> previous instanceof Map && value instanceof Map
? merge((Map<String, Object>) previous, (Map<String, Object>) value)
: value);
});
return result;
}
}
Loading
Loading