Repository navigation
add: apollo opentelemetry metric. #149
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
teaho2015
wants to merge
6
commits into
apolloconfig:main
Choose a base branch
from
teaho-infra:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
6e631f7
feat: export Apollo client metrics through OpenTelemetry
teaho2015 6d95278
Merge branch 'main' into main
teaho2015 c824c33
fix(plugin): do not claim the global OpenTelemetry slot and keep gaug…
teaho2015 d285582
test(plugin): let the OpenTelemetry exporter tests fail on unexpected…
teaho2015 2854ffb
style(plugin): apply the official code style to the OpenTelemetry exp…
teaho2015 09f25f1
test(plugin): exercise null and empty tags after the exporter is init…
teaho2015 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,63 @@ | ||
| <?xml version="1.0" encoding="UTF-8"?> | ||
| <!-- | ||
| ~ Copyright 2022 Apollo Authors | ||
| ~ | ||
| ~ 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. | ||
| ~ | ||
| --> | ||
| <project xmlns="http://maven.apache.org/POM/4.0.0" | ||
| xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" | ||
| xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> | ||
| <modelVersion>4.0.0</modelVersion> | ||
| <parent> | ||
| <artifactId>apollo-plugin</artifactId> | ||
| <groupId>com.ctrip.framework.apollo</groupId> | ||
| <version>${revision}</version> | ||
| <relativePath>../pom.xml</relativePath> | ||
| </parent> | ||
|
|
||
| <artifactId>apollo-plugin-client-opentelemetry</artifactId> | ||
| <name>Apollo Plugin OpenTelemetry</name> | ||
| <packaging>jar</packaging> | ||
|
|
||
| <dependencies> | ||
| <dependency> | ||
| <groupId>com.ctrip.framework.apollo</groupId> | ||
| <artifactId>apollo-client</artifactId> | ||
| <scope>provided</scope> | ||
| </dependency> | ||
| <dependency> | ||
| <groupId>io.opentelemetry</groupId> | ||
| <artifactId>opentelemetry-api</artifactId> | ||
| <version>1.62.0</version> | ||
| </dependency> | ||
| <!-- Test dependencies --> | ||
| <dependency> | ||
| <groupId>io.opentelemetry</groupId> | ||
| <artifactId>opentelemetry-sdk-testing</artifactId> | ||
| <version>1.62.0</version> | ||
| <scope>test</scope> | ||
| </dependency> | ||
| <dependency> | ||
| <groupId>junit</groupId> | ||
| <artifactId>junit</artifactId> | ||
| <scope>test</scope> | ||
| </dependency> | ||
| <dependency> | ||
| <groupId>org.mockito</groupId> | ||
| <artifactId>mockito-inline</artifactId> | ||
| <scope>test</scope> | ||
| </dependency> | ||
| </dependencies> | ||
|
|
||
| </project> |
240 changes: 240 additions & 0 deletions
240
...ework/apollo/monitor/internal/exporter/impl/OpenTelemetryApolloClientMetricsExporter.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,240 @@ | ||
| /* | ||
| * Copyright 2026 Apollo Authors | ||
| * | ||
| * 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.ctrip.framework.apollo.monitor.internal.exporter.impl; | ||
|
|
||
| import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory; | ||
| import com.ctrip.framework.apollo.monitor.internal.exporter.AbstractApolloClientMetricsExporter; | ||
| import com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporter; | ||
| import io.opentelemetry.api.GlobalOpenTelemetry; | ||
| import io.opentelemetry.api.OpenTelemetry; | ||
| import io.opentelemetry.api.common.Attributes; | ||
| import io.opentelemetry.api.common.AttributesBuilder; | ||
| import io.opentelemetry.api.metrics.DoubleCounter; | ||
| import io.opentelemetry.api.metrics.Meter; | ||
| import io.opentelemetry.api.metrics.MeterProvider; | ||
| import io.opentelemetry.api.metrics.ObservableDoubleGauge; | ||
| import io.opentelemetry.api.metrics.ObservableDoubleMeasurement; | ||
|
|
||
| import java.util.Map; | ||
| import java.util.concurrent.ConcurrentHashMap; | ||
| import org.slf4j.Logger; | ||
|
|
||
| /** | ||
| * OpenTelemetry implementation of Apollo client metrics exporter. | ||
| * Only uses OpenTelemetry API layer (no SDK dependency). | ||
| * | ||
| * <p>Two design notes that matter for correctness: | ||
| * | ||
| * <ul> | ||
| * <li>The global OpenTelemetry instance is never claimed eagerly. | ||
| * {@link GlobalOpenTelemetry#get()} registers a no-op global as a side effect, which would | ||
| * make a later {@code OpenTelemetrySdk.buildAndRegisterGlobal()} fail with | ||
| * {@link IllegalStateException}. | ||
| * This exporter therefore uses {@link GlobalOpenTelemetry#getOrNoop()} and re-resolves the | ||
| * global on every use, so it works whether Apollo starts before or after the application's | ||
| * OpenTelemetry SDK is registered. | ||
| * <li>Gauges are asynchronous (observable) instruments. A synchronous gauge only reports a point | ||
| * when it is set, so an idle collection cycle drops the series entirely for delta-preferred | ||
| * metric readers. Observable gauges are asked for their value on every collection, so the | ||
| * last known value keeps being reported. | ||
| * </ul> | ||
| * | ||
| * @author leon.he@walmart.com | ||
| */ | ||
| public class OpenTelemetryApolloClientMetricsExporter extends AbstractApolloClientMetricsExporter | ||
| implements ApolloClientMetricsExporter { | ||
|
|
||
| private static final String OPENTELEMETRY = "opentelemetry"; | ||
| private static final String METER_NAME = "apollo-client"; | ||
| private static final String COUNTER_UNIT = "1"; | ||
| private static final String GAUGE_UNIT = "1"; | ||
|
|
||
| /** | ||
| * Placeholder used when the OpenTelemetry API unexpectedly returns a null observable gauge. | ||
| */ | ||
| private static final ObservableDoubleGauge NOOP_OBSERVABLE_GAUGE = new ObservableDoubleGauge() { | ||
| @Override | ||
| public void close() { | ||
| // nothing to close | ||
| } | ||
| }; | ||
|
|
||
| private final Logger logger = | ||
| DeferredLoggerFactory.getLogger(OpenTelemetryApolloClientMetricsExporter.class); | ||
|
|
||
| /** | ||
| * Latest known value of every gauge series, keyed by metric name plus attribute set. | ||
| */ | ||
| private final Map<SeriesKey, Double> gaugeValues = new ConcurrentHashMap<>(); | ||
|
|
||
| /** | ||
| * Observable gauges created so far. An observable instrument is registered once per meter; the | ||
| * callback attached to it reports the cached values on every collection. | ||
| */ | ||
| private final Map<String, ObservableDoubleGauge> gaugeMap = new ConcurrentHashMap<>(); | ||
|
|
||
| private Map<String, DoubleCounter> counterMap; | ||
|
|
||
| @Override | ||
| public void doInit() { | ||
| // Initialize maps | ||
| counterMap = new ConcurrentHashMap<>(); | ||
| logger.info("OpenTelemetry metrics exporter initialized for meter: {}", METER_NAME); | ||
| } | ||
|
|
||
| @Override | ||
| public boolean isSupport(String form) { | ||
| return OPENTELEMETRY.equals(form); | ||
| } | ||
|
|
||
| @Override | ||
| public void registerOrUpdateCounterSample(String name, Map<String, String> tags, | ||
| double incrValue) { | ||
| Meter meter = getMeter(); | ||
| if (meter == null) { | ||
| logger.warn("OpenTelemetry meter not available yet, skipping counter registration for '{}'", | ||
| name); | ||
| return; | ||
| } | ||
| DoubleCounter counter = counterMap.computeIfAbsent(name, key -> meter.counterBuilder(key) | ||
| .setDescription("Apollo counter metrics").setUnit(COUNTER_UNIT).ofDoubles().build()); | ||
| Attributes attributes = getOrCreateAttributes(tags); | ||
| counter.add(incrValue, attributes); | ||
|
|
||
| if (logger.isDebugEnabled()) { | ||
| logger.debug("Updated OpenTelemetry counter '{}' with value: {}, tags: {}", name, incrValue, | ||
| tags); | ||
| } | ||
| } | ||
|
|
||
| @Override | ||
| public void registerOrUpdateGaugeSample(String name, Map<String, String> tags, double value) { | ||
| // Remember the latest value of this series. The observable gauge callback reports it on every | ||
| // collection, so a series is not lost while it stays idle. | ||
| Attributes attributes = getOrCreateAttributes(tags); | ||
| gaugeValues.put(new SeriesKey(name, attributes), value); | ||
|
|
||
| Meter meter = getMeter(); | ||
| if (meter == null) { | ||
| logger.warn("OpenTelemetry meter not available yet, skipping gauge registration for '{}'", | ||
| name); | ||
| return; | ||
| } | ||
| // Register the observable gauge if not already registered. Its callback reports the cached | ||
| // values on every collection, so no further action is needed when the gauge already exists. | ||
| gaugeMap.computeIfAbsent(name, key -> { | ||
| ObservableDoubleGauge gauge = | ||
| meter.gaugeBuilder(key).setDescription("Apollo gauge metrics").setUnit(GAUGE_UNIT) | ||
| .buildWithCallback(measurement -> reportGaugeValues(measurement, key)); | ||
| // A null gauge is not expected from the OpenTelemetry API, but be defensive so that a | ||
| // failure here does not break the metrics collection. | ||
| return gauge != null ? gauge : NOOP_OBSERVABLE_GAUGE; | ||
| }); | ||
|
|
||
| if (logger.isDebugEnabled()) { | ||
| logger.debug("Updated OpenTelemetry gauge '{}' with value: {}, tags: {}", name, value, tags); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Reports every cached gauge value of the given metric to the SDK. Invoked on each collection by | ||
| * the SDK, which keeps idle series alive. | ||
| */ | ||
| private void reportGaugeValues(ObservableDoubleMeasurement measurement, String metricName) { | ||
| gaugeValues.forEach((series, value) -> { | ||
| if (!series.name.equals(metricName)) { | ||
| return; | ||
| } | ||
| measurement.record(value, series.attributes); | ||
| }); | ||
| } | ||
|
|
||
| @Override | ||
| public String response() { | ||
| // Return simple status information since we're only using API layer | ||
| int counterCount = counterMap != null ? counterMap.size() : 0; | ||
| int gaugeCount = gaugeMap != null ? gaugeMap.size() : 0; | ||
|
|
||
| String meterStatus = getMeter() != null ? METER_NAME : "not initialized"; | ||
| return String.format( | ||
| "OpenTelemetry metrics exporter status - Counters: %d, Gauges: %d, Meter: %s", counterCount, | ||
| gaugeCount, meterStatus); | ||
| } | ||
|
|
||
| /** | ||
| * Resolves the meter from the currently registered global OpenTelemetry instance. | ||
| * | ||
| * <p>{@link GlobalOpenTelemetry#getOrNoop()} is used on purpose: unlike {@link | ||
| * GlobalOpenTelemetry#get()} it does not claim the global slot, so an application that registers | ||
| * its OpenTelemetry SDK later is not affected by this exporter having been initialized first. | ||
| * The global is re-resolved on every call so that the exporter picks up the SDK once it is | ||
| * registered. | ||
| * | ||
| * @return the meter, or {@code null} when no OpenTelemetry SDK is registered yet | ||
| */ | ||
| private Meter getMeter() { | ||
| OpenTelemetry openTelemetry = GlobalOpenTelemetry.getOrNoop(); | ||
| if (openTelemetry == OpenTelemetry.noop()) { | ||
| return null; | ||
| } | ||
| MeterProvider meterProvider = openTelemetry.getMeterProvider(); | ||
| if (meterProvider == null) { | ||
| return null; | ||
| } | ||
| return meterProvider.meterBuilder(METER_NAME).build(); | ||
| } | ||
|
|
||
| private Attributes getOrCreateAttributes(Map<String, String> tags) { | ||
| if (tags == null || tags.isEmpty()) { | ||
| return Attributes.empty(); | ||
| } | ||
| AttributesBuilder builder = Attributes.builder(); | ||
| tags.forEach(builder::put); | ||
| return builder.build(); | ||
| } | ||
|
|
||
| /** | ||
| * Identifies a gauge series by its metric name and attribute set. | ||
| */ | ||
| private static final class SeriesKey { | ||
|
|
||
| private final String name; | ||
| private final Attributes attributes; | ||
|
|
||
| private SeriesKey(String name, Attributes attributes) { | ||
| this.name = name; | ||
| this.attributes = attributes; | ||
| } | ||
|
|
||
| @Override | ||
| public boolean equals(Object o) { | ||
| if (this == o) { | ||
| return true; | ||
| } | ||
| if (!(o instanceof SeriesKey)) { | ||
| return false; | ||
| } | ||
| SeriesKey other = (SeriesKey) o; | ||
| return name.equals(other.name) && attributes.equals(other.attributes); | ||
| } | ||
|
|
||
| @Override | ||
| public int hashCode() { | ||
| return 31 * name.hashCode() + attributes.hashCode(); | ||
| } | ||
| } | ||
| } | ||
1 change: 1 addition & 0 deletions
1
...services/com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| com.ctrip.framework.apollo.monitor.internal.exporter.impl.OpenTelemetryApolloClientMetricsExporter |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Cached gauges are not registered after SDK registration.
A gauge that receives its value before the SDK is registered keeps the value in
gaugeValues, but the observable gauge is not created. WhengetMeter()returnsnull,registerOrUpdateGaugeSamplereturns beforegaugeMap.computeIfAbsentruns. After the SDK is registered, the scheduled export handles only listeners that report updated samples. Without another update to the same metric name, the gauge is never created, and collections omit its cached value until that update arrives.Reconcile pending gauge registrations during the periodic exporter work, even when no listener changed. Once a meter is available, create the observable gauge for each cached metric name that has no registration. Keep the
computeIfAbsentregistration idempotent for names that already have a gauge.Add a regression test that records
12.0before SDK registration, registers the SDK, and collects without another gauge update.