diff --git a/custom/build.gradle.kts b/custom/build.gradle.kts index cf1d8614e..3122383ab 100644 --- a/custom/build.gradle.kts +++ b/custom/build.gradle.kts @@ -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") @@ -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") } diff --git a/custom/src/main/java/com/splunk/opentelemetry/jmx/JmxMetricInsightSupervisor.java b/custom/src/main/java/com/splunk/opentelemetry/jmx/JmxMetricInsightSupervisor.java new file mode 100644 index 000000000..f5380e146 --- /dev/null +++ b/custom/src/main/java/com/splunk/opentelemetry/jmx/JmxMetricInsightSupervisor.java @@ -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 agentInstance = + new AtomicReference<>(); + + private final JmxMetricsService metricsService; + @Nullable private Map 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 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"); + } + } +} diff --git a/custom/src/main/java/com/splunk/opentelemetry/jmx/JmxMetricsConfigurationCustomizerProvider.java b/custom/src/main/java/com/splunk/opentelemetry/jmx/JmxMetricsConfigurationCustomizerProvider.java new file mode 100644 index 000000000..def7d02b6 --- /dev/null +++ b/custom/src/main/java/com/splunk/opentelemetry/jmx/JmxMetricsConfigurationCustomizerProvider.java @@ -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. + * + *

{@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 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 merged = + merge(upstreamConfig, DeclarativeConfigProperties.toMap(splunkJava.get("jmx"))); + Map javaConfig = DeclarativeConfigProperties.toMap(splunkJava); + javaConfig.put("jmx", merged); + Map 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 merge( + Map defaults, Map overrides) { + Map result = new LinkedHashMap<>(defaults); + overrides.forEach((key, value) -> { + result.compute( + key, + (k, previous) -> previous instanceof Map && value instanceof Map + ? merge((Map) previous, (Map) value) + : value); + }); + return result; + } +} diff --git a/custom/src/main/java/com/splunk/opentelemetry/jmx/JmxMetricsService.java b/custom/src/main/java/com/splunk/opentelemetry/jmx/JmxMetricsService.java new file mode 100644 index 000000000..98efdf880 --- /dev/null +++ b/custom/src/main/java/com/splunk/opentelemetry/jmx/JmxMetricsService.java @@ -0,0 +1,135 @@ +/* + * 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.Collections.emptyList; +import static java.util.Collections.singletonMap; +import static java.util.Objects.requireNonNull; +import static java.util.stream.Collectors.toList; + +import io.opentelemetry.api.OpenTelemetry; +import io.opentelemetry.api.common.KeyValue; +import io.opentelemetry.api.common.Value; +import io.opentelemetry.api.incubator.config.DeclarativeConfigProperties; +import io.opentelemetry.instrumentation.jmx.JmxTelemetry; +import io.opentelemetry.instrumentation.jmx.JmxTelemetryBuilder; +import java.io.ByteArrayInputStream; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; + +/** Collects distribution-configured JMX metrics using an existing SDK, independently of startup. */ +public final class JmxMetricsService implements AutoCloseable { + private final OpenTelemetry openTelemetry; + private AutoCloseable collection; + + public JmxMetricsService(OpenTelemetry openTelemetry) { + this.openTelemetry = requireNonNull(openTelemetry, "openTelemetry"); + } + + /** + * Parses inline rules and starts local collection through the supplied SDK's metric readers. + * + *

Repeated calls while running leave the current collection unchanged. Close this service + * before starting it with different rules. The caller owns its lifecycle, including shutdown. + * + * @param jmxConfig the {@code distribution.splunk.java.jmx} node containing upstream JMX settings + * and optional inline {@code rules} + * @return whether collection is running + * @throws IllegalArgumentException if the rules or settings are invalid + */ + public synchronized boolean start(DeclarativeConfigProperties jmxConfig) { + if (collection != null) { + return true; + } + + collection = createTelemetry(jmxConfig).start(); + return true; + } + + /** Validates replacement settings before stopping the current collection. */ + synchronized void reconfigure(DeclarativeConfigProperties jmxConfig) throws Exception { + JmxTelemetry telemetry = createTelemetry(jmxConfig); + close(); + collection = telemetry.start(); + } + + synchronized boolean isRunning() { + return collection != null; + } + + private JmxTelemetry createTelemetry(DeclarativeConfigProperties jmxConfig) { + JmxTelemetryBuilder builder = UpstreamJmxConfiguration.createBuilder(openTelemetry, jmxConfig); + + List rules = jmxConfig.getStructuredList("rules", emptyList()); + if (!rules.isEmpty()) { + // TODO: Upstream builder change to accept parsed DeclarativeConfigProperties as well. + // It could be then: builder.addRules(DeclarativeConfigProperties.toMap(jmxConfig)); + + List> ruleMaps = + rules.stream().map(DeclarativeConfigProperties::toMap).collect(toList()); + // JSON is valid YAML; use the existing OpenTelemetry API to encode it for the upstream + // parser. + String json = toValue(singletonMap("rules", ruleMaps)).asString(); + builder.addRules(new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8))); + } + + return builder.build(); + } + + /** Stops discovery and unregisters metric callbacks. May be called more than once. */ + @Override + public synchronized void close() throws Exception { + if (collection != null) { + try { + collection.close(); + } finally { + collection = null; + } + } + } + + private static Value toValue(Object value) { + if (value == null) { + return Value.empty(); + } + if (value instanceof String) { + return Value.of((String) value); + } + if (value instanceof Boolean) { + return Value.of((Boolean) value); + } + if (value instanceof Long) { + return Value.of((Long) value); + } + if (value instanceof Double) { + return Value.of((Double) value); + } + if (value instanceof List) { + return Value.of(((List) value).stream().map(JmxMetricsService::toValue).collect(toList())); + } + if (value instanceof Map) { + return Value.of( + ((Map) value) + .entrySet().stream() + .map(entry -> KeyValue.of((String) entry.getKey(), toValue(entry.getValue()))) + .toArray(KeyValue[]::new)); + } + throw new IllegalArgumentException( + "Unsupported JMX rule value type: " + value.getClass().getName()); + } +} diff --git a/custom/src/main/java/com/splunk/opentelemetry/jmx/JmxUpstreamDisablingCustomizerProvider.java b/custom/src/main/java/com/splunk/opentelemetry/jmx/JmxUpstreamDisablingCustomizerProvider.java new file mode 100644 index 000000000..5e36b3922 --- /dev/null +++ b/custom/src/main/java/com/splunk/opentelemetry/jmx/JmxUpstreamDisablingCustomizerProvider.java @@ -0,0 +1,104 @@ +/* + * 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.Collections.emptyList; + +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 java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.logging.Logger; +import javax.annotation.Nullable; + +/** + * Reserves distribution-owned JMX collection before upstream snapshots instrumentation enablement. + * + *

The JMX settings stay in place so other model customizers can modify them before {@link + * JmxMetricsConfigurationCustomizerProvider} merges them. Both providers are temporary until + * upstream supports inline JMX rules. + */ +@AutoService(DeclarativeConfigurationCustomizerProvider.class) +public class JmxUpstreamDisablingCustomizerProvider + implements DeclarativeConfigurationCustomizerProvider { + private static final Logger logger = + Logger.getLogger(JmxUpstreamDisablingCustomizerProvider.class.getName()); + + // Null means upstream retains ownership. Otherwise preserve the user's enablement decision + // before injecting disabled: [jmx], which is only intended to stop the upstream collector. + @Nullable private static volatile Boolean originalJmxEnabled; + + @Override + public void customize(DeclarativeConfigurationCustomizer customizer) { + customizer.addModelCustomizer(model -> { + originalJmxEnabled = null; + if (model.getDistribution() == null) { + return model; + } + DeclarativeConfigProperties distribution = + DeclarativeConfiguration.toConfigProperties(model.getDistribution()); + if (!distribution.get("splunk").get("java").getPropertyKeys().contains("jmx")) { + return model; + } + + DeclarativeConfigProperties instrumentation = + distribution.get("javaagent").get("instrumentation"); + boolean enabled = isJmxEnabled(instrumentation); + + // Explicit disablement prevents upstream from starting even with default rules. + // Both JMX nodes stay intact for other customizers and the late merge. + Map agentInstrumentation = DeclarativeConfigProperties.toMap(instrumentation); + List disabled = + new ArrayList<>(instrumentation.getScalarList("disabled", String.class, emptyList())); + if (!disabled.contains("jmx")) { + disabled.add("jmx"); + } + agentInstrumentation.put("disabled", disabled); + Map javaagent = + DeclarativeConfigProperties.toMap(distribution.get("javaagent")); + javaagent.put("instrumentation", agentInstrumentation); + model.getDistribution().setExtensionProperty("javaagent", javaagent); + originalJmxEnabled = enabled; + logger.info("Using distribution.splunk.java.jmx; upstream JMX instrumentation is disabled"); + return model; + }); + } + + @Override + public int order() { + // JavaagentDistributionAccessCustomizerProvider (order 0) copies the enablement settings into + // AgentDistributionConfig. Changing the model after that cannot disable upstream JMX. + return -1; + } + + @Nullable + static Boolean getOriginalJmxEnabled() { + return originalJmxEnabled; + } + + private static boolean isJmxEnabled(DeclarativeConfigProperties instrumentation) { + if (instrumentation.getScalarList("disabled", String.class, emptyList()).contains("jmx")) { + return false; + } + return instrumentation.getScalarList("enabled", String.class, emptyList()).contains("jmx") + || instrumentation.getBoolean("default_enabled", true); + } +} diff --git a/custom/src/main/java/com/splunk/opentelemetry/jmx/SplunkJmxMetricsInitializer.java b/custom/src/main/java/com/splunk/opentelemetry/jmx/SplunkJmxMetricsInitializer.java new file mode 100644 index 000000000..f5b459cb5 --- /dev/null +++ b/custom/src/main/java/com/splunk/opentelemetry/jmx/SplunkJmxMetricsInitializer.java @@ -0,0 +1,67 @@ +/* + * 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 io.opentelemetry.sdk.autoconfigure.AutoConfigureUtil.isDeclarativeConfig; + +import com.google.auto.service.AutoService; +import io.opentelemetry.api.incubator.config.DeclarativeConfigProperties; +import io.opentelemetry.javaagent.extension.AgentListener; +import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk; +import java.util.logging.Level; +import java.util.logging.Logger; + +@AutoService(AgentListener.class) +public class SplunkJmxMetricsInitializer implements AgentListener, AutoCloseable { + private static final Logger logger = + Logger.getLogger(SplunkJmxMetricsInitializer.class.getName()); + private static final String CONFIG_PATH = "distribution.splunk.java.jmx"; + + private JmxMetricInsightSupervisor supervisor; + + @Override + public synchronized void afterAgent(AutoConfiguredOpenTelemetrySdk sdk) { + if (supervisor != null) { + return; + } + + DeclarativeConfigProperties config = + isDeclarativeConfig(sdk) ? JmxMetricsConfigurationCustomizerProvider.getJmxConfig() : null; + // Publish the same lifecycle owner for OpAMP, including when JMX is disabled or unmanaged. + supervisor = JmxMetricInsightSupervisor.initialize(sdk.getOpenTelemetrySdk(), config); + + try { + supervisor.start(); + } catch (Exception e) { + logger.log(Level.WARNING, "Unable to start JMX metrics from " + CONFIG_PATH, e); + // Keep the supervisor available so a later remote update can repair invalid startup rules. + } + } + + @Override + public synchronized void close() { + if (supervisor != null) { + try { + supervisor.close(); + } catch (Exception e) { + logger.log(Level.WARNING, "Unable to stop JMX metrics collection", e); + } finally { + supervisor = null; + } + } + } +} diff --git a/custom/src/main/java/com/splunk/opentelemetry/jmx/UpstreamJmxConfiguration.java b/custom/src/main/java/com/splunk/opentelemetry/jmx/UpstreamJmxConfiguration.java new file mode 100644 index 000000000..12eb207a9 --- /dev/null +++ b/custom/src/main/java/com/splunk/opentelemetry/jmx/UpstreamJmxConfiguration.java @@ -0,0 +1,87 @@ +/* + * 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. + */ + +// Includes work from: +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package com.splunk.opentelemetry.jmx; + +import static io.opentelemetry.instrumentation.api.incubator.config.internal.SelectorConfig.Stability.STABLE; +import static java.util.Collections.emptyList; + +import io.opentelemetry.api.OpenTelemetry; +import io.opentelemetry.api.incubator.config.DeclarativeConfigProperties; +import io.opentelemetry.instrumentation.api.config.IncludeExclude; +import io.opentelemetry.instrumentation.api.incubator.config.internal.SelectorConfig; +import io.opentelemetry.instrumentation.jmx.JmxTelemetry; +import io.opentelemetry.instrumentation.jmx.JmxTelemetryBuilder; +import java.nio.file.Paths; +import java.time.Duration; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * Temporary adapter for the package-private setup in upstream {@code JmxMetricInsightInstaller}. + * Keep this in sync with instrumentation/jmx-metrics/javaagent until upstream supports inline + * rules, then remove it together with the distribution-specific startup wiring. + */ +final class UpstreamJmxConfiguration { + private static final Logger logger = Logger.getLogger(UpstreamJmxConfiguration.class.getName()); + + private UpstreamJmxConfiguration() {} + + static JmxTelemetryBuilder createBuilder( + OpenTelemetry openTelemetry, DeclarativeConfigProperties config) { + JmxTelemetryBuilder builder = + JmxTelemetry.builder(openTelemetry) + .beanDiscoveryDelay( + Duration.ofMillis( + config.get("discovery").getLong("delay", Duration.ofMinutes(1).toMillis()))); + + config.getScalarList("config", String.class, emptyList()).stream() + .map(Paths::get) + .forEach(path -> { + try { + builder.addRules(path); + } catch (RuntimeException e) { + // Match upstream: a bad external file must not prevent other rules from being loaded. + logger.log(Level.SEVERE, "Error while loading JMX configuration from " + path, e); + } + }); + + List unstableInclude = + config + .get("metrics") + .get("experimental") + .getScalarList("included", String.class, emptyList()); + // Bundled JVM rules overlap with runtime-telemetry. + builder.setInternalMetricsSystemFilter(IncludeExclude.builder().setExcluded("jvm").build()); + builder.setInternalMetricsUnstableMetricsFilter( + unstableInclude.isEmpty() + ? IncludeExclude.builder().setExcluded("*").build() + : IncludeExclude.builder().setIncluded(unstableInclude).build()); + + IncludeExclude metrics = SelectorConfig.resolve(config, "jmx", "metrics", STABLE); + if (metrics != null) { + builder.setMetrics(metrics); + } + return builder; + } +} diff --git a/custom/src/test/java/com/splunk/opentelemetry/jmx/JmxMetricInsightSupervisorTest.java b/custom/src/test/java/com/splunk/opentelemetry/jmx/JmxMetricInsightSupervisorTest.java new file mode 100644 index 000000000..38e8ed06d --- /dev/null +++ b/custom/src/test/java/com/splunk/opentelemetry/jmx/JmxMetricInsightSupervisorTest.java @@ -0,0 +1,230 @@ +/* + * 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 org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.awaitility.Awaitility.await; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import io.opentelemetry.api.incubator.config.DeclarativeConfigProperties; +import io.opentelemetry.instrumentation.testing.internal.AutoCleanupExtension; +import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.DeclarativeConfiguration; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; +import java.io.ByteArrayInputStream; +import java.lang.management.ManagementFactory; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import javax.management.ObjectName; +import javax.management.StandardMBean; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.mockito.ArgumentCaptor; + +class JmxMetricInsightSupervisorTest { + private static final String RULES = + """ + rules: + - bean: splunk.test:type=SupervisedMonitor + mapping: + CallCount: + metric: %s + type: counter + unit: "{call}" + """; + + @RegisterExtension static final AutoCleanupExtension cleanup = AutoCleanupExtension.create(); + + private final InMemoryMetricReader reader = InMemoryMetricReader.create(); + private OpenTelemetrySdk sdk; + + @BeforeEach + void setUp() throws Exception { + sdk = + OpenTelemetrySdk.builder() + .setMeterProvider(SdkMeterProvider.builder().registerMetricReader(reader).build()) + .build(); + cleanup.deferCleanup(sdk); + var server = ManagementFactory.getPlatformMBeanServer(); + var name = new ObjectName("splunk.test:type=SupervisedMonitor"); + server.registerMBean(new StandardMBean(() -> 7, CallMonitorMBean.class), name); + cleanup.deferCleanup(() -> server.unregisterMBean(name)); + } + + @Test + void replacesEntireConfigurationAndClosesCollection() throws Exception { + var supervisor = + newSupervisor( + RULES.formatted("test.supervisor.original") + + "metrics:\n included: [test.supervisor.*]\n"); + supervisor.start(); + awaitMetric("test.supervisor.original"); + + supervisor.applyConfiguration(config(RULES.formatted("test.supervisor.updated"))); + awaitMetric("test.supervisor.updated"); + + // The complete replacement drops the startup inclusion filter. + supervisor.applyConfiguration(config(RULES.formatted("other.allowed"))); + awaitMetric("other.allowed"); + supervisor.applyConfiguration(config(RULES.formatted("test.supervisor.restored"))); + awaitMetric("test.supervisor.restored"); + + supervisor.applyConfiguration(DeclarativeConfigProperties.empty()); + assertThat(metrics()).isEmpty(); + + supervisor.close(); + assertThat(metrics()).isEmpty(); + assertThatThrownBy( + () -> supervisor.applyConfiguration(config(RULES.formatted("test.supervisor.closed")))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("closed"); + } + + @Test + void invalidRulesLeavePreviousCollectionActiveAndCanBeCorrected() throws Exception { + var supervisor = newSupervisor(RULES.formatted("test.supervisor.original")); + supervisor.start(); + awaitMetric("test.supervisor.original"); + + assertThatThrownBy(() -> + supervisor.applyConfiguration( + config( + RULES + .formatted("test.supervisor.invalid") + .replace("type: counter", "type: invalid")))) + .isInstanceOf(IllegalArgumentException.class); + awaitMetric("test.supervisor.original"); + + supervisor.applyConfiguration(config(RULES.formatted("test.supervisor.corrected"))); + awaitMetric("test.supervisor.corrected"); + } + + @Test + void remoteUpdateCanRepairInvalidStartupRules() throws Exception { + var supervisor = + newSupervisor( + RULES.formatted("test.supervisor.invalid").replace("type: counter", "type: invalid")); + assertThatThrownBy(supervisor::start).isInstanceOf(IllegalArgumentException.class); + + supervisor.applyConfiguration(config(RULES.formatted("test.supervisor.corrected"))); + + awaitMetric("test.supervisor.corrected"); + } + + @Test + void identicalUpdatesDoNotRestartCollection() throws Exception { + JmxMetricsService service = mock(JmxMetricsService.class); + var startup = config("discovery:\n delay: 1000\nmetrics:\n excluded: [other.*]\n"); + var supervisor = new JmxMetricInsightSupervisor(service, startup); + var update = config("discovery:\n delay: 2000\n"); + + supervisor.applyConfiguration(update); + supervisor.applyConfiguration(update); + supervisor.applyConfiguration(DeclarativeConfigProperties.empty()); + supervisor.applyConfiguration(DeclarativeConfigProperties.empty()); + + ArgumentCaptor configuration = + ArgumentCaptor.forClass(DeclarativeConfigProperties.class); + verify(service, times(2)).reconfigure(configuration.capture()); + verifyNoMoreInteractions(service); + assertThat(DeclarativeConfigProperties.toMap(configuration.getAllValues().get(0))) + .isEqualTo(Map.of("discovery", Map.of("delay", 2000L))); + assertThat(configuration.getAllValues().get(1).getPropertyKeys()).isEmpty(); + } + + @Test + void canRetryPreviousSettingsAfterReplacementFailsToStart() throws Exception { + JmxMetricsService service = mock(JmxMetricsService.class); + when(service.start(any())).thenReturn(true); + doThrow(new IllegalStateException("Cannot start collection")) + .doNothing() + .when(service) + .reconfigure(any()); + var startup = config("discovery:\n delay: 1000\n"); + var supervisor = new JmxMetricInsightSupervisor(service, startup); + supervisor.start(); + + assertThatThrownBy(() -> supervisor.applyConfiguration(config("discovery:\n delay: 2000\n"))) + .isInstanceOf(IllegalStateException.class); + + supervisor.applyConfiguration(startup); + + verify(service, times(2)).reconfigure(any()); + } + + @Test + void disabledOrUnmanagedStartupRejectsRemoteUpdates() { + JmxMetricsService service = mock(JmxMetricsService.class); + var supervisor = new JmxMetricInsightSupervisor(service, null); + + supervisor.start(); + + assertThatThrownBy(() -> supervisor.applyConfiguration(DeclarativeConfigProperties.empty())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("enabled at agent startup"); + verifyNoInteractions(service); + } + + private JmxMetricInsightSupervisor newSupervisor(String configuration) { + var supervisor = new JmxMetricInsightSupervisor(sdk, config(configuration)); + cleanup.deferCleanup(supervisor); + return supervisor; + } + + private void awaitMetric(String name) { + await() + .atMost(Duration.ofSeconds(10)) + .untilAsserted(() -> + assertThat(metrics()) + .singleElement() + .satisfies(metric -> { + assertThat(metric.getName()).isEqualTo(name); + assertThat(metric.getLongSumData().getPoints()) + .singleElement() + .satisfies(point -> assertThat(point.getValue()).isEqualTo(7)); + })); + } + + private List metrics() { + return reader.collectAllMetrics().stream() + .filter( + metric -> metric.getInstrumentationScopeInfo().getName().equals("io.opentelemetry.jmx")) + .toList(); + } + + private static DeclarativeConfigProperties config(String yaml) { + return DeclarativeConfiguration.toConfigProperties( + new ByteArrayInputStream(yaml.getBytes(StandardCharsets.UTF_8))); + } + + public interface CallMonitorMBean { + long getCallCount(); + } +} diff --git a/custom/src/test/java/com/splunk/opentelemetry/jmx/JmxMetricsConfigurationCustomizerProviderTest.java b/custom/src/test/java/com/splunk/opentelemetry/jmx/JmxMetricsConfigurationCustomizerProviderTest.java new file mode 100644 index 000000000..f0ecee1ac --- /dev/null +++ b/custom/src/test/java/com/splunk/opentelemetry/jmx/JmxMetricsConfigurationCustomizerProviderTest.java @@ -0,0 +1,429 @@ +/* + * 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 com.splunk.opentelemetry.testing.declarativeconfig.DeclarativeConfigTestUtil.parse; +import static io.opentelemetry.sdk.autoconfigure.AutoConfigureUtil.getDistributionConfig; +import static io.opentelemetry.sdk.autoconfigure.AutoConfigureUtil.getInstrumentationConfig; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +import io.opentelemetry.api.incubator.config.DeclarativeConfigProperties; +import io.opentelemetry.javaagent.extension.instrumentation.internal.AgentDistributionConfig; +import io.opentelemetry.javaagent.tooling.config.JavaagentDistributionAccessCustomizerProvider; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.DeclarativeConfiguration; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.DeclarativeConfigurationBuilder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.DeclarativeConfigurationCustomizer; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.DeclarativeConfigurationCustomizerProvider; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OpenTelemetryConfigurationModel; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.UnaryOperator; +import java.util.logging.Handler; +import java.util.logging.Level; +import java.util.logging.LogRecord; +import java.util.logging.Logger; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.ArgumentCaptor; + +class JmxMetricsConfigurationCustomizerProviderTest { + @Test + void mergesSettingsAndPreservesInstrumentationAndOtherConfiguration() { + Logger logger = Logger.getLogger(JmxUpstreamDisablingCustomizerProvider.class.getName()); + Handler handler = mock(Handler.class); + logger.addHandler(handler); + OpenTelemetryConfigurationModel model; + try { + model = + customize( + """ + file_format: "1.2" + instrumentation/development: + java: + jmx: + discovery: + delay: 1000 + config: [legacy.yaml] + metrics: + included: [legacy.*] + excluded: [legacy.ignored] + jdbc: + enabled: true + distribution: + javaagent: + exclude_classes: [keep.*] + instrumentation: + enabled: [jmx, jdbc] + disabled: [servlet] + splunk: + other: keep + java: + other: + enabled: true + jmx: + discovery: + delay: 2000 + metrics: + included: [custom.*] + rules: + - bean: test:type=Monitor + """); + } finally { + logger.removeHandler(handler); + } + + assertThat(getInstrumentationConfig(model).getPropertyKeys()) + .containsExactlyInAnyOrder("jmx", "jdbc"); + assertThat(DeclarativeConfigProperties.toMap(getInstrumentationConfig(model).get("jmx"))) + .isEqualTo( + Map.of( + "discovery", Map.of("delay", 1000L), + "config", List.of("legacy.yaml"), + "metrics", + Map.of( + "included", List.of("legacy.*"), "excluded", List.of("legacy.ignored")))); + assertThat(getInstrumentationConfig(model).get("jdbc").getBoolean("enabled")).isTrue(); + var jmx = getDistributionConfig(model).get("java").get("jmx"); + assertThat(DeclarativeConfigProperties.toMap(jmx)) + .isEqualTo( + Map.of( + "discovery", Map.of("delay", 2000L), + "config", List.of("legacy.yaml"), + "metrics", + Map.of("included", List.of("custom.*"), "excluded", List.of("legacy.ignored")), + "rules", List.of(Map.of("bean", "test:type=Monitor")))); + assertThat( + DeclarativeConfigProperties.toMap( + JmxMetricsConfigurationCustomizerProvider.getJmxConfig())) + .isEqualTo(DeclarativeConfigProperties.toMap(jmx)); + assertThat(getDistributionConfig(model).getString("other")).isEqualTo("keep"); + assertThat(getDistributionConfig(model).get("java").get("other").getBoolean("enabled")) + .isTrue(); + var javaagent = + DeclarativeConfiguration.toConfigProperties(model.getDistribution()).get("javaagent"); + assertThat(javaagent.getScalarList("exclude_classes", String.class)).containsExactly("keep.*"); + assertThat(javaagent.get("instrumentation").getScalarList("enabled", String.class)) + .containsExactly("jmx", "jdbc"); + assertThat(javaagent.get("instrumentation").getScalarList("disabled", String.class)) + .containsExactly("servlet", "jmx"); + + ArgumentCaptor records = ArgumentCaptor.forClass(LogRecord.class); + verify(handler, atLeastOnce()).publish(records.capture()); + assertThat(records.getAllValues()) + .anySatisfy(record -> { + assertThat(record.getLevel()).isEqualTo(Level.INFO); + assertThat(record.getMessage()).contains("upstream JMX instrumentation is disabled"); + }); + } + + @Test + void disablesUpstreamWithoutMergingJmxSettings() { + var builder = new DeclarativeConfigurationBuilder(); + new JmxUpstreamDisablingCustomizerProvider().customize(builder); + var model = + builder.customizeModel( + parse( + """ + file_format: '1.2' + instrumentation/development: + java: + jmx: + discovery: + delay: 1000 + distribution: + splunk: + java: + jmx: {} + """)); + + assertThat(getInstrumentationConfig(model).get("jmx").get("discovery").getLong("delay")) + .isEqualTo(1000); + assertThat(getDistributionConfig(model).get("java").get("jmx").getPropertyKeys()).isEmpty(); + assertThat(JmxUpstreamDisablingCustomizerProvider.getOriginalJmxEnabled()).isTrue(); + assertThat( + DeclarativeConfiguration.toConfigProperties(model.getDistribution()) + .get("javaagent") + .get("instrumentation") + .getScalarList("disabled", String.class)) + .containsExactly("jmx"); + } + + @Test + void mergesAfterOtherCustomizersAndBeforeFinalModelCapture() { + String yaml = + """ + file_format: '1.2' + instrumentation/development: + java: + jmx: + discovery: + delay: 1000 + config: [original.yaml] + distribution: + splunk: + java: + jmx: + discovery: + delay: 2000 + rules: + - bean: test:type=Original + """; + var replacement = + modelCustomizer( + Integer.MAX_VALUE - 2, + model -> { + // Upstream already saw the disablement, but both JMX nodes are still available. + assertThat(AgentDistributionConfig.get().isInstrumentationEnabled("jmx")).isFalse(); + assertThat( + getInstrumentationConfig(model).get("jmx").get("discovery").getLong("delay")) + .isEqualTo(1000); + assertThat( + getDistributionConfig(model) + .get("java") + .get("jmx") + .get("discovery") + .getLong("delay")) + .isEqualTo(2000); + var updated = + parse( + yaml.replace("original.yaml", "customized.yaml") + .replace("2000", "4000") + .replace("test:type=Original", "test:type=Customized")); + updated + .getDistribution() + .setExtensionProperty( + "javaagent", + model.getDistribution().getExtensionProperties().get("javaagent")); + return updated; + }); + var capturedConfig = new AtomicReference>(); + var capture = + modelCustomizer( + Integer.MAX_VALUE, + model -> { + assertThat( + DeclarativeConfigProperties.toMap(getInstrumentationConfig(model).get("jmx"))) + .isEqualTo( + Map.of( + "discovery", Map.of("delay", 1000L), + "config", List.of("customized.yaml"))); + capturedConfig.set( + DeclarativeConfigProperties.toMap( + JmxMetricsConfigurationCustomizerProvider.getJmxConfig())); + return model; + }); + + AgentDistributionConfig.resetForTest(); + try { + var model = + customize( + yaml, replacement, capture, new JavaagentDistributionAccessCustomizerProvider()); + + assertThat(AgentDistributionConfig.get().isInstrumentationEnabled("jmx")).isFalse(); + var expected = + Map.of( + "discovery", Map.of("delay", 4000L), + "config", List.of("customized.yaml"), + "rules", List.of(Map.of("bean", "test:type=Customized"))); + assertThat( + DeclarativeConfigProperties.toMap( + getDistributionConfig(model).get("java").get("jmx"))) + .isEqualTo(expected); + assertThat(capturedConfig.get()).isEqualTo(expected); + } finally { + AgentDistributionConfig.resetForTest(); + } + } + + @Test + void doesNotStartCustomCollectionWhenDistributionJmxIsAddedTooLate() { + // Clear any previous startup snapshot before creating the node in a later customizer. + customize("file_format: '1.2'\ndistribution:\n splunk:\n java:\n jmx: {}\n"); + var addDistributionJmx = + modelCustomizer( + 1, + model -> + parse( + """ + file_format: '1.2' + instrumentation/development: + java: + jmx: + config: [upstream.yaml] + distribution: + splunk: + java: + jmx: {} + """)); + + AgentDistributionConfig.resetForTest(); + try { + var model = + customize( + "file_format: '1.2'\n", + addDistributionJmx, + new JavaagentDistributionAccessCustomizerProvider()); + + assertThat(AgentDistributionConfig.get().isInstrumentationEnabled("jmx")).isTrue(); + assertThat(getInstrumentationConfig(model).get("jmx").getScalarList("config", String.class)) + .containsExactly("upstream.yaml"); + assertThat(JmxMetricsConfigurationCustomizerProvider.getJmxConfig()).isNull(); + } finally { + AgentDistributionConfig.resetForTest(); + } + } + + @ParameterizedTest + @ValueSource(strings = {"", "distribution:\n splunk:\n java:\n other: {}\n"}) + void leavesUpstreamUntouchedWithoutDistributionJmx(String distribution) { + // First populate the startup snapshot to ensure an absent node clears stale state. + customize("file_format: '1.2'\ndistribution:\n splunk:\n java:\n jmx: {}\n"); + var model = + customize( + """ + file_format: "1.2" + instrumentation/development: + java: + jmx: + discovery: + delay: 3000 + """ + + distribution); + + assertThat(getInstrumentationConfig(model).get("jmx").get("discovery").getLong("delay")) + .isEqualTo(3000); + assertThat(JmxMetricsConfigurationCustomizerProvider.getJmxConfig()).isNull(); + if (model.getDistribution() != null) { + assertThat(model.getDistribution().getExtensionProperties()).doesNotContainKey("javaagent"); + } + } + + @ParameterizedTest + @ValueSource(strings = {"jmx:", "jmx: {}", "jmx:\n rules: []"}) + void takesOverEvenForAnEmptyDistributionJmxNode(String node) { + var model = + customize( + """ + file_format: '1.2' + instrumentation/development: + java: + jmx: + config: [legacy.yaml] + discovery: + delay: 3000 + metrics: + excluded: [legacy.ignored] + distribution: + splunk: + java: + """ + + node.indent(6)); + + assertThat(JmxMetricsConfigurationCustomizerProvider.getJmxConfig()).isNotNull(); + assertThat( + JmxMetricsConfigurationCustomizerProvider.getJmxConfig() + .get("discovery") + .getLong("delay")) + .isEqualTo(3000); + assertThat( + JmxMetricsConfigurationCustomizerProvider.getJmxConfig() + .getScalarList("config", String.class)) + .containsExactly("legacy.yaml"); + assertThat( + DeclarativeConfigProperties.toMap( + JmxMetricsConfigurationCustomizerProvider.getJmxConfig())) + .isEqualTo( + DeclarativeConfigProperties.toMap(getDistributionConfig(model).get("java").get("jmx"))); + assertThat(DeclarativeConfigProperties.toMap(getInstrumentationConfig(model).get("jmx"))) + .isEqualTo( + Map.of( + "discovery", Map.of("delay", 3000L), + "config", List.of("legacy.yaml"), + "metrics", Map.of("excluded", List.of("legacy.ignored")))); + assertThat( + DeclarativeConfiguration.toConfigProperties(model.getDistribution()) + .get("javaagent") + .get("instrumentation") + .getScalarList("disabled", String.class)) + .containsExactly("jmx"); + } + + @ParameterizedTest + @MethodSource("enablement") + void preservesOriginalEnablementForCustomCollection(String selectors, boolean enabled) { + var model = + customize( + "file_format: '1.2'\ndistribution:\n javaagent:\n instrumentation:\n" + + selectors.indent(6) + + " splunk:\n java:\n jmx: {}\n"); + + assertThat(JmxMetricsConfigurationCustomizerProvider.getJmxConfig() != null).isEqualTo(enabled); + assertThat( + DeclarativeConfiguration.toConfigProperties(model.getDistribution()) + .get("javaagent") + .get("instrumentation") + .getScalarList("disabled", String.class)) + .containsOnlyOnce("jmx"); + } + + private static Stream enablement() { + return Stream.of( + Arguments.of("default_enabled: false", false), + Arguments.of("default_enabled: false\nenabled: [jmx]", true), + Arguments.of("enabled: [jmx]\ndisabled: [jmx]", false), + Arguments.of("disabled: [jmx]", false), + Arguments.of("disabled: [jdbc]", true)); + } + + private static OpenTelemetryConfigurationModel customize( + String yaml, DeclarativeConfigurationCustomizerProvider... additionalProviders) { + var builder = new DeclarativeConfigurationBuilder(); + Stream.concat( + Stream.of( + new JmxMetricsConfigurationCustomizerProvider(), + new JmxUpstreamDisablingCustomizerProvider()), + Arrays.stream(additionalProviders)) + .sorted(Comparator.comparingInt(DeclarativeConfigurationCustomizerProvider::order)) + .forEach(provider -> provider.customize(builder)); + return builder.customizeModel(parse(yaml)); + } + + private static DeclarativeConfigurationCustomizerProvider modelCustomizer( + int order, UnaryOperator customization) { + return new DeclarativeConfigurationCustomizerProvider() { + @Override + public void customize(DeclarativeConfigurationCustomizer customizer) { + customizer.addModelCustomizer(customization); + } + + @Override + public int order() { + return order; + } + }; + } +} diff --git a/custom/src/test/java/com/splunk/opentelemetry/jmx/JmxMetricsInitializerTest.java b/custom/src/test/java/com/splunk/opentelemetry/jmx/JmxMetricsInitializerTest.java new file mode 100644 index 000000000..47ddaf44f --- /dev/null +++ b/custom/src/test/java/com/splunk/opentelemetry/jmx/JmxMetricsInitializerTest.java @@ -0,0 +1,466 @@ +/* + * 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 io.opentelemetry.sdk.autoconfigure.AutoConfigureUtil.getConfigProvider; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.awaitility.Awaitility.await; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.verify; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.instrumentation.jmx.JmxTelemetry; +import io.opentelemetry.instrumentation.testing.internal.AutoCleanupExtension; +import io.opentelemetry.javaagent.extension.AgentListener; +import io.opentelemetry.javaagent.extension.instrumentation.internal.AgentDistributionConfig; +import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.DeclarativeConfiguration; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.DeclarativeConfigurationCustomizerProvider; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.export.MetricExporter; +import io.opentelemetry.sdk.testing.exporter.InMemoryMetricExporter; +import java.lang.management.ManagementFactory; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.logging.Handler; +import java.util.logging.LogRecord; +import java.util.logging.Logger; +import javax.management.ObjectName; +import javax.management.StandardMBean; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.ArgumentCaptor; + +class JmxMetricsInitializerTest { + private static final String YAML = + """ + file_format: "1.2" + meter_provider: + readers: + - periodic: + interval: 50 + exporter: + console: + instrumentation/development: + java: + jmx: + discovery: + delay: 1000 + distribution: + splunk: + java: + jmx: + rules: + - bean: splunk.test:type=CallMonitor + metricAttribute: + source: const(inline) + mapping: + CallCount: + metric: petclinic.repository.call.count + type: counter + unit: "{call}" + desc: Completed repository calls. + CallTime: + metric: petclinic.repository.call.duration.average + type: gauge + sourceUnit: ms + unit: s + desc: Average repository call duration. + """; + + @RegisterExtension static final AutoCleanupExtension autoCleanup = AutoCleanupExtension.create(); + + @TempDir Path tempDir; + + private final InMemoryMetricExporter exporter = InMemoryMetricExporter.create(); + private SplunkJmxMetricsInitializer initializer; + + @BeforeEach + void setUp() { + AgentDistributionConfig.resetForTest(); + autoCleanup.deferCleanup(AgentDistributionConfig::resetForTest); + // Exercise the generated agent-listener SPI registration as well as the SDK customizer SPI. + initializer = + (SplunkJmxMetricsInitializer) + ComponentLoader.loadList( + ComponentLoader.forClassLoader(getClass().getClassLoader()), + AgentListener.class) + .stream() + .filter(SplunkJmxMetricsInitializer.class::isInstance) + .findFirst() + .orElseThrow(); + autoCleanup.deferCleanup(initializer); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void exportsInlineRulesUsingTheConfiguredSdk(boolean registerAfterStartup) throws Exception { + CallMonitor monitor = new CallMonitor(); + if (!registerAfterStartup) { + registerMBean(monitor); + } + AutoConfiguredOpenTelemetrySdk sdk = createSdk(YAML); + + assertThat(AgentDistributionConfig.get().isInstrumentationEnabled("jmx")).isFalse(); + assertThat( + getConfigProvider(sdk) + .getInstrumentationConfig("jmx") + .get("discovery") + .getLong("delay")) + .isEqualTo(1000); + + initializer.afterAgent(sdk); + autoCleanup.deferCleanup(initializer); + // Repeated startup must not register duplicate callbacks. + initializer.afterAgent(sdk); + if (registerAfterStartup) { + registerMBean(monitor); + } + + await() + .atMost(Duration.ofSeconds(10)) + .untilAsserted(() -> { + MetricData count = lastMetric("petclinic.repository.call.count"); + assertThat(count.getInstrumentationScopeInfo().getName()) + .isEqualTo("io.opentelemetry.jmx"); + assertThat(count.getUnit()).isEqualTo("{call}"); + assertThat(count.getDescription()).isEqualTo("Completed repository calls."); + assertThat(count.getLongSumData().isMonotonic()).isTrue(); + assertThat(count.getLongSumData().getPoints()) + .singleElement() + .satisfies(point -> { + assertThat(point.getValue()).isEqualTo(7); + assertThat(point.getAttributes()) + .isEqualTo(Attributes.builder().put("source", "inline").build()); + }); + MetricData time = lastMetric("petclinic.repository.call.duration.average"); + assertThat(time.getUnit()).isEqualTo("s"); + assertThat(time.getDoubleGaugeData().getPoints()) + .singleElement() + .satisfies(point -> assertThat(point.getValue()).isEqualTo(0.25)); + }); + + monitor.callCount = 11; + await() + .atMost(Duration.ofSeconds(5)) + .untilAsserted(() -> + assertThat(lastMetric("petclinic.repository.call.count").getLongSumData().getPoints()) + .singleElement() + .satisfies(point -> assertThat(point.getValue()).isEqualTo(11))); + + initializer.close(); + exporter.reset(); + sdk.getOpenTelemetrySdk() + .getSdkMeterProvider() + .forceFlush() + .join(5, java.util.concurrent.TimeUnit.SECONDS); + assertThat(jmxMetrics()).isEmpty(); + } + + @Test + void remoteUpdatesUseTheStartupCollectionSupervisor() throws Exception { + registerMBean(new CallMonitor()); + AutoConfiguredOpenTelemetrySdk sdk = createSdk(YAML); + initializer.afterAgent(sdk); + + var supervisor = JmxMetricInsightSupervisor.getInstance(); + supervisor.applyConfiguration( + DeclarativeConfiguration.toConfigProperties( + Map.of( + "rules", + List.of( + Map.of( + "bean", + "splunk.test:type=CallMonitor", + "mapping", + Map.of( + "CallCount", + Map.of( + "metric", "petclinic.remote.call.count", + "type", "counter", + "unit", "{call}"))))))); + + await() + .atMost(Duration.ofSeconds(10)) + .untilAsserted(() -> { + exporter.reset(); + sdk.getOpenTelemetrySdk() + .getSdkMeterProvider() + .forceFlush() + .join(5, java.util.concurrent.TimeUnit.SECONDS); + assertThat(jmxMetrics()) + .extracting(MetricData::getName) + .contains("petclinic.remote.call.count") + .doesNotContain( + "petclinic.repository.call.count", "petclinic.repository.call.duration.average"); + }); + + initializer.close(); + assertThatThrownBy(JmxMetricInsightSupervisor::getInstance) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void appliesDistributionMetricFilters() throws Exception { + registerMBean(new CallMonitor()); + AutoConfiguredOpenTelemetrySdk sdk = + createSdk( + YAML.replace( + "\n jmx:\n", + "\n jmx:\n metrics:\n included: [petclinic.*]\n excluded: [petclinic.repository.call.duration.*]\n")); + + initializer.afterAgent(sdk); + autoCleanup.deferCleanup(initializer); + + await() + .atMost(Duration.ofSeconds(10)) + .untilAsserted(() -> assertThat(jmxMetrics()).isNotEmpty()); + assertThat(jmxMetrics()) + .extracting(MetricData::getName) + .containsOnly("petclinic.repository.call.count"); + } + + @Test + void supportsSharedRulePropertiesAndEmptyMetricMappings() throws Exception { + registerMBean(new CallMonitor()); + AutoConfiguredOpenTelemetrySdk sdk = + createSdk( + """ + file_format: "1.2" + meter_provider: + readers: + - periodic: + interval: 50 + exporter: + console: + distribution: + splunk: + java: + jmx: + rules: + - beans: ["splunk.test:type=CallMonitor"] + prefix: petclinic. + type: gauge + unit: "{call}" + dropNegativeValues: true + mapping: + CallCount: + """); + + initializer.afterAgent(sdk); + autoCleanup.deferCleanup(initializer); + + await() + .atMost(Duration.ofSeconds(10)) + .untilAsserted(() -> + assertThat(lastMetric("petclinic.CallCount").getLongGaugeData().getPoints()) + .singleElement() + .satisfies(point -> assertThat(point.getValue()).isEqualTo(7))); + } + + @ParameterizedTest + @ValueSource( + strings = { + "file_format: '1.2'", + "file_format: '1.2'\ndistribution:\n splunk:\n java:\n other: {}" + }) + void doesNotStartWithoutDistributionJmxNode(String yaml) throws Exception { + AutoConfiguredOpenTelemetrySdk sdk = createSdk(yaml); + try (var jmx = mockStatic(JmxTelemetry.class)) { + initializer.afterAgent(sdk); + jmx.verifyNoInteractions(); + } + } + + @Test + void respectsDisabledJmxInstrumentation() throws Exception { + AutoConfiguredOpenTelemetrySdk sdk = + createSdk( + YAML.replace( + "distribution:\n", + """ + distribution: + javaagent: + instrumentation: + disabled: [jmx] + """)); + try (var jmx = mockStatic(JmxTelemetry.class)) { + initializer.afterAgent(sdk); + jmx.verifyNoInteractions(); + } + } + + @Test + void startsBuiltinsForAnEmptyDistributionNode() throws Exception { + var server = ManagementFactory.getPlatformMBeanServer(); + var name = new ObjectName("splunk.test:type=BuiltIn"); + server.registerMBean(new StandardMBean(new CallMonitor(), CallMonitorMBean.class), name); + autoCleanup.deferCleanup(() -> server.unregisterMBean(name)); + AutoConfiguredOpenTelemetrySdk sdk = + createSdk( + """ + file_format: "1.2" + meter_provider: + readers: + - periodic: + interval: 50 + exporter: + console: + distribution: + splunk: + java: + jmx: + """); + + assertThat(AgentDistributionConfig.get().isInstrumentationEnabled("jmx")).isFalse(); + initializer.afterAgent(sdk); + autoCleanup.deferCleanup(initializer); + + await() + .atMost(Duration.ofSeconds(10)) + .untilAsserted(() -> + assertThat(lastMetric("test.jmx.builtin.stable").getLongSumData().getPoints()) + .singleElement() + .satisfies(point -> assertThat(point.getValue()).isEqualTo(7))); + } + + @Test + void doesNotStartForEnvironmentConfiguration() { + AutoConfiguredOpenTelemetrySdk sdk = + AutoConfiguredOpenTelemetrySdk.builder() + .addPropertiesSupplier(() -> + Map.of( + "otel.traces.exporter", + "none", + "otel.metrics.exporter", + "none", + "otel.logs.exporter", + "none")) + .disableShutdownHook() + .build(); + autoCleanup.deferCleanup(sdk.getOpenTelemetrySdk()); + try (var jmx = mockStatic(JmxTelemetry.class)) { + initializer.afterAgent(sdk); + jmx.verifyNoInteractions(); + } + } + + @Test + void reportsInvalidRulesWithoutFailingAgentStartup() throws Exception { + AutoConfiguredOpenTelemetrySdk sdk = createSdk(YAML.replace("type: counter", "type: invalid")); + Logger logger = Logger.getLogger(SplunkJmxMetricsInitializer.class.getName()); + Handler handler = mock(Handler.class); + logger.addHandler(handler); + autoCleanup.deferCleanup(() -> logger.removeHandler(handler)); + + initializer.afterAgent(sdk); + + ArgumentCaptor record = ArgumentCaptor.forClass(LogRecord.class); + verify(handler).publish(record.capture()); + assertThat(record.getValue().getMessage()).contains("distribution.splunk.java.jmx"); + assertThat(record.getValue().getThrown()).isInstanceOf(IllegalArgumentException.class); + assertThat(jmxMetrics()).isEmpty(); + } + + private AutoConfiguredOpenTelemetrySdk createSdk(String yaml) throws Exception { + Path configFile = tempDir.resolve("otel.yaml"); + Files.writeString(configFile, yaml); + ComponentLoader delegate = ComponentLoader.forClassLoader(getClass().getClassLoader()); + ComponentLoader loader = + new ComponentLoader() { + @Override + public Iterable load(Class spiClass) { + List providers = new ArrayList<>(ComponentLoader.loadList(delegate, spiClass)); + if (spiClass == DeclarativeConfigurationCustomizerProvider.class) { + DeclarativeConfigurationCustomizerProvider customizer = + builder -> + builder.addMetricExporterCustomizer( + MetricExporter.class, (ignored, config) -> exporter); + providers.add(spiClass.cast(customizer)); + } + return providers; + } + }; + System.setProperty("otel.config.file", configFile.toString()); + try { + AutoConfiguredOpenTelemetrySdk sdk = + AutoConfiguredOpenTelemetrySdk.builder() + .setComponentLoader(loader) + .addPropertiesSupplier(() -> Map.of("otel.config.file", configFile.toString())) + .disableShutdownHook() + .build(); + autoCleanup.deferCleanup(sdk.getOpenTelemetrySdk()); + return sdk; + } finally { + System.clearProperty("otel.config.file"); + } + } + + private void registerMBean(CallMonitor monitor) throws Exception { + var server = ManagementFactory.getPlatformMBeanServer(); + var name = new ObjectName("splunk.test:type=CallMonitor"); + server.registerMBean(new StandardMBean(monitor, CallMonitorMBean.class), name); + autoCleanup.deferCleanup(() -> server.unregisterMBean(name)); + } + + private MetricData lastMetric(String name) { + List metrics = + exporter.getFinishedMetricItems().stream() + .filter(metric -> metric.getName().equals(name)) + .toList(); + assertThat(metrics).isNotEmpty(); + return metrics.get(metrics.size() - 1); + } + + private List jmxMetrics() { + return exporter.getFinishedMetricItems().stream() + .filter( + metric -> metric.getInstrumentationScopeInfo().getName().equals("io.opentelemetry.jmx")) + .toList(); + } + + public interface CallMonitorMBean { + long getCallCount(); + + long getCallTime(); + } + + public static class CallMonitor implements CallMonitorMBean { + volatile long callCount = 7; + + @Override + public long getCallCount() { + return callCount; + } + + @Override + public long getCallTime() { + return 250; + } + } +} diff --git a/custom/src/test/java/com/splunk/opentelemetry/jmx/JmxMetricsServiceTest.java b/custom/src/test/java/com/splunk/opentelemetry/jmx/JmxMetricsServiceTest.java new file mode 100644 index 000000000..7b935c6e1 --- /dev/null +++ b/custom/src/test/java/com/splunk/opentelemetry/jmx/JmxMetricsServiceTest.java @@ -0,0 +1,299 @@ +/* + * 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 io.opentelemetry.api.common.AttributeKey.stringKey; +import static io.opentelemetry.api.incubator.config.DeclarativeConfigProperties.empty; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.awaitility.Awaitility.await; + +import io.opentelemetry.api.incubator.config.DeclarativeConfigProperties; +import io.opentelemetry.instrumentation.testing.internal.AutoCleanupExtension; +import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.DeclarativeConfiguration; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; +import java.io.ByteArrayInputStream; +import java.lang.management.ManagementFactory; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import javax.management.ObjectName; +import javax.management.StandardMBean; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.io.TempDir; + +class JmxMetricsServiceTest { + private static final String RULES = + """ + rules: + - bean: splunk.test:type=DynamicCallMonitor + mapping: + CallCount: + metric: %s + type: counter + unit: "{call}" + """; + + @RegisterExtension static final AutoCleanupExtension autoCleanup = AutoCleanupExtension.create(); + + private final InMemoryMetricReader reader = InMemoryMetricReader.create(); + private OpenTelemetrySdk sdk; + + @TempDir Path tempDir; + + @BeforeEach + void setUp() throws Exception { + // No agent lifecycle, declarative SDK startup, or global configuration is required. + sdk = + OpenTelemetrySdk.builder() + .setMeterProvider(SdkMeterProvider.builder().registerMetricReader(reader).build()) + .build(); + autoCleanup.deferCleanup(sdk); + + var server = ManagementFactory.getPlatformMBeanServer(); + var name = new ObjectName("splunk.test:type=DynamicCallMonitor"); + server.registerMBean(new StandardMBean(() -> 7, CallMonitorMBean.class), name); + autoCleanup.deferCleanup(() -> server.unregisterMBean(name)); + } + + @Test + void startsAfterSdkCreationAndCanRestartWithDifferentRules() throws Exception { + JmxMetricsService service = newService(); + assertThat(service.start(empty())).isTrue(); + service.close(); + + var firstRules = config(RULES.formatted("petclinic.first")); + assertThat(service.start(firstRules)).isTrue(); + assertThat(service.start(firstRules)).isTrue(); + awaitMetric("petclinic.first"); + + service.close(); + service.close(); + assertThat(jmxMetrics()).isEmpty(); + + assertThatThrownBy(() -> + service.start( + config( + RULES + .formatted("petclinic.invalid") + .replace("type: counter", "type: invalid")))) + .isInstanceOf(IllegalArgumentException.class); + assertThat(jmxMetrics()).isEmpty(); + + assertThat(service.start(config(RULES.formatted("petclinic.second")))).isTrue(); + awaitMetric("petclinic.second"); + assertThat(jmxMetrics()).extracting(MetricData::getName).containsExactly("petclinic.second"); + } + + @Test + void instancesHaveIndependentRulesSettingsAndLifecycles() throws Exception { + JmxMetricsService first = newService(); + JmxMetricsService second = newService(); + assertThat(first.start(config(RULES.formatted("petclinic.first")))).isTrue(); + assertThat( + second.start( + config( + RULES.formatted("petclinic.second") + + """ + - bean: splunk.test:type=DynamicCallMonitor + mapping: + CallCount: + metric: petclinic.filtered + type: counter + unit: "{call}" + """ + + """ + discovery: + delay: 1000 + metrics: + included: [petclinic.second] + """))) + .isTrue(); + + await() + .atMost(Duration.ofSeconds(10)) + .untilAsserted(() -> + assertThat(jmxMetrics()) + .extracting(MetricData::getName) + .containsExactlyInAnyOrder("petclinic.first", "petclinic.second")); + + first.close(); + assertThat(jmxMetrics()) + .singleElement() + .satisfies(metric -> { + assertThat(metric.getName()).isEqualTo("petclinic.second"); + assertThat(metric.getLongSumData().getPoints()) + .singleElement() + .satisfies(point -> assertThat(point.getValue()).isEqualTo(7)); + }); + } + + @Test + void preservesEscapedStringsAndUnicodeInRuleDescriptionsAndAttributes() { + String description = "Calls \"per repository\"\\path\n\tżółw"; + String label = "Repository \"calls\"\\path żółw"; + var rules = + DeclarativeConfiguration.toConfigProperties( + Map.of( + "rules", + List.of( + Map.of( + "bean", "splunk.test:type=DynamicCallMonitor", + "metricAttribute", Map.of("label", "const(" + label + ")"), + "mapping", + Map.of( + "CallCount", + Map.of( + "metric", "petclinic.escaped", + "type", "counter", + "unit", "{call}", + "desc", description)))))); + + assertThat(newService().start(rules)).isTrue(); + + awaitMetric("petclinic.escaped"); + assertThat(jmxMetrics()) + .singleElement() + .satisfies(metric -> { + assertThat(metric.getDescription()).isEqualTo(description); + assertThat(metric.getLongSumData().getPoints()) + .singleElement() + .satisfies(point -> + assertThat(point.getAttributes().get(stringKey("label"))).isEqualTo(label)); + }); + } + + @Test + void loadsExternalAndInlineRulesWhileSkippingBadFiles() throws Exception { + Path valid = tempDir.resolve("valid.yaml"); + Path invalid = tempDir.resolve("invalid.yaml"); + Files.writeString(valid, RULES.formatted("petclinic.file")); + Files.writeString(invalid, "rules: [not-a-rule]"); + var rules = + config( + RULES.formatted("petclinic.inline") + + """ + config: + - "%s" + - "%s" + - "%s" + """ + .formatted(tempDir.resolve("missing.yaml"), invalid, valid)); + + newService().start(rules); + + await() + .atMost(Duration.ofSeconds(10)) + .untilAsserted(() -> + assertThat(jmxMetrics()) + .extracting(MetricData::getName) + .containsExactlyInAnyOrder("petclinic.file", "petclinic.inline")); + } + + @Test + void matchesUpstreamStableDefaultsAndExperimentalOptIn() throws Exception { + var server = ManagementFactory.getPlatformMBeanServer(); + var stable = new ObjectName("splunk.test:type=BuiltIn"); + var unstable = new ObjectName("Catalina:type=GlobalRequestProcessor,name=custom-test"); + server.registerMBean(new StandardMBean(() -> 7, CallMonitorMBean.class), stable); + server.registerMBean(new StandardMBean(() -> 7, TomcatMBean.class), unstable); + autoCleanup.deferCleanup(() -> server.unregisterMBean(stable)); + autoCleanup.deferCleanup(() -> server.unregisterMBean(unstable)); + JmxMetricsService service = newService(); + + service.start(empty()); + awaitMetric("test.jmx.builtin.stable"); + // JVM rules are excluded and experimental metrics are not collected by default. + assertThat(jmxMetrics()) + .extracting(MetricData::getName) + .containsExactly("test.jmx.builtin.stable"); + + service.close(); + service.start( + config( + """ + metrics: + experimental: + included: [tomcat.request.count] + """)); + await() + .atMost(Duration.ofSeconds(10)) + .untilAsserted(() -> + assertThat(jmxMetrics()) + .extracting(MetricData::getName) + .containsExactlyInAnyOrder("test.jmx.builtin.stable", "tomcat.request.count")); + + service.close(); + service.start( + config( + """ + metrics: + experimental: + included: [tomcat.*] + excluded: [tomcat.*] + """)); + awaitMetric("test.jmx.builtin.stable"); + } + + private JmxMetricsService newService() { + JmxMetricsService service = new JmxMetricsService(sdk); + autoCleanup.deferCleanup(service); + return service; + } + + private void awaitMetric(String name) { + await() + .atMost(Duration.ofSeconds(10)) + .untilAsserted(() -> + assertThat(jmxMetrics()) + .singleElement() + .satisfies(metric -> { + assertThat(metric.getName()).isEqualTo(name); + assertThat(metric.getLongSumData().getPoints()) + .singleElement() + .satisfies(point -> assertThat(point.getValue()).isEqualTo(7)); + })); + } + + private List jmxMetrics() { + return reader.collectAllMetrics().stream() + .filter( + metric -> metric.getInstrumentationScopeInfo().getName().equals("io.opentelemetry.jmx")) + .toList(); + } + + private static DeclarativeConfigProperties config(String yaml) { + return DeclarativeConfiguration.toConfigProperties( + new ByteArrayInputStream(yaml.getBytes(StandardCharsets.UTF_8))); + } + + public interface CallMonitorMBean { + long getCallCount(); + } + + public interface TomcatMBean { + long getrequestCount(); + } +} diff --git a/custom/src/test/resources/jmx/rules/tomcat.yaml b/custom/src/test/resources/jmx/rules/tomcat.yaml new file mode 100644 index 000000000..da9dfb81f --- /dev/null +++ b/custom/src/test/resources/jmx/rules/tomcat.yaml @@ -0,0 +1,7 @@ +rules: + - bean: splunk.test:type=BuiltIn + mapping: + CallCount: + metric: test.jmx.builtin.stable + type: counter + unit: "{call}" diff --git a/docs/metrics.md b/docs/metrics.md index 20da5b877..ad171ce35 100644 --- a/docs/metrics.md +++ b/docs/metrics.md @@ -31,6 +31,107 @@ These metrics are enabled only when memory profiler is enabled. | `jvm.gc.pause.count` | [Counter][c] | Number of gc pauses. This metric will be removed in a future release. | | `jvm.gc.pause.totalTime` | [Counter][c] | Time spent in GC pause. This metric will be removed in a future release. | +## Custom JMX metrics in declarative configuration + +Define inline JMX mapping rules under `distribution.splunk.java.jmx.rules` in the +file selected by `otel.config.file`: + +```yaml +file_format: "1.2" +meter_provider: + readers: + - periodic: + exporter: + otlp_http: + +distribution: + splunk: + java: + jmx: + discovery: + delay: 5000 + metrics: + included: [petclinic.*] + rules: + - bean: petclinic:type=CallMonitor + mapping: + CallCount: + metric: petclinic.repository.call.count + type: gauge + unit: "{call}" + desc: Completed repository calls since the last reset. + CallTime: + metric: petclinic.repository.call.duration.average + type: gauge + sourceUnit: ms + unit: s + desc: Average repository call duration since the last reset. +``` + +Rules use the [upstream JMX mapping syntax](https://github.com/open-telemetry/opentelemetry-java-instrumentation/blob/main/instrumentation/jmx-metrics/README.md). +The agent collects from MBeans in the current JVM and exports through the configured +`meter_provider` readers. No remote JMX connection is required. + +The distribution JMX node accepts the same settings and defaults as the upstream agent: + +* `discovery.delay`: MBean discovery delay in milliseconds (default: `60000`). +* `config`: a list of paths to external JMX mapping files. Invalid files are logged and skipped. +* `metrics.included` / `metrics.excluded`: filters applied to all JMX metric names. +* `metrics.experimental.included`: opt in to experimental built-in metrics by name. + +Stable built-in metrics are enabled by default, except bundled JVM rules that overlap with +runtime telemetry. Inline and external custom rules do not require experimental opt-in. +The inclusion filter in the example restricts collection to the Petclinic metric names. +An empty distribution JMX node selects upstream defaults. + +When `distribution.splunk.java` contains `jmx`, the agent takes ownership of JMX collection. +If `instrumentation/development.java.jmx` is also present, its settings are merged into the +distribution node while the instrumentation node is retained. Distribution values take precedence; +nested mappings are merged and configured lists replace the corresponding upstream lists. +The takeover is logged at INFO level, and upstream JMX startup is disabled automatically to +prevent duplicate collection. Without a distribution JMX node, upstream behavior is unchanged. + +Explicit `jmx` enable/disable selectors in `distribution.javaagent.instrumentation` are respected +before the takeover. They determine whether the custom collection starts; the automatically +injected upstream disablement does not disable it. Invalid inline rules are logged and skipped. + +JMX configuration is customized in two stages: + +* `JmxUpstreamDisablingCustomizerProvider` runs at order `-1`. It saves the original enablement + decision and disables upstream JMX before `JavaagentDistributionAccessCustomizerProvider` + snapshots instrumentation enablement at order `0`. Both JMX nodes remain available to other + model customizers. +* `JmxMetricsConfigurationCustomizerProvider` runs at order `Integer.MAX_VALUE - 1`. It merges + the customized JMX settings while retaining the instrumentation node, and captures the merged + settings for `JmxMetricsInitializer`. Order `Integer.MAX_VALUE` is reserved for final model + capture, including the OpAMP configuration interceptor. + +Running the entire customization late would leave upstream JMX enabled: changing the model does +not update its earlier enablement snapshot. Saving the original decision also ensures that our +injected disablement does not turn off distribution-owned collection. + +The distribution JMX node must exist before the early stage; enablement is evaluated then using +the configured selectors and their defaults. Customizers that create this node or change enablement +must run before order `-1`. Later customizers can change the JMX mapping rules and collection +settings before the merge. A node first added after the early stage does not start custom +collection, because upstream may already be enabled. + +When OpAMP remote configuration is enabled, updates under `distribution.splunk.java.jmx` are +applied by `JmxMetricInsightSupervisor`, which also owns the startup collection. Each received JMX +node is a complete replacement for the current JMX configuration. Omitted settings use their +defaults, and an empty node resets collection to defaults, clearing previous custom rules and +filters. A message without this JMX node leaves collection unchanged, and an identical +configuration does not restart it. New rules are validated before stopping the previous +collection; invalid inline rules are reported as a failed remote update. + +Remote JMX updates require distribution-owned JMX to be enabled at startup, for example with +`distribution.splunk.java.jmx: {}`. Startup disablement remains effective, and an already-running +upstream collector cannot be taken over remotely. + +This distribution-specific startup wiring and upstream configuration adapter are temporary and +isolated in `custom`'s `com.splunk.opentelemetry.jmx` package for removal when upstream supports +embedded rules. + ## Webengine Attributes > :construction:  Status: Experimental diff --git a/opamp/src/main/java/com/splunk/opentelemetry/opamp/OpampActivator.java b/opamp/src/main/java/com/splunk/opentelemetry/opamp/OpampActivator.java index 5e4d5140f..aa05978c6 100644 --- a/opamp/src/main/java/com/splunk/opentelemetry/opamp/OpampActivator.java +++ b/opamp/src/main/java/com/splunk/opentelemetry/opamp/OpampActivator.java @@ -21,6 +21,7 @@ import static java.util.logging.Level.WARNING; import com.google.auto.service.AutoService; +import com.splunk.opentelemetry.jmx.JmxMetricInsightSupervisor; import com.splunk.opentelemetry.opamp.effectiveconfig.EffectiveConfigReporter; import com.splunk.opentelemetry.opamp.effectiveconfig.UpdatableEffectiveConfigState; import com.splunk.opentelemetry.profiler.ProfilingSupervisor; @@ -125,6 +126,7 @@ private static RemoteConfigProcessor buildRemoteConfigProcessor( return new RemoteConfigProcessorImpl( ProfilingSupervisor.SUPPLIER.get(), SnapshotProfilingSupervisor.SUPPLIER.get(), + JmxMetricInsightSupervisor.getInstance(), effectiveConfigReporter); } return RemoteConfigProcessor.NOOP; diff --git a/opamp/src/main/java/com/splunk/opentelemetry/opamp/RemoteConfigProcessorImpl.java b/opamp/src/main/java/com/splunk/opentelemetry/opamp/RemoteConfigProcessorImpl.java index 453902158..2eb99ad45 100644 --- a/opamp/src/main/java/com/splunk/opentelemetry/opamp/RemoteConfigProcessorImpl.java +++ b/opamp/src/main/java/com/splunk/opentelemetry/opamp/RemoteConfigProcessorImpl.java @@ -16,9 +16,8 @@ package com.splunk.opentelemetry.opamp; -import static io.opentelemetry.api.incubator.config.DeclarativeConfigProperties.empty; - import com.google.common.annotations.VisibleForTesting; +import com.splunk.opentelemetry.jmx.JmxMetricInsightSupervisor; import com.splunk.opentelemetry.opamp.effectiveconfig.EffectiveConfigReporter; import com.splunk.opentelemetry.profiler.ProfilerConfiguration; import com.splunk.opentelemetry.profiler.ProfilerDeclarativeConfigurationFactory; @@ -49,14 +48,17 @@ public class RemoteConfigProcessorImpl implements RemoteConfigProcessor { private final ProfilingSupervisor profilingSupervisor; private final SnapshotProfilingSupervisor snapshotProfilingSupervisor; + private final JmxMetricInsightSupervisor jmxMetricInsightSupervisor; private final EffectiveConfigReporter effectiveConfigReporter; public RemoteConfigProcessorImpl( ProfilingSupervisor profilingSupervisor, SnapshotProfilingSupervisor snapshotProfilingSupervisor, + JmxMetricInsightSupervisor jmxMetricInsightSupervisor, EffectiveConfigReporter effectiveConfigReporter) { this.profilingSupervisor = Objects.requireNonNull(profilingSupervisor); this.snapshotProfilingSupervisor = Objects.requireNonNull(snapshotProfilingSupervisor); + this.jmxMetricInsightSupervisor = Objects.requireNonNull(jmxMetricInsightSupervisor); this.effectiveConfigReporter = Objects.requireNonNull(effectiveConfigReporter); } @@ -83,9 +85,7 @@ public void applyConfig(AgentRemoteConfig remoteConfig, OpampClient opampClient) DeclarativeConfigProperties remoteConfigProperties = toDeclarativeConfigProperties(configFile); DeclarativeConfigProperties distributionRemoteConfigProperties = - remoteConfigProperties - .getStructured("distribution", empty()) - .getStructured("splunk", empty()); + remoteConfigProperties.get("distribution").get("splunk"); // Update profiler configuration only when profiling node exists if (distributionRemoteConfigProperties.getPropertyKeys().contains(PROFILING_NODE_NAME)) { @@ -93,6 +93,8 @@ public void applyConfig(AgentRemoteConfig remoteConfig, OpampClient opampClient) applySnapshotProfilingConfiguration(distributionRemoteConfigProperties); } + handleJmxConfiguration(remoteConfigProperties); + // Confirm to the OpAMP Server that remote config has been applied. reportRemoteConfigStatus( remoteConfig.config_hash, RemoteConfigStatuses.RemoteConfigStatuses_APPLIED, opampClient); @@ -107,10 +109,19 @@ public void applyConfig(AgentRemoteConfig remoteConfig, OpampClient opampClient) effectiveConfigReporter.reportEffectiveConfigIfChanged(); } + private void handleJmxConfiguration(DeclarativeConfigProperties remoteConfigProperties) + throws Exception { + DeclarativeConfigProperties javaConfig = + remoteConfigProperties.get("distribution").get("splunk").get("java"); + if (javaConfig.getPropertyKeys().contains("jmx")) { + jmxMetricInsightSupervisor.applyConfiguration(javaConfig.get("jmx")); + } + } + private void applyAlwaysOnProfilingConfiguration( DeclarativeConfigProperties distributionRemoteConfigProperties) { DeclarativeConfigProperties profilingConfig = - distributionRemoteConfigProperties.getStructured(PROFILING_NODE_NAME, empty()); + distributionRemoteConfigProperties.get(PROFILING_NODE_NAME); if (!profilingConfig.getPropertyKeys().contains(ALWAYS_ON_NODE_NAME)) { // Always On Profiling is managed by profiling.always_on.cpu_profiler node so if parent // node is missing then there is nothing to do. @@ -139,7 +150,7 @@ private void applySnapshotProfilingConfiguration( DeclarativeConfigProperties distributionRemoteConfigProperties) { SnapshotProfilingConfiguration receivedConfiguration = SnapshotProfilingDeclarativeConfigurationFactory.create( - distributionRemoteConfigProperties.getStructured(PROFILING_NODE_NAME, empty())); + distributionRemoteConfigProperties.get(PROFILING_NODE_NAME)); SnapshotProfilingConfiguration currentConfiguration = SnapshotProfilingConfiguration.SUPPLIER.get(); diff --git a/opamp/src/test/java/com/splunk/opentelemetry/opamp/RemoteConfigProcessorImplTest.java b/opamp/src/test/java/com/splunk/opentelemetry/opamp/RemoteConfigProcessorImplTest.java index 4e0d520b3..da1161c64 100644 --- a/opamp/src/test/java/com/splunk/opentelemetry/opamp/RemoteConfigProcessorImplTest.java +++ b/opamp/src/test/java/com/splunk/opentelemetry/opamp/RemoteConfigProcessorImplTest.java @@ -17,17 +17,21 @@ package com.splunk.opentelemetry.opamp; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; +import com.splunk.opentelemetry.jmx.JmxMetricInsightSupervisor; import com.splunk.opentelemetry.opamp.effectiveconfig.EffectiveConfigReporter; import com.splunk.opentelemetry.profiler.ProfilerConfiguration; import com.splunk.opentelemetry.profiler.ProfilingSupervisor; import com.splunk.opentelemetry.profiler.snapshot.SnapshotProfilingConfiguration; import com.splunk.opentelemetry.profiler.snapshot.SnapshotProfilingSupervisor; +import io.opentelemetry.api.incubator.config.DeclarativeConfigProperties; import io.opentelemetry.opamp.client.OpampClient; import java.time.Duration; import java.util.List; @@ -51,6 +55,7 @@ class RemoteConfigProcessorImplTest { @Mock ProfilingSupervisor profilingSupervisor; @Mock SnapshotProfilingSupervisor snapshotProfilingSupervisor; + @Mock JmxMetricInsightSupervisor jmxMetricInsightSupervisor; @Mock EffectiveConfigReporter effectiveConfigReporter; @Mock OpampClient opampClient; private RemoteConfigProcessorImpl handler; @@ -62,7 +67,10 @@ void setUp() { SnapshotProfilingConfiguration.defaultConfiguration()); handler = new RemoteConfigProcessorImpl( - profilingSupervisor, snapshotProfilingSupervisor, effectiveConfigReporter); + profilingSupervisor, + snapshotProfilingSupervisor, + jmxMetricInsightSupervisor, + effectiveConfigReporter); } @AfterEach @@ -111,7 +119,8 @@ void shouldMarkRemoteConfigAsAppliedWhenProfilingConfigIsNotProvided() { assertThat(status.error_message).isEmpty(); assertThat(ProfilerConfiguration.SUPPLIER.get().isEnabled()).isFalse(); verify(effectiveConfigReporter).reportEffectiveConfigIfChanged(); - verifyNoInteractions(profilingSupervisor, snapshotProfilingSupervisor); + verifyNoInteractions( + profilingSupervisor, snapshotProfilingSupervisor, jmxMetricInsightSupervisor); } @Test @@ -138,7 +147,8 @@ void shouldReportErrorWhenRemoteConfigProcessingFailed() { assertThat(ProfilerConfiguration.SUPPLIER.get().isEnabled()).isFalse(); assertThat(ProfilerConfiguration.SUPPLIER.get().getCallStackInterval().toMillis()) .isEqualTo(10000); - verifyNoInteractions(profilingSupervisor, snapshotProfilingSupervisor); + verifyNoInteractions( + profilingSupervisor, snapshotProfilingSupervisor, jmxMetricInsightSupervisor); verify(effectiveConfigReporter).reportEffectiveConfigIfChanged(); } @@ -157,10 +167,81 @@ void shouldIgnoreRemoteConfigWithoutExpectedConfigFile() { // then assertThat(ProfilerConfiguration.SUPPLIER.get().isEnabled()).isFalse(); - verifyNoInteractions(opampClient, profilingSupervisor, snapshotProfilingSupervisor); + verifyNoInteractions( + opampClient, profilingSupervisor, snapshotProfilingSupervisor, jmxMetricInsightSupervisor); verify(effectiveConfigReporter, never()).reportEffectiveConfigIfChanged(); } + @Nested + class JmxConfigurationTest { + @Test + void forwardsDistributionJmxSettingsToSupervisor() throws Exception { + AgentRemoteConfig remoteConfig = + createRemoteConfig( + ByteString.encodeUtf8("jmx-config-hash"), + """ + distribution: + splunk: + java: + jmx: + discovery: + delay: 2000 + rules: + - bean: test:type=Monitor + """); + + handler.applyConfig(remoteConfig, opampClient); + + ArgumentCaptor configuration = + ArgumentCaptor.forClass(DeclarativeConfigProperties.class); + verify(jmxMetricInsightSupervisor).applyConfiguration(configuration.capture()); + assertThat(DeclarativeConfigProperties.toMap(configuration.getValue())) + .isEqualTo( + Map.of( + "discovery", Map.of("delay", 2000L), + "rules", List.of(Map.of("bean", "test:type=Monitor")))); + assertThat(getFinalReportedRemoteConfigStatus().status) + .isEqualTo(RemoteConfigStatuses.RemoteConfigStatuses_APPLIED); + verifyNoInteractions(profilingSupervisor, snapshotProfilingSupervisor); + verify(effectiveConfigReporter).reportEffectiveConfigIfChanged(); + } + + @Test + void forwardsAnEmptyDistributionJmxNode() throws Exception { + AgentRemoteConfig remoteConfig = + createRemoteConfig( + ByteString.encodeUtf8("jmx-config-hash"), + "distribution:\n splunk:\n java:\n jmx:\n"); + + handler.applyConfig(remoteConfig, opampClient); + + ArgumentCaptor configuration = + ArgumentCaptor.forClass(DeclarativeConfigProperties.class); + verify(jmxMetricInsightSupervisor).applyConfiguration(configuration.capture()); + assertThat(configuration.getValue().getPropertyKeys()).isEmpty(); + assertThat(getFinalReportedRemoteConfigStatus().status) + .isEqualTo(RemoteConfigStatuses.RemoteConfigStatuses_APPLIED); + } + + @Test + void reportsFailureWhenSupervisorCannotApplyTheUpdate() throws Exception { + doThrow(new IllegalArgumentException("Invalid JMX rules")) + .when(jmxMetricInsightSupervisor) + .applyConfiguration(any()); + AgentRemoteConfig remoteConfig = + createRemoteConfig( + ByteString.encodeUtf8("jmx-config-hash"), + "distribution:\n splunk:\n java:\n jmx: {}\n"); + + handler.applyConfig(remoteConfig, opampClient); + + RemoteConfigStatus status = getFinalReportedRemoteConfigStatus(); + assertThat(status.status).isEqualTo(RemoteConfigStatuses.RemoteConfigStatuses_FAILED); + assertThat(status.error_message).contains("Invalid JMX rules"); + verify(effectiveConfigReporter).reportEffectiveConfigIfChanged(); + } + } + @Nested class AlwaysOnProfilerTest { @Test