repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/SlidingWindow.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/SlidingWindow.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.aggregate; import org.apache.dubbo.common.utils.Assert; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicReferenceArray; import java.util.concurrent.locks.ReentrantLock; /** * SlidingWindow adopts sliding window algorithm for statistics. * <p> * A window contains {@code paneCount} panes, * {@code intervalInMs} = {@code paneCount} * {@code paneIntervalInMs} * * @param <T> Value type for window statistics. */ public abstract class SlidingWindow<T> { /** * The number of panes the sliding window contains. */ protected int paneCount; /** * Total time interval of the sliding window in milliseconds. */ protected long intervalInMs; /** * Time interval of a pane in milliseconds. */ protected long paneIntervalInMs; /** * The panes reference, supports atomic operations. */ protected final AtomicReferenceArray<Pane<T>> referenceArray; /** * The lock is used only when current pane is deprecated. */ private final ReentrantLock updateLock = new ReentrantLock(); protected SlidingWindow(int paneCount, long intervalInMs) { Assert.assertTrue(paneCount > 0, "pane count is invalid: " + paneCount); Assert.assertTrue(intervalInMs > 0, "total time interval of the sliding window should be positive"); Assert.assertTrue(intervalInMs % paneCount == 0, "total time interval needs to be evenly divided"); this.paneCount = paneCount; this.intervalInMs = intervalInMs; this.paneIntervalInMs = intervalInMs / paneCount; this.referenceArray = new AtomicReferenceArray<>(paneCount); } /** * Get the pane at the current timestamp. * * @return the pane at current timestamp. */ public Pane<T> currentPane() { return currentPane(System.currentTimeMillis()); } /** * Get the pane at the specified timestamp in milliseconds. * * @param timeMillis a timestamp in milliseconds. * @return the pane at the specified timestamp if the time is valid; null if time is invalid. */ public Pane<T> currentPane(long timeMillis) { if (timeMillis < 0) { return null; } int paneIdx = calculatePaneIdx(timeMillis); long paneStartInMs = calculatePaneStart(timeMillis); while (true) { Pane<T> oldPane = referenceArray.get(paneIdx); // Create a pane instance when the pane does not exist. if (oldPane == null) { Pane<T> pane = new Pane<>(paneIntervalInMs, paneStartInMs, newEmptyValue(timeMillis)); if (referenceArray.compareAndSet(paneIdx, null, pane)) { return pane; } else { // Contention failed, the thread will yield its time slice to wait for pane available. Thread.yield(); } } // else if (paneStartInMs == oldPane.getStartInMs()) { return oldPane; } // The pane has deprecated. To avoid the overhead of creating a new instance, reset the original pane // directly. else if (paneStartInMs > oldPane.getStartInMs()) { if (updateLock.tryLock()) { try { return resetPaneTo(oldPane, paneStartInMs); } finally { updateLock.unlock(); } } else { // Contention failed, the thread will yield its time slice to wait for pane available. Thread.yield(); } } // The specified timestamp has passed. else if (paneStartInMs < oldPane.getStartInMs()) { return new Pane<>(paneIntervalInMs, paneStartInMs, newEmptyValue(timeMillis)); } } } /** * Get statistic value from pane at the specified timestamp. * * @param timeMillis the specified timestamp in milliseconds. * @return the statistic value if pane at the specified timestamp is up-to-date; otherwise null. */ public T getPaneValue(long timeMillis) { if (timeMillis < 0) { return null; } int paneIdx = calculatePaneIdx(timeMillis); Pane<T> pane = referenceArray.get(paneIdx); if (pane == null || !pane.isTimeInWindow(timeMillis)) { return null; } return pane.getValue(); } /** * Create a new statistic value for pane. * * @param timeMillis the specified timestamp in milliseconds. * @return new empty statistic value. */ public abstract T newEmptyValue(long timeMillis); /** * Reset given pane to the specified start time and reset the value. * * @param pane the given pane. * @param startInMs the start timestamp of the pane in milliseconds. * @return reset pane. */ protected abstract Pane<T> resetPaneTo(final Pane<T> pane, long startInMs); /** * Calculate the pane index corresponding to the specified timestamp. * * @param timeMillis the specified timestamp. * @return the pane index corresponding to the specified timestamp. */ private int calculatePaneIdx(long timeMillis) { return (int) ((timeMillis / paneIntervalInMs) % paneCount); } /** * Calculate the pane start corresponding to the specified timestamp. * * @param timeMillis the specified timestamp. * @return the pane start corresponding to the specified timestamp. */ protected long calculatePaneStart(long timeMillis) { return timeMillis - timeMillis % paneIntervalInMs; } /** * Checks if the specified pane is deprecated at the current timestamp. * * @param pane the specified pane. * @return true if the pane is deprecated; otherwise false. */ public boolean isPaneDeprecated(final Pane<T> pane) { return isPaneDeprecated(System.currentTimeMillis(), pane); } /** * Checks if the specified pane is deprecated at the specified timestamp. * * @param timeMillis the specified time. * @param pane the specified pane. * @return true if the pane is deprecated; otherwise false. */ public boolean isPaneDeprecated(long timeMillis, final Pane<T> pane) { // the pane is '[)' return (timeMillis - pane.getStartInMs()) > intervalInMs; } /** * Get valid pane list for entire sliding window at the current time. * The list will only contain "valid" panes. * * @return valid pane list for entire sliding window. */ public List<Pane<T>> list() { return list(System.currentTimeMillis()); } /** * Get valid pane list for entire sliding window at the specified time. * The list will only contain "valid" panes. * * @param timeMillis the specified time. * @return valid pane list for entire sliding window. */ public List<Pane<T>> list(long timeMillis) { if (timeMillis < 0) { return new ArrayList<>(); } List<Pane<T>> result = new ArrayList<>(paneCount); for (int idx = 0; idx < paneCount; idx++) { Pane<T> pane = referenceArray.get(idx); if (pane == null || isPaneDeprecated(timeMillis, pane)) { continue; } result.add(pane); } return result; } /** * Get aggregated value list for entire sliding window at the current time. * The list will only contain value from "valid" panes. * * @return aggregated value list for entire sliding window. */ public List<T> values() { return values(System.currentTimeMillis()); } /** * Get aggregated value list for entire sliding window at the specified time. * The list will only contain value from "valid" panes. * * @return aggregated value list for entire sliding window. */ public List<T> values(long timeMillis) { if (timeMillis < 0) { return new ArrayList<>(); } List<T> result = new ArrayList<>(paneCount); for (int idx = 0; idx < paneCount; idx++) { Pane<T> pane = referenceArray.get(idx); if (pane == null || isPaneDeprecated(timeMillis, pane)) { continue; } result.add(pane.getValue()); } return result; } /** * Get total interval of the sliding window in milliseconds. * * @return the total interval in milliseconds. */ public long getIntervalInMs() { return intervalInMs; } /** * Get pane interval of the sliding window in milliseconds. * * @return the interval of a pane in milliseconds. */ public long getPaneIntervalInMs() { return paneIntervalInMs; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/TimeWindowCounter.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/TimeWindowCounter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.aggregate; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.LongAdder; /** * Wrapper around Counter like Long and Integer. */ public class TimeWindowCounter { private final LongAdderSlidingWindow slidingWindow; public TimeWindowCounter(int bucketNum, long timeWindowSeconds) { this.slidingWindow = new LongAdderSlidingWindow(bucketNum, TimeUnit.SECONDS.toMillis(timeWindowSeconds)); } public double get() { double result = 0.0; List<LongAdder> windows = this.slidingWindow.values(); for (LongAdder window : windows) { result += window.sum(); } return result; } public long bucketLivedSeconds() { return TimeUnit.MILLISECONDS.toSeconds( this.slidingWindow.values().size() * this.slidingWindow.getPaneIntervalInMs()); } public long bucketLivedMillSeconds() { return this.slidingWindow.getIntervalInMs() - (System.currentTimeMillis() - this.slidingWindow.currentPane().getEndInMs()); } public void increment() { this.increment(1L); } public void increment(Long step) { this.slidingWindow.currentPane().getValue().add(step); } public void decrement() { this.decrement(1L); } public void decrement(Long step) { this.slidingWindow.currentPane().getValue().add(-step); } /** * Sliding window of type LongAdder. */ private static class LongAdderSlidingWindow extends SlidingWindow<LongAdder> { public LongAdderSlidingWindow(int sampleCount, long intervalInMs) { super(sampleCount, intervalInMs); } @Override public LongAdder newEmptyValue(long timeMillis) { return new LongAdder(); } @Override protected Pane<LongAdder> resetPaneTo(final Pane<LongAdder> pane, long startTime) { pane.setStartInMs(startTime); pane.getValue().reset(); return pane; } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/DubboAbstractTDigest.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/DubboAbstractTDigest.java
/* * Licensed to Ted Dunning under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.aggregate; import com.tdunning.math.stats.Centroid; import com.tdunning.math.stats.TDigest; public abstract class DubboAbstractTDigest extends TDigest { boolean recordAllData = false; /** * Same as {@link #weightedAverageSorted(double, double, double, double)} but flips * the order of the variables if <code>x2</code> is greater than * <code>x1</code>. */ static double weightedAverage(double x1, double w1, double x2, double w2) { if (x1 <= x2) { return weightedAverageSorted(x1, w1, x2, w2); } else { return weightedAverageSorted(x2, w2, x1, w1); } } /** * Compute the weighted average between <code>x1</code> with a weight of * <code>w1</code> and <code>x2</code> with a weight of <code>w2</code>. * This expects <code>x1</code> to be less than or equal to <code>x2</code> * and is guaranteed to return a number in <code>[x1, x2]</code>. An * explicit check is required since this isn't guaranteed with floating-point * numbers. */ private static double weightedAverageSorted(double x1, double w1, double x2, double w2) { assert x1 <= x2; final double x = (x1 * w1 + x2 * w2) / (w1 + w2); return Math.max(x1, Math.min(x, x2)); } abstract void add(double x, int w, Centroid base); /** * Sets up so that all centroids will record all data assigned to them. For testing only, really. */ @Override public TDigest recordAllData() { recordAllData = true; return this; } @Override public boolean isRecording() { return recordAllData; } /** * Adds a sample to a histogram. * * @param x The value to add. */ @Override public void add(double x) { add(x, 1); } @Override public void add(TDigest other) { for (Centroid centroid : other.centroids()) { add(centroid.mean(), centroid.count(), centroid); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/utils/MetricsSupportUtil.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/utils/MetricsSupportUtil.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.utils; import org.apache.dubbo.common.utils.ClassUtils; public class MetricsSupportUtil { public static boolean isSupportMetrics() { return isClassPresent("io.micrometer.core.instrument.MeterRegistry"); } public static boolean isSupportPrometheus() { return isClassPresent("io.micrometer.prometheus.PrometheusConfig") && isClassPresent("io.prometheus.client.exporter.BasicAuthHttpConnectionFactory") && isClassPresent("io.prometheus.client.exporter.HttpConnectionFactory") && isClassPresent("io.prometheus.client.exporter.PushGateway"); } private static boolean isClassPresent(String className) { return ClassUtils.isPresent(className, MetricsSupportUtil.class.getClassLoader()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/report/AbstractMetricsExport.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/report/AbstractMetricsExport.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.report; import org.apache.dubbo.metrics.model.MethodMetric; import org.apache.dubbo.rpc.model.ApplicationModel; /** * Store public information such as application */ public abstract class AbstractMetricsExport implements MetricsExport { private volatile Boolean serviceLevel; private final ApplicationModel applicationModel; public AbstractMetricsExport(ApplicationModel applicationModel) { this.applicationModel = applicationModel; } public ApplicationModel getApplicationModel() { return applicationModel; } public String getAppName() { return getApplicationModel().getApplicationName(); } protected boolean getServiceLevel() { initServiceLevelConfig(); return this.serviceLevel; } private void initServiceLevelConfig() { if (serviceLevel == null) { synchronized (this) { if (serviceLevel == null) { this.serviceLevel = MethodMetric.isServiceLevel(getApplicationModel()); } } } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/report/MetricsReporterFactory.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/report/MetricsReporterFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.report; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Adaptive; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; /** * The factory interface to create the instance of {@link MetricsReporter}. */ @SPI(value = "nop", scope = ExtensionScope.APPLICATION) public interface MetricsReporterFactory { /** * Create metrics reporter. * * @param url URL * @return Metrics reporter implementation. */ @Adaptive({CommonConstants.PROTOCOL_KEY}) MetricsReporter createMetricsReporter(URL url); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/report/MetricsExport.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/report/MetricsExport.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.report; import org.apache.dubbo.metrics.model.MetricsCategory; import org.apache.dubbo.metrics.model.sample.MetricSample; import java.util.List; /** * Metrics data export. * Export data in a unified format for external collection(e.g. Prometheus). */ public interface MetricsExport { /** * export all. */ List<MetricSample> export(MetricsCategory category); /** * Check if samples have been changed. * Note that this method will reset the changed flag to false using CAS. * * @return true if samples have been changed */ boolean calSamplesChanged(); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/report/AbstractMetricsReporterFactory.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/report/AbstractMetricsReporterFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.report; import org.apache.dubbo.rpc.model.ApplicationModel; /** * AbstractMetricsReporterFactory. */ public abstract class AbstractMetricsReporterFactory implements MetricsReporterFactory { private final ApplicationModel applicationModel; public AbstractMetricsReporterFactory(ApplicationModel applicationModel) { this.applicationModel = applicationModel; } protected ApplicationModel getApplicationModel() { return applicationModel; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/report/MetricsReporter.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/report/MetricsReporter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.report; /** * Metrics Reporter. * Report metrics to specific metrics server(e.g. Prometheus). */ public interface MetricsReporter { /** * Initialize metrics reporter. */ void init(); void resetIfSamplesChanged(); String getResponse(); default String getResponseWithName(String metricsName) { return null; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/MetricsDispatcher.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/MetricsDispatcher.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.event; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.metrics.collector.MetricsCollector; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.List; /** * Global spi event publisher */ public class MetricsDispatcher extends SimpleMetricsEventMulticaster { @SuppressWarnings({"rawtypes"}) public MetricsDispatcher(ApplicationModel applicationModel) { ScopeBeanFactory beanFactory = applicationModel.getBeanFactory(); ExtensionLoader<MetricsCollector> extensionLoader = applicationModel.getExtensionLoader(MetricsCollector.class); if (extensionLoader != null) { List<MetricsCollector> customizeCollectors = extensionLoader.getActivateExtensions(); for (MetricsCollector customizeCollector : customizeCollectors) { beanFactory.registerBean(customizeCollector); } customizeCollectors.forEach(this::addListener); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/MetricsInitEvent.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/MetricsInitEvent.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.event; import org.apache.dubbo.metrics.MetricsConstants; import org.apache.dubbo.metrics.model.MethodMetric; import org.apache.dubbo.metrics.model.MetricsSupport; import org.apache.dubbo.metrics.model.key.MetricsLevel; import org.apache.dubbo.metrics.model.key.TypeWrapper; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.model.ApplicationModel; import static org.apache.dubbo.metrics.MetricsConstants.ATTACHMENT_KEY_SERVICE; import static org.apache.dubbo.metrics.model.key.MetricsKey.METRIC_REQUESTS; public class MetricsInitEvent extends TimeCounterEvent { private static final TypeWrapper METRIC_EVENT = new TypeWrapper(MetricsLevel.SERVICE, METRIC_REQUESTS); public MetricsInitEvent(ApplicationModel source, TypeWrapper typeWrapper) { super(source, typeWrapper); } public static MetricsInitEvent toMetricsInitEvent( ApplicationModel applicationModel, Invocation invocation, boolean serviceLevel) { MethodMetric methodMetric = new MethodMetric(applicationModel, invocation, serviceLevel); MetricsInitEvent initEvent = new MetricsInitEvent(applicationModel, METRIC_EVENT); initEvent.putAttachment(MetricsConstants.INVOCATION, invocation); initEvent.putAttachment(MetricsConstants.METHOD_METRICS, methodMetric); initEvent.putAttachment(ATTACHMENT_KEY_SERVICE, MetricsSupport.getInterfaceName(invocation)); initEvent.putAttachment(MetricsConstants.INVOCATION_SIDE, MetricsSupport.getSide(invocation)); return initEvent; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/SimpleMetricsEventMulticaster.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/SimpleMetricsEventMulticaster.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.event; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.metrics.listener.MetricsLifeListener; import org.apache.dubbo.metrics.listener.MetricsListener; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.function.Consumer; /** * A simple event publisher that defines lifecycle events and supports rt events */ public class SimpleMetricsEventMulticaster implements MetricsEventMulticaster { private final List<MetricsListener<?>> listeners = Collections.synchronizedList(new ArrayList<>()); @Override public void addListener(MetricsListener<?> listener) { listeners.add(listener); } @Override @SuppressWarnings({"rawtypes", "unchecked"}) public void publishEvent(MetricsEvent event) { if (validateIfApplicationConfigExist(event)) return; for (MetricsListener listener : listeners) { if (listener.isSupport(event)) { listener.onEvent(event); } } } private boolean validateIfApplicationConfigExist(MetricsEvent event) { if (event.getSource() != null) { // Check if exist application config return StringUtils.isEmpty(event.appName()); } return false; } @Override @SuppressWarnings({"unchecked"}) public void publishFinishEvent(TimeCounterEvent event) { publishTimeEvent(event, metricsLifeListener -> metricsLifeListener.onEventFinish(event)); } @Override @SuppressWarnings({"unchecked"}) public void publishErrorEvent(TimeCounterEvent event) { publishTimeEvent(event, metricsLifeListener -> metricsLifeListener.onEventError(event)); } @SuppressWarnings({"rawtypes"}) private void publishTimeEvent(MetricsEvent event, Consumer<MetricsLifeListener> consumer) { if (validateIfApplicationConfigExist(event)) return; if (event instanceof TimeCounterEvent) { ((TimeCounterEvent) event).getTimePair().end(); } for (MetricsListener listener : listeners) { if (listener instanceof MetricsLifeListener && listener.isSupport(event)) { consumer.accept(((MetricsLifeListener) listener)); } } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/data/ApplicationStatComposite.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/data/ApplicationStatComposite.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.data; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.metrics.model.MetricsCategory; import org.apache.dubbo.metrics.model.MetricsSupport; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.model.sample.GaugeMetricSample; import org.apache.dubbo.metrics.model.sample.MetricSample; import org.apache.dubbo.metrics.report.AbstractMetricsExport; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; /** * Application-level data container, for the initialized MetricsKey, * different from the null value of the Map type (the key is not displayed when there is no data), * the key is displayed and the initial data is 0 value of the AtomicLong type */ public class ApplicationStatComposite extends AbstractMetricsExport { public ApplicationStatComposite(ApplicationModel applicationModel) { super(applicationModel); } private final Map<MetricsKey, AtomicLong> applicationNumStats = new ConcurrentHashMap<>(); private final AtomicBoolean samplesChanged = new AtomicBoolean(true); public void init(List<MetricsKey> appKeys) { if (CollectionUtils.isEmpty(appKeys)) { return; } appKeys.forEach(appKey -> { applicationNumStats.put(appKey, new AtomicLong(0L)); }); samplesChanged.set(true); } public void incrementSize(MetricsKey metricsKey, int size) { if (!applicationNumStats.containsKey(metricsKey)) { return; } applicationNumStats.get(metricsKey).getAndAdd(size); } public void setAppKey(MetricsKey metricsKey, Long num) { if (!applicationNumStats.containsKey(metricsKey)) { return; } applicationNumStats.get(metricsKey).set(num); } public List<MetricSample> export(MetricsCategory category) { List<MetricSample> list = new ArrayList<>(); for (MetricsKey type : applicationNumStats.keySet()) { list.add(convertToSample(type, category, applicationNumStats.get(type))); } return list; } @SuppressWarnings({"rawtypes"}) private GaugeMetricSample convertToSample(MetricsKey type, MetricsCategory category, AtomicLong targetNumber) { return new GaugeMetricSample<>( type, MetricsSupport.applicationTags(getApplicationModel()), category, targetNumber, AtomicLong::get); } public Map<MetricsKey, AtomicLong> getApplicationNumStats() { return applicationNumStats; } @Override public boolean calSamplesChanged() { // CAS to get and reset the flag in an atomic operation return samplesChanged.compareAndSet(true, false); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/data/ServiceStatComposite.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/data/ServiceStatComposite.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.data; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import org.apache.dubbo.metrics.model.MetricsCategory; import org.apache.dubbo.metrics.model.ServiceKeyMetric; import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper; import org.apache.dubbo.metrics.model.sample.GaugeMetricSample; import org.apache.dubbo.metrics.model.sample.MetricSample; import org.apache.dubbo.metrics.report.AbstractMetricsExport; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; /** * Service-level data container, for the initialized MetricsKey, * different from the null value of the Map type (the key is not displayed when there is no data), * the key is displayed and the initial data is 0 value of the AtomicLong type */ public class ServiceStatComposite extends AbstractMetricsExport { private final AtomicBoolean samplesChanged = new AtomicBoolean(true); public ServiceStatComposite(ApplicationModel applicationModel) { super(applicationModel); } private final ConcurrentHashMap<MetricsKeyWrapper, ConcurrentHashMap<ServiceKeyMetric, AtomicLong>> serviceWrapperNumStats = new ConcurrentHashMap<>(); public void initWrapper(List<MetricsKeyWrapper> metricsKeyWrappers) { if (CollectionUtils.isEmpty(metricsKeyWrappers)) { return; } metricsKeyWrappers.forEach(appKey -> { serviceWrapperNumStats.put(appKey, new ConcurrentHashMap<>()); }); samplesChanged.set(true); } public void incrementServiceKey(MetricsKeyWrapper wrapper, String serviceKey, int size) { incrementExtraServiceKey(wrapper, serviceKey, null, size); } public void incrementExtraServiceKey( MetricsKeyWrapper wrapper, String serviceKey, Map<String, String> extra, int size) { if (!serviceWrapperNumStats.containsKey(wrapper)) { return; } ServiceKeyMetric serviceKeyMetric = new ServiceKeyMetric(getApplicationModel(), serviceKey); if (extra != null) { serviceKeyMetric.setExtraInfo(extra); } ConcurrentHashMap<ServiceKeyMetric, AtomicLong> map = serviceWrapperNumStats.get(wrapper); AtomicLong metrics = map.get(serviceKeyMetric); if (metrics == null) { metrics = ConcurrentHashMapUtils.computeIfAbsent(map, serviceKeyMetric, k -> new AtomicLong(0L)); samplesChanged.set(true); } metrics.getAndAdd(size); // MetricsSupport.fillZero(serviceWrapperNumStats); } public void setServiceKey(MetricsKeyWrapper wrapper, String serviceKey, int num) { setExtraServiceKey(wrapper, serviceKey, num, null); } public void setExtraServiceKey(MetricsKeyWrapper wrapper, String serviceKey, int num, Map<String, String> extra) { if (!serviceWrapperNumStats.containsKey(wrapper)) { return; } ServiceKeyMetric serviceKeyMetric = new ServiceKeyMetric(getApplicationModel(), serviceKey); if (extra != null) { serviceKeyMetric.setExtraInfo(extra); } ConcurrentHashMap<ServiceKeyMetric, AtomicLong> stats = serviceWrapperNumStats.get(wrapper); AtomicLong metrics = stats.get(serviceKeyMetric); if (metrics == null) { metrics = ConcurrentHashMapUtils.computeIfAbsent(stats, serviceKeyMetric, k -> new AtomicLong(0L)); samplesChanged.set(true); } metrics.set(num); } @Override public List<MetricSample> export(MetricsCategory category) { List<MetricSample> list = new ArrayList<>(); for (MetricsKeyWrapper wrapper : serviceWrapperNumStats.keySet()) { Map<ServiceKeyMetric, AtomicLong> stringAtomicLongMap = serviceWrapperNumStats.get(wrapper); for (ServiceKeyMetric serviceKeyMetric : stringAtomicLongMap.keySet()) { list.add(new GaugeMetricSample<>( wrapper, serviceKeyMetric.getTags(), category, stringAtomicLongMap, value -> value.get( serviceKeyMetric) .get())); } } return list; } @Override public boolean calSamplesChanged() { // CAS to get and reset the flag in an atomic operation return samplesChanged.compareAndSet(true, false); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/data/RtStatComposite.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/data/RtStatComposite.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.data; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import org.apache.dubbo.metrics.model.MethodMetric; import org.apache.dubbo.metrics.model.Metric; import org.apache.dubbo.metrics.model.MetricsCategory; import org.apache.dubbo.metrics.model.ServiceKeyMetric; import org.apache.dubbo.metrics.model.container.AtomicLongContainer; import org.apache.dubbo.metrics.model.container.LongAccumulatorContainer; import org.apache.dubbo.metrics.model.container.LongContainer; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper; import org.apache.dubbo.metrics.model.key.MetricsPlaceValue; import org.apache.dubbo.metrics.model.sample.GaugeMetricSample; import org.apache.dubbo.metrics.model.sample.MetricSample; import org.apache.dubbo.metrics.report.AbstractMetricsExport; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.LongAccumulator; import java.util.function.BiConsumer; import java.util.stream.Collectors; /** * The data container of the rt dimension, including application, service, and method levels, * if there is no actual call to the existing call method, * the key will not be displayed when exporting (to be optimized) */ @SuppressWarnings({"rawtypes", "unchecked"}) public class RtStatComposite extends AbstractMetricsExport { private final AtomicBoolean samplesChanged = new AtomicBoolean(true); public RtStatComposite(ApplicationModel applicationModel) { super(applicationModel); } private final ConcurrentHashMap<String, List<LongContainer<? extends Number>>> rtStats = new ConcurrentHashMap<>(); public void init(MetricsPlaceValue... placeValues) { if (placeValues == null) { return; } for (MetricsPlaceValue placeValue : placeValues) { List<LongContainer<? extends Number>> containers = initStats(placeValue); for (LongContainer<? extends Number> container : containers) { ConcurrentHashMapUtils.computeIfAbsent( rtStats, container.getMetricsKeyWrapper().getType(), k -> new ArrayList<>()) .add(container); } } samplesChanged.set(true); } private List<LongContainer<? extends Number>> initStats(MetricsPlaceValue placeValue) { List<LongContainer<? extends Number>> singleRtStats = new ArrayList<>(); singleRtStats.add(new AtomicLongContainer(new MetricsKeyWrapper(MetricsKey.METRIC_RT_LAST, placeValue))); singleRtStats.add(new LongAccumulatorContainer( new MetricsKeyWrapper(MetricsKey.METRIC_RT_MIN, placeValue), new LongAccumulator(Long::min, Long.MAX_VALUE))); singleRtStats.add(new LongAccumulatorContainer( new MetricsKeyWrapper(MetricsKey.METRIC_RT_MAX, placeValue), new LongAccumulator(Long::max, Long.MIN_VALUE))); singleRtStats.add(new AtomicLongContainer( new MetricsKeyWrapper(MetricsKey.METRIC_RT_SUM, placeValue), (responseTime, longAccumulator) -> longAccumulator.addAndGet(responseTime))); // AvgContainer is a special counter that stores the number of times but outputs function of sum/times AtomicLongContainer avgContainer = new AtomicLongContainer( new MetricsKeyWrapper(MetricsKey.METRIC_RT_AVG, placeValue), (k, v) -> v.incrementAndGet()); avgContainer.setValueSupplier(applicationName -> { LongContainer<? extends Number> totalContainer = rtStats.values().stream() .flatMap(List::stream) .filter(longContainer -> longContainer.isKeyWrapper(MetricsKey.METRIC_RT_SUM, placeValue.getType())) .findFirst() .get(); AtomicLong totalRtTimes = avgContainer.get(applicationName); AtomicLong totalRtSum = (AtomicLong) totalContainer.get(applicationName); return totalRtSum.get() / totalRtTimes.get(); }); singleRtStats.add(avgContainer); return singleRtStats; } public void calcServiceKeyRt(String registryOpType, Long responseTime, Metric key) { for (LongContainer container : rtStats.get(registryOpType)) { Number current = (Number) container.get(key); if (current == null) { container.putIfAbsent(key, container.getInitFunc().apply(key)); samplesChanged.set(true); current = (Number) container.get(key); } container.getConsumerFunc().accept(responseTime, current); } } public void calcServiceKeyRt(Invocation invocation, String registryOpType, Long responseTime) { List<Action> actions; if (invocation.getServiceModel() != null && invocation.getServiceModel().getServiceKey() != null) { Map<String, Object> attributeMap = invocation.getServiceModel().getServiceMetadata().getAttributeMap(); Map<String, List<Action>> cache = (Map<String, List<Action>>) attributeMap.get("ServiceKeyRt"); if (cache == null) { attributeMap.putIfAbsent("ServiceKeyRt", new ConcurrentHashMap<>(32)); cache = (Map<String, List<Action>>) attributeMap.get("ServiceKeyRt"); } actions = cache.get(registryOpType); if (actions == null) { actions = calServiceRtActions(invocation, registryOpType); cache.putIfAbsent(registryOpType, actions); samplesChanged.set(true); actions = cache.get(registryOpType); } } else { actions = calServiceRtActions(invocation, registryOpType); } for (Action action : actions) { action.run(responseTime); } } private List<Action> calServiceRtActions(Invocation invocation, String registryOpType) { List<Action> actions; actions = new LinkedList<>(); ServiceKeyMetric key = new ServiceKeyMetric(getApplicationModel(), invocation.getTargetServiceUniqueName()); for (LongContainer container : rtStats.get(registryOpType)) { Number current = (Number) container.get(key); if (current == null) { container.putIfAbsent(key, container.getInitFunc().apply(key)); samplesChanged.set(true); current = (Number) container.get(key); } actions.add(new Action(container.getConsumerFunc(), current)); } return actions; } public void calcMethodKeyRt(Invocation invocation, String registryOpType, Long responseTime) { List<Action> actions; if (getServiceLevel() && invocation.getServiceModel() != null && invocation.getServiceModel().getServiceMetadata() != null) { Map<String, Object> attributeMap = invocation.getServiceModel().getServiceMetadata().getAttributeMap(); Map<String, List<Action>> cache = (Map<String, List<Action>>) attributeMap.get("MethodKeyRt"); if (cache == null) { attributeMap.putIfAbsent("MethodKeyRt", new ConcurrentHashMap<>(32)); cache = (Map<String, List<Action>>) attributeMap.get("MethodKeyRt"); } actions = cache.get(registryOpType); if (actions == null) { actions = calMethodRtActions(invocation, registryOpType); cache.putIfAbsent(registryOpType, actions); samplesChanged.set(true); actions = cache.get(registryOpType); } } else { actions = calMethodRtActions(invocation, registryOpType); } for (Action action : actions) { action.run(responseTime); } } private List<Action> calMethodRtActions(Invocation invocation, String registryOpType) { List<Action> actions; actions = new LinkedList<>(); for (LongContainer container : rtStats.get(registryOpType)) { MethodMetric key = new MethodMetric(getApplicationModel(), invocation, getServiceLevel()); Number current = (Number) container.get(key); if (current == null) { container.putIfAbsent(key, container.getInitFunc().apply(key)); samplesChanged.set(true); current = (Number) container.get(key); } actions.add(new Action(container.getConsumerFunc(), current)); } return actions; } public List<MetricSample> export(MetricsCategory category) { List<MetricSample> list = new ArrayList<>(); for (List<LongContainer<? extends Number>> containers : rtStats.values()) { for (LongContainer<? extends Number> container : containers) { MetricsKeyWrapper metricsKeyWrapper = container.getMetricsKeyWrapper(); for (Metric key : container.keySet()) { // Use keySet to obtain the original key instance reference of ConcurrentHashMap to avoid early // recycling of the micrometer list.add(new GaugeMetricSample<>( metricsKeyWrapper.targetKey(), metricsKeyWrapper.targetDesc(), key.getTags(), category, key, value -> container.getValueSupplier().apply(value))); } } } return list; } public List<LongContainer<? extends Number>> getRtStats() { return rtStats.values().stream().flatMap(List::stream).collect(Collectors.toList()); } private static class Action { private final BiConsumer<Long, Number> consumerFunc; private final Number initValue; public Action(BiConsumer<Long, Number> consumerFunc, Number initValue) { this.consumerFunc = consumerFunc; this.initValue = initValue; } public void run(Long responseTime) { consumerFunc.accept(responseTime, initValue); } } @Override public boolean calSamplesChanged() { // CAS to get and reset the flag in an atomic operation return samplesChanged.compareAndSet(true, false); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/data/BaseStatComposite.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/data/BaseStatComposite.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.data; import org.apache.dubbo.metrics.collector.MetricsCollector; import org.apache.dubbo.metrics.model.ApplicationMetric; import org.apache.dubbo.metrics.model.MethodMetric; import org.apache.dubbo.metrics.model.MetricsCategory; import org.apache.dubbo.metrics.model.ServiceKeyMetric; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper; import org.apache.dubbo.metrics.model.sample.MetricSample; import org.apache.dubbo.metrics.report.MetricsExport; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * As a data aggregator, use internal data containers calculates and classifies * the registry data collected by {@link MetricsCollector MetricsCollector}, and * provides an {@link MetricsExport MetricsExport} interface for exporting standard output formats. */ public abstract class BaseStatComposite implements MetricsExport { private ApplicationStatComposite applicationStatComposite; private ServiceStatComposite serviceStatComposite; private MethodStatComposite methodStatComposite; private RtStatComposite rtStatComposite; public BaseStatComposite(ApplicationModel applicationModel) { init(new ApplicationStatComposite(applicationModel)); init(new ServiceStatComposite(applicationModel)); init(new MethodStatComposite(applicationModel)); init(new RtStatComposite(applicationModel)); } protected void init(ApplicationStatComposite applicationStatComposite) { this.applicationStatComposite = applicationStatComposite; } protected void init(ServiceStatComposite serviceStatComposite) { this.serviceStatComposite = serviceStatComposite; } protected void init(MethodStatComposite methodStatComposite) { this.methodStatComposite = methodStatComposite; } protected void init(RtStatComposite rtStatComposite) { this.rtStatComposite = rtStatComposite; } public void calcApplicationRt(String registryOpType, Long responseTime) { rtStatComposite.calcServiceKeyRt( registryOpType, responseTime, new ApplicationMetric(rtStatComposite.getApplicationModel())); } public void calcServiceKeyRt(String serviceKey, String registryOpType, Long responseTime) { rtStatComposite.calcServiceKeyRt( registryOpType, responseTime, new ServiceKeyMetric(rtStatComposite.getApplicationModel(), serviceKey)); } public void calcServiceKeyRt(Invocation invocation, String registryOpType, Long responseTime) { rtStatComposite.calcServiceKeyRt(invocation, registryOpType, responseTime); } public void calcMethodKeyRt(Invocation invocation, String registryOpType, Long responseTime) { rtStatComposite.calcMethodKeyRt(invocation, registryOpType, responseTime); } public void setServiceKey(MetricsKeyWrapper metricsKey, String serviceKey, int num) { serviceStatComposite.setServiceKey(metricsKey, serviceKey, num); } public void setServiceKey(MetricsKeyWrapper metricsKey, String serviceKey, int num, Map<String, String> extra) { serviceStatComposite.setExtraServiceKey(metricsKey, serviceKey, num, extra); } public void incrementApp(MetricsKey metricsKey, int size) { applicationStatComposite.incrementSize(metricsKey, size); } public void incrementServiceKey(MetricsKeyWrapper metricsKeyWrapper, String attServiceKey, int size) { serviceStatComposite.incrementServiceKey(metricsKeyWrapper, attServiceKey, size); } public void incrementServiceKey( MetricsKeyWrapper metricsKeyWrapper, String attServiceKey, Map<String, String> extra, int size) { serviceStatComposite.incrementExtraServiceKey(metricsKeyWrapper, attServiceKey, extra, size); } public void incrementMethodKey(MetricsKeyWrapper metricsKeyWrapper, MethodMetric methodMetric, int size) { methodStatComposite.incrementMethodKey(metricsKeyWrapper, methodMetric, size); } public void initMethodKey(MetricsKeyWrapper metricsKeyWrapper, Invocation invocation) { methodStatComposite.initMethodKey(metricsKeyWrapper, invocation); } @Override public List<MetricSample> export(MetricsCategory category) { List<MetricSample> list = new ArrayList<>(); list.addAll(applicationStatComposite.export(category)); list.addAll(rtStatComposite.export(category)); list.addAll(serviceStatComposite.export(category)); list.addAll(methodStatComposite.export(category)); return list; } public ApplicationStatComposite getApplicationStatComposite() { return applicationStatComposite; } public RtStatComposite getRtStatComposite() { return rtStatComposite; } public void setAppKey(MetricsKey metricsKey, Long num) { applicationStatComposite.setAppKey(metricsKey, num); } @Override public boolean calSamplesChanged() { // Should ensure that all the composite's samplesChanged have been compareAndSet, and cannot flip the `or` logic boolean changed = applicationStatComposite.calSamplesChanged(); changed = rtStatComposite.calSamplesChanged() || changed; changed = serviceStatComposite.calSamplesChanged() || changed; changed = methodStatComposite.calSamplesChanged() || changed; return changed; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/data/MethodStatComposite.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/data/MethodStatComposite.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.data; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import org.apache.dubbo.metrics.exception.MetricsNeverHappenException; import org.apache.dubbo.metrics.model.MethodMetric; import org.apache.dubbo.metrics.model.MetricsCategory; import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper; import org.apache.dubbo.metrics.model.sample.CounterMetricSample; import org.apache.dubbo.metrics.model.sample.GaugeMetricSample; import org.apache.dubbo.metrics.model.sample.MetricSample; import org.apache.dubbo.metrics.report.AbstractMetricsExport; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; /** * Method-level data container, * if there is no actual call to the existing call method, * the key will not be displayed when exporting (to be optimized) */ public class MethodStatComposite extends AbstractMetricsExport { private final AtomicBoolean samplesChanged = new AtomicBoolean(true); public MethodStatComposite(ApplicationModel applicationModel) { super(applicationModel); } private final ConcurrentHashMap<MetricsKeyWrapper, ConcurrentHashMap<MethodMetric, AtomicLong>> methodNumStats = new ConcurrentHashMap<>(); public void initWrapper(List<MetricsKeyWrapper> metricsKeyWrappers) { if (CollectionUtils.isEmpty(metricsKeyWrappers)) { return; } metricsKeyWrappers.forEach(appKey -> { methodNumStats.put(appKey, new ConcurrentHashMap<>()); }); samplesChanged.set(true); } public void initMethodKey(MetricsKeyWrapper wrapper, Invocation invocation) { if (!methodNumStats.containsKey(wrapper)) { return; } ConcurrentHashMapUtils.computeIfAbsent( methodNumStats.get(wrapper), new MethodMetric(getApplicationModel(), invocation, getServiceLevel()), k -> new AtomicLong(0L)); samplesChanged.set(true); } public void incrementMethodKey(MetricsKeyWrapper wrapper, MethodMetric methodMetric, int size) { if (!methodNumStats.containsKey(wrapper)) { return; } AtomicLong stat = methodNumStats.get(wrapper).get(methodMetric); if (stat == null) { ConcurrentHashMapUtils.computeIfAbsent( methodNumStats.get(wrapper), methodMetric, (k) -> new AtomicLong(0L)); samplesChanged.set(true); stat = methodNumStats.get(wrapper).get(methodMetric); } stat.getAndAdd(size); // MetricsSupport.fillZero(methodNumStats); } public List<MetricSample> export(MetricsCategory category) { List<MetricSample> list = new ArrayList<>(); for (MetricsKeyWrapper wrapper : methodNumStats.keySet()) { Map<MethodMetric, AtomicLong> stringAtomicLongMap = methodNumStats.get(wrapper); for (MethodMetric methodMetric : stringAtomicLongMap.keySet()) { if (wrapper.getSampleType() == MetricSample.Type.COUNTER) { list.add(new CounterMetricSample<>( wrapper, methodMetric.getTags(), category, stringAtomicLongMap.get(methodMetric))); } else if (wrapper.getSampleType() == MetricSample.Type.GAUGE) { list.add(new GaugeMetricSample<>( wrapper, methodMetric.getTags(), category, stringAtomicLongMap, value -> value.get( methodMetric) .get())); } else { throw new MetricsNeverHappenException("Unsupported metricSample type: " + wrapper.getSampleType()); } } } return list; } @Override public boolean calSamplesChanged() { // CAS to get and reset the flag in an atomic operation return samplesChanged.compareAndSet(true, false); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/AbstractMetricsKeyListener.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/AbstractMetricsKeyListener.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.listener; import org.apache.dubbo.metrics.event.MetricsEvent; import org.apache.dubbo.metrics.event.MetricsEventBus; import org.apache.dubbo.metrics.event.TimeCounterEvent; import org.apache.dubbo.metrics.model.key.MetricsKey; import java.util.function.Consumer; /** * According to the event template of {@link MetricsEventBus}, * build a consistent static method for general and custom monitoring consume methods * */ public abstract class AbstractMetricsKeyListener extends AbstractMetricsListener<TimeCounterEvent> implements MetricsLifeListener<TimeCounterEvent> { private final MetricsKey metricsKey; public AbstractMetricsKeyListener(MetricsKey metricsKey) { this.metricsKey = metricsKey; } /** * The MetricsKey type determines whether events are supported */ @Override public boolean isSupport(MetricsEvent event) { return super.isSupport(event) && event.isAssignableFrom(metricsKey); } @Override public void onEvent(TimeCounterEvent event) {} public static AbstractMetricsKeyListener onEvent(MetricsKey metricsKey, Consumer<TimeCounterEvent> postFunc) { return new AbstractMetricsKeyListener(metricsKey) { @Override public void onEvent(TimeCounterEvent event) { postFunc.accept(event); } }; } public static AbstractMetricsKeyListener onFinish(MetricsKey metricsKey, Consumer<TimeCounterEvent> finishFunc) { return new AbstractMetricsKeyListener(metricsKey) { @Override public void onEventFinish(TimeCounterEvent event) { finishFunc.accept(event); } }; } public static AbstractMetricsKeyListener onError(MetricsKey metricsKey, Consumer<TimeCounterEvent> errorFunc) { return new AbstractMetricsKeyListener(metricsKey) { @Override public void onEventError(TimeCounterEvent event) { errorFunc.accept(event); } }; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/MetricsLifeListener.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/MetricsLifeListener.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.listener; import org.apache.dubbo.metrics.event.TimeCounterEvent; /** * Metrics Listener. */ public interface MetricsLifeListener<E extends TimeCounterEvent> extends MetricsListener<E> { default void onEventFinish(E event) {} default void onEventError(E event) {} }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/MetricsApplicationListener.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/MetricsApplicationListener.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.listener; import org.apache.dubbo.metrics.collector.CombMetricsCollector; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.model.key.MetricsPlaceValue; /** * App-level listener type, in most cases, can use the static method * to produce an anonymous listener for general monitoring */ public class MetricsApplicationListener extends AbstractMetricsKeyListener { public MetricsApplicationListener(MetricsKey metricsKey) { super(metricsKey); } /** * Perform auto-increment on the monitored key, * Can use a custom listener instead of this generic operation * * @param metricsKey Monitor key * @param collector Corresponding collector */ public static AbstractMetricsKeyListener onPostEventBuild( MetricsKey metricsKey, CombMetricsCollector<?> collector) { return AbstractMetricsKeyListener.onEvent(metricsKey, event -> collector.increment(metricsKey)); } /** * To end the monitoring normally, in addition to increasing the number of corresponding indicators, * use the introspection method to calculate the relevant rt indicators * * @param metricsKey Monitor key * @param collector Corresponding collector */ public static AbstractMetricsKeyListener onFinishEventBuild( MetricsKey metricsKey, MetricsPlaceValue placeType, CombMetricsCollector<?> collector) { return AbstractMetricsKeyListener.onFinish(metricsKey, event -> { collector.increment(metricsKey); collector.addApplicationRt(placeType.getType(), event.getTimePair().calc()); }); } /** * Similar to onFinishEventBuild */ public static AbstractMetricsKeyListener onErrorEventBuild( MetricsKey metricsKey, MetricsPlaceValue placeType, CombMetricsCollector<?> collector) { return AbstractMetricsKeyListener.onError(metricsKey, event -> { collector.increment(metricsKey); collector.addApplicationRt(placeType.getType(), event.getTimePair().calc()); }); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/MetricsServiceListener.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/MetricsServiceListener.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.listener; import org.apache.dubbo.metrics.collector.ServiceMetricsCollector; import org.apache.dubbo.metrics.event.TimeCounterEvent; import org.apache.dubbo.metrics.model.MetricsSupport; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.model.key.MetricsPlaceValue; /** * Service-level listener type, in most cases, can use the static method * to produce an anonymous listener for general monitoring. * Similar to App-level */ public class MetricsServiceListener extends AbstractMetricsKeyListener { public MetricsServiceListener(MetricsKey metricsKey) { super(metricsKey); } public static AbstractMetricsKeyListener onPostEventBuild( MetricsKey metricsKey, MetricsPlaceValue placeType, ServiceMetricsCollector<TimeCounterEvent> collector) { return AbstractMetricsKeyListener.onEvent( metricsKey, event -> MetricsSupport.increment(metricsKey, placeType, collector, event)); } public static AbstractMetricsKeyListener onFinishEventBuild( MetricsKey metricsKey, MetricsPlaceValue placeType, ServiceMetricsCollector<TimeCounterEvent> collector) { return AbstractMetricsKeyListener.onFinish( metricsKey, event -> MetricsSupport.incrAndAddRt(metricsKey, placeType, collector, event)); } public static AbstractMetricsKeyListener onErrorEventBuild( MetricsKey metricsKey, MetricsPlaceValue placeType, ServiceMetricsCollector<TimeCounterEvent> collector) { return AbstractMetricsKeyListener.onError( metricsKey, event -> MetricsSupport.incrAndAddRt(metricsKey, placeType, collector, event)); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/AbstractMetricsListener.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/AbstractMetricsListener.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.listener; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import org.apache.dubbo.common.utils.ReflectionUtils; import org.apache.dubbo.metrics.event.MetricsEvent; import java.util.concurrent.ConcurrentHashMap; public abstract class AbstractMetricsListener<E extends MetricsEvent> implements MetricsListener<E> { private final ConcurrentHashMap<Class<?>, Boolean> eventMatchCache = new ConcurrentHashMap<>(); /** * Whether to support the general determination of event points depends on the event type */ public boolean isSupport(MetricsEvent event) { Boolean eventMatch = ConcurrentHashMapUtils.computeIfAbsent( eventMatchCache, event.getClass(), clazz -> ReflectionUtils.match(getClass(), AbstractMetricsListener.class, event)); return event.isAvailable() && eventMatch; } @Override public abstract void onEvent(E event); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/monitor/Monitor.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/monitor/Monitor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.monitor; import org.apache.dubbo.common.Node; /** * Monitor. (SPI, Prototype, ThreadSafe) * * @see org.apache.dubbo.monitor.MonitorFactory#getMonitor(org.apache.dubbo.common.URL) */ @Deprecated public interface Monitor extends Node, MonitorService {}
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/monitor/MonitorFactory.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/monitor/MonitorFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.monitor; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Adaptive; import org.apache.dubbo.common.extension.SPI; /** * MonitorFactory. (SPI, Singleton, ThreadSafe) */ @Deprecated @SPI public interface MonitorFactory { /** * Create monitor. * * @param url * @return monitor */ @Adaptive(CommonConstants.PROTOCOL_KEY) Monitor getMonitor(URL url); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/monitor/MonitorService.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/monitor/MonitorService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.monitor; import org.apache.dubbo.common.URL; import java.util.List; /** * MonitorService. (SPI, Prototype, ThreadSafe) */ @Deprecated public interface MonitorService { /** * Collect monitor data * 1. support invocation count: count://host/interface?application=foo&method=foo&provider=10.20.153.11:20880&success=12&failure=2&elapsed=135423423 * 1.1 host,application,interface,group,version,method: record source host/application/interface/method * 1.2 add provider address parameter if it's data sent from consumer, otherwise, add source consumer's address in parameters * 1.3 success,failure,elapsed: record success count, failure count, and total cost for success invocations, average cost (total cost/success calls) * * @param statistics */ void collect(URL statistics); /** * Lookup monitor data * 1. support lookup by day: count://host/interface?application=foo&method=foo&side=provider&view=chart&date=2012-07-03 * 1.1 host,application,interface,group,version,method: query criteria for looking up by host, application, interface, method. When one criterion is not present, it means ALL will be accepted, but 0.0.0.0 is ALL for host * 1.2 side=consumer,provider: decide the data from which side, both provider and consumer are returned by default * 1.3 default value is view=summary, to return the summarized data for the whole day. view=chart will return the URL address showing the whole day trend which is convenient for embedding in other web page * 1.4 date=2012-07-03: specify the date to collect the data, today is the default value * * @param query * @return statistics */ List<URL> lookup(URL query); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/monitor/Constants.java
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/monitor/Constants.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.monitor; @Deprecated public interface Constants { String DUBBO_PROVIDER = "dubbo.provider"; String DUBBO_CONSUMER = "dubbo.consumer"; String DUBBO_PROVIDER_METHOD = "dubbo.provider.method"; String DUBBO_CONSUMER_METHOD = "dubbo.consumer.method"; String SERVICE = "service"; String DUBBO_GROUP = "dubbo"; String LOGSTAT_PROTOCOL = "logstat"; String COUNT_PROTOCOL = "count"; String MONITOR_SEND_DATA_INTERVAL_KEY = "interval"; int DEFAULT_MONITOR_SEND_DATA_INTERVAL = 60000; String SUCCESS_KEY = "success"; String FAILURE_KEY = "failure"; String INPUT_KEY = "input"; String OUTPUT_KEY = "output"; String ELAPSED_KEY = "elapsed"; String CONCURRENT_KEY = "concurrent"; String MAX_INPUT_KEY = "max.input"; String MAX_OUTPUT_KEY = "max.output"; String MAX_ELAPSED_KEY = "max.elapsed"; String MAX_CONCURRENT_KEY = "max.concurrent"; }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-metadata/src/test/java/org/apache/dubbo/metrics/metadata/MetadataStatCompositeTest.java
dubbo-metrics/dubbo-metrics-metadata/src/test/java/org/apache/dubbo/metrics/metadata/MetadataStatCompositeTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.metadata; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.metrics.data.ApplicationStatComposite; import org.apache.dubbo.metrics.data.BaseStatComposite; import org.apache.dubbo.metrics.data.RtStatComposite; import org.apache.dubbo.metrics.data.ServiceStatComposite; import org.apache.dubbo.metrics.model.ApplicationMetric; import org.apache.dubbo.metrics.model.Metric; import org.apache.dubbo.metrics.model.container.LongContainer; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import java.util.Map; import java.util.Optional; import java.util.concurrent.atomic.AtomicLong; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.metrics.metadata.MetadataMetricsConstants.OP_TYPE_PUSH; import static org.apache.dubbo.metrics.metadata.MetadataMetricsConstants.OP_TYPE_STORE_PROVIDER_INTERFACE; import static org.apache.dubbo.metrics.metadata.MetadataMetricsConstants.OP_TYPE_SUBSCRIBE; public class MetadataStatCompositeTest { private ApplicationModel applicationModel; private BaseStatComposite statComposite; @BeforeEach public void setup() { FrameworkModel frameworkModel = FrameworkModel.defaultModel(); applicationModel = frameworkModel.newApplication(); ApplicationConfig application = new ApplicationConfig(); application.setName("App1"); applicationModel.getApplicationConfigManager().setApplication(application); statComposite = new BaseStatComposite(applicationModel) { @Override protected void init(ApplicationStatComposite applicationStatComposite) { super.init(applicationStatComposite); applicationStatComposite.init(MetadataMetricsConstants.APP_LEVEL_KEYS); } @Override protected void init(ServiceStatComposite serviceStatComposite) { super.init(serviceStatComposite); serviceStatComposite.initWrapper(MetadataMetricsConstants.SERVICE_LEVEL_KEYS); } @Override protected void init(RtStatComposite rtStatComposite) { super.init(rtStatComposite); rtStatComposite.init(OP_TYPE_PUSH, OP_TYPE_SUBSCRIBE, OP_TYPE_STORE_PROVIDER_INTERFACE); } }; } @Test void testInit() { Assertions.assertEquals( statComposite .getApplicationStatComposite() .getApplicationNumStats() .size(), MetadataMetricsConstants.APP_LEVEL_KEYS.size()); // (rt)5 * (push,subscribe,service)3 Assertions.assertEquals( 5 * 3, statComposite.getRtStatComposite().getRtStats().size()); statComposite .getApplicationStatComposite() .getApplicationNumStats() .values() .forEach((v -> Assertions.assertEquals(v.get(), new AtomicLong(0L).get()))); statComposite.getRtStatComposite().getRtStats().forEach(rtContainer -> { for (Map.Entry<Metric, ? extends Number> entry : rtContainer.entrySet()) { Assertions.assertEquals(0L, rtContainer.getValueSupplier().apply(entry.getKey())); } }); } @Test void testIncrement() { statComposite.incrementApp(MetricsKey.METADATA_PUSH_METRIC_NUM, 1); Assertions.assertEquals( 1L, statComposite .getApplicationStatComposite() .getApplicationNumStats() .get(MetricsKey.METADATA_PUSH_METRIC_NUM) .get()); } @Test void testCalcRt() { statComposite.calcApplicationRt(OP_TYPE_SUBSCRIBE.getType(), 10L); Assertions.assertTrue(statComposite.getRtStatComposite().getRtStats().stream() .anyMatch(longContainer -> longContainer.specifyType(OP_TYPE_SUBSCRIBE.getType()))); Optional<LongContainer<? extends Number>> subContainer = statComposite.getRtStatComposite().getRtStats().stream() .filter(longContainer -> longContainer.specifyType(OP_TYPE_SUBSCRIBE.getType())) .findFirst(); subContainer.ifPresent(v -> Assertions.assertEquals( 10L, v.get(new ApplicationMetric(applicationModel)).longValue())); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-metadata/src/test/java/org/apache/dubbo/metrics/metadata/MetadataMetricsCollectorTest.java
dubbo-metrics/dubbo-metrics-metadata/src/test/java/org/apache/dubbo/metrics/metadata/MetadataMetricsCollectorTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.metadata; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.metrics.event.MetricsDispatcher; import org.apache.dubbo.metrics.event.MetricsEvent; import org.apache.dubbo.metrics.event.MetricsEventBus; import org.apache.dubbo.metrics.metadata.collector.MetadataMetricsCollector; import org.apache.dubbo.metrics.metadata.event.MetadataEvent; import org.apache.dubbo.metrics.model.TimePair; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper; import org.apache.dubbo.metrics.model.sample.GaugeMetricSample; import org.apache.dubbo.metrics.model.sample.MetricSample; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Objects; import java.util.stream.Collectors; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_APPLICATION_NAME; import static org.apache.dubbo.metrics.metadata.MetadataMetricsConstants.OP_TYPE_PUSH; import static org.apache.dubbo.metrics.metadata.MetadataMetricsConstants.OP_TYPE_STORE_PROVIDER_INTERFACE; import static org.apache.dubbo.metrics.metadata.MetadataMetricsConstants.OP_TYPE_SUBSCRIBE; class MetadataMetricsCollectorTest { private ApplicationModel applicationModel; private MetadataMetricsCollector collector; @BeforeEach public void setup() { FrameworkModel frameworkModel = FrameworkModel.defaultModel(); applicationModel = frameworkModel.newApplication(); ApplicationConfig config = new ApplicationConfig(); config.setName("MockMetrics"); applicationModel.getApplicationConfigManager().setApplication(config); applicationModel.getBeanFactory().getOrRegisterBean(MetricsDispatcher.class); collector = applicationModel.getBeanFactory().getOrRegisterBean(MetadataMetricsCollector.class); collector.setCollectEnabled(true); } @Test void testListener() { MetadataEvent event = MetadataEvent.toPushEvent(applicationModel); MetricsEvent otherEvent = new MetricsEvent(applicationModel, null, null, null) {}; Assertions.assertTrue(collector.isSupport(event)); Assertions.assertFalse(collector.isSupport(otherEvent)); } @AfterEach public void teardown() { applicationModel.destroy(); } @Test void testPushMetrics() { // MetadataMetricsCollector collector = getCollector(); MetadataEvent pushEvent = MetadataEvent.toPushEvent(applicationModel); MetricsEventBus.post(pushEvent, () -> { List<MetricSample> metricSamples = collector.collect(); // push success +1 Assertions.assertEquals(MetadataMetricsConstants.APP_LEVEL_KEYS.size(), metricSamples.size()); Assertions.assertTrue( metricSamples.stream().allMatch(metricSample -> metricSample instanceof GaugeMetricSample)); Assertions.assertTrue(metricSamples.stream() .anyMatch(metricSample -> ((GaugeMetricSample) metricSample).applyAsDouble() == 1)); return null; }); // push finish rt +1 List<MetricSample> metricSamples = collector.collect(); // App(6) + rt(5) = 7 Assertions.assertEquals(MetadataMetricsConstants.APP_LEVEL_KEYS.size() + 5, metricSamples.size()); long c1 = pushEvent.getTimePair().calc(); pushEvent = MetadataEvent.toPushEvent(applicationModel); TimePair lastTimePair = pushEvent.getTimePair(); MetricsEventBus.post( pushEvent, () -> { try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } return null; }, Objects::nonNull); // push error rt +1 long c2 = lastTimePair.calc(); metricSamples = collector.collect(); // App(6) + rt(5) Assertions.assertEquals(MetadataMetricsConstants.APP_LEVEL_KEYS.size() + 5, metricSamples.size()); // calc rt for (MetricSample sample : metricSamples) { Map<String, String> tags = sample.getTags(); Assertions.assertEquals(tags.get(TAG_APPLICATION_NAME), applicationModel.getApplicationName()); } @SuppressWarnings("rawtypes") Map<String, Long> sampleMap = metricSamples.stream() .collect(Collectors.toMap(MetricSample::getName, k -> ((GaugeMetricSample) k).applyAsLong())); Assertions.assertEquals( sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_LAST, OP_TYPE_PUSH).targetKey()), lastTimePair.calc()); Assertions.assertEquals( sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MIN, OP_TYPE_PUSH).targetKey()), Math.min(c1, c2)); Assertions.assertEquals( sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MAX, OP_TYPE_PUSH).targetKey()), Math.max(c1, c2)); Assertions.assertEquals( sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_AVG, OP_TYPE_PUSH).targetKey()), (c1 + c2) / 2); Assertions.assertEquals( sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_SUM, OP_TYPE_PUSH).targetKey()), c1 + c2); } @Test void testSubscribeMetrics() { // MetadataMetricsCollector collector = getCollector(); MetadataEvent subscribeEvent = MetadataEvent.toSubscribeEvent(applicationModel); MetricsEventBus.post(subscribeEvent, () -> { List<MetricSample> metricSamples = collector.collect(); // push success +1 Assertions.assertEquals(MetadataMetricsConstants.APP_LEVEL_KEYS.size(), metricSamples.size()); Assertions.assertTrue( metricSamples.stream().allMatch(metricSample -> metricSample instanceof GaugeMetricSample)); Assertions.assertTrue(metricSamples.stream() .anyMatch(metricSample -> ((GaugeMetricSample) metricSample).applyAsDouble() == 1)); return null; }); long c1 = subscribeEvent.getTimePair().calc(); // push finish rt +1 List<MetricSample> metricSamples = collector.collect(); // App(6) + rt(5) = 7 Assertions.assertEquals(MetadataMetricsConstants.APP_LEVEL_KEYS.size() + 5, metricSamples.size()); subscribeEvent = MetadataEvent.toSubscribeEvent(applicationModel); TimePair lastTimePair = subscribeEvent.getTimePair(); MetricsEventBus.post( subscribeEvent, () -> { try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } return null; }, Objects::nonNull); // push error rt +1 long c2 = lastTimePair.calc(); metricSamples = collector.collect(); // App(6) + rt(5) Assertions.assertEquals(MetadataMetricsConstants.APP_LEVEL_KEYS.size() + 5, metricSamples.size()); // calc rt for (MetricSample sample : metricSamples) { Map<String, String> tags = sample.getTags(); Assertions.assertEquals(tags.get(TAG_APPLICATION_NAME), applicationModel.getApplicationName()); } @SuppressWarnings("rawtypes") Map<String, Long> sampleMap = metricSamples.stream() .collect(Collectors.toMap(MetricSample::getName, k -> ((GaugeMetricSample) k).applyAsLong())); Assertions.assertEquals( sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_LAST, OP_TYPE_SUBSCRIBE).targetKey()), lastTimePair.calc()); Assertions.assertEquals( sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MIN, OP_TYPE_SUBSCRIBE).targetKey()), Math.min(c1, c2)); Assertions.assertEquals( sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MAX, OP_TYPE_SUBSCRIBE).targetKey()), Math.max(c1, c2)); Assertions.assertEquals( sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_AVG, OP_TYPE_SUBSCRIBE).targetKey()), (c1 + c2) / 2); Assertions.assertEquals( sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_SUM, OP_TYPE_SUBSCRIBE).targetKey()), c1 + c2); } @Test void testStoreProviderMetadataMetrics() { // MetadataMetricsCollector collector = getCollector(); String serviceKey = "store.provider.test"; MetadataEvent metadataEvent = MetadataEvent.toServiceSubscribeEvent(applicationModel, serviceKey); MetricsEventBus.post(metadataEvent, () -> { List<MetricSample> metricSamples = collector.collect(); // App(6) + service success(1) Assertions.assertEquals(MetadataMetricsConstants.APP_LEVEL_KEYS.size() + 1, metricSamples.size()); Assertions.assertTrue( metricSamples.stream().allMatch(metricSample -> metricSample instanceof GaugeMetricSample)); Assertions.assertTrue(metricSamples.stream() .anyMatch(metricSample -> ((GaugeMetricSample) metricSample).applyAsDouble() == 1)); return null; }); // push finish rt +1 List<MetricSample> metricSamples = collector.collect(); // App(6) + service total/success(2) + rt(5) = 7 Assertions.assertEquals(MetadataMetricsConstants.APP_LEVEL_KEYS.size() + 2 + 5, metricSamples.size()); long c1 = metadataEvent.getTimePair().calc(); metadataEvent = MetadataEvent.toServiceSubscribeEvent(applicationModel, serviceKey); TimePair lastTimePair = metadataEvent.getTimePair(); MetricsEventBus.post( metadataEvent, () -> { try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } return null; }, Objects::nonNull); // push error rt +1 long c2 = lastTimePair.calc(); metricSamples = collector.collect(); // App(6) + service total/success/failed(3) + rt(5) Assertions.assertEquals(MetadataMetricsConstants.APP_LEVEL_KEYS.size() + 3 + 5, metricSamples.size()); // calc rt for (MetricSample sample : metricSamples) { Map<String, String> tags = sample.getTags(); Assertions.assertEquals(tags.get(TAG_APPLICATION_NAME), applicationModel.getApplicationName()); } @SuppressWarnings("rawtypes") Map<String, Long> sampleMap = metricSamples.stream() .collect(Collectors.toMap(MetricSample::getName, k -> ((GaugeMetricSample) k).applyAsLong())); Assertions.assertEquals( sampleMap.get( new MetricsKeyWrapper(MetricsKey.METRIC_RT_LAST, OP_TYPE_STORE_PROVIDER_INTERFACE).targetKey()), lastTimePair.calc()); Assertions.assertEquals( sampleMap.get( new MetricsKeyWrapper(MetricsKey.METRIC_RT_MIN, OP_TYPE_STORE_PROVIDER_INTERFACE).targetKey()), Math.min(c1, c2)); Assertions.assertEquals( sampleMap.get( new MetricsKeyWrapper(MetricsKey.METRIC_RT_MAX, OP_TYPE_STORE_PROVIDER_INTERFACE).targetKey()), Math.max(c1, c2)); Assertions.assertEquals( sampleMap.get( new MetricsKeyWrapper(MetricsKey.METRIC_RT_AVG, OP_TYPE_STORE_PROVIDER_INTERFACE).targetKey()), (c1 + c2) / 2); Assertions.assertEquals( sampleMap.get( new MetricsKeyWrapper(MetricsKey.METRIC_RT_SUM, OP_TYPE_STORE_PROVIDER_INTERFACE).targetKey()), c1 + c2); } @Test void testMetadataPushNum() { for (int i = 0; i < 10; i++) { MetadataEvent event = MetadataEvent.toPushEvent(applicationModel); if (i % 2 == 0) { MetricsEventBus.post(event, () -> true, r -> r); } else { MetricsEventBus.post(event, () -> false, r -> r); } } List<MetricSample> samples = collector.collect(); GaugeMetricSample<?> totalNum = getSample(MetricsKey.METADATA_PUSH_METRIC_NUM.getName(), samples); GaugeMetricSample<?> succeedNum = getSample(MetricsKey.METADATA_PUSH_METRIC_NUM_SUCCEED.getName(), samples); GaugeMetricSample<?> failedNum = getSample(MetricsKey.METADATA_PUSH_METRIC_NUM_FAILED.getName(), samples); Assertions.assertEquals(10, totalNum.applyAsLong()); Assertions.assertEquals(5, succeedNum.applyAsLong()); Assertions.assertEquals(5, failedNum.applyAsLong()); } @Test void testSubscribeSum() { for (int i = 0; i < 10; i++) { MetadataEvent event = MetadataEvent.toSubscribeEvent(applicationModel); if (i % 2 == 0) { MetricsEventBus.post(event, () -> true, r -> r); } else { MetricsEventBus.post(event, () -> false, r -> r); } } List<MetricSample> samples = collector.collect(); GaugeMetricSample<?> totalNum = getSample(MetricsKey.METADATA_SUBSCRIBE_METRIC_NUM.getName(), samples); GaugeMetricSample<?> succeedNum = getSample(MetricsKey.METADATA_SUBSCRIBE_METRIC_NUM_SUCCEED.getName(), samples); GaugeMetricSample<?> failedNum = getSample(MetricsKey.METADATA_SUBSCRIBE_METRIC_NUM_FAILED.getName(), samples); Assertions.assertEquals(10, totalNum.applyAsLong()); Assertions.assertEquals(5, succeedNum.applyAsLong()); Assertions.assertEquals(5, failedNum.applyAsLong()); } GaugeMetricSample<?> getSample(String name, List<MetricSample> samples) { return (GaugeMetricSample<?>) samples.stream() .filter(metricSample -> metricSample.getName().equals(name)) .findFirst() .orElseThrow(NoSuchElementException::new); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/MetadataMetricsConstants.java
dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/MetadataMetricsConstants.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.metadata; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper; import org.apache.dubbo.metrics.model.key.MetricsLevel; import org.apache.dubbo.metrics.model.key.MetricsPlaceValue; import java.util.Arrays; import java.util.List; import static org.apache.dubbo.metrics.model.key.MetricsKey.METADATA_PUSH_METRIC_NUM; import static org.apache.dubbo.metrics.model.key.MetricsKey.METADATA_PUSH_METRIC_NUM_FAILED; import static org.apache.dubbo.metrics.model.key.MetricsKey.METADATA_PUSH_METRIC_NUM_SUCCEED; import static org.apache.dubbo.metrics.model.key.MetricsKey.METADATA_SUBSCRIBE_METRIC_NUM; import static org.apache.dubbo.metrics.model.key.MetricsKey.METADATA_SUBSCRIBE_METRIC_NUM_FAILED; import static org.apache.dubbo.metrics.model.key.MetricsKey.METADATA_SUBSCRIBE_METRIC_NUM_SUCCEED; import static org.apache.dubbo.metrics.model.key.MetricsKey.STORE_PROVIDER_METADATA; import static org.apache.dubbo.metrics.model.key.MetricsKey.STORE_PROVIDER_METADATA_FAILED; import static org.apache.dubbo.metrics.model.key.MetricsKey.STORE_PROVIDER_METADATA_SUCCEED; public interface MetadataMetricsConstants { MetricsPlaceValue OP_TYPE_PUSH = MetricsPlaceValue.of("push", MetricsLevel.APP); MetricsPlaceValue OP_TYPE_SUBSCRIBE = MetricsPlaceValue.of("subscribe", MetricsLevel.APP); MetricsPlaceValue OP_TYPE_STORE_PROVIDER_INTERFACE = MetricsPlaceValue.of("store.provider.interface", MetricsLevel.SERVICE); // App-level List<MetricsKey> APP_LEVEL_KEYS = Arrays.asList( METADATA_PUSH_METRIC_NUM, METADATA_PUSH_METRIC_NUM_SUCCEED, METADATA_PUSH_METRIC_NUM_FAILED, METADATA_SUBSCRIBE_METRIC_NUM, METADATA_SUBSCRIBE_METRIC_NUM_SUCCEED, METADATA_SUBSCRIBE_METRIC_NUM_FAILED); // Service-level List<MetricsKeyWrapper> SERVICE_LEVEL_KEYS = Arrays.asList( new MetricsKeyWrapper(STORE_PROVIDER_METADATA, OP_TYPE_STORE_PROVIDER_INTERFACE), new MetricsKeyWrapper(STORE_PROVIDER_METADATA_SUCCEED, OP_TYPE_STORE_PROVIDER_INTERFACE), new MetricsKeyWrapper(STORE_PROVIDER_METADATA_FAILED, OP_TYPE_STORE_PROVIDER_INTERFACE)); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/collector/MetadataMetricsCollector.java
dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/collector/MetadataMetricsCollector.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.metadata.collector; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.metrics.collector.CombMetricsCollector; import org.apache.dubbo.metrics.collector.MetricsCollector; import org.apache.dubbo.metrics.data.ApplicationStatComposite; import org.apache.dubbo.metrics.data.BaseStatComposite; import org.apache.dubbo.metrics.data.RtStatComposite; import org.apache.dubbo.metrics.data.ServiceStatComposite; import org.apache.dubbo.metrics.metadata.MetadataMetricsConstants; import org.apache.dubbo.metrics.metadata.event.MetadataEvent; import org.apache.dubbo.metrics.metadata.event.MetadataSubDispatcher; import org.apache.dubbo.metrics.model.MetricsCategory; import org.apache.dubbo.metrics.model.sample.MetricSample; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.ArrayList; import java.util.List; import java.util.Optional; import static org.apache.dubbo.metrics.metadata.MetadataMetricsConstants.OP_TYPE_PUSH; import static org.apache.dubbo.metrics.metadata.MetadataMetricsConstants.OP_TYPE_STORE_PROVIDER_INTERFACE; import static org.apache.dubbo.metrics.metadata.MetadataMetricsConstants.OP_TYPE_SUBSCRIBE; /** * Registry implementation of {@link MetricsCollector} */ @Activate public class MetadataMetricsCollector extends CombMetricsCollector<MetadataEvent> { private Boolean collectEnabled = null; private final ApplicationModel applicationModel; public MetadataMetricsCollector(ApplicationModel applicationModel) { super(new BaseStatComposite(applicationModel) { @Override protected void init(ApplicationStatComposite applicationStatComposite) { super.init(applicationStatComposite); applicationStatComposite.init(MetadataMetricsConstants.APP_LEVEL_KEYS); } @Override protected void init(ServiceStatComposite serviceStatComposite) { super.init(serviceStatComposite); serviceStatComposite.initWrapper(MetadataMetricsConstants.SERVICE_LEVEL_KEYS); } @Override protected void init(RtStatComposite rtStatComposite) { super.init(rtStatComposite); rtStatComposite.init(OP_TYPE_PUSH, OP_TYPE_SUBSCRIBE, OP_TYPE_STORE_PROVIDER_INTERFACE); } }); super.setEventMulticaster(new MetadataSubDispatcher(this)); this.applicationModel = applicationModel; } public void setCollectEnabled(Boolean collectEnabled) { if (collectEnabled != null) { this.collectEnabled = collectEnabled; } } @Override public boolean isCollectEnabled() { if (collectEnabled == null) { ConfigManager configManager = applicationModel.getApplicationConfigManager(); configManager.getMetrics().ifPresent(metricsConfig -> setCollectEnabled(metricsConfig.getEnableMetadata())); } return Optional.ofNullable(collectEnabled).orElse(false); } @Override public List<MetricSample> collect() { List<MetricSample> list = new ArrayList<>(); if (!isCollectEnabled()) { return list; } list.addAll(super.export(MetricsCategory.METADATA)); return list; } @Override public boolean calSamplesChanged() { return stats.calSamplesChanged(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataSubDispatcher.java
dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataSubDispatcher.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.metadata.event; import org.apache.dubbo.metrics.event.SimpleMetricsEventMulticaster; import org.apache.dubbo.metrics.listener.MetricsApplicationListener; import org.apache.dubbo.metrics.listener.MetricsServiceListener; import org.apache.dubbo.metrics.metadata.collector.MetadataMetricsCollector; import org.apache.dubbo.metrics.model.key.CategoryOverall; import org.apache.dubbo.metrics.model.key.MetricsCat; import org.apache.dubbo.metrics.model.key.MetricsKey; import java.util.Arrays; import java.util.List; import static org.apache.dubbo.metrics.metadata.MetadataMetricsConstants.OP_TYPE_PUSH; import static org.apache.dubbo.metrics.metadata.MetadataMetricsConstants.OP_TYPE_STORE_PROVIDER_INTERFACE; import static org.apache.dubbo.metrics.metadata.MetadataMetricsConstants.OP_TYPE_SUBSCRIBE; public final class MetadataSubDispatcher extends SimpleMetricsEventMulticaster { public MetadataSubDispatcher(MetadataMetricsCollector collector) { CategorySet.ALL.forEach(categorySet -> { super.addListener(categorySet.getPost().getEventFunc().apply(collector)); if (categorySet.getFinish() != null) { super.addListener(categorySet.getFinish().getEventFunc().apply(collector)); } if (categorySet.getError() != null) { super.addListener(categorySet.getError().getEventFunc().apply(collector)); } }); } /** * A closer aggregation of MetricsCat, a summary collection of certain types of events */ interface CategorySet { CategoryOverall APPLICATION_PUSH = new CategoryOverall( OP_TYPE_PUSH, MCat.APPLICATION_PUSH_POST, MCat.APPLICATION_PUSH_FINISH, MCat.APPLICATION_PUSH_ERROR); CategoryOverall APPLICATION_SUBSCRIBE = new CategoryOverall( OP_TYPE_SUBSCRIBE, MCat.APPLICATION_SUBSCRIBE_POST, MCat.APPLICATION_SUBSCRIBE_FINISH, MCat.APPLICATION_SUBSCRIBE_ERROR); CategoryOverall SERVICE_SUBSCRIBE = new CategoryOverall( OP_TYPE_STORE_PROVIDER_INTERFACE, MCat.SERVICE_SUBSCRIBE_POST, MCat.SERVICE_SUBSCRIBE_FINISH, MCat.SERVICE_SUBSCRIBE_ERROR); List<CategoryOverall> ALL = Arrays.asList(APPLICATION_PUSH, APPLICATION_SUBSCRIBE, SERVICE_SUBSCRIBE); } /** * {@link MetricsCat} MetricsCat collection, for better classification processing * Except for a few custom functions, most of them can build standard event listening functions through the static methods of MetricsApplicationListener */ interface MCat { // MetricsPushListener MetricsCat APPLICATION_PUSH_POST = new MetricsCat(MetricsKey.METADATA_PUSH_METRIC_NUM, MetricsApplicationListener::onPostEventBuild); MetricsCat APPLICATION_PUSH_FINISH = new MetricsCat( MetricsKey.METADATA_PUSH_METRIC_NUM_SUCCEED, MetricsApplicationListener::onFinishEventBuild); MetricsCat APPLICATION_PUSH_ERROR = new MetricsCat( MetricsKey.METADATA_PUSH_METRIC_NUM_FAILED, MetricsApplicationListener::onErrorEventBuild); // MetricsSubscribeListener MetricsCat APPLICATION_SUBSCRIBE_POST = new MetricsCat(MetricsKey.METADATA_SUBSCRIBE_METRIC_NUM, MetricsApplicationListener::onPostEventBuild); MetricsCat APPLICATION_SUBSCRIBE_FINISH = new MetricsCat( MetricsKey.METADATA_SUBSCRIBE_METRIC_NUM_SUCCEED, MetricsApplicationListener::onFinishEventBuild); MetricsCat APPLICATION_SUBSCRIBE_ERROR = new MetricsCat( MetricsKey.METADATA_SUBSCRIBE_METRIC_NUM_FAILED, MetricsApplicationListener::onErrorEventBuild); // MetricsSubscribeListener MetricsCat SERVICE_SUBSCRIBE_POST = new MetricsCat(MetricsKey.STORE_PROVIDER_METADATA, MetricsServiceListener::onPostEventBuild); MetricsCat SERVICE_SUBSCRIBE_FINISH = new MetricsCat(MetricsKey.STORE_PROVIDER_METADATA_SUCCEED, MetricsServiceListener::onFinishEventBuild); MetricsCat SERVICE_SUBSCRIBE_ERROR = new MetricsCat(MetricsKey.STORE_PROVIDER_METADATA_FAILED, MetricsServiceListener::onErrorEventBuild); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataEvent.java
dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataEvent.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.metadata.event; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; import org.apache.dubbo.metrics.event.TimeCounterEvent; import org.apache.dubbo.metrics.metadata.collector.MetadataMetricsCollector; import org.apache.dubbo.metrics.model.key.MetricsLevel; import org.apache.dubbo.metrics.model.key.TypeWrapper; import org.apache.dubbo.rpc.model.ApplicationModel; import static org.apache.dubbo.metrics.MetricsConstants.ATTACHMENT_KEY_SERVICE; import static org.apache.dubbo.metrics.model.key.MetricsKey.METADATA_PUSH_METRIC_NUM; import static org.apache.dubbo.metrics.model.key.MetricsKey.METADATA_PUSH_METRIC_NUM_FAILED; import static org.apache.dubbo.metrics.model.key.MetricsKey.METADATA_PUSH_METRIC_NUM_SUCCEED; import static org.apache.dubbo.metrics.model.key.MetricsKey.METADATA_SUBSCRIBE_METRIC_NUM; import static org.apache.dubbo.metrics.model.key.MetricsKey.METADATA_SUBSCRIBE_METRIC_NUM_FAILED; import static org.apache.dubbo.metrics.model.key.MetricsKey.METADATA_SUBSCRIBE_METRIC_NUM_SUCCEED; import static org.apache.dubbo.metrics.model.key.MetricsKey.STORE_PROVIDER_METADATA; import static org.apache.dubbo.metrics.model.key.MetricsKey.STORE_PROVIDER_METADATA_FAILED; import static org.apache.dubbo.metrics.model.key.MetricsKey.STORE_PROVIDER_METADATA_SUCCEED; /** * Registry related events */ public class MetadataEvent extends TimeCounterEvent { public MetadataEvent(ApplicationModel applicationModel, TypeWrapper typeWrapper) { super(applicationModel, typeWrapper); ScopeBeanFactory beanFactory = applicationModel.getBeanFactory(); MetadataMetricsCollector collector; if (!beanFactory.isDestroyed()) { collector = beanFactory.getBean(MetadataMetricsCollector.class); super.setAvailable(collector != null && collector.isCollectEnabled()); } } public static MetadataEvent toPushEvent(ApplicationModel applicationModel) { return new MetadataEvent( applicationModel, new TypeWrapper( MetricsLevel.APP, METADATA_PUSH_METRIC_NUM, METADATA_PUSH_METRIC_NUM_SUCCEED, METADATA_PUSH_METRIC_NUM_FAILED)); } public static MetadataEvent toSubscribeEvent(ApplicationModel applicationModel) { return new MetadataEvent( applicationModel, new TypeWrapper( MetricsLevel.APP, METADATA_SUBSCRIBE_METRIC_NUM, METADATA_SUBSCRIBE_METRIC_NUM_SUCCEED, METADATA_SUBSCRIBE_METRIC_NUM_FAILED)); } public static MetadataEvent toServiceSubscribeEvent(ApplicationModel applicationModel, String serviceKey) { MetadataEvent metadataEvent = new MetadataEvent( applicationModel, new TypeWrapper( MetricsLevel.APP, STORE_PROVIDER_METADATA, STORE_PROVIDER_METADATA_SUCCEED, STORE_PROVIDER_METADATA_FAILED)); metadataEvent.putAttachment(ATTACHMENT_KEY_SERVICE, serviceKey); return metadataEvent; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporterFactoryTest.java
dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporterFactoryTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.prometheus; import org.apache.dubbo.common.URL; import org.apache.dubbo.metrics.report.MetricsReporter; import org.apache.dubbo.rpc.model.ApplicationModel; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class PrometheusMetricsReporterFactoryTest { @Test void test() { ApplicationModel applicationModel = ApplicationModel.defaultModel(); PrometheusMetricsReporterFactory factory = new PrometheusMetricsReporterFactory(applicationModel); MetricsReporter reporter = factory.createMetricsReporter(URL.valueOf("prometheus://localhost:9090/")); Assertions.assertTrue(reporter instanceof PrometheusMetricsReporter); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsThreadPoolTest.java
dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsThreadPoolTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.prometheus; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.MetricsConfig; import org.apache.dubbo.config.nested.PrometheusConfig; import org.apache.dubbo.metrics.collector.DefaultMetricsCollector; import org.apache.dubbo.metrics.collector.sample.ThreadRejectMetricsCountSampler; import org.apache.dubbo.metrics.model.sample.GaugeMetricSample; import org.apache.dubbo.metrics.model.sample.MetricSample; import org.apache.dubbo.rpc.model.ApplicationModel; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import com.sun.net.httpserver.HttpServer; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.MetricsConstants.PROTOCOL_PROMETHEUS; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_APPLICATION_NAME; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_HOSTNAME; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_IP; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_THREAD_NAME; import static org.apache.dubbo.common.utils.NetUtils.getLocalHost; import static org.apache.dubbo.common.utils.NetUtils.getLocalHostName; public class PrometheusMetricsThreadPoolTest { private ApplicationModel applicationModel; private MetricsConfig metricsConfig; DefaultMetricsCollector metricsCollector; HttpServer prometheusExporterHttpServer; @BeforeEach public void setup() { applicationModel = ApplicationModel.defaultModel(); ApplicationConfig config = new ApplicationConfig(); config.setName("MockMetrics"); applicationModel.getApplicationConfigManager().setApplication(config); metricsConfig = new MetricsConfig(); metricsConfig.setProtocol(PROTOCOL_PROMETHEUS); metricsCollector = applicationModel.getBeanFactory().getOrRegisterBean(DefaultMetricsCollector.class); } @AfterEach public void teardown() { applicationModel.destroy(); if (prometheusExporterHttpServer != null) { prometheusExporterHttpServer.stop(0); } } @Test void testExporterThreadpoolName() { int port = 30899; PrometheusConfig prometheusConfig = new PrometheusConfig(); PrometheusConfig.Exporter exporter = new PrometheusConfig.Exporter(); exporter.setEnabled(true); prometheusConfig.setExporter(exporter); metricsConfig.setPrometheus(prometheusConfig); metricsConfig.setEnableJvm(false); metricsCollector.setCollectEnabled(true); metricsConfig.setEnableThreadpool(true); metricsCollector.collectApplication(); PrometheusMetricsReporter reporter = new PrometheusMetricsReporter(metricsConfig.toUrl(), applicationModel); reporter.init(); exportHttpServer(reporter, port); if (metricsConfig.getEnableThreadpool()) { metricsCollector.registryDefaultSample(); } try (CloseableHttpClient client = HttpClients.createDefault()) { HttpGet request = new HttpGet("http://localhost:" + port + "/metrics"); CloseableHttpResponse response = client.execute(request); InputStream inputStream = response.getEntity().getContent(); String text = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)) .lines() .collect(Collectors.joining("\n")); Assertions.assertTrue(text.contains("dubbo_thread_pool_core_size")); Assertions.assertTrue(text.contains("dubbo_thread_pool_thread_count")); } catch (Exception e) { Assertions.fail(e); } finally { reporter.destroy(); } } private void exportHttpServer(PrometheusMetricsReporter reporter, int port) { try { prometheusExporterHttpServer = HttpServer.create(new InetSocketAddress(port), 0); prometheusExporterHttpServer.createContext("/metrics", httpExchange -> { reporter.resetIfSamplesChanged(); String response = reporter.getPrometheusRegistry().scrape(); httpExchange.sendResponseHeaders(200, response.getBytes().length); try (OutputStream os = httpExchange.getResponseBody()) { os.write(response.getBytes()); } }); // start ServerImpl dispatcher thread. prometheusExporterHttpServer.start(); } catch (IOException e) { throw new RuntimeException(e); } } @Test @SuppressWarnings("rawtypes") void testThreadPoolRejectMetrics() { DefaultMetricsCollector collector = new DefaultMetricsCollector(applicationModel); collector.setCollectEnabled(true); collector.setApplicationName(applicationModel.getApplicationName()); String threadPoolExecutorName = "DubboServerHandler-20816"; ThreadRejectMetricsCountSampler threadRejectMetricsCountSampler = new ThreadRejectMetricsCountSampler(collector); threadRejectMetricsCountSampler.inc(threadPoolExecutorName, threadPoolExecutorName); threadRejectMetricsCountSampler.addMetricName(threadPoolExecutorName); List<MetricSample> samples = collector.collect(); for (MetricSample sample : samples) { Assertions.assertTrue(sample instanceof GaugeMetricSample); GaugeMetricSample gaugeSample = (GaugeMetricSample) sample; Map<String, String> tags = gaugeSample.getTags(); Assertions.assertEquals(tags.get(TAG_APPLICATION_NAME), "MockMetrics"); Assertions.assertEquals(tags.get(TAG_THREAD_NAME), threadPoolExecutorName); Assertions.assertEquals(tags.get(TAG_IP), getLocalHost()); Assertions.assertEquals(tags.get(TAG_HOSTNAME), getLocalHostName()); Assertions.assertEquals(gaugeSample.applyAsLong(), 1); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporterTest.java
dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporterTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.prometheus; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.MetricsConfig; import org.apache.dubbo.config.nested.PrometheusConfig; import org.apache.dubbo.metrics.collector.DefaultMetricsCollector; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; import java.util.concurrent.ScheduledExecutorService; import java.util.stream.Collectors; import com.sun.net.httpserver.HttpServer; import io.micrometer.prometheus.PrometheusMeterRegistry; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.MetricsConstants.PROTOCOL_PROMETHEUS; class PrometheusMetricsReporterTest { private MetricsConfig metricsConfig; private ApplicationModel applicationModel; private FrameworkModel frameworkModel; HttpServer prometheusExporterHttpServer; @BeforeEach public void setup() { metricsConfig = new MetricsConfig(); applicationModel = ApplicationModel.defaultModel(); metricsConfig.setProtocol(PROTOCOL_PROMETHEUS); frameworkModel = FrameworkModel.defaultModel(); frameworkModel.getBeanFactory().getOrRegisterBean(DefaultMetricsCollector.class); } @AfterEach public void teardown() { applicationModel.destroy(); if (prometheusExporterHttpServer != null) { prometheusExporterHttpServer.stop(0); } } @Test void testJvmMetrics() { metricsConfig.setEnableJvm(true); String name = "metrics-test"; ApplicationModel.defaultModel().getApplicationConfigManager().setApplication(new ApplicationConfig(name)); PrometheusMetricsReporter reporter = new PrometheusMetricsReporter(metricsConfig.toUrl(), applicationModel); reporter.init(); PrometheusMeterRegistry prometheusRegistry = reporter.getPrometheusRegistry(); Double d1 = prometheusRegistry.getPrometheusRegistry().getSampleValue("none_exist_metric"); Double d2 = prometheusRegistry .getPrometheusRegistry() .getSampleValue( "jvm_gc_memory_promoted_bytes_total", new String[] {"application_name"}, new String[] {name}); Assertions.assertNull(d1); Assertions.assertNull(d2); } @Test void testExporter() { int port = 31539; // NetUtils.getAvailablePort(); PrometheusConfig prometheusConfig = new PrometheusConfig(); PrometheusConfig.Exporter exporter = new PrometheusConfig.Exporter(); exporter.setEnabled(true); prometheusConfig.setExporter(exporter); metricsConfig.setPrometheus(prometheusConfig); metricsConfig.setEnableJvm(true); ApplicationModel.defaultModel() .getApplicationConfigManager() .setApplication(new ApplicationConfig("metrics-test")); PrometheusMetricsReporter reporter = new PrometheusMetricsReporter(metricsConfig.toUrl(), applicationModel); reporter.init(); exportHttpServer(reporter, port); try { Thread.sleep(5000); } catch (InterruptedException e) { throw new RuntimeException(e); } try (CloseableHttpClient client = HttpClients.createDefault()) { HttpGet request = new HttpGet("http://localhost:" + port + "/metrics"); CloseableHttpResponse response = client.execute(request); InputStream inputStream = response.getEntity().getContent(); String text = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)) .lines() .collect(Collectors.joining("\n")); Assertions.assertTrue(text.contains("jvm_gc_memory_promoted_bytes_total")); } catch (Exception e) { Assertions.fail(e); } finally { reporter.destroy(); } } @Test void testPushgateway() { PrometheusConfig prometheusConfig = new PrometheusConfig(); PrometheusConfig.Pushgateway pushgateway = new PrometheusConfig.Pushgateway(); pushgateway.setJob("mock"); pushgateway.setBaseUrl("localhost:9091"); pushgateway.setEnabled(true); pushgateway.setPushInterval(1); prometheusConfig.setPushgateway(pushgateway); metricsConfig.setPrometheus(prometheusConfig); PrometheusMetricsReporter reporter = new PrometheusMetricsReporter(metricsConfig.toUrl(), applicationModel); reporter.init(); ScheduledExecutorService executor = reporter.getPushJobExecutor(); Assertions.assertTrue(executor != null && !executor.isTerminated() && !executor.isShutdown()); reporter.destroy(); Assertions.assertTrue(executor.isTerminated() || executor.isShutdown()); } private void exportHttpServer(PrometheusMetricsReporter reporter, int port) { try { prometheusExporterHttpServer = HttpServer.create(new InetSocketAddress(port), 0); prometheusExporterHttpServer.createContext("/metrics", httpExchange -> { reporter.resetIfSamplesChanged(); String response = reporter.getPrometheusRegistry().scrape(); httpExchange.sendResponseHeaders(200, response.getBytes().length); try (OutputStream os = httpExchange.getResponseBody()) { os.write(response.getBytes()); } }); Thread httpServerThread = new Thread(prometheusExporterHttpServer::start); httpServerThread.start(); } catch (IOException e) { throw new RuntimeException(e); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-prometheus/src/main/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporterFactory.java
dubbo-metrics/dubbo-metrics-prometheus/src/main/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporterFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.prometheus; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.metrics.report.AbstractMetricsReporterFactory; import org.apache.dubbo.metrics.report.MetricsReporter; import org.apache.dubbo.rpc.model.ApplicationModel; import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR; /** * MetricsReporterFactory to create PrometheusMetricsReporter. */ public class PrometheusMetricsReporterFactory extends AbstractMetricsReporterFactory { private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(PrometheusMetricsReporterFactory.class); public PrometheusMetricsReporterFactory(ApplicationModel applicationModel) { super(applicationModel); } @Override public MetricsReporter createMetricsReporter(URL url) { try { return new PrometheusMetricsReporter(url, getApplicationModel()); } catch (NoClassDefFoundError ncde) { String msg = ncde.getMessage(); if (dependenciesNotFound(msg)) { logger.error( INTERNAL_ERROR, "", "", "Failed to load class \"org.apache.dubbo.metrics.prometheus.PrometheusMetricsReporter\".", ncde); logger.error( INTERNAL_ERROR, "", "", "Defaulting to no-operation (NOP) metricsReporter implementation", ncde); logger.error( INTERNAL_ERROR, "", "", "Introduce the micrometer-core package to use the ability of metrics", ncde); return new NopPrometheusMetricsReporter(); } else { logger.error(INTERNAL_ERROR, "", "", "Failed to instantiate PrometheusMetricsReporter", ncde); throw ncde; } } } private static boolean dependenciesNotFound(String msg) { if (msg == null) { return false; } if (msg.contains("io/micrometer/core/instrument/composite/CompositeMeterRegistry")) { return true; } return msg.contains("io.micrometer.core.instrument.composite.CompositeMeterRegistry"); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-prometheus/src/main/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporterCmd.java
dubbo-metrics/dubbo-metrics-prometheus/src/main/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporterCmd.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.prometheus; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.JsonUtils; import org.apache.dubbo.metrics.report.MetricsReporter; import org.apache.dubbo.qos.api.BaseCommand; import org.apache.dubbo.qos.api.Cmd; import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import java.io.CharArrayReader; import java.io.IOException; import java.io.LineNumberReader; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; @Cmd(name = "metrics", summary = "reuse qos report") public class PrometheusMetricsReporterCmd implements BaseCommand { private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(PrometheusMetricsReporterCmd.class); public FrameworkModel frameworkModel; public PrometheusMetricsReporterCmd(FrameworkModel frameworkModel) { this.frameworkModel = frameworkModel; } @Override public String execute(CommandContext commandContext, String[] args) { List<ApplicationModel> models = frameworkModel.getApplicationModels(); String result = "There is no application with data"; if (notSpecifyApplication(args)) { result = useFirst(models, result); } else { result = specifyApplication(args[0], models); } return result; } private boolean notSpecifyApplication(String[] args) { return args == null || args.length == 0; } private String useFirst(List<ApplicationModel> models, String result) { for (ApplicationModel model : models) { String current = getResponseByApplication(model); // Contains at least one line "text/plain; version=0.0.4; charset=utf-8" if (getLineNumber(current) > 1) { result = current; break; } } return result; } private String specifyApplication(String appName, List<ApplicationModel> models) { if ("application_all".equals(appName)) { return allApplication(models); } else { return specifySingleApplication(appName, models); } } private String specifySingleApplication(String appName, List<ApplicationModel> models) { Optional<ApplicationModel> modelOptional = models.stream() .filter(applicationModel -> appName.equals(applicationModel.getApplicationName())) .findFirst(); if (modelOptional.isPresent()) { return getResponseByApplication(modelOptional.get()); } else { return "Not exist application: " + appName; } } private String allApplication(List<ApplicationModel> models) { Map<String, String> appResultMap = new HashMap<>(); for (ApplicationModel model : models) { appResultMap.put(model.getApplicationName(), getResponseByApplication(model)); } return JsonUtils.toJson(appResultMap); } @Override public boolean logResult() { return false; } private String getResponseByApplication(ApplicationModel applicationModel) { String response = "MetricsReporter not init"; MetricsReporter metricsReporter = applicationModel.getBeanFactory().getBean(PrometheusMetricsReporter.class); if (metricsReporter != null) { long begin = System.currentTimeMillis(); if (logger.isDebugEnabled()) { logger.debug("scrape begin"); } metricsReporter.resetIfSamplesChanged(); if (logger.isDebugEnabled()) { logger.debug(String.format("scrape end,Elapsed Time:%s", System.currentTimeMillis() - begin)); } response = metricsReporter.getResponse(); } return response; } private static long getLineNumber(String content) { LineNumberReader lnr = new LineNumberReader(new CharArrayReader(content.toCharArray())); try { lnr.skip(Long.MAX_VALUE); lnr.close(); } catch (IOException ignore) { } return lnr.getLineNumber(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-prometheus/src/main/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporter.java
dubbo-metrics/dubbo-metrics-prometheus/src/main/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.prometheus; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.NamedThreadFactory; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.metrics.report.AbstractMetricsReporter; import org.apache.dubbo.rpc.model.ApplicationModel; import java.io.IOException; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import io.micrometer.prometheus.PrometheusConfig; import io.micrometer.prometheus.PrometheusMeterRegistry; import io.prometheus.client.exporter.BasicAuthHttpConnectionFactory; import io.prometheus.client.exporter.PushGateway; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_METRICS_COLLECTOR_EXCEPTION; import static org.apache.dubbo.common.constants.MetricsConstants.PROMETHEUS_DEFAULT_JOB_NAME; import static org.apache.dubbo.common.constants.MetricsConstants.PROMETHEUS_DEFAULT_PUSH_INTERVAL; import static org.apache.dubbo.common.constants.MetricsConstants.PROMETHEUS_PUSHGATEWAY_BASE_URL_KEY; import static org.apache.dubbo.common.constants.MetricsConstants.PROMETHEUS_PUSHGATEWAY_ENABLED_KEY; import static org.apache.dubbo.common.constants.MetricsConstants.PROMETHEUS_PUSHGATEWAY_JOB_KEY; import static org.apache.dubbo.common.constants.MetricsConstants.PROMETHEUS_PUSHGATEWAY_PASSWORD_KEY; import static org.apache.dubbo.common.constants.MetricsConstants.PROMETHEUS_PUSHGATEWAY_PUSH_INTERVAL_KEY; import static org.apache.dubbo.common.constants.MetricsConstants.PROMETHEUS_PUSHGATEWAY_USERNAME_KEY; /** * Metrics reporter for prometheus. */ public class PrometheusMetricsReporter extends AbstractMetricsReporter { private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(PrometheusMetricsReporter.class); private final PrometheusMeterRegistry prometheusRegistry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT); private ScheduledExecutorService pushJobExecutor = null; public PrometheusMetricsReporter(URL url, ApplicationModel applicationModel) { super(url, applicationModel); } @Override public void doInit() { addMeterRegistry(prometheusRegistry); schedulePushJob(); } public String getResponse() { return prometheusRegistry.scrape(); } private void schedulePushJob() { boolean pushEnabled = url.getParameter(PROMETHEUS_PUSHGATEWAY_ENABLED_KEY, false); if (pushEnabled) { String baseUrl = url.getParameter(PROMETHEUS_PUSHGATEWAY_BASE_URL_KEY); String job = url.getParameter(PROMETHEUS_PUSHGATEWAY_JOB_KEY, PROMETHEUS_DEFAULT_JOB_NAME); int pushInterval = url.getParameter(PROMETHEUS_PUSHGATEWAY_PUSH_INTERVAL_KEY, PROMETHEUS_DEFAULT_PUSH_INTERVAL); String username = url.getParameter(PROMETHEUS_PUSHGATEWAY_USERNAME_KEY); String password = url.getParameter(PROMETHEUS_PUSHGATEWAY_PASSWORD_KEY); NamedThreadFactory threadFactory = new NamedThreadFactory("prometheus-push-job", true); pushJobExecutor = Executors.newScheduledThreadPool(1, threadFactory); PushGateway pushGateway = new PushGateway(baseUrl); if (!StringUtils.isBlank(username)) { pushGateway.setConnectionFactory(new BasicAuthHttpConnectionFactory(username, password)); } pushJobExecutor.scheduleWithFixedDelay( () -> push(pushGateway, job), pushInterval, pushInterval, TimeUnit.SECONDS); } } protected void push(PushGateway pushGateway, String job) { try { resetIfSamplesChanged(); pushGateway.pushAdd(prometheusRegistry.getPrometheusRegistry(), job); } catch (IOException e) { logger.error( COMMON_METRICS_COLLECTOR_EXCEPTION, "", "", "Error occurred when pushing metrics to prometheus: ", e); } } @Override public void doDestroy() { if (pushJobExecutor != null) { pushJobExecutor.shutdownNow(); } } /** * ut only */ @Deprecated public ScheduledExecutorService getPushJobExecutor() { return pushJobExecutor; } /** * ut only */ @Deprecated public PrometheusMeterRegistry getPrometheusRegistry() { return prometheusRegistry; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-prometheus/src/main/java/org/apache/dubbo/metrics/prometheus/NopPrometheusMetricsReporter.java
dubbo-metrics/dubbo-metrics-prometheus/src/main/java/org/apache/dubbo/metrics/prometheus/NopPrometheusMetricsReporter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.prometheus; import org.apache.dubbo.metrics.report.MetricsReporter; /** * NopMetricsReporter is a trivial implementation of MetricsReporter * which do nothing when micro-meter package is not exist. */ public class NopPrometheusMetricsReporter implements MetricsReporter { @Override public void init() {} @Override public void resetIfSamplesChanged() {} @Override public String getResponse() { return ""; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/rpc/cluster/filter/MetricsClusterFilterTest.java
dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/rpc/cluster/filter/MetricsClusterFilterTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.rpc.cluster.filter; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.metrics.collector.DefaultMetricsCollector; import org.apache.dubbo.metrics.filter.MetricsFilter; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.model.sample.CounterMetricSample; import org.apache.dubbo.metrics.model.sample.MetricSample; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.cluster.filter.support.MetricsClusterFilter; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; import java.util.stream.Collectors; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; class MetricsClusterFilterTest { private ApplicationModel applicationModel; private MetricsFilter filter; private MetricsClusterFilter metricsClusterFilter; private DefaultMetricsCollector collector; private RpcInvocation invocation; private final Invoker<?> invoker = mock(Invoker.class); private static final String INTERFACE_NAME = "org.apache.dubbo.MockInterface"; private static final String METHOD_NAME = "mockMethod"; private static final String GROUP = "mockGroup"; private static final String VERSION = "1.0.0"; private String side; private AtomicBoolean initApplication = new AtomicBoolean(false); @BeforeEach public void setup() { ApplicationConfig config = new ApplicationConfig(); config.setName("MockMetrics"); // RpcContext.getContext().setAttachment("MockMetrics","MockMetrics"); applicationModel = ApplicationModel.defaultModel(); applicationModel.getApplicationConfigManager().setApplication(config); invocation = new RpcInvocation(); filter = new MetricsFilter(); collector = applicationModel.getBeanFactory().getOrRegisterBean(DefaultMetricsCollector.class); if (!initApplication.get()) { collector.collectApplication(); initApplication.set(true); } filter.setApplicationModel(applicationModel); side = CommonConstants.CONSUMER; invocation.setInvoker(new TestMetricsInvoker(side)); RpcContext.getServiceContext() .setUrl(URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&side=" + side)); metricsClusterFilter = new MetricsClusterFilter(); metricsClusterFilter.setApplicationModel(applicationModel); } @AfterEach public void teardown() { applicationModel.destroy(); } @Test public void testNoProvider() { testClusterFilterError( RpcException.FORBIDDEN_EXCEPTION, MetricsKey.METRIC_REQUESTS_SERVICE_UNAVAILABLE_FAILED.getNameByType(CommonConstants.CONSUMER)); } private void testClusterFilterError(int errorCode, String name) { collector.setCollectEnabled(true); given(invoker.invoke(invocation)).willThrow(new RpcException(errorCode)); initParam(); Long count = 1L; for (int i = 0; i < count; i++) { try { metricsClusterFilter.invoke(invoker, invocation); } catch (Exception e) { Assertions.assertTrue(e instanceof RpcException); metricsClusterFilter.onError(e, invoker, invocation); } } Map<String, MetricSample> metricsMap = getMetricsMap(); Assertions.assertTrue(metricsMap.containsKey(name)); MetricSample sample = metricsMap.get(name); Assertions.assertSame(((CounterMetricSample) sample).getValue().longValue(), count); teardown(); } private void initParam() { invocation.setTargetServiceUniqueName(GROUP + "/" + INTERFACE_NAME + ":" + VERSION); invocation.setMethodName(METHOD_NAME); invocation.setParameterTypes(new Class[] {String.class}); } private Map<String, MetricSample> getMetricsMap() { List<MetricSample> samples = collector.collect(); List<MetricSample> samples1 = new ArrayList<>(); for (MetricSample sample : samples) { if (sample.getName().contains("dubbo.thread.pool")) { continue; } samples1.add(sample); } return samples1.stream().collect(Collectors.toMap(MetricSample::getName, Function.identity())); } public class TestMetricsInvoker implements Invoker { private String side; public TestMetricsInvoker(String side) { this.side = side; } @Override public Class getInterface() { return null; } @Override public Result invoke(Invocation invocation) throws RpcException { return null; } @Override public URL getUrl() { return URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&side=" + side); } @Override public boolean isAvailable() { return true; } @Override public void destroy() {} } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/rpc/cluster/filter/MockInvocation.java
dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/rpc/cluster/filter/MockInvocation.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.rpc.cluster.filter; import org.apache.dubbo.rpc.AttachmentsAdapter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.model.ServiceModel; import java.util.HashMap; import java.util.Map; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; /** * MockInvocation.java */ public class MockInvocation extends RpcInvocation { private Map<String, Object> attachments; public MockInvocation() { attachments = new HashMap<>(); attachments.put(PATH_KEY, "dubbo"); attachments.put(GROUP_KEY, "dubbo"); attachments.put(VERSION_KEY, "1.0.0"); attachments.put(DUBBO_VERSION_KEY, "1.0.0"); attachments.put(TOKEN_KEY, "sfag"); attachments.put(TIMEOUT_KEY, "1000"); } @Override public String getTargetServiceUniqueName() { return null; } @Override public String getProtocolServiceKey() { return null; } public String getMethodName() { return "echo"; } @Override public String getServiceName() { return "DemoService"; } public Class<?>[] getParameterTypes() { return new Class[] {String.class}; } public Object[] getArguments() { return new Object[] {"aa"}; } public Map<String, String> getAttachments() { return new AttachmentsAdapter.ObjectToStringMap(attachments); } @Override public Map<String, Object> getObjectAttachments() { return attachments; } @Override public void setAttachment(String key, String value) { setObjectAttachment(key, value); } @Override public void setAttachment(String key, Object value) { setObjectAttachment(key, value); } @Override public void setObjectAttachment(String key, Object value) { attachments.put(key, value); } @Override public void setAttachmentIfAbsent(String key, String value) { setObjectAttachmentIfAbsent(key, value); } @Override public void setAttachmentIfAbsent(String key, Object value) { setObjectAttachmentIfAbsent(key, value); } @Override public void setObjectAttachmentIfAbsent(String key, Object value) { attachments.put(key, value); } public Invoker<?> getInvoker() { return null; } @Override public void setServiceModel(ServiceModel serviceModel) {} @Override public ServiceModel getServiceModel() { return null; } @Override public Object put(Object key, Object value) { return null; } @Override public Object get(Object key) { return null; } @Override public Map<Object, Object> getAttributes() { return null; } public String getAttachment(String key) { return (String) getObjectAttachments().get(key); } @Override public Object getObjectAttachment(String key) { return attachments.get(key); } public String getAttachment(String key, String defaultValue) { return (String) getObjectAttachments().get(key); } @Override public Object getObjectAttachment(String key, Object defaultValue) { Object result = attachments.get(key); if (result == null) { return defaultValue; } return result; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/DefaultMetricsServiceTest.java
dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/DefaultMetricsServiceTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; import org.apache.dubbo.metrics.collector.MetricsCollector; import org.apache.dubbo.metrics.model.MetricsCategory; import org.apache.dubbo.metrics.model.sample.GaugeMetricSample; import org.apache.dubbo.metrics.model.sample.MetricSample; import org.apache.dubbo.metrics.service.DefaultMetricsService; import org.apache.dubbo.metrics.service.MetricsEntity; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Collections; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.mockito.Mockito.when; @SuppressWarnings("rawtypes") public class DefaultMetricsServiceTest { private MetricsCollector metricsCollector; private DefaultMetricsService defaultMetricsService; @BeforeEach public void setUp() { ApplicationModel applicationModel = Mockito.mock(ApplicationModel.class); ScopeBeanFactory beanFactory = Mockito.mock(ScopeBeanFactory.class); metricsCollector = Mockito.mock(MetricsCollector.class); when(applicationModel.getBeanFactory()).thenReturn(beanFactory); when(beanFactory.getBeansOfType(MetricsCollector.class)) .thenReturn(Collections.singletonList(metricsCollector)); defaultMetricsService = new DefaultMetricsService(applicationModel); } @Test public void testGetMetricsByCategories() { MetricSample sample = new GaugeMetricSample<>( "testMetric", "testDescription", null, MetricsCategory.REQUESTS, 42, value -> 42.0); when(metricsCollector.collect()).thenReturn(Collections.singletonList(sample)); List<MetricsCategory> categories = Collections.singletonList(MetricsCategory.REQUESTS); Map<MetricsCategory, List<MetricsEntity>> result = defaultMetricsService.getMetricsByCategories(categories); Assertions.assertNotNull(result); Assertions.assertEquals(1, result.size()); List<MetricsEntity> entities = result.get(MetricsCategory.REQUESTS); Assertions.assertNotNull(entities); Assertions.assertEquals(1, entities.size()); MetricsEntity entity = entities.get(0); Assertions.assertEquals("testMetric", entity.getName()); Assertions.assertEquals(42.0, entity.getValue()); Assertions.assertEquals(MetricsCategory.REQUESTS, entity.getCategory()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/TestMetricsInvoker.java
dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/TestMetricsInvoker.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; public class TestMetricsInvoker implements Invoker { private String side; public TestMetricsInvoker(String side) { this.side = side; } @Override public Class getInterface() { return null; } @Override public Result invoke(Invocation invocation) throws RpcException { return null; } @Override public URL getUrl() { return URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&side=" + side); } @Override public boolean isAvailable() { return true; } @Override public void destroy() {} }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/AggregateMetricsCollectorTest.java
dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/AggregateMetricsCollectorTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.collector; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.ReflectionUtils; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.MetricsConfig; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.config.nested.AggregationConfig; import org.apache.dubbo.metrics.MetricsConstants; import org.apache.dubbo.metrics.TestMetricsInvoker; import org.apache.dubbo.metrics.aggregate.TimeWindowCounter; import org.apache.dubbo.metrics.event.MetricsDispatcher; import org.apache.dubbo.metrics.event.MetricsEventBus; import org.apache.dubbo.metrics.event.RequestEvent; import org.apache.dubbo.metrics.filter.MetricsFilter; import org.apache.dubbo.metrics.listener.MetricsListener; import org.apache.dubbo.metrics.model.MethodMetric; import org.apache.dubbo.metrics.model.MetricsSupport; import org.apache.dubbo.metrics.model.TimePair; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.model.key.TypeWrapper; import org.apache.dubbo.metrics.model.sample.GaugeMetricSample; import org.apache.dubbo.metrics.model.sample.MetricSample; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_GROUP_KEY; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_INTERFACE_KEY; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_METHOD_KEY; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_VERSION_KEY; import static org.apache.dubbo.metrics.MetricsConstants.ATTACHMENT_KEY_SERVICE; import static org.apache.dubbo.metrics.model.MetricsCategory.QPS; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; class AggregateMetricsCollectorTest { private ApplicationModel applicationModel; private DefaultMetricsCollector defaultCollector; private String interfaceName; private String methodName; private String group; private String version; private RpcInvocation invocation; private String side; private MetricsDispatcher metricsDispatcher; private AggregateMetricsCollector collector; private MetricsFilter metricsFilter; public MethodMetric getTestMethodMetric() { MethodMetric methodMetric = new MethodMetric(applicationModel, invocation, MethodMetric.isServiceLevel(applicationModel)); methodMetric.setGroup("TestGroup"); methodMetric.setVersion("1.0.0"); methodMetric.setSide("PROVIDER"); return methodMetric; } @BeforeEach public void setup() { applicationModel = ApplicationModel.defaultModel(); ApplicationConfig config = new ApplicationConfig(); config.setName("MockMetrics"); applicationModel.getApplicationConfigManager().setApplication(config); MetricsConfig metricsConfig = new MetricsConfig(); AggregationConfig aggregationConfig = new AggregationConfig(); aggregationConfig.setEnabled(true); aggregationConfig.setBucketNum(12); aggregationConfig.setTimeWindowSeconds(120); metricsConfig.setAggregation(aggregationConfig); metricsConfig.setEnableRpc(true); applicationModel.getApplicationConfigManager().setMetrics(metricsConfig); metricsDispatcher = applicationModel.getBeanFactory().getOrRegisterBean(MetricsDispatcher.class); defaultCollector = applicationModel.getBeanFactory().getBean(DefaultMetricsCollector.class); collector = applicationModel.getBeanFactory().getOrRegisterBean(AggregateMetricsCollector.class); collector.setCollectEnabled(true); defaultCollector = new DefaultMetricsCollector(applicationModel); defaultCollector.setCollectEnabled(true); metricsFilter = new MetricsFilter(); metricsFilter.setApplicationModel(applicationModel); interfaceName = "org.apache.dubbo.MockInterface"; methodName = "mockMethod"; group = "mockGroup"; version = "1.0.0"; invocation = new RpcInvocation(methodName, interfaceName, "serviceKey", null, null); invocation.setTargetServiceUniqueName(group + "/" + interfaceName + ":" + version); invocation.setAttachment(GROUP_KEY, group); invocation.setAttachment(VERSION_KEY, version); side = CommonConstants.CONSUMER; invocation.setInvoker(new TestMetricsInvoker(side)); invocation.setTargetServiceUniqueName(group + "/" + interfaceName + ":" + version); RpcContext.getServiceContext() .setUrl(URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&side=" + side)); } @Test void testListener() { AggregateMetricsCollector metricsCollector = new AggregateMetricsCollector(applicationModel); RequestEvent event = RequestEvent.toRequestEvent( applicationModel, null, null, null, invocation, MetricsSupport.getSide(invocation), MethodMetric.isServiceLevel(applicationModel)); RequestEvent beforeEvent = RequestEvent.toRequestErrorEvent( applicationModel, null, null, invocation, MetricsSupport.getSide(invocation), RpcException.FORBIDDEN_EXCEPTION, MethodMetric.isServiceLevel(applicationModel)); Assertions.assertTrue(metricsCollector.isSupport(event)); Assertions.assertTrue(metricsCollector.isSupport(beforeEvent)); } @AfterEach public void teardown() { applicationModel.destroy(); } @Test void testRequestsMetrics() { String applicationName = applicationModel.getApplicationName(); defaultCollector.setApplicationName(applicationName); metricsFilter.invoke(new TestMetricsInvoker(side), invocation); try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } AppResponse mockRpcResult = new AppResponse(); mockRpcResult.setException(new RpcException(RpcException.NETWORK_EXCEPTION)); Result result = AsyncRpcResult.newDefaultAsyncResult(mockRpcResult, invocation); metricsFilter.onResponse(result, new TestMetricsInvoker(side), invocation); List<MetricSample> samples = collector.collect(); for (MetricSample sample : samples) { Map<String, String> tags = sample.getTags(); Assertions.assertEquals(tags.get(TAG_INTERFACE_KEY), interfaceName); Assertions.assertEquals(tags.get(TAG_METHOD_KEY), methodName); Assertions.assertEquals(tags.get(TAG_GROUP_KEY), group); Assertions.assertEquals(tags.get(TAG_VERSION_KEY), version); } samples = collector.collect(); @SuppressWarnings("rawtypes") Map<String, Long> sampleMap = samples.stream() .collect(Collectors.toMap(MetricSample::getName, k -> ((GaugeMetricSample) k).applyAsLong())); Assertions.assertEquals(sampleMap.get(MetricsKey.METRIC_REQUESTS_NETWORK_FAILED_AGG.getNameByType(side)), 1L); Assertions.assertTrue(sampleMap.containsKey(MetricsKey.METRIC_QPS.getNameByType(side))); } @Test public void testQPS() { ApplicationModel applicationModel = mock(ApplicationModel.class); ConfigManager configManager = mock(ConfigManager.class); MetricsConfig metricsConfig = mock(MetricsConfig.class); ScopeBeanFactory beanFactory = mock(ScopeBeanFactory.class); AggregationConfig aggregationConfig = mock(AggregationConfig.class); when(applicationModel.getApplicationConfigManager()).thenReturn(configManager); when(applicationModel.getBeanFactory()).thenReturn(beanFactory); DefaultMetricsCollector defaultMetricsCollector = new DefaultMetricsCollector(applicationModel); when(beanFactory.getBean(DefaultMetricsCollector.class)).thenReturn(defaultMetricsCollector); when(configManager.getMetrics()).thenReturn(Optional.of(metricsConfig)); when(metricsConfig.getAggregation()).thenReturn(aggregationConfig); when(aggregationConfig.getEnabled()).thenReturn(Boolean.TRUE); AggregateMetricsCollector collector = new AggregateMetricsCollector(applicationModel); MethodMetric methodMetric = getTestMethodMetric(); TimeWindowCounter qpsCounter = new TimeWindowCounter(10, 120); for (int i = 0; i < 10000; i++) { qpsCounter.increment(); } @SuppressWarnings("unchecked") ConcurrentHashMap<MethodMetric, TimeWindowCounter> qps = (ConcurrentHashMap<MethodMetric, TimeWindowCounter>) ReflectionUtils.getField(collector, "qps"); qps.put(methodMetric, qpsCounter); List<MetricSample> collectedQPS = new ArrayList<>(); ReflectionUtils.invoke(collector, "collectQPS", collectedQPS); Assertions.assertFalse(collectedQPS.isEmpty()); Assertions.assertEquals(1, collectedQPS.size()); MetricSample sample = collectedQPS.get(0); Assertions.assertEquals(MetricsKey.METRIC_QPS.getNameByType("PROVIDER"), sample.getName()); Assertions.assertEquals(MetricsKey.METRIC_QPS.getDescription(), sample.getDescription()); Assertions.assertEquals(QPS, sample.getCategory()); Assertions.assertEquals(10000, ((TimeWindowCounter) ((GaugeMetricSample<?>) sample).getValue()).get()); } @Test public void testRtAggregation() { metricsDispatcher.addListener(collector); ConfigManager configManager = applicationModel.getApplicationConfigManager(); MetricsConfig config = configManager.getMetrics().orElse(null); AggregationConfig aggregationConfig = new AggregationConfig(); aggregationConfig.setEnabled(true); config.setAggregation(aggregationConfig); List<Long> rtList = new ArrayList<>(); rtList.add(10L); rtList.add(20L); rtList.add(30L); for (Long requestTime : rtList) { RequestEvent requestEvent = RequestEvent.toRequestEvent( applicationModel, null, null, null, invocation, MetricsSupport.getSide(invocation), MethodMetric.isServiceLevel(applicationModel)); TestRequestEvent testRequestEvent = new TestRequestEvent(requestEvent.getSource(), requestEvent.getTypeWrapper()); testRequestEvent.putAttachment(MetricsConstants.INVOCATION, invocation); testRequestEvent.putAttachment(ATTACHMENT_KEY_SERVICE, MetricsSupport.getInterfaceName(invocation)); testRequestEvent.putAttachment(MetricsConstants.INVOCATION_SIDE, MetricsSupport.getSide(invocation)); testRequestEvent.setRt(requestTime); MetricsEventBus.post(testRequestEvent, () -> null); } List<MetricSample> samples = collector.collect(); for (MetricSample sample : samples) { GaugeMetricSample gaugeMetricSample = (GaugeMetricSample<?>) sample; if (gaugeMetricSample.getName().endsWith("max.milliseconds.aggregate")) { Assertions.assertEquals(30, gaugeMetricSample.applyAsDouble()); } if (gaugeMetricSample.getName().endsWith("min.milliseconds.aggregate")) { Assertions.assertEquals(10L, gaugeMetricSample.applyAsDouble()); } if (gaugeMetricSample.getName().endsWith("avg.milliseconds.aggregate")) { Assertions.assertEquals(20L, gaugeMetricSample.applyAsDouble()); } } } @Test void testP95AndP99() throws InterruptedException { metricsDispatcher.addListener(collector); ConfigManager configManager = applicationModel.getApplicationConfigManager(); MetricsConfig config = configManager.getMetrics().orElse(null); AggregationConfig aggregationConfig = new AggregationConfig(); aggregationConfig.setEnabled(true); config.setAggregation(aggregationConfig); List<Long> requestTimes = new ArrayList<>(10000); for (int i = 0; i < 300; i++) { requestTimes.add(Double.valueOf(1000 * Math.random()).longValue()); } Collections.sort(requestTimes); double p95Index = 0.95 * (requestTimes.size() - 1); double p99Index = 0.99 * (requestTimes.size() - 1); double manualP95 = requestTimes.get((int) Math.round(p95Index)); double manualP99 = requestTimes.get((int) Math.round(p99Index)); for (Long requestTime : requestTimes) { RequestEvent requestEvent = RequestEvent.toRequestEvent( applicationModel, null, null, null, invocation, MetricsSupport.getSide(invocation), MethodMetric.isServiceLevel(applicationModel)); TestRequestEvent testRequestEvent = new TestRequestEvent(requestEvent.getSource(), requestEvent.getTypeWrapper()); testRequestEvent.putAttachment(MetricsConstants.INVOCATION, invocation); testRequestEvent.putAttachment(ATTACHMENT_KEY_SERVICE, MetricsSupport.getInterfaceName(invocation)); testRequestEvent.putAttachment(MetricsConstants.INVOCATION_SIDE, MetricsSupport.getSide(invocation)); testRequestEvent.setRt(requestTime); MetricsEventBus.post(testRequestEvent, () -> null); } Thread.sleep(4000L); List<MetricSample> samples = collector.collect(); GaugeMetricSample<?> p95Sample = samples.stream() .filter(sample -> sample.getName().endsWith("p95")) .map(sample -> (GaugeMetricSample<?>) sample) .findFirst() .orElse(null); GaugeMetricSample<?> p99Sample = samples.stream() .filter(sample -> sample.getName().endsWith("p99")) .map(sample -> (GaugeMetricSample<?>) sample) .findFirst() .orElse(null); Assertions.assertNotNull(p95Sample); Assertions.assertNotNull(p99Sample); double p95 = p95Sample.applyAsDouble(); double p99 = p99Sample.applyAsDouble(); // An error of less than 5% is allowed Assertions.assertTrue(Math.abs(1 - p95 / manualP95) < 0.05); Assertions.assertTrue(Math.abs(1 - p99 / manualP99) < 0.05); } @Test void testGenericCache() { List<Class<?>> classGenerics = ReflectionUtils.getClassGenerics(AggregateMetricsCollector.class, MetricsListener.class); Assertions.assertTrue(CollectionUtils.isNotEmpty(classGenerics)); Assertions.assertEquals(RequestEvent.class, classGenerics.get(0)); } public static class TestRequestEvent extends RequestEvent { private long rt; public TestRequestEvent(ApplicationModel applicationModel, TypeWrapper typeWrapper) { super(applicationModel, null, null, null, typeWrapper); } public void setRt(long rt) { this.rt = rt; } @Override public TimePair getTimePair() { return new TestTimePair(rt); } } public static class TestTimePair extends TimePair { long rt; public TestTimePair(long rt) { super(rt); this.rt = rt; } @Override public long calc() { return this.rt; } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/InitServiceMetricsTest.java
dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/InitServiceMetricsTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.collector; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.MetricsConfig; import org.apache.dubbo.config.nested.AggregationConfig; import org.apache.dubbo.metrics.aggregate.TimeWindowCounter; import org.apache.dubbo.metrics.event.MetricsEventBus; import org.apache.dubbo.metrics.event.MetricsInitEvent; import org.apache.dubbo.metrics.model.MethodMetric; import org.apache.dubbo.metrics.model.ServiceKeyMetric; import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper; import org.apache.dubbo.metrics.model.key.MetricsLevel; import org.apache.dubbo.metrics.model.key.MetricsPlaceValue; import org.apache.dubbo.metrics.model.sample.CounterMetricSample; import org.apache.dubbo.metrics.model.sample.GaugeMetricSample; import org.apache.dubbo.metrics.model.sample.MetricSample; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.metrics.DefaultConstants.INIT_AGG_METHOD_KEYS; import static org.apache.dubbo.metrics.DefaultConstants.INIT_DEFAULT_METHOD_KEYS; import static org.apache.dubbo.metrics.model.key.MetricsKey.METRIC_REQUESTS; import static org.apache.dubbo.metrics.model.key.MetricsKey.METRIC_REQUESTS_PROCESSING; class InitServiceMetricsTest { private ApplicationModel applicationModel; private String interfaceName; private String methodName; private String group; private String version; private String side; private DefaultMetricsCollector defaultCollector; private AggregateMetricsCollector aggregateMetricsCollector; @BeforeEach public void setup() { FrameworkModel frameworkModel = FrameworkModel.defaultModel(); applicationModel = frameworkModel.newApplication(); ApplicationConfig config = new ApplicationConfig(); config.setName("MockMetrics"); MetricsConfig metricsConfig = new MetricsConfig(); AggregationConfig aggregationConfig = new AggregationConfig(); aggregationConfig.setEnabled(true); aggregationConfig.setBucketNum(12); aggregationConfig.setTimeWindowSeconds(120); metricsConfig.setAggregation(aggregationConfig); applicationModel.getApplicationConfigManager().setMetrics(metricsConfig); applicationModel.getApplicationConfigManager().setApplication(config); defaultCollector = applicationModel.getBeanFactory().getBean(DefaultMetricsCollector.class); defaultCollector.setCollectEnabled(true); aggregateMetricsCollector = applicationModel.getBeanFactory().getOrRegisterBean(AggregateMetricsCollector.class); aggregateMetricsCollector.setCollectEnabled(true); interfaceName = "org.apache.dubbo.MockInterface"; methodName = "mockMethod"; group = "mockGroup"; version = "1.0.0"; side = CommonConstants.PROVIDER_SIDE; String serviceKey = group + "/" + interfaceName + ":" + version; String protocolServiceKey = serviceKey + ":dubbo"; RpcInvocation invocation = new RpcInvocation( serviceKey, null, methodName, interfaceName, protocolServiceKey, null, null, null, null, null, null); MetricsEventBus.publish(MetricsInitEvent.toMetricsInitEvent( applicationModel, invocation, MethodMetric.isServiceLevel(applicationModel))); } @AfterEach public void teardown() { applicationModel.destroy(); } @Test void testMetricsInitEvent() { List<MetricSample> metricSamples = defaultCollector.collect(); // INIT_DEFAULT_METHOD_KEYS.size() = 6 Assertions.assertEquals(INIT_DEFAULT_METHOD_KEYS.size(), metricSamples.size()); List<String> metricsNames = metricSamples.stream().map(MetricSample::getName).collect(Collectors.toList()); String REQUESTS = new MetricsKeyWrapper(METRIC_REQUESTS, MetricsPlaceValue.of(side, MetricsLevel.SERVICE)).targetKey(); String PROCESSING = new MetricsKeyWrapper( METRIC_REQUESTS_PROCESSING, MetricsPlaceValue.of(side, MetricsLevel.SERVICE)) .targetKey(); Assertions.assertTrue(metricsNames.contains(REQUESTS)); Assertions.assertTrue(metricsNames.contains(PROCESSING)); for (MetricSample metricSample : metricSamples) { if (metricSample instanceof GaugeMetricSample) { GaugeMetricSample<?> gaugeMetricSample = (GaugeMetricSample<?>) metricSample; Object objVal = gaugeMetricSample.getValue(); if (objVal instanceof Map) { Map<ServiceKeyMetric, AtomicLong> value = (Map<ServiceKeyMetric, AtomicLong>) objVal; Assertions.assertTrue(value.values().stream().allMatch(atomicLong -> atomicLong.intValue() == 0)); } } else { AtomicLong value = (AtomicLong) ((CounterMetricSample<?>) metricSample).getValue(); Assertions.assertEquals(0, value.intValue()); } } List<MetricSample> samples = aggregateMetricsCollector.collect(); // INIT_AGG_METHOD_KEYS.size(10) + qps(1) + rt(4) +rtAgr(3)= 18 Assertions.assertEquals(INIT_AGG_METHOD_KEYS.size() + 1 + 4 + 3, samples.size()); for (MetricSample metricSample : samples) { if (metricSample instanceof GaugeMetricSample) { GaugeMetricSample<?> gaugeMetricSample = (GaugeMetricSample<?>) metricSample; Object objVal = gaugeMetricSample.getValue(); if (objVal instanceof TimeWindowCounter) { Assertions.assertEquals(0.0, ((TimeWindowCounter) objVal).get()); } } } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/DefaultCollectorTest.java
dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/DefaultCollectorTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.collector; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.MetricsConfig; import org.apache.dubbo.metrics.TestMetricsInvoker; import org.apache.dubbo.metrics.event.MetricsDispatcher; import org.apache.dubbo.metrics.event.RequestEvent; import org.apache.dubbo.metrics.filter.MetricsFilter; import org.apache.dubbo.metrics.model.MethodMetric; import org.apache.dubbo.metrics.model.MetricsSupport; import org.apache.dubbo.metrics.model.ServiceKeyMetric; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper; import org.apache.dubbo.metrics.model.key.MetricsLevel; import org.apache.dubbo.metrics.model.key.MetricsPlaceValue; import org.apache.dubbo.metrics.model.sample.CounterMetricSample; import org.apache.dubbo.metrics.model.sample.GaugeMetricSample; import org.apache.dubbo.metrics.model.sample.MetricSample; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_APPLICATION_NAME; import static org.apache.dubbo.metrics.DefaultConstants.METRIC_FILTER_EVENT; import static org.apache.dubbo.metrics.model.key.MetricsKey.METRIC_REQUESTS; import static org.apache.dubbo.metrics.model.key.MetricsKey.METRIC_REQUESTS_PROCESSING; import static org.apache.dubbo.metrics.model.key.MetricsKey.METRIC_REQUESTS_SUCCEED; import static org.apache.dubbo.metrics.model.key.MetricsKey.METRIC_REQUESTS_TIMEOUT; import static org.apache.dubbo.metrics.model.key.MetricsKey.METRIC_REQUESTS_TOTAL_FAILED; class DefaultCollectorTest { private ApplicationModel applicationModel; private String interfaceName; private String methodName; private String group; private String version; private RpcInvocation invocation; private String side; MetricsDispatcher metricsDispatcher; DefaultMetricsCollector defaultCollector; MetricsFilter metricsFilter; @BeforeEach public void setup() { FrameworkModel frameworkModel = FrameworkModel.defaultModel(); applicationModel = frameworkModel.newApplication(); ApplicationConfig config = new ApplicationConfig(); config.setName("MockMetrics"); MetricsConfig metricsConfig = new MetricsConfig(); metricsConfig.setEnableRpc(true); applicationModel.getApplicationConfigManager().setApplication(config); applicationModel.getApplicationConfigManager().setMetrics(metricsConfig); metricsDispatcher = applicationModel.getBeanFactory().getOrRegisterBean(MetricsDispatcher.class); defaultCollector = applicationModel.getBeanFactory().getBean(DefaultMetricsCollector.class); defaultCollector.setCollectEnabled(true); interfaceName = "org.apache.dubbo.MockInterface"; methodName = "mockMethod"; group = "mockGroup"; version = "1.0.0"; invocation = new RpcInvocation(methodName, interfaceName, "serviceKey", null, null); invocation.setTargetServiceUniqueName(group + "/" + interfaceName + ":" + version); invocation.setAttachment(GROUP_KEY, group); invocation.setAttachment(VERSION_KEY, version); side = CommonConstants.CONSUMER; invocation.setInvoker(new TestMetricsInvoker(side)); invocation.setTargetServiceUniqueName(group + "/" + interfaceName + ":" + version); RpcContext.getServiceContext() .setUrl(URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&side=" + side)); metricsFilter = new MetricsFilter(); metricsFilter.setApplicationModel(applicationModel); } @Test void testListener() { DefaultMetricsCollector metricsCollector = new DefaultMetricsCollector(applicationModel); RequestEvent event = RequestEvent.toRequestEvent( applicationModel, null, null, null, invocation, MetricsSupport.getSide(invocation), MethodMetric.isServiceLevel(applicationModel)); RequestEvent beforeEvent = RequestEvent.toRequestErrorEvent( applicationModel, null, null, invocation, MetricsSupport.getSide(invocation), RpcException.FORBIDDEN_EXCEPTION, MethodMetric.isServiceLevel(applicationModel)); Assertions.assertTrue(metricsCollector.isSupport(event)); Assertions.assertTrue(metricsCollector.isSupport(beforeEvent)); } @AfterEach public void teardown() { applicationModel.destroy(); } /** * No rt metrics because Aggregate calc */ @Test void testRequestEventNoRt() { applicationModel.getBeanFactory().getOrRegisterBean(MetricsDispatcher.class); DefaultMetricsCollector collector = applicationModel.getBeanFactory().getOrRegisterBean(DefaultMetricsCollector.class); collector.setCollectEnabled(true); ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DefaultCollectorTest.class); logger.warn("0-99", "", "", "Test error code message."); metricsFilter.invoke(new TestMetricsInvoker(side), invocation); try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } AppResponse mockRpcResult = new AppResponse(); // mockRpcResult.setException(new RpcException("hessian")); Result result = AsyncRpcResult.newDefaultAsyncResult(mockRpcResult, invocation); metricsFilter.onResponse(result, new TestMetricsInvoker(side), invocation); RequestEvent eventObj = (RequestEvent) invocation.get(METRIC_FILTER_EVENT); long c1 = eventObj.getTimePair().calc(); // push finish rt +1 List<MetricSample> metricSamples = collector.collect(); // num(total+success+processing) + rt(5) + error code = 9 Assertions.assertEquals(metricSamples.size(), 9); List<String> metricsNames = metricSamples.stream().map(MetricSample::getName).collect(Collectors.toList()); // No error will contain total+success+processing String REQUESTS = new MetricsKeyWrapper(METRIC_REQUESTS, MetricsPlaceValue.of(side, MetricsLevel.SERVICE)).targetKey(); String SUCCEED = new MetricsKeyWrapper( METRIC_REQUESTS_SUCCEED, MetricsPlaceValue.of(side, MetricsLevel.SERVICE)) .targetKey(); String PROCESSING = new MetricsKeyWrapper( METRIC_REQUESTS_PROCESSING, MetricsPlaceValue.of(side, MetricsLevel.SERVICE)) .targetKey(); Assertions.assertTrue(metricsNames.contains(REQUESTS)); Assertions.assertTrue(metricsNames.contains(SUCCEED)); Assertions.assertTrue(metricsNames.contains(PROCESSING)); for (MetricSample metricSample : metricSamples) { if (metricSample instanceof GaugeMetricSample) { GaugeMetricSample<?> gaugeMetricSample = (GaugeMetricSample<?>) metricSample; Object objVal = gaugeMetricSample.getValue(); if (objVal instanceof Map) { Map<ServiceKeyMetric, AtomicLong> value = (Map<ServiceKeyMetric, AtomicLong>) objVal; if (metricSample.getName().equals(REQUESTS)) { Assertions.assertTrue( value.values().stream().allMatch(atomicLong -> atomicLong.intValue() == 1)); } if (metricSample.getName().equals(PROCESSING)) { Assertions.assertTrue( value.values().stream().allMatch(atomicLong -> atomicLong.intValue() == 0)); } } } else { AtomicLong value = (AtomicLong) ((CounterMetricSample<?>) metricSample).getValue(); if (metricSample.getName().equals(SUCCEED)) { Assertions.assertEquals(1, value.intValue()); } } } metricsFilter.invoke(new TestMetricsInvoker(side), invocation); try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } metricsFilter.onError( new RpcException(RpcException.TIMEOUT_EXCEPTION, "timeout"), new TestMetricsInvoker(side), invocation); eventObj = (RequestEvent) invocation.get(METRIC_FILTER_EVENT); long c2 = eventObj.getTimePair().calc(); metricSamples = collector.collect(); // num(total+success+error+total_error+processing) + rt(5) + error code = 11 Assertions.assertEquals(11, metricSamples.size()); String TIMEOUT = new MetricsKeyWrapper( METRIC_REQUESTS_TIMEOUT, MetricsPlaceValue.of(side, MetricsLevel.SERVICE)) .targetKey(); String TOTAL_FAILED = new MetricsKeyWrapper( METRIC_REQUESTS_TOTAL_FAILED, MetricsPlaceValue.of(side, MetricsLevel.SERVICE)) .targetKey(); for (MetricSample metricSample : metricSamples) { if (metricSample instanceof GaugeMetricSample) { GaugeMetricSample<?> gaugeMetricSample = (GaugeMetricSample<?>) metricSample; Object objVal = gaugeMetricSample.getValue(); if (objVal instanceof Map) { Map<ServiceKeyMetric, AtomicLong> value = (Map<ServiceKeyMetric, AtomicLong>) ((GaugeMetricSample<?>) metricSample).getValue(); if (metricSample.getName().equals(REQUESTS)) { Assertions.assertTrue( value.values().stream().allMatch(atomicLong -> atomicLong.intValue() == 2)); } if (metricSample.getName().equals(REQUESTS)) { Assertions.assertTrue( value.values().stream().allMatch(atomicLong -> atomicLong.intValue() == 2)); } if (metricSample.getName().equals(PROCESSING)) { Assertions.assertTrue( value.values().stream().allMatch(atomicLong -> atomicLong.intValue() == 0)); } if (metricSample.getName().equals(TIMEOUT)) { Assertions.assertTrue( value.values().stream().allMatch(atomicLong -> atomicLong.intValue() == 1)); } if (metricSample.getName().equals(TOTAL_FAILED)) { Assertions.assertTrue( value.values().stream().allMatch(atomicLong -> atomicLong.intValue() == 1)); } } } else { AtomicLong value = (AtomicLong) ((CounterMetricSample<?>) metricSample).getValue(); if (metricSample.getName().equals(SUCCEED)) { Assertions.assertEquals(1, value.intValue()); } } } // calc rt for (MetricSample sample : metricSamples) { Map<String, String> tags = sample.getTags(); Assertions.assertEquals(tags.get(TAG_APPLICATION_NAME), applicationModel.getApplicationName()); } Map<String, Long> sampleMap = metricSamples.stream() .filter(metricSample -> metricSample instanceof GaugeMetricSample) .collect(Collectors.toMap(MetricSample::getName, k -> ((GaugeMetricSample) k).applyAsLong())); Assertions.assertEquals( sampleMap.get(new MetricsKeyWrapper( MetricsKey.METRIC_RT_LAST, MetricsPlaceValue.of(side, MetricsLevel.SERVICE)) .targetKey()), c2); Assertions.assertEquals( sampleMap.get(new MetricsKeyWrapper( MetricsKey.METRIC_RT_MIN, MetricsPlaceValue.of(side, MetricsLevel.SERVICE)) .targetKey()), Math.min(c1, c2)); Assertions.assertEquals( sampleMap.get(new MetricsKeyWrapper( MetricsKey.METRIC_RT_MAX, MetricsPlaceValue.of(side, MetricsLevel.SERVICE)) .targetKey()), Math.max(c1, c2)); Assertions.assertEquals( sampleMap.get(new MetricsKeyWrapper( MetricsKey.METRIC_RT_AVG, MetricsPlaceValue.of(side, MetricsLevel.SERVICE)) .targetKey()), (c1 + c2) / 2); Assertions.assertEquals( sampleMap.get(new MetricsKeyWrapper( MetricsKey.METRIC_RT_SUM, MetricsPlaceValue.of(side, MetricsLevel.SERVICE)) .targetKey()), c1 + c2); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/sample/ThreadPoolMetricsSamplerTest.java
dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/sample/ThreadPoolMetricsSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.collector.sample; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.store.DataStore; import org.apache.dubbo.common.store.DataStoreUpdateListener; import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository; import org.apache.dubbo.metrics.collector.DefaultMetricsCollector; import org.apache.dubbo.metrics.model.ThreadPoolMetric; import org.apache.dubbo.metrics.model.sample.GaugeMetricSample; import org.apache.dubbo.metrics.model.sample.MetricSample; import org.apache.dubbo.rpc.model.ApplicationModel; import java.lang.reflect.Field; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SHARED_EXECUTOR_SERVICE_COMPONENT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_SERVICE_COMPONENT_KEY; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @SuppressWarnings("all") public class ThreadPoolMetricsSamplerTest { ThreadPoolMetricsSampler sampler; @BeforeEach void setUp() { DefaultMetricsCollector collector = new DefaultMetricsCollector(applicationModel); sampler = new ThreadPoolMetricsSampler(collector); } @Test void testSample() { ExecutorService executorService = java.util.concurrent.Executors.newFixedThreadPool(5); ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) executorService; sampler.addExecutors("testPool", executorService); List<MetricSample> metricSamples = sampler.sample(); Assertions.assertEquals(6, metricSamples.size()); boolean coreSizeFound = false; boolean maxSizeFound = false; boolean activeSizeFound = false; boolean threadCountFound = false; boolean queueSizeFound = false; boolean largestSizeFound = false; for (MetricSample sample : metricSamples) { ThreadPoolMetric threadPoolMetric = ((ThreadPoolMetric) ((GaugeMetricSample) sample).getValue()); switch (sample.getName()) { case "dubbo.thread.pool.core.size": coreSizeFound = true; Assertions.assertEquals(5, threadPoolMetric.getCorePoolSize()); break; case "dubbo.thread.pool.largest.size": largestSizeFound = true; Assertions.assertEquals(0, threadPoolMetric.getLargestPoolSize()); break; case "dubbo.thread.pool.max.size": maxSizeFound = true; Assertions.assertEquals(5, threadPoolMetric.getMaximumPoolSize()); break; case "dubbo.thread.pool.active.size": activeSizeFound = true; Assertions.assertEquals(0, threadPoolMetric.getActiveCount()); break; case "dubbo.thread.pool.thread.count": threadCountFound = true; Assertions.assertEquals(0, threadPoolMetric.getPoolSize()); break; case "dubbo.thread.pool.queue.size": queueSizeFound = true; Assertions.assertEquals(0, threadPoolMetric.getQueueSize()); break; } } Assertions.assertTrue(coreSizeFound); Assertions.assertTrue(maxSizeFound); Assertions.assertTrue(activeSizeFound); Assertions.assertTrue(threadCountFound); Assertions.assertTrue(queueSizeFound); Assertions.assertTrue(largestSizeFound); executorService.shutdown(); } private DefaultMetricsCollector collector; private ThreadPoolMetricsSampler sampler2; @Mock private ApplicationModel applicationModel; @Mock ScopeBeanFactory scopeBeanFactory; @Mock private DataStore dataStore; @Mock private FrameworkExecutorRepository frameworkExecutorRepository; @Mock private ExtensionLoader<DataStore> extensionLoader; @BeforeEach public void setUp2() { MockitoAnnotations.openMocks(this); collector = new DefaultMetricsCollector(applicationModel); sampler2 = new ThreadPoolMetricsSampler(collector); when(scopeBeanFactory.getBean(FrameworkExecutorRepository.class)).thenReturn(new FrameworkExecutorRepository()); collector.collectApplication(); when(applicationModel.getBeanFactory()).thenReturn(scopeBeanFactory); when(applicationModel.getExtensionLoader(DataStore.class)).thenReturn(extensionLoader); when(extensionLoader.getDefaultExtension()).thenReturn(dataStore); } @Test public void testRegistryDefaultSampleThreadPoolExecutor() throws NoSuchFieldException, IllegalAccessException { Map<String, Object> serverExecutors = new HashMap<>(); Map<String, Object> clientExecutors = new HashMap<>(); ExecutorService serverExecutor = Executors.newFixedThreadPool(5); ExecutorService clientExecutor = Executors.newFixedThreadPool(5); serverExecutors.put("server1", serverExecutor); clientExecutors.put("client1", clientExecutor); when(dataStore.get(EXECUTOR_SERVICE_COMPONENT_KEY)).thenReturn(serverExecutors); when(dataStore.get(CONSUMER_SHARED_EXECUTOR_SERVICE_COMPONENT_KEY)).thenReturn(clientExecutors); when(frameworkExecutorRepository.getSharedExecutor()).thenReturn(Executors.newFixedThreadPool(5)); sampler2.registryDefaultSampleThreadPoolExecutor(); Field f = ThreadPoolMetricsSampler.class.getDeclaredField("sampleThreadPoolExecutor"); f.setAccessible(true); Map<String, ThreadPoolExecutor> executors = (Map<String, ThreadPoolExecutor>) f.get(sampler2); Assertions.assertEquals(8, executors.size()); Assertions.assertTrue(executors.containsKey("DubboServerHandler-server1")); Assertions.assertTrue(executors.containsKey("DubboClientHandler-client1")); Assertions.assertTrue(executors.containsKey("sharedExecutor")); serverExecutor.shutdown(); clientExecutor.shutdown(); } @Test void testDataSourceNotify() throws Exception { ArgumentCaptor<DataStoreUpdateListener> captor = ArgumentCaptor.forClass(DataStoreUpdateListener.class); when(scopeBeanFactory.getBean(FrameworkExecutorRepository.class)).thenReturn(frameworkExecutorRepository); when(frameworkExecutorRepository.getSharedExecutor()).thenReturn(null); sampler2.registryDefaultSampleThreadPoolExecutor(); Field f = ThreadPoolMetricsSampler.class.getDeclaredField("sampleThreadPoolExecutor"); f.setAccessible(true); Map<String, ThreadPoolExecutor> executors = (Map<String, ThreadPoolExecutor>) f.get(sampler2); Assertions.assertEquals(0, executors.size()); verify(dataStore).addListener(captor.capture()); Assertions.assertEquals(sampler2, captor.getValue()); ExecutorService executorService = Executors.newFixedThreadPool(5); sampler2.onUpdate(EXECUTOR_SERVICE_COMPONENT_KEY, "20880", executorService); executors = (Map<String, ThreadPoolExecutor>) f.get(sampler2); Assertions.assertEquals(1, executors.size()); Assertions.assertTrue(executors.containsKey("DubboServerHandler-20880")); sampler2.onUpdate(CONSUMER_SHARED_EXECUTOR_SERVICE_COMPONENT_KEY, "client", executorService); Assertions.assertEquals(2, executors.size()); Assertions.assertTrue(executors.containsKey("DubboClientHandler-client")); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/filter/MetricsFilterTest.java
dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/filter/MetricsFilterTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.filter; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.MetricsConfig; import org.apache.dubbo.metrics.TestMetricsInvoker; import org.apache.dubbo.metrics.collector.DefaultMetricsCollector; import org.apache.dubbo.metrics.event.MetricsEventBus; import org.apache.dubbo.metrics.event.RequestEvent; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper; import org.apache.dubbo.metrics.model.key.MetricsLevel; import org.apache.dubbo.metrics.model.key.MetricsPlaceValue; import org.apache.dubbo.metrics.model.sample.CounterMetricSample; import org.apache.dubbo.metrics.model.sample.MetricSample; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; import java.util.stream.Collectors; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE; import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_PARAMETER_DESC; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_GROUP_KEY; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_INTERFACE_KEY; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_METHOD_KEY; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_VERSION_KEY; import static org.apache.dubbo.metrics.DefaultConstants.METRIC_FILTER_EVENT; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; class MetricsFilterTest { private ApplicationModel applicationModel; private MetricsFilter filter; private DefaultMetricsCollector collector; private RpcInvocation invocation; private final Invoker<?> invoker = mock(Invoker.class); private static final String INTERFACE_NAME = "org.apache.dubbo.MockInterface"; private static final String METHOD_NAME = "mockMethod"; private static final String GROUP = "mockGroup"; private static final String VERSION = "1.0.0_BETA"; private String side; private AtomicBoolean initApplication = new AtomicBoolean(false); @BeforeEach public void setup() { ApplicationConfig config = new ApplicationConfig(); config.setName("MockMetrics"); applicationModel = ApplicationModel.defaultModel(); MetricsConfig metricsConfig = new MetricsConfig(); metricsConfig.setEnableRpc(true); applicationModel.getApplicationConfigManager().setApplication(config); applicationModel.getApplicationConfigManager().setMetrics(metricsConfig); invocation = new RpcInvocation(); filter = new MetricsFilter(); collector = applicationModel.getBeanFactory().getOrRegisterBean(DefaultMetricsCollector.class); if (!initApplication.get()) { collector.collectApplication(); initApplication.set(true); } filter.setApplicationModel(applicationModel); side = CommonConstants.CONSUMER; invocation.setInvoker(new TestMetricsInvoker(side)); RpcContext.getServiceContext() .setUrl(URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&side=" + side)); } @AfterEach public void teardown() { applicationModel.destroy(); } @Test void testCollectDisabled() { given(invoker.invoke(invocation)).willReturn(new AppResponse("success")); filter.invoke(invoker, invocation); Map<String, MetricSample> metricsMap = getMetricsMap(); metricsMap.remove(MetricsKey.APPLICATION_METRIC_INFO.getName()); Assertions.assertTrue(metricsMap.isEmpty()); } @Test void testUnknownFailedRequests() { collector.setCollectEnabled(true); given(invoker.invoke(invocation)).willThrow(new RpcException("failed")); initParam(); try { filter.invoke(invoker, invocation); } catch (Exception e) { Assertions.assertTrue(e instanceof RpcException); filter.onError(e, invoker, invocation); } Map<String, MetricSample> metricsMap = getMetricsMap(); Assertions.assertTrue(metricsMap.containsKey(MetricsKey.METRIC_REQUESTS_FAILED.getNameByType(side))); Assertions.assertFalse(metricsMap.containsKey(MetricsKey.METRIC_REQUESTS_SUCCEED.getNameByType(side))); MetricSample sample = metricsMap.get(MetricsKey.METRIC_REQUESTS_FAILED.getNameByType(side)); Map<String, String> tags = sample.getTags(); Assertions.assertEquals(tags.get(TAG_INTERFACE_KEY), INTERFACE_NAME); Assertions.assertEquals(tags.get(TAG_METHOD_KEY), METHOD_NAME); Assertions.assertEquals(tags.get(TAG_GROUP_KEY), GROUP); Assertions.assertEquals(tags.get(TAG_VERSION_KEY), VERSION); } @Test void testBusinessFailedRequests() { collector.setCollectEnabled(true); given(invoker.invoke(invocation)).willThrow(new RpcException(RpcException.BIZ_EXCEPTION)); initParam(); try { filter.invoke(invoker, invocation); } catch (Exception e) { Assertions.assertTrue(e instanceof RpcException); filter.onError(e, invoker, invocation); } Map<String, MetricSample> metricsMap = getMetricsMap(); Assertions.assertTrue(metricsMap.containsKey(MetricsKey.METRIC_REQUEST_BUSINESS_FAILED.getNameByType(side))); Assertions.assertFalse(metricsMap.containsKey(MetricsKey.METRIC_REQUESTS_SUCCEED.getNameByType(side))); MetricSample sample = metricsMap.get(MetricsKey.METRIC_REQUEST_BUSINESS_FAILED.getNameByType(side)); Map<String, String> tags = sample.getTags(); Assertions.assertEquals(tags.get(TAG_INTERFACE_KEY), INTERFACE_NAME); Assertions.assertEquals(tags.get(TAG_METHOD_KEY), METHOD_NAME); Assertions.assertEquals(tags.get(TAG_GROUP_KEY), GROUP); Assertions.assertEquals(tags.get(TAG_VERSION_KEY), VERSION); } @Test void testTimeoutRequests() { collector.setCollectEnabled(true); given(invoker.invoke(invocation)).willThrow(new RpcException(RpcException.TIMEOUT_EXCEPTION)); initParam(); Long count = 2L; for (int i = 0; i < count; i++) { try { filter.invoke(invoker, invocation); } catch (Exception e) { Assertions.assertTrue(e instanceof RpcException); filter.onError(e, invoker, invocation); } } Map<String, MetricSample> metricsMap = getMetricsMap(); Assertions.assertTrue(metricsMap.containsKey(MetricsKey.METRIC_REQUESTS_TIMEOUT.getNameByType(side))); Assertions.assertTrue(metricsMap.containsKey(MetricsKey.METRIC_REQUESTS_TOTAL_FAILED.getNameByType(side))); MetricSample timeoutSample = metricsMap.get(MetricsKey.METRIC_REQUESTS_TIMEOUT.getNameByType(side)); Assertions.assertSame(((CounterMetricSample) timeoutSample).getValue().longValue(), count); CounterMetricSample failedSample = (CounterMetricSample) metricsMap.get(MetricsKey.METRIC_REQUESTS_TOTAL_FAILED.getNameByType(side)); Assertions.assertSame(failedSample.getValue().longValue(), count); } @Test void testLimitRequests() { collector.setCollectEnabled(true); given(invoker.invoke(invocation)).willThrow(new RpcException(RpcException.LIMIT_EXCEEDED_EXCEPTION)); initParam(); Long count = 3L; for (int i = 0; i < count; i++) { try { filter.invoke(invoker, invocation); } catch (Exception e) { Assertions.assertTrue(e instanceof RpcException); filter.onError(e, invoker, invocation); } } Map<String, MetricSample> metricsMap = getMetricsMap(); Assertions.assertTrue(metricsMap.containsKey(MetricsKey.METRIC_REQUESTS_LIMIT.getNameByType(side))); MetricSample sample = metricsMap.get(MetricsKey.METRIC_REQUESTS_LIMIT.getNameByType(side)); Assertions.assertSame(((CounterMetricSample) sample).getValue().longValue(), count); } @Test void testSucceedRequests() { collector.setCollectEnabled(true); given(invoker.invoke(invocation)).willReturn(new AppResponse("success")); initParam(); Result result = filter.invoke(invoker, invocation); filter.onResponse(result, invoker, invocation); Map<String, MetricSample> metricsMap = getMetricsMap(); Assertions.assertFalse(metricsMap.containsKey(MetricsKey.METRIC_REQUEST_BUSINESS_FAILED.getNameByType(side))); Assertions.assertTrue(metricsMap.containsKey(MetricsKey.METRIC_REQUESTS_SUCCEED.getNameByType(side))); MetricSample sample = metricsMap.get(MetricsKey.METRIC_REQUESTS_SUCCEED.getNameByType(side)); Map<String, String> tags = sample.getTags(); Assertions.assertEquals(tags.get(TAG_INTERFACE_KEY), INTERFACE_NAME); Assertions.assertEquals(tags.get(TAG_METHOD_KEY), METHOD_NAME); Assertions.assertEquals(tags.get(TAG_GROUP_KEY), GROUP); Assertions.assertEquals(tags.get(TAG_VERSION_KEY), VERSION); } @Test void testMissingGroup() { collector.setCollectEnabled(true); given(invoker.invoke(invocation)).willReturn(new AppResponse("success")); invocation.setTargetServiceUniqueName(INTERFACE_NAME + ":" + VERSION); invocation.setMethodName(METHOD_NAME); invocation.setParameterTypes(new Class[] {String.class}); Result result = filter.invoke(invoker, invocation); filter.onResponse(result, invoker, invocation); Map<String, MetricSample> metricsMap = getMetricsMap(); MetricSample sample = metricsMap.get(MetricsKey.METRIC_REQUESTS_SUCCEED.getNameByType(side)); Map<String, String> tags = sample.getTags(); Assertions.assertEquals(tags.get(TAG_INTERFACE_KEY), INTERFACE_NAME); Assertions.assertEquals(tags.get(TAG_METHOD_KEY), METHOD_NAME); Assertions.assertNull(tags.get(TAG_GROUP_KEY)); Assertions.assertEquals(tags.get(TAG_VERSION_KEY), VERSION); } @Test public void testErrors() { testFilterError(RpcException.SERIALIZATION_EXCEPTION, MetricsKey.METRIC_REQUESTS_CODEC_FAILED); testFilterError(RpcException.NETWORK_EXCEPTION, MetricsKey.METRIC_REQUESTS_NETWORK_FAILED); } private void testFilterError(int errorCode, MetricsKey metricsKey) { String targetKey = new MetricsKeyWrapper(metricsKey, MetricsPlaceValue.of(side, MetricsLevel.METHOD)).targetKey(); setup(); collector.setCollectEnabled(true); given(invoker.invoke(invocation)).willThrow(new RpcException(errorCode)); initParam(); Long count = 1L; for (int i = 0; i < count; i++) { try { filter.invoke(invoker, invocation); } catch (Exception e) { Assertions.assertTrue(e instanceof RpcException); filter.onError(e, invoker, invocation); } } Map<String, MetricSample> metricsMap = getMetricsMap(); Assertions.assertFalse(metricsMap.containsKey(metricsKey.getName())); MetricSample sample = metricsMap.get(targetKey); Assertions.assertSame(((CounterMetricSample<?>) sample).getValue().longValue(), count); Assertions.assertFalse(metricsMap.containsKey(metricsKey.getName())); Map<String, String> tags = sample.getTags(); Assertions.assertEquals(tags.get(TAG_INTERFACE_KEY), INTERFACE_NAME); Assertions.assertEquals(tags.get(TAG_METHOD_KEY), METHOD_NAME); Assertions.assertEquals(tags.get(TAG_GROUP_KEY), GROUP); Assertions.assertEquals(tags.get(TAG_VERSION_KEY), VERSION); teardown(); } @Test void testMissingVersion() { collector.setCollectEnabled(true); given(invoker.invoke(invocation)).willReturn(new AppResponse("success")); invocation.setTargetServiceUniqueName(GROUP + "/" + INTERFACE_NAME); invocation.setMethodName(METHOD_NAME); invocation.setParameterTypes(new Class[] {String.class}); Result result = filter.invoke(invoker, invocation); filter.onResponse(result, invoker, invocation); Map<String, MetricSample> metricsMap = getMetricsMap(); MetricSample sample = metricsMap.get(MetricsKey.METRIC_REQUESTS_SUCCEED.getNameByType(side)); Map<String, String> tags = sample.getTags(); Assertions.assertEquals(tags.get(TAG_INTERFACE_KEY), INTERFACE_NAME); Assertions.assertEquals(tags.get(TAG_METHOD_KEY), METHOD_NAME); Assertions.assertEquals(tags.get(TAG_GROUP_KEY), GROUP); Assertions.assertNull(tags.get(TAG_VERSION_KEY)); } @Test void testMissingGroupAndVersion() { collector.setCollectEnabled(true); given(invoker.invoke(invocation)).willReturn(new AppResponse("success")); invocation.setTargetServiceUniqueName(INTERFACE_NAME); invocation.setMethodName(METHOD_NAME); invocation.setParameterTypes(new Class[] {String.class}); Result result = filter.invoke(invoker, invocation); filter.onResponse(result, invoker, invocation); Map<String, MetricSample> metricsMap = getMetricsMap(); MetricSample sample = metricsMap.get(MetricsKey.METRIC_REQUESTS_SUCCEED.getNameByType(side)); Map<String, String> tags = sample.getTags(); Assertions.assertEquals(tags.get(TAG_INTERFACE_KEY), INTERFACE_NAME); Assertions.assertEquals(tags.get(TAG_METHOD_KEY), METHOD_NAME); Assertions.assertNull(tags.get(TAG_GROUP_KEY)); Assertions.assertNull(tags.get(TAG_VERSION_KEY)); } @Test void testGenericCall() { collector.setCollectEnabled(true); given(invoker.invoke(invocation)).willReturn(new AppResponse("success")); invocation.setTargetServiceUniqueName(INTERFACE_NAME); invocation.setMethodName(METHOD_NAME); invocation.setParameterTypes(new Class[] {String.class}); Result result = filter.invoke(invoker, invocation); invocation.setMethodName($INVOKE); invocation.setParameterTypesDesc(GENERIC_PARAMETER_DESC); invocation.setArguments(new Object[] {METHOD_NAME, new String[] {"java.lang.String"}, new Object[] {"mock"}}); filter.onResponse(result, invoker, invocation); Map<String, MetricSample> metricsMap = getMetricsMap(); MetricSample sample = metricsMap.get(MetricsKey.METRIC_REQUESTS_PROCESSING.getNameByType(side)); Map<String, String> tags = sample.getTags(); Assertions.assertEquals(tags.get(TAG_INTERFACE_KEY), INTERFACE_NAME); Assertions.assertEquals(tags.get(TAG_METHOD_KEY), METHOD_NAME); } private void initParam() { invocation.setTargetServiceUniqueName(GROUP + "/" + INTERFACE_NAME + ":" + VERSION); invocation.setMethodName(METHOD_NAME); invocation.setParameterTypes(new Class[] {String.class}); } private Map<String, MetricSample> getMetricsMap() { List<MetricSample> samples = collector.collect(); List<MetricSample> samples1 = new ArrayList<>(); for (MetricSample sample : samples) { if (sample.getName().contains("dubbo.thread.pool")) { continue; } samples1.add(sample); } return samples1.stream().collect(Collectors.toMap(MetricSample::getName, Function.identity())); } @Test void testThrowable() { invocation.setTargetServiceUniqueName(INTERFACE_NAME); invocation.setMethodName(METHOD_NAME); invocation.setParameterTypes(new Class[] {String.class}); given(invoker.invoke(invocation)).willReturn(new AppResponse("success")); Result result = filter.invoke(invoker, invocation); result.setException(new RuntimeException("failed")); Object eventObj = invocation.get(METRIC_FILTER_EVENT); if (eventObj != null) { Assertions.assertDoesNotThrow(() -> MetricsEventBus.after((RequestEvent) eventObj, result)); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/metrics/service/MetricsEntityTest.java
dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/metrics/service/MetricsEntityTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.metrics.service; import org.apache.dubbo.metrics.model.MetricsCategory; import org.apache.dubbo.metrics.service.MetricsEntity; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; class MetricsEntityTest { private static String name; private static Map<String, String> tags; private static MetricsCategory category; private static Object value; @BeforeAll public static void setup() { name = "test"; tags = new HashMap<>(); category = MetricsCategory.REQUESTS; value = 1; } @Test void test() { MetricsEntity entity = new MetricsEntity(name, tags, category, value); Assertions.assertEquals(entity.getName(), name); Assertions.assertEquals(entity.getTags(), tags); Assertions.assertEquals(entity.getCategory(), category); Assertions.assertEquals(entity.getValue(), value); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/metrics/model/MethodMetricTest.java
dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/metrics/model/MethodMetricTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.metrics.model; import org.apache.dubbo.common.URL; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.MetricsConfig; import org.apache.dubbo.metrics.model.MethodMetric; import org.apache.dubbo.metrics.model.key.MetricsLevel; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Map; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_APPLICATION_NAME; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_GROUP_KEY; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_INTERFACE_KEY; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_METHOD_KEY; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_VERSION_KEY; class MethodMetricTest { private static ApplicationModel applicationModel; private static String interfaceName; private static String methodName; private static String group; private static String version; private static RpcInvocation invocation; @BeforeAll public static void setup() { ApplicationConfig config = new ApplicationConfig(); config.setName("MockMetrics"); applicationModel = ApplicationModel.defaultModel(); applicationModel.getApplicationConfigManager().setApplication(config); interfaceName = "org.apache.dubbo.MockInterface"; methodName = "mockMethod"; group = "mockGroup"; version = "1.0.0"; invocation = new RpcInvocation(methodName, interfaceName, "serviceKey", null, null); invocation.setTargetServiceUniqueName(group + "/" + interfaceName + ":" + version); invocation.setAttachment(GROUP_KEY, group); invocation.setAttachment(VERSION_KEY, version); RpcContext.getServiceContext() .setUrl(URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&side=consumer")); } @AfterAll public static void destroy() { ApplicationModel.defaultModel().destroy(); } @Test void test() { MethodMetric metric = new MethodMetric(applicationModel, invocation, MethodMetric.isServiceLevel(applicationModel)); Assertions.assertEquals(metric.getServiceKey(), interfaceName); Assertions.assertEquals(metric.getMethodName(), methodName); Assertions.assertEquals(metric.getGroup(), group); Assertions.assertEquals(metric.getVersion(), version); Map<String, String> tags = metric.getTags(); Assertions.assertEquals(tags.get(TAG_APPLICATION_NAME), applicationModel.getApplicationName()); Assertions.assertEquals(tags.get(TAG_INTERFACE_KEY), interfaceName); Assertions.assertEquals(tags.get(TAG_METHOD_KEY), methodName); Assertions.assertEquals(tags.get(TAG_GROUP_KEY), group); Assertions.assertEquals(tags.get(TAG_VERSION_KEY), version); } @Test void testServiceMetrics() { MetricsConfig metricConfig = new MetricsConfig(); applicationModel.getApplicationConfigManager().setMetrics(metricConfig); metricConfig.setRpcLevel(MetricsLevel.SERVICE.name()); MethodMetric metric = new MethodMetric(applicationModel, invocation, MethodMetric.isServiceLevel(applicationModel)); Assertions.assertEquals(metric.getServiceKey(), interfaceName); Assertions.assertNull(metric.getMethodName(), methodName); Assertions.assertEquals(metric.getGroup(), group); Assertions.assertEquals(metric.getVersion(), version); Map<String, String> tags = metric.getTags(); Assertions.assertEquals(tags.get(TAG_APPLICATION_NAME), applicationModel.getApplicationName()); Assertions.assertEquals(tags.get(TAG_INTERFACE_KEY), interfaceName); Assertions.assertNull(tags.get(TAG_METHOD_KEY)); Assertions.assertEquals(tags.get(TAG_GROUP_KEY), group); Assertions.assertEquals(tags.get(TAG_VERSION_KEY), version); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/metrics/model/sample/GaugeMetricSampleTest.java
dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/metrics/model/sample/GaugeMetricSampleTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.metrics.model.sample; import org.apache.dubbo.metrics.model.MetricsCategory; import org.apache.dubbo.metrics.model.sample.GaugeMetricSample; import org.apache.dubbo.metrics.model.sample.MetricSample; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; import java.util.function.ToDoubleFunction; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; class GaugeMetricSampleTest { private static String name; private static String description; private static Map<String, String> tags; private static MetricsCategory category; private static String baseUnit; private static AtomicLong value; private static ToDoubleFunction<AtomicLong> apply; @BeforeAll public static void setup() { name = "test"; description = "test"; tags = new HashMap<>(); category = MetricsCategory.REQUESTS; baseUnit = "byte"; value = new AtomicLong(1); apply = AtomicLong::longValue; } @Test void test() { GaugeMetricSample<?> sample = new GaugeMetricSample<>(name, description, tags, category, baseUnit, value, apply); Assertions.assertEquals(sample.getName(), name); Assertions.assertEquals(sample.getDescription(), description); Assertions.assertEquals(sample.getTags(), tags); Assertions.assertEquals(sample.getType(), MetricSample.Type.GAUGE); Assertions.assertEquals(sample.getCategory(), category); Assertions.assertEquals(sample.getBaseUnit(), baseUnit); Assertions.assertEquals(1, sample.applyAsLong()); value.set(2); Assertions.assertEquals(2, sample.applyAsLong()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/metrics/model/sample/ErrorCodeSampleTest.java
dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/metrics/model/sample/ErrorCodeSampleTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.metrics.model.sample; import org.apache.dubbo.common.utils.Assert; import org.apache.dubbo.common.utils.ReflectionUtils; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.metrics.collector.DefaultMetricsCollector; import org.apache.dubbo.metrics.collector.sample.ErrorCodeMetricsListenRegister; import org.apache.dubbo.metrics.collector.sample.ErrorCodeSampler; import org.apache.dubbo.metrics.model.sample.CounterMetricSample; import org.apache.dubbo.metrics.model.sample.MetricSample; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import java.util.List; import java.util.concurrent.atomic.AtomicLong; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; public class ErrorCodeSampleTest { @Test void testErrorCodeMetric() { FrameworkModel frameworkModel = FrameworkModel.defaultModel(); ApplicationModel applicationModel = frameworkModel.newApplication(); ApplicationConfig applicationConfig = new ApplicationConfig(); applicationConfig.setName("MyApplication1"); applicationModel.getApplicationConfigManager().setApplication(applicationConfig); DefaultMetricsCollector defaultMetricsCollector = new DefaultMetricsCollector(applicationModel); defaultMetricsCollector.setCollectEnabled(true); ErrorCodeSampler sampler = (ErrorCodeSampler) ReflectionUtils.getField(defaultMetricsCollector, "errorCodeSampler"); ErrorCodeMetricsListenRegister register = (ErrorCodeMetricsListenRegister) ReflectionUtils.getField(sampler, "register"); register.onMessage("0-1", null); register.onMessage("0-1", null); register.onMessage("0-2", null); register.onMessage("0-2", null); register.onMessage("1-2", null); register.onMessage("1-2", null); register.onMessage("1-3", null); register.onMessage("1-3", null); List<MetricSample> samples = defaultMetricsCollector.collect(); Assert.assertTrue(samples.size() == 4, "Wrong number of samples."); samples.forEach(metricSample -> Assert.assertTrue( ((AtomicLong) ((CounterMetricSample<?>) metricSample).getValue()).get() == 2L, "Sample count error.")); } @AfterEach public void tearDown() { FrameworkModel.defaultModel().destroy(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/metrics/model/sample/MetricSampleTest.java
dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/metrics/model/sample/MetricSampleTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.metrics.model.sample; import org.apache.dubbo.metrics.model.MetricsCategory; import org.apache.dubbo.metrics.model.sample.MetricSample; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; class MetricSampleTest { private static String name; private static String description; private static Map<String, String> tags; private static MetricSample.Type type; private static MetricsCategory category; private static String baseUnit; @BeforeAll public static void setup() { name = "test"; description = "test"; tags = new HashMap<>(); type = MetricSample.Type.GAUGE; category = MetricsCategory.REQUESTS; baseUnit = "byte"; } @Test void test() { MetricSample sample = new MetricSample(name, description, tags, type, category, baseUnit); Assertions.assertEquals(sample.getName(), name); Assertions.assertEquals(sample.getDescription(), description); Assertions.assertEquals(sample.getTags(), tags); Assertions.assertEquals(sample.getType(), type); Assertions.assertEquals(sample.getCategory(), category); Assertions.assertEquals(sample.getBaseUnit(), baseUnit); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/monitor/support/MonitorFilterTest.java
dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/monitor/support/MonitorFilterTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.monitor.support; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.monitor.Monitor; import org.apache.dubbo.monitor.MonitorFactory; import org.apache.dubbo.monitor.MonitorService; import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.METHOD_KEY; import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; import static org.apache.dubbo.monitor.Constants.CONCURRENT_KEY; import static org.apache.dubbo.monitor.Constants.FAILURE_KEY; import static org.apache.dubbo.monitor.Constants.SUCCESS_KEY; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; class MonitorFilterTest { private volatile URL lastStatistics; private volatile Invocation lastInvocation; private final Invoker<MonitorService> serviceInvoker = new Invoker<MonitorService>() { @Override public Class<MonitorService> getInterface() { return MonitorService.class; } public URL getUrl() { return URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":20880?" + APPLICATION_KEY + "=abc&" + SIDE_KEY + "=" + CONSUMER_SIDE) .putAttribute(MONITOR_KEY, URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":7070")); } @Override public boolean isAvailable() { return false; } @Override public Result invoke(Invocation invocation) throws RpcException { lastInvocation = invocation; return AsyncRpcResult.newDefaultAsyncResult(invocation); } @Override public void destroy() {} }; private MonitorFactory monitorFactory = url -> new Monitor() { public URL getUrl() { return url; } @Override public boolean isAvailable() { return true; } @Override public void destroy() {} public void collect(URL statistics) { MonitorFilterTest.this.lastStatistics = statistics; } public List<URL> lookup(URL query) { return Arrays.asList(MonitorFilterTest.this.lastStatistics); } }; @Test void testFilter() throws Exception { MonitorFilter monitorFilter = new MonitorFilter(); monitorFilter.setMonitorFactory(monitorFactory); Invocation invocation = new RpcInvocation("aaa", MonitorService.class.getName(), "", new Class<?>[0], new Object[0]); RpcContext.getServiceContext() .setRemoteAddress(NetUtils.getLocalHost(), 20880) .setLocalAddress(NetUtils.getLocalHost(), 2345); Result result = monitorFilter.invoke(serviceInvoker, invocation); result.whenCompleteWithContext((r, t) -> { if (t == null) { monitorFilter.onResponse(r, serviceInvoker, invocation); } else { monitorFilter.onError(t, serviceInvoker, invocation); } }); while (lastStatistics == null) { Thread.sleep(10); } Assertions.assertEquals("abc", lastStatistics.getParameter(APPLICATION_KEY)); Assertions.assertEquals(MonitorService.class.getName(), lastStatistics.getParameter(INTERFACE_KEY)); Assertions.assertEquals("aaa", lastStatistics.getParameter(METHOD_KEY)); Assertions.assertEquals(NetUtils.getLocalHost() + ":20880", lastStatistics.getParameter(PROVIDER)); Assertions.assertEquals(NetUtils.getLocalHost(), lastStatistics.getAddress()); Assertions.assertNull(lastStatistics.getParameter(CONSUMER)); Assertions.assertEquals(1, lastStatistics.getParameter(SUCCESS_KEY, 0)); Assertions.assertEquals(0, lastStatistics.getParameter(FAILURE_KEY, 0)); Assertions.assertEquals(1, lastStatistics.getParameter(CONCURRENT_KEY, 0)); Assertions.assertEquals(invocation, lastInvocation); } @Test void testSkipMonitorIfNotHasKey() { MonitorFilter monitorFilter = new MonitorFilter(); MonitorFactory mockMonitorFactory = mock(MonitorFactory.class); monitorFilter.setMonitorFactory(mockMonitorFactory); Invocation invocation = new RpcInvocation("aaa", MonitorService.class.getName(), "", new Class<?>[0], new Object[0]); Invoker invoker = mock(Invoker.class); given(invoker.getUrl()) .willReturn(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":20880?" + APPLICATION_KEY + "=abc&" + SIDE_KEY + "=" + CONSUMER_SIDE)); monitorFilter.invoke(invoker, invocation); verify(mockMonitorFactory, never()).getMonitor(any(URL.class)); } @Test void testGenericFilter() throws Exception { MonitorFilter monitorFilter = new MonitorFilter(); monitorFilter.setMonitorFactory(monitorFactory); Invocation invocation = new RpcInvocation( "$invoke", MonitorService.class.getName(), "", new Class<?>[] {String.class, String[].class, Object[].class}, new Object[] {"xxx", new String[] {}, new Object[] {}}); RpcContext.getServiceContext() .setRemoteAddress(NetUtils.getLocalHost(), 20880) .setLocalAddress(NetUtils.getLocalHost(), 2345); Result result = monitorFilter.invoke(serviceInvoker, invocation); result.whenCompleteWithContext((r, t) -> { if (t == null) { monitorFilter.onResponse(r, serviceInvoker, invocation); } else { monitorFilter.onError(t, serviceInvoker, invocation); } }); while (lastStatistics == null) { Thread.sleep(10); } Assertions.assertEquals("abc", lastStatistics.getParameter(APPLICATION_KEY)); Assertions.assertEquals(MonitorService.class.getName(), lastStatistics.getParameter(INTERFACE_KEY)); Assertions.assertEquals("xxx", lastStatistics.getParameter(METHOD_KEY)); Assertions.assertEquals(NetUtils.getLocalHost() + ":20880", lastStatistics.getParameter(PROVIDER)); Assertions.assertEquals(NetUtils.getLocalHost(), lastStatistics.getAddress()); Assertions.assertNull(lastStatistics.getParameter(CONSUMER)); Assertions.assertEquals(1, lastStatistics.getParameter(SUCCESS_KEY, 0)); Assertions.assertEquals(0, lastStatistics.getParameter(FAILURE_KEY, 0)); Assertions.assertEquals(1, lastStatistics.getParameter(CONCURRENT_KEY, 0)); Assertions.assertEquals(invocation, lastInvocation); } @Test void testSafeFailForMonitorCollectFail() { MonitorFilter monitorFilter = new MonitorFilter(); MonitorFactory mockMonitorFactory = mock(MonitorFactory.class); Monitor mockMonitor = mock(Monitor.class); Mockito.doThrow(new RuntimeException()).when(mockMonitor).collect(any(URL.class)); monitorFilter.setMonitorFactory(mockMonitorFactory); given(mockMonitorFactory.getMonitor(any(URL.class))).willReturn(mockMonitor); Invocation invocation = new RpcInvocation("aaa", MonitorService.class.getName(), "", new Class<?>[0], new Object[0]); monitorFilter.invoke(serviceInvoker, invocation); } @Test void testOnResponseWithoutStartTime() { MonitorFilter monitorFilter = new MonitorFilter(); MonitorFactory mockMonitorFactory = mock(MonitorFactory.class); Monitor mockMonitor = mock(Monitor.class); monitorFilter.setMonitorFactory(mockMonitorFactory); given(mockMonitorFactory.getMonitor(any(URL.class))).willReturn(mockMonitor); Invocation invocation = new RpcInvocation("aaa", MonitorService.class.getName(), "", new Class<?>[0], new Object[0]); Result result = monitorFilter.invoke(serviceInvoker, invocation); invocation.getAttributes().remove("monitor_filter_start_time"); monitorFilter.onResponse(result, serviceInvoker, invocation); } @Test void testOnErrorWithoutStartTime() { MonitorFilter monitorFilter = new MonitorFilter(); MonitorFactory mockMonitorFactory = mock(MonitorFactory.class); Monitor mockMonitor = mock(Monitor.class); monitorFilter.setMonitorFactory(mockMonitorFactory); given(mockMonitorFactory.getMonitor(any(URL.class))).willReturn(mockMonitor); Invocation invocation = new RpcInvocation("aaa", MonitorService.class.getName(), "", new Class<?>[0], new Object[0]); Throwable rpcException = new RpcException(); monitorFilter.onError(rpcException, serviceInvoker, invocation); } @AfterEach public void destroy() { ApplicationModel applicationModel = ApplicationModel.defaultModel(); applicationModel.destroy(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/MetricsClusterFilter.java
dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/MetricsClusterFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.rpc.cluster.filter.support; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.metrics.collector.DefaultMetricsCollector; import org.apache.dubbo.metrics.event.MetricsDispatcher; import org.apache.dubbo.metrics.event.MetricsEventBus; import org.apache.dubbo.metrics.event.RequestEvent; import org.apache.dubbo.metrics.model.MethodMetric; import org.apache.dubbo.rpc.BaseFilter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.cluster.filter.ClusterFilter; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ScopeModelAware; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; @Activate(group = CONSUMER, onClass = "org.apache.dubbo.metrics.collector.DefaultMetricsCollector") public class MetricsClusterFilter implements ClusterFilter, BaseFilter.Listener, ScopeModelAware { private ApplicationModel applicationModel; private DefaultMetricsCollector collector; private String appName; private MetricsDispatcher metricsDispatcher; private boolean serviceLevel; @Override public void setApplicationModel(ApplicationModel applicationModel) { this.applicationModel = applicationModel; this.collector = applicationModel.getBeanFactory().getBean(DefaultMetricsCollector.class); this.appName = applicationModel.tryGetApplicationName(); this.metricsDispatcher = applicationModel.getBeanFactory().getBean(MetricsDispatcher.class); this.serviceLevel = MethodMetric.isServiceLevel(applicationModel); } @Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { return invoker.invoke(invocation); } @Override public void onResponse(Result result, Invoker<?> invoker, Invocation invocation) { handleMethodException(result.getException(), invocation); } @Override public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) { handleMethodException(t, invocation); } private void handleMethodException(Throwable t, Invocation invocation) { if (collector == null || !collector.isCollectEnabled()) { return; } if (t instanceof RpcException) { RpcException e = (RpcException) t; if (e.isForbidden()) { MetricsEventBus.publish(RequestEvent.toRequestErrorEvent( applicationModel, appName, metricsDispatcher, invocation, CONSUMER_SIDE, e.getCode(), serviceLevel)); } } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/MetricsGlobalRegistry.java
dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/MetricsGlobalRegistry.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics; import org.apache.dubbo.config.MetricsConfig; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Optional; import io.micrometer.core.instrument.Metrics; import io.micrometer.core.instrument.composite.CompositeMeterRegistry; /** * Get the micrometer meter registry, can choose spring, micrometer, dubbo */ public class MetricsGlobalRegistry { private static CompositeMeterRegistry compositeRegistry = new CompositeMeterRegistry(); /** * Use CompositeMeterRegistry according to the following priority * 1. If useGlobalRegistry is configured, use the micrometer global CompositeMeterRegistry * 2. If there is a spring actuator, use spring's CompositeMeterRegistry * 3. Dubbo's own CompositeMeterRegistry is used by default */ public static CompositeMeterRegistry getCompositeRegistry(ApplicationModel applicationModel) { Optional<MetricsConfig> configOptional = applicationModel.getApplicationConfigManager().getMetrics(); if (configOptional.isPresent() && configOptional.get().getUseGlobalRegistry() != null && configOptional.get().getUseGlobalRegistry()) { return Metrics.globalRegistry; } else { return compositeRegistry; } } public static CompositeMeterRegistry getCompositeRegistry() { return getCompositeRegistry(ApplicationModel.defaultModel()); } public static void setCompositeRegistry(CompositeMeterRegistry compositeRegistry) { MetricsGlobalRegistry.compositeRegistry = compositeRegistry; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/DefaultConstants.java
dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/DefaultConstants.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper; import org.apache.dubbo.metrics.model.key.MetricsLevel; import org.apache.dubbo.metrics.model.key.MetricsPlaceValue; import org.apache.dubbo.metrics.model.sample.MetricSample; import java.util.Arrays; import java.util.List; import static org.apache.dubbo.metrics.model.key.MetricsKey.METRIC_REQUESTS; import static org.apache.dubbo.metrics.model.key.MetricsKey.METRIC_REQUESTS_CODEC_FAILED; import static org.apache.dubbo.metrics.model.key.MetricsKey.METRIC_REQUESTS_FAILED; import static org.apache.dubbo.metrics.model.key.MetricsKey.METRIC_REQUESTS_LIMIT; import static org.apache.dubbo.metrics.model.key.MetricsKey.METRIC_REQUESTS_NETWORK_FAILED; import static org.apache.dubbo.metrics.model.key.MetricsKey.METRIC_REQUESTS_PROCESSING; import static org.apache.dubbo.metrics.model.key.MetricsKey.METRIC_REQUESTS_SERVICE_UNAVAILABLE_FAILED; import static org.apache.dubbo.metrics.model.key.MetricsKey.METRIC_REQUESTS_SUCCEED; import static org.apache.dubbo.metrics.model.key.MetricsKey.METRIC_REQUESTS_TIMEOUT; import static org.apache.dubbo.metrics.model.key.MetricsKey.METRIC_REQUESTS_TOTAL_FAILED; import static org.apache.dubbo.metrics.model.key.MetricsKey.METRIC_REQUEST_BUSINESS_FAILED; public interface DefaultConstants { String METRIC_FILTER_EVENT = "metric_filter_event"; String METRIC_THROWABLE = "metric_filter_throwable"; List<MetricsKeyWrapper> METHOD_LEVEL_KEYS = Arrays.asList( new MetricsKeyWrapper(METRIC_REQUESTS, MetricsPlaceValue.of(CommonConstants.PROVIDER, MetricsLevel.METHOD)), new MetricsKeyWrapper(METRIC_REQUESTS, MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD)), // METRIC_REQUESTS_PROCESSING use GAUGE new MetricsKeyWrapper( METRIC_REQUESTS_PROCESSING, MetricsPlaceValue.of(CommonConstants.PROVIDER, MetricsLevel.METHOD)) .setSampleType(MetricSample.Type.GAUGE), new MetricsKeyWrapper( METRIC_REQUESTS_PROCESSING, MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD)) .setSampleType(MetricSample.Type.GAUGE), new MetricsKeyWrapper( METRIC_REQUESTS_SUCCEED, MetricsPlaceValue.of(CommonConstants.PROVIDER, MetricsLevel.METHOD)), new MetricsKeyWrapper( METRIC_REQUESTS_SUCCEED, MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD)), new MetricsKeyWrapper( METRIC_REQUEST_BUSINESS_FAILED, MetricsPlaceValue.of(CommonConstants.PROVIDER, MetricsLevel.METHOD)), new MetricsKeyWrapper( METRIC_REQUEST_BUSINESS_FAILED, MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD)), new MetricsKeyWrapper( METRIC_REQUESTS_TIMEOUT, MetricsPlaceValue.of(CommonConstants.PROVIDER, MetricsLevel.METHOD)), new MetricsKeyWrapper( METRIC_REQUESTS_TIMEOUT, MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD)), new MetricsKeyWrapper( METRIC_REQUESTS_LIMIT, MetricsPlaceValue.of(CommonConstants.PROVIDER, MetricsLevel.METHOD)), new MetricsKeyWrapper( METRIC_REQUESTS_LIMIT, MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD)), new MetricsKeyWrapper( METRIC_REQUESTS_FAILED, MetricsPlaceValue.of(CommonConstants.PROVIDER, MetricsLevel.METHOD)), new MetricsKeyWrapper( METRIC_REQUESTS_FAILED, MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD)), new MetricsKeyWrapper( METRIC_REQUESTS_TOTAL_FAILED, MetricsPlaceValue.of(CommonConstants.PROVIDER, MetricsLevel.METHOD)), new MetricsKeyWrapper( METRIC_REQUESTS_TOTAL_FAILED, MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD)), new MetricsKeyWrapper( METRIC_REQUESTS_NETWORK_FAILED, MetricsPlaceValue.of(CommonConstants.PROVIDER, MetricsLevel.METHOD)), new MetricsKeyWrapper( METRIC_REQUESTS_NETWORK_FAILED, MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD)), new MetricsKeyWrapper( METRIC_REQUESTS_SERVICE_UNAVAILABLE_FAILED, MetricsPlaceValue.of(CommonConstants.PROVIDER, MetricsLevel.METHOD)), new MetricsKeyWrapper( METRIC_REQUESTS_SERVICE_UNAVAILABLE_FAILED, MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD)), new MetricsKeyWrapper( METRIC_REQUESTS_CODEC_FAILED, MetricsPlaceValue.of(CommonConstants.PROVIDER, MetricsLevel.METHOD)), new MetricsKeyWrapper( METRIC_REQUESTS_CODEC_FAILED, MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD))); List<MetricsKey> INIT_AGG_METHOD_KEYS = Arrays.asList( MetricsKey.METRIC_REQUESTS_TOTAL_AGG, MetricsKey.METRIC_REQUESTS_SUCCEED_AGG, MetricsKey.METRIC_REQUESTS_FAILED_AGG, MetricsKey.METRIC_REQUEST_BUSINESS_FAILED_AGG, MetricsKey.METRIC_REQUESTS_TIMEOUT_AGG, MetricsKey.METRIC_REQUESTS_LIMIT_AGG, MetricsKey.METRIC_REQUESTS_TOTAL_FAILED_AGG, MetricsKey.METRIC_REQUESTS_NETWORK_FAILED_AGG, MetricsKey.METRIC_REQUESTS_CODEC_FAILED_AGG, MetricsKey.METRIC_REQUESTS_TOTAL_SERVICE_UNAVAILABLE_FAILED_AGG); List<MetricsKey> INIT_DEFAULT_METHOD_KEYS = Arrays.asList( MetricsKey.METRIC_REQUESTS, MetricsKey.METRIC_REQUESTS_PROCESSING, MetricsKey.METRIC_REQUESTS_FAILED_AGG, MetricsKey.METRIC_REQUESTS_SUCCEED, MetricsKey.METRIC_REQUESTS_TOTAL_FAILED, MetricsKey.METRIC_REQUEST_BUSINESS_FAILED); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/MetricsScopeModelInitializer.java
dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/MetricsScopeModelInitializer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; import org.apache.dubbo.metrics.event.MetricsDispatcher; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ScopeModelInitializer; public class MetricsScopeModelInitializer implements ScopeModelInitializer { @Override public void initializeApplicationModel(ApplicationModel applicationModel) { ScopeBeanFactory beanFactory = applicationModel.getBeanFactory(); beanFactory.registerBean(MetricsDispatcher.class); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/HistogramMetricsCollector.java
dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/HistogramMetricsCollector.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.collector; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import org.apache.dubbo.config.MetricsConfig; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.config.nested.HistogramConfig; import org.apache.dubbo.metrics.MetricsConstants; import org.apache.dubbo.metrics.MetricsGlobalRegistry; import org.apache.dubbo.metrics.event.RequestEvent; import org.apache.dubbo.metrics.listener.AbstractMetricsListener; import org.apache.dubbo.metrics.model.MethodMetric; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.model.sample.MetricSample; import org.apache.dubbo.metrics.register.HistogramMetricRegister; import org.apache.dubbo.metrics.sample.HistogramMetricSample; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import io.micrometer.core.instrument.Timer; import static org.apache.dubbo.metrics.model.MetricsCategory.RT; public class HistogramMetricsCollector extends AbstractMetricsListener<RequestEvent> implements MetricsCollector<RequestEvent> { private final ConcurrentHashMap<MethodMetric, Timer> rt = new ConcurrentHashMap<>(); private HistogramMetricRegister metricRegister; private final ApplicationModel applicationModel; private static final Integer[] DEFAULT_BUCKETS_MS = new Integer[] {100, 300, 500, 1000, 3000, 5000, 10000}; private boolean serviceLevel; public HistogramMetricsCollector(ApplicationModel applicationModel) { this.applicationModel = applicationModel; ConfigManager configManager = applicationModel.getApplicationConfigManager(); MetricsConfig config = configManager.getMetrics().orElse(null); if (config == null || config.getHistogram() == null || config.getHistogram().getEnabled() == null || Boolean.TRUE.equals(config.getHistogram().getEnabled())) { registerListener(); HistogramConfig histogram; if (config == null || config.getHistogram() == null) { histogram = new HistogramConfig(); } else { histogram = config.getHistogram(); } if (!Boolean.TRUE.equals(histogram.getEnabledPercentiles()) && histogram.getBucketsMs() == null) { histogram.setBucketsMs(DEFAULT_BUCKETS_MS); } metricRegister = new HistogramMetricRegister( MetricsGlobalRegistry.getCompositeRegistry(applicationModel), histogram); this.serviceLevel = MethodMetric.isServiceLevel(applicationModel); } } private void registerListener() { applicationModel .getBeanFactory() .getBean(DefaultMetricsCollector.class) .getEventMulticaster() .addListener(this); } @Override public void onEvent(RequestEvent event) {} @Override public void onEventFinish(RequestEvent event) { onRTEvent(event); } @Override public void onEventError(RequestEvent event) { onRTEvent(event); } private void onRTEvent(RequestEvent event) { if (metricRegister != null) { MethodMetric metric = new MethodMetric( applicationModel, event.getAttachmentValue(MetricsConstants.INVOCATION), serviceLevel); long responseTime = event.getTimePair().calc(); HistogramMetricSample sample = new HistogramMetricSample( MetricsKey.METRIC_RT_HISTOGRAM.getNameByType(metric.getSide()), MetricsKey.METRIC_RT_HISTOGRAM.getDescription(), metric.getTags(), RT); Timer timer = ConcurrentHashMapUtils.computeIfAbsent(rt, metric, k -> metricRegister.register(sample)); timer.record(responseTime, TimeUnit.MILLISECONDS); } } @Override public List<MetricSample> collect() { return new ArrayList<>(); } @Override public boolean calSamplesChanged() { // Histogram is directly register micrometer return false; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/DefaultMetricsCollector.java
dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/DefaultMetricsCollector.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.collector; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.metrics.DefaultConstants; import org.apache.dubbo.metrics.MetricsConstants; import org.apache.dubbo.metrics.collector.sample.ErrorCodeSampler; import org.apache.dubbo.metrics.collector.sample.MetricsCountSampleConfigurer; import org.apache.dubbo.metrics.collector.sample.MetricsSampler; import org.apache.dubbo.metrics.collector.sample.SimpleMetricsCountSampler; import org.apache.dubbo.metrics.collector.sample.ThreadPoolMetricsSampler; import org.apache.dubbo.metrics.data.BaseStatComposite; import org.apache.dubbo.metrics.data.MethodStatComposite; import org.apache.dubbo.metrics.data.RtStatComposite; import org.apache.dubbo.metrics.event.DefaultSubDispatcher; import org.apache.dubbo.metrics.event.MetricsEvent; import org.apache.dubbo.metrics.event.MetricsInitEvent; import org.apache.dubbo.metrics.event.RequestEvent; import org.apache.dubbo.metrics.event.TimeCounterEvent; import org.apache.dubbo.metrics.model.ApplicationMetric; import org.apache.dubbo.metrics.model.MetricsCategory; import org.apache.dubbo.metrics.model.MetricsSupport; import org.apache.dubbo.metrics.model.key.MetricsLevel; import org.apache.dubbo.metrics.model.key.MetricsPlaceValue; import org.apache.dubbo.metrics.model.sample.CounterMetricSample; import org.apache.dubbo.metrics.model.sample.MetricSample; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import static org.apache.dubbo.metrics.DefaultConstants.INIT_DEFAULT_METHOD_KEYS; import static org.apache.dubbo.metrics.model.MetricsCategory.APPLICATION; import static org.apache.dubbo.metrics.model.key.MetricsKey.APPLICATION_METRIC_INFO; import static org.apache.dubbo.metrics.model.key.MetricsKey.METRIC_REQUESTS_SERVICE_UNAVAILABLE_FAILED; /** * Default implementation of {@link MetricsCollector} */ @Activate public class DefaultMetricsCollector extends CombMetricsCollector<RequestEvent> { private boolean collectEnabled = false; private volatile boolean threadpoolCollectEnabled = false; private volatile boolean metricsInitEnabled = true; private final ThreadPoolMetricsSampler threadPoolSampler = new ThreadPoolMetricsSampler(this); private final ErrorCodeSampler errorCodeSampler; private String applicationName; private final ApplicationModel applicationModel; private final List<MetricsSampler> samplers = new ArrayList<>(); private final List<MetricsCollector> collectors = new ArrayList<>(); private final AtomicBoolean initialized = new AtomicBoolean(); private final AtomicBoolean samplesChanged = new AtomicBoolean(); public DefaultMetricsCollector(ApplicationModel applicationModel) { super(new BaseStatComposite(applicationModel) { @Override protected void init(MethodStatComposite methodStatComposite) { super.init(methodStatComposite); methodStatComposite.initWrapper(DefaultConstants.METHOD_LEVEL_KEYS); } @Override protected void init(RtStatComposite rtStatComposite) { super.init(rtStatComposite); rtStatComposite.init( MetricsPlaceValue.of(CommonConstants.PROVIDER, MetricsLevel.METHOD), MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD)); } }); super.setEventMulticaster(new DefaultSubDispatcher(this)); this.samplers.add(applicationSampler); this.samplers.add(threadPoolSampler); this.samplesChanged.set(true); this.errorCodeSampler = new ErrorCodeSampler(this); this.applicationModel = applicationModel; } public void addSampler(MetricsSampler sampler) { samplers.add(sampler); samplesChanged.set(true); } public void setApplicationName(String applicationName) { this.applicationName = applicationName; } public String getApplicationName() { return this.applicationName; } public ApplicationModel getApplicationModel() { return this.applicationModel; } public void setCollectEnabled(Boolean collectEnabled) { this.collectEnabled = collectEnabled; } @Override public boolean isCollectEnabled() { return collectEnabled; } public boolean isThreadpoolCollectEnabled() { return threadpoolCollectEnabled; } public void setThreadpoolCollectEnabled(boolean threadpoolCollectEnabled) { this.threadpoolCollectEnabled = threadpoolCollectEnabled; } public boolean isMetricsInitEnabled() { return metricsInitEnabled; } public void setMetricsInitEnabled(boolean metricsInitEnabled) { this.metricsInitEnabled = metricsInitEnabled; } public void collectApplication() { this.setApplicationName(applicationModel.getApplicationName()); applicationSampler.inc(applicationName, MetricsEvent.Type.APPLICATION_INFO); } public void registryDefaultSample() { this.threadPoolSampler.registryDefaultSampleThreadPoolExecutor(); } @Override public List<MetricSample> collect() { List<MetricSample> list = new ArrayList<>(); if (!isCollectEnabled()) { return list; } for (MetricsSampler sampler : samplers) { List<MetricSample> sample = sampler.sample(); list.addAll(sample); } list.addAll(super.export(MetricsCategory.REQUESTS)); return list; } @Override public boolean isSupport(MetricsEvent event) { return event instanceof RequestEvent || event instanceof MetricsInitEvent; } @Override public void onEvent(TimeCounterEvent event) { if (event instanceof MetricsInitEvent) { if (!metricsInitEnabled) { return; } if (initialized.compareAndSet(false, true)) { collectors.addAll(applicationModel.getBeanFactory().getBeansOfType(MetricsCollector.class)); } collectors.stream().forEach(collector -> collector.initMetrics(event)); return; } super.onEvent(event); } @Override public void initMetrics(MetricsEvent event) { MetricsPlaceValue dynamicPlaceType = MetricsPlaceValue.of(event.getAttachmentValue(MetricsConstants.INVOCATION_SIDE), MetricsLevel.METHOD); INIT_DEFAULT_METHOD_KEYS.stream() .forEach(key -> MetricsSupport.init(key, dynamicPlaceType, (MethodMetricsCollector) this, event)); MetricsSupport.init( METRIC_REQUESTS_SERVICE_UNAVAILABLE_FAILED, MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD), (MethodMetricsCollector) this, event); } public SimpleMetricsCountSampler<String, MetricsEvent.Type, ApplicationMetric> applicationSampler = new SimpleMetricsCountSampler<String, MetricsEvent.Type, ApplicationMetric>() { @Override public List<MetricSample> sample() { List<MetricSample> samples = new ArrayList<>(); this.getCount(MetricsEvent.Type.APPLICATION_INFO) .filter(e -> !e.isEmpty()) .ifPresent(map -> map.forEach((k, v) -> samples.add(new CounterMetricSample<>( APPLICATION_METRIC_INFO.getName(), APPLICATION_METRIC_INFO.getDescription(), k.getTags(), APPLICATION, v)))); return samples; } @Override protected void countConfigure( MetricsCountSampleConfigurer<String, MetricsEvent.Type, ApplicationMetric> sampleConfigure) { sampleConfigure.configureMetrics(configure -> new ApplicationMetric(applicationModel)); } @Override public boolean calSamplesChanged() { return false; } }; @Override public boolean calSamplesChanged() { // CAS to get and reset the flag in an atomic operation boolean changed = samplesChanged.compareAndSet(true, false); // Should ensure that all the sampler's samplesChanged have been compareAndSet, and cannot flip the `or` logic changed = stats.calSamplesChanged() || changed; for (MetricsSampler sampler : samplers) { changed = sampler.calSamplesChanged() || changed; } return changed; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/AggregateMetricsCollector.java
dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/AggregateMetricsCollector.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.collector; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import org.apache.dubbo.config.MetricsConfig; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.config.nested.AggregationConfig; import org.apache.dubbo.metrics.MetricsConstants; import org.apache.dubbo.metrics.aggregate.TimeWindowAggregator; import org.apache.dubbo.metrics.aggregate.TimeWindowCounter; import org.apache.dubbo.metrics.aggregate.TimeWindowQuantile; import org.apache.dubbo.metrics.event.MetricsEvent; import org.apache.dubbo.metrics.event.RequestEvent; import org.apache.dubbo.metrics.model.MethodMetric; import org.apache.dubbo.metrics.model.MetricsSupport; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper; import org.apache.dubbo.metrics.model.key.MetricsLevel; import org.apache.dubbo.metrics.model.key.MetricsPlaceValue; import org.apache.dubbo.metrics.model.sample.GaugeMetricSample; import org.apache.dubbo.metrics.model.sample.MetricSample; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; import static org.apache.dubbo.metrics.DefaultConstants.INIT_AGG_METHOD_KEYS; import static org.apache.dubbo.metrics.DefaultConstants.METRIC_THROWABLE; import static org.apache.dubbo.metrics.model.MetricsCategory.QPS; import static org.apache.dubbo.metrics.model.MetricsCategory.REQUESTS; import static org.apache.dubbo.metrics.model.MetricsCategory.RT; /** * Aggregation metrics collector implementation of {@link MetricsCollector}. * This collector only enabled when metrics aggregation config is enabled. */ public class AggregateMetricsCollector implements MetricsCollector<RequestEvent> { private int bucketNum = DEFAULT_BUCKET_NUM; private int timeWindowSeconds = DEFAULT_TIME_WINDOW_SECONDS; private int qpsTimeWindowMillSeconds = DEFAULT_QPS_TIME_WINDOW_MILL_SECONDS; private final ConcurrentHashMap<MetricsKeyWrapper, ConcurrentHashMap<MethodMetric, TimeWindowCounter>> methodTypeCounter = new ConcurrentHashMap<>(); private final ConcurrentMap<MethodMetric, TimeWindowQuantile> rt = new ConcurrentHashMap<>(); private final ConcurrentHashMap<MethodMetric, TimeWindowCounter> qps = new ConcurrentHashMap<>(); private final ApplicationModel applicationModel; private static final Integer DEFAULT_COMPRESSION = 100; private static final Integer DEFAULT_BUCKET_NUM = 10; private static final Integer DEFAULT_TIME_WINDOW_SECONDS = 120; private static final Integer DEFAULT_QPS_TIME_WINDOW_MILL_SECONDS = 3000; private Boolean collectEnabled = null; private boolean enableQps; private boolean enableRtPxx; private boolean enableRt; private boolean enableRequest; private final AtomicBoolean samplesChanged = new AtomicBoolean(true); private final ConcurrentMap<MethodMetric, TimeWindowAggregator> rtAgr = new ConcurrentHashMap<>(); private boolean serviceLevel; public AggregateMetricsCollector(ApplicationModel applicationModel) { this.applicationModel = applicationModel; ConfigManager configManager = applicationModel.getApplicationConfigManager(); if (isCollectEnabled()) { // only registered when aggregation is enabled. Optional<MetricsConfig> optional = configManager.getMetrics(); if (optional.isPresent()) { registerListener(); AggregationConfig aggregation = optional.get().getAggregation(); this.bucketNum = Optional.ofNullable(aggregation.getBucketNum()).orElse(DEFAULT_BUCKET_NUM); this.timeWindowSeconds = Optional.ofNullable(aggregation.getTimeWindowSeconds()).orElse(DEFAULT_TIME_WINDOW_SECONDS); this.qpsTimeWindowMillSeconds = Optional.ofNullable(aggregation.getQpsTimeWindowMillSeconds()) .orElse(DEFAULT_QPS_TIME_WINDOW_MILL_SECONDS); this.enableQps = Optional.ofNullable(aggregation.getEnableQps()).orElse(true); this.enableRtPxx = Optional.ofNullable(aggregation.getEnableRtPxx()).orElse(true); this.enableRt = Optional.ofNullable(aggregation.getEnableRt()).orElse(true); this.enableRequest = Optional.ofNullable(aggregation.getEnableRequest()).orElse(true); } this.serviceLevel = MethodMetric.isServiceLevel(applicationModel); } } public void setCollectEnabled(Boolean collectEnabled) { if (collectEnabled != null) { this.collectEnabled = collectEnabled; } } @Override public boolean isCollectEnabled() { if (collectEnabled == null) { ConfigManager configManager = applicationModel.getApplicationConfigManager(); configManager .getMetrics() .ifPresent(metricsConfig -> setCollectEnabled(metricsConfig.getAggregation().getEnabled())); } return Optional.ofNullable(collectEnabled).orElse(false); } @Override public boolean isSupport(MetricsEvent event) { return event instanceof RequestEvent; } @Override public void onEvent(RequestEvent event) { if (enableQps) { MethodMetric metric = calcWindowCounter(event, MetricsKey.METRIC_REQUESTS); TimeWindowCounter qpsCounter = qps.get(metric); if (qpsCounter == null) { qpsCounter = ConcurrentHashMapUtils.computeIfAbsent( qps, metric, methodMetric -> new TimeWindowCounter( bucketNum, TimeUnit.MILLISECONDS.toSeconds(qpsTimeWindowMillSeconds))); samplesChanged.set(true); } qpsCounter.increment(); } } @Override public void onEventFinish(RequestEvent event) { MetricsKey targetKey = MetricsKey.METRIC_REQUESTS_SUCCEED; Object throwableObj = event.getAttachmentValue(METRIC_THROWABLE); if (throwableObj != null) { targetKey = MetricsSupport.getAggMetricsKey((Throwable) throwableObj); } calcWindowCounter(event, targetKey); onRTEvent(event); } @Override public void onEventError(RequestEvent event) { if (enableRequest) { MetricsKey targetKey = MetricsKey.METRIC_REQUESTS_FAILED; Object throwableObj = event.getAttachmentValue(METRIC_THROWABLE); if (throwableObj != null) { targetKey = MetricsSupport.getAggMetricsKey((Throwable) throwableObj); } calcWindowCounter(event, targetKey); } if (enableRt || enableRtPxx) { onRTEvent(event); } } private void onRTEvent(RequestEvent event) { MethodMetric metric = new MethodMetric(applicationModel, event.getAttachmentValue(MetricsConstants.INVOCATION), serviceLevel); long responseTime = event.getTimePair().calc(); if (enableRt) { TimeWindowQuantile quantile = rt.get(metric); if (quantile == null) { quantile = ConcurrentHashMapUtils.computeIfAbsent( rt, metric, k -> new TimeWindowQuantile(DEFAULT_COMPRESSION, bucketNum, timeWindowSeconds)); samplesChanged.set(true); } quantile.add(responseTime); } if (enableRtPxx) { TimeWindowAggregator timeWindowAggregator = rtAgr.get(metric); if (timeWindowAggregator == null) { timeWindowAggregator = ConcurrentHashMapUtils.computeIfAbsent( rtAgr, metric, methodMetric -> new TimeWindowAggregator(bucketNum, timeWindowSeconds)); samplesChanged.set(true); } timeWindowAggregator.add(responseTime); } } private MethodMetric calcWindowCounter(RequestEvent event, MetricsKey targetKey) { MetricsPlaceValue placeType = MetricsPlaceValue.of(event.getAttachmentValue(MetricsConstants.INVOCATION_SIDE), MetricsLevel.SERVICE); MetricsKeyWrapper metricsKeyWrapper = new MetricsKeyWrapper(targetKey, placeType); MethodMetric metric = new MethodMetric(applicationModel, event.getAttachmentValue(MetricsConstants.INVOCATION), serviceLevel); ConcurrentMap<MethodMetric, TimeWindowCounter> counter = ConcurrentHashMapUtils.computeIfAbsent( methodTypeCounter, metricsKeyWrapper, k -> new ConcurrentHashMap<>()); TimeWindowCounter windowCounter = counter.get(metric); if (windowCounter == null) { windowCounter = ConcurrentHashMapUtils.computeIfAbsent( counter, metric, methodMetric -> new TimeWindowCounter(bucketNum, timeWindowSeconds)); samplesChanged.set(true); } windowCounter.increment(); return metric; } @Override public List<MetricSample> collect() { List<MetricSample> list = new ArrayList<>(); if (!isCollectEnabled()) { return list; } collectRequests(list); collectQPS(list); collectRT(list); return list; } private void collectRequests(List<MetricSample> list) { collectBySide(list, PROVIDER_SIDE); collectBySide(list, CONSUMER_SIDE); } private void collectBySide(List<MetricSample> list, String side) { collectMethod(list, side, MetricsKey.METRIC_REQUESTS_TOTAL_AGG); collectMethod(list, side, MetricsKey.METRIC_REQUESTS_SUCCEED_AGG); collectMethod(list, side, MetricsKey.METRIC_REQUESTS_FAILED_AGG); collectMethod(list, side, MetricsKey.METRIC_REQUEST_BUSINESS_FAILED_AGG); collectMethod(list, side, MetricsKey.METRIC_REQUESTS_TIMEOUT_AGG); collectMethod(list, side, MetricsKey.METRIC_REQUESTS_LIMIT_AGG); collectMethod(list, side, MetricsKey.METRIC_REQUESTS_TOTAL_FAILED_AGG); collectMethod(list, side, MetricsKey.METRIC_REQUESTS_NETWORK_FAILED_AGG); collectMethod(list, side, MetricsKey.METRIC_REQUESTS_CODEC_FAILED_AGG); collectMethod(list, side, MetricsKey.METRIC_REQUESTS_TOTAL_SERVICE_UNAVAILABLE_FAILED_AGG); } private void collectMethod(List<MetricSample> list, String side, MetricsKey metricsKey) { MetricsKeyWrapper metricsKeyWrapper = new MetricsKeyWrapper(metricsKey, MetricsPlaceValue.of(side, MetricsLevel.SERVICE)); ConcurrentHashMap<MethodMetric, TimeWindowCounter> windowCounter = methodTypeCounter.get(metricsKeyWrapper); if (windowCounter != null) { windowCounter.forEach((k, v) -> list.add(new GaugeMetricSample<>( metricsKey.getNameByType(k.getSide()), metricsKey.getDescription(), k.getTags(), REQUESTS, v, TimeWindowCounter::get))); } } private void collectQPS(List<MetricSample> list) { qps.forEach((k, v) -> list.add(new GaugeMetricSample<>( MetricsKey.METRIC_QPS.getNameByType(k.getSide()), MetricsKey.METRIC_QPS.getDescription(), k.getTags(), QPS, v, value -> { double total = value.get(); long millSeconds = value.bucketLivedMillSeconds(); return total / millSeconds * 1000; }))); } private void collectRT(List<MetricSample> list) { rt.forEach((k, v) -> { list.add(new GaugeMetricSample<>( MetricsKey.METRIC_RT_P99.getNameByType(k.getSide()), MetricsKey.METRIC_RT_P99.getDescription(), k.getTags(), RT, v, value -> value.quantile(0.99))); list.add(new GaugeMetricSample<>( MetricsKey.METRIC_RT_P95.getNameByType(k.getSide()), MetricsKey.METRIC_RT_P95.getDescription(), k.getTags(), RT, v, value -> value.quantile(0.95))); list.add(new GaugeMetricSample<>( MetricsKey.METRIC_RT_P90.getNameByType(k.getSide()), MetricsKey.METRIC_RT_P90.getDescription(), k.getTags(), RT, v, value -> value.quantile(0.90))); list.add(new GaugeMetricSample<>( MetricsKey.METRIC_RT_P50.getNameByType(k.getSide()), MetricsKey.METRIC_RT_P50.getDescription(), k.getTags(), RT, v, value -> value.quantile(0.50))); }); rtAgr.forEach((k, v) -> { list.add(new GaugeMetricSample<>( MetricsKey.METRIC_RT_MIN_AGG.getNameByType(k.getSide()), MetricsKey.METRIC_RT_MIN_AGG.getDescription(), k.getTags(), RT, v, value -> v.get().getMin())); list.add(new GaugeMetricSample<>( MetricsKey.METRIC_RT_MAX_AGG.getNameByType(k.getSide()), MetricsKey.METRIC_RT_MAX_AGG.getDescription(), k.getTags(), RT, v, value -> v.get().getMax())); list.add(new GaugeMetricSample<>( MetricsKey.METRIC_RT_AVG_AGG.getNameByType(k.getSide()), MetricsKey.METRIC_RT_AVG_AGG.getDescription(), k.getTags(), RT, v, value -> v.get().getAvg())); }); } private void registerListener() { applicationModel .getBeanFactory() .getBean(DefaultMetricsCollector.class) .getEventMulticaster() .addListener(this); } @Override public void initMetrics(MetricsEvent event) { MethodMetric metric = new MethodMetric(applicationModel, event.getAttachmentValue(MetricsConstants.INVOCATION), serviceLevel); if (enableQps) { initMethodMetric(event); initQpsMetric(metric); } if (enableRt) { initRtMetric(metric); } if (enableRtPxx) { initRtAgrMetric(metric); } } public void initMethodMetric(MetricsEvent event) { INIT_AGG_METHOD_KEYS.stream().forEach(key -> initWindowCounter(event, key)); } public void initQpsMetric(MethodMetric metric) { ConcurrentHashMapUtils.computeIfAbsent( qps, metric, methodMetric -> new TimeWindowCounter(bucketNum, timeWindowSeconds)); samplesChanged.set(true); } public void initRtMetric(MethodMetric metric) { ConcurrentHashMapUtils.computeIfAbsent( rt, metric, k -> new TimeWindowQuantile(DEFAULT_COMPRESSION, bucketNum, timeWindowSeconds)); samplesChanged.set(true); } public void initRtAgrMetric(MethodMetric metric) { ConcurrentHashMapUtils.computeIfAbsent( rtAgr, metric, k -> new TimeWindowAggregator(bucketNum, timeWindowSeconds)); samplesChanged.set(true); } public void initWindowCounter(MetricsEvent event, MetricsKey targetKey) { MetricsKeyWrapper metricsKeyWrapper = new MetricsKeyWrapper( targetKey, MetricsPlaceValue.of(event.getAttachmentValue(MetricsConstants.INVOCATION_SIDE), MetricsLevel.SERVICE)); MethodMetric metric = new MethodMetric(applicationModel, event.getAttachmentValue(MetricsConstants.INVOCATION), serviceLevel); ConcurrentMap<MethodMetric, TimeWindowCounter> counter = ConcurrentHashMapUtils.computeIfAbsent( methodTypeCounter, metricsKeyWrapper, k -> new ConcurrentHashMap<>()); ConcurrentHashMapUtils.computeIfAbsent( counter, metric, methodMetric -> new TimeWindowCounter(bucketNum, timeWindowSeconds)); samplesChanged.set(true); } @Override public boolean calSamplesChanged() { // CAS to get and reset the flag in an atomic operation return samplesChanged.compareAndSet(true, false); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/ErrorCodeMetricsListenRegister.java
dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/ErrorCodeMetricsListenRegister.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.collector.sample; import org.apache.dubbo.common.logger.LogListener; import org.apache.dubbo.common.logger.support.FailsafeErrorTypeAwareLogger; import org.apache.dubbo.metrics.model.key.MetricsKey; /** * Listen the log of all {@link FailsafeErrorTypeAwareLogger} instances, and add error code count to {@link ErrorCodeSampler}. */ public class ErrorCodeMetricsListenRegister implements LogListener { private final ErrorCodeSampler errorCodeSampler; public ErrorCodeMetricsListenRegister(ErrorCodeSampler errorCodeSampler) { FailsafeErrorTypeAwareLogger.registerGlobalListen(this); this.errorCodeSampler = errorCodeSampler; this.errorCodeSampler.addMetricName(MetricsKey.ERROR_CODE_COUNT.getName()); } @Override public void onMessage(String code, String msg) { errorCodeSampler.inc(code, MetricsKey.ERROR_CODE_COUNT.getName()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/MetricsCountSampler.java
dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/MetricsCountSampler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.collector.sample; import org.apache.dubbo.metrics.model.Metric; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; public interface MetricsCountSampler<S, K, M extends Metric> extends MetricsSampler { void inc(S source, K metricName); Optional<ConcurrentHashMap<M, AtomicLong>> getCount(K metricName); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/ErrorCodeSampler.java
dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/ErrorCodeSampler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.collector.sample; import org.apache.dubbo.metrics.collector.DefaultMetricsCollector; import org.apache.dubbo.metrics.model.ErrorCodeMetric; import org.apache.dubbo.metrics.model.MetricsCategory; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.model.sample.CounterMetricSample; import org.apache.dubbo.metrics.model.sample.MetricSample; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; /** * This sampler is used to count the number of occurrences of each error code. */ public class ErrorCodeSampler extends MetricsNameCountSampler<String, String, ErrorCodeMetric> { private final ErrorCodeMetricsListenRegister register; /** * Map<ErrorCode,Metric> */ private final Map<String, ErrorCodeMetric> errorCodeMetrics; public ErrorCodeSampler(DefaultMetricsCollector collector) { super(collector, MetricsCategory.ERROR_CODE, MetricsKey.ERROR_CODE_COUNT); this.register = new ErrorCodeMetricsListenRegister(this); this.errorCodeMetrics = new ConcurrentHashMap<>(); } @Override protected MetricSample provideMetricsSample( ErrorCodeMetric metric, AtomicLong count, MetricsKey metricsKey, MetricsCategory metricsCategory) { return new CounterMetricSample<>( metricsKey.getNameByType(metric.getErrorCode()), metricsKey.getDescription(), metric.getTags(), metricsCategory, count); } @Override protected void countConfigure(MetricsCountSampleConfigurer<String, String, ErrorCodeMetric> sampleConfigure) { sampleConfigure.configureMetrics(configure -> { String errorCode = configure.getSource(); ErrorCodeMetric metric = errorCodeMetrics.get(errorCode); if (metric == null) { metric = new ErrorCodeMetric(collector.getApplicationModel().getApplicationName(), errorCode); errorCodeMetrics.put(errorCode, metric); } return metric; }); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/SimpleMetricsCountSampler.java
dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/SimpleMetricsCountSampler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.collector.sample; import org.apache.dubbo.common.utils.Assert; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import org.apache.dubbo.metrics.model.Metric; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; /** * @param <S> request source * @param <K> metricsName * @param <M> metric */ public abstract class SimpleMetricsCountSampler<S, K, M extends Metric> implements MetricsCountSampler<S, K, M> { private final ConcurrentHashMap<M, AtomicLong> EMPTY_COUNT = new ConcurrentHashMap<>(); private final ConcurrentHashMap<K, ConcurrentHashMap<M, AtomicLong>> metricCounter = new ConcurrentHashMap<>(); @Override public void inc(S source, K metricName) { getAtomicCounter(source, metricName).incrementAndGet(); } @Override public Optional<ConcurrentHashMap<M, AtomicLong>> getCount(K metricName) { return Optional.ofNullable(metricCounter.get(metricName) == null ? EMPTY_COUNT : metricCounter.get(metricName)); } protected abstract void countConfigure(MetricsCountSampleConfigurer<S, K, M> sampleConfigure); private AtomicLong getAtomicCounter(S source, K metricsName) { MetricsCountSampleConfigurer<S, K, M> sampleConfigure = new MetricsCountSampleConfigurer<>(); sampleConfigure.setSource(source); sampleConfigure.setMetricsName(metricsName); this.countConfigure(sampleConfigure); ConcurrentHashMap<M, AtomicLong> metricAtomic = metricCounter.get(metricsName); if (metricAtomic == null) { metricAtomic = ConcurrentHashMapUtils.computeIfAbsent(metricCounter, metricsName, k -> new ConcurrentHashMap<>()); } Assert.notNull(sampleConfigure.getMetric(), "metrics is null"); AtomicLong atomicCounter = metricAtomic.get(sampleConfigure.getMetric()); if (atomicCounter == null) { atomicCounter = ConcurrentHashMapUtils.computeIfAbsent( metricAtomic, sampleConfigure.getMetric(), k -> new AtomicLong()); } return atomicCounter; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/ThreadRejectMetricsCountSampler.java
dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/ThreadRejectMetricsCountSampler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.collector.sample; import org.apache.dubbo.metrics.collector.DefaultMetricsCollector; import org.apache.dubbo.metrics.model.MetricsCategory; import org.apache.dubbo.metrics.model.ThreadPoolRejectMetric; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.model.sample.GaugeMetricSample; import org.apache.dubbo.metrics.model.sample.MetricSample; import java.util.concurrent.atomic.AtomicLong; import static org.apache.dubbo.metrics.model.MetricsCategory.THREAD_POOL; public class ThreadRejectMetricsCountSampler extends MetricsNameCountSampler<String, String, ThreadPoolRejectMetric> { public ThreadRejectMetricsCountSampler(DefaultMetricsCollector collector) { super(collector, THREAD_POOL, MetricsKey.THREAD_POOL_THREAD_REJECT_COUNT); } @Override protected MetricSample provideMetricsSample( ThreadPoolRejectMetric metric, AtomicLong count, MetricsKey metricsKey, MetricsCategory metricsCategory) { return new GaugeMetricSample<>( metricsKey.getNameByType(metric.getThreadPoolName()), metricsKey.getDescription(), metric.getTags(), metricsCategory, count, AtomicLong::get); } @Override protected void countConfigure( MetricsCountSampleConfigurer<String, String, ThreadPoolRejectMetric> sampleConfigure) { sampleConfigure.configureMetrics( configure -> new ThreadPoolRejectMetric(collector.getApplicationName(), configure.getSource())); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/MetricThreadPoolExhaustedListener.java
dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/MetricThreadPoolExhaustedListener.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.collector.sample; import org.apache.dubbo.common.threadpool.event.ThreadPoolExhaustedEvent; import org.apache.dubbo.common.threadpool.event.ThreadPoolExhaustedListener; import org.apache.dubbo.metrics.collector.DefaultMetricsCollector; public class MetricThreadPoolExhaustedListener implements ThreadPoolExhaustedListener { private final ThreadRejectMetricsCountSampler threadRejectMetricsCountSampler; private final String threadPoolExecutorName; public MetricThreadPoolExhaustedListener(String threadPoolExecutorName, DefaultMetricsCollector collector) { this.threadPoolExecutorName = threadPoolExecutorName; this.threadRejectMetricsCountSampler = new ThreadRejectMetricsCountSampler(collector); } public MetricThreadPoolExhaustedListener(String threadPoolExecutorName, ThreadRejectMetricsCountSampler sampler) { this.threadPoolExecutorName = threadPoolExecutorName; this.threadRejectMetricsCountSampler = sampler; this.threadRejectMetricsCountSampler.addMetricName(threadPoolExecutorName); } @Override public void onEvent(ThreadPoolExhaustedEvent event) { threadRejectMetricsCountSampler.inc(threadPoolExecutorName, threadPoolExecutorName); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/MetricsCountSampleConfigurer.java
dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/MetricsCountSampleConfigurer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.collector.sample; import org.apache.dubbo.metrics.model.Metric; import java.util.function.Function; public class MetricsCountSampleConfigurer<S, K, M extends Metric> { public S source; public K metricName; public M metric; public void setSource(S source) { this.source = source; } public MetricsCountSampleConfigurer<S, K, M> setMetricsName(K metricName) { this.metricName = metricName; return this; } public MetricsCountSampleConfigurer<S, K, M> configureMetrics( Function<MetricsCountSampleConfigurer<S, K, M>, M> builder) { this.metric = builder.apply(this); return this; } public S getSource() { return source; } public M getMetric() { return metric; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/ThreadPoolMetricsSampler.java
dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/ThreadPoolMetricsSampler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.collector.sample; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.store.DataStore; import org.apache.dubbo.common.store.DataStoreUpdateListener; import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository; import org.apache.dubbo.common.threadpool.support.AbortPolicyWithReport; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import org.apache.dubbo.metrics.collector.DefaultMetricsCollector; import org.apache.dubbo.metrics.model.ThreadPoolMetric; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.model.sample.GaugeMetricSample; import org.apache.dubbo.metrics.model.sample.MetricSample; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.atomic.AtomicBoolean; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SHARED_EXECUTOR_SERVICE_COMPONENT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_SERVICE_COMPONENT_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_METRICS_COLLECTOR_EXCEPTION; import static org.apache.dubbo.config.Constants.CLIENT_THREAD_POOL_PREFIX; import static org.apache.dubbo.config.Constants.SERVER_THREAD_POOL_NAME; import static org.apache.dubbo.config.Constants.SERVER_THREAD_POOL_PREFIX; import static org.apache.dubbo.metrics.model.MetricsCategory.THREAD_POOL; public class ThreadPoolMetricsSampler implements MetricsSampler, DataStoreUpdateListener { private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ThreadPoolMetricsSampler.class); private final DefaultMetricsCollector collector; private FrameworkExecutorRepository frameworkExecutorRepository; private DataStore dataStore; private final Map<String, ThreadPoolExecutor> sampleThreadPoolExecutor = new ConcurrentHashMap<>(); private final ConcurrentHashMap<String, ThreadPoolMetric> threadPoolMetricMap = new ConcurrentHashMap<>(); private final AtomicBoolean samplesChanged = new AtomicBoolean(true); public ThreadPoolMetricsSampler(DefaultMetricsCollector collector) { this.collector = collector; } @Override public void onUpdate(String componentName, String key, Object value) { if (EXECUTOR_SERVICE_COMPONENT_KEY.equals(componentName)) { if (value instanceof ThreadPoolExecutor) { addExecutors(SERVER_THREAD_POOL_PREFIX + key, (ThreadPoolExecutor) value); } } else if (CONSUMER_SHARED_EXECUTOR_SERVICE_COMPONENT_KEY.equals(componentName)) { if (value instanceof ThreadPoolExecutor) { addExecutors(CLIENT_THREAD_POOL_PREFIX + key, (ThreadPoolExecutor) value); } } } public void addExecutors(String name, ExecutorService executorService) { Optional.ofNullable(executorService) .filter(Objects::nonNull) .filter(e -> e instanceof ThreadPoolExecutor) .map(e -> (ThreadPoolExecutor) e) .ifPresent(threadPoolExecutor -> { if (sampleThreadPoolExecutor.put(name, threadPoolExecutor) == null) { samplesChanged.set(true); } }); } @Override public List<MetricSample> sample() { List<MetricSample> metricSamples = new ArrayList<>(); sampleThreadPoolExecutor.forEach((name, executor) -> { metricSamples.addAll(createMetricsSample(name, executor)); }); return metricSamples; } private List<MetricSample> createMetricsSample(String name, ThreadPoolExecutor executor) { List<MetricSample> list = new ArrayList<>(); ThreadPoolMetric threadPoolMetric = ConcurrentHashMapUtils.computeIfAbsent( threadPoolMetricMap, name, v -> new ThreadPoolMetric(collector.getApplicationName(), name, executor)); list.add(new GaugeMetricSample<>( MetricsKey.THREAD_POOL_CORE_SIZE, threadPoolMetric.getTags(), THREAD_POOL, threadPoolMetric, ThreadPoolMetric::getCorePoolSize)); list.add(new GaugeMetricSample<>( MetricsKey.THREAD_POOL_LARGEST_SIZE, threadPoolMetric.getTags(), THREAD_POOL, threadPoolMetric, ThreadPoolMetric::getLargestPoolSize)); list.add(new GaugeMetricSample<>( MetricsKey.THREAD_POOL_MAX_SIZE, threadPoolMetric.getTags(), THREAD_POOL, threadPoolMetric, ThreadPoolMetric::getMaximumPoolSize)); list.add(new GaugeMetricSample<>( MetricsKey.THREAD_POOL_ACTIVE_SIZE, threadPoolMetric.getTags(), THREAD_POOL, threadPoolMetric, ThreadPoolMetric::getActiveCount)); list.add(new GaugeMetricSample<>( MetricsKey.THREAD_POOL_THREAD_COUNT, threadPoolMetric.getTags(), THREAD_POOL, threadPoolMetric, ThreadPoolMetric::getPoolSize)); list.add(new GaugeMetricSample<>( MetricsKey.THREAD_POOL_QUEUE_SIZE, threadPoolMetric.getTags(), THREAD_POOL, threadPoolMetric, ThreadPoolMetric::getQueueSize)); return list; } public void registryDefaultSampleThreadPoolExecutor() { ApplicationModel applicationModel = collector.getApplicationModel(); if (applicationModel == null) { return; } addRpcExecutors(); addFrameworkExecutors(); addExecutorRejectMetrics(); } private void addExecutorRejectMetrics() { ThreadRejectMetricsCountSampler threadRejectMetricsCountSampler = new ThreadRejectMetricsCountSampler(collector); this.sampleThreadPoolExecutor.entrySet().stream() .filter(entry -> entry.getKey().startsWith(SERVER_THREAD_POOL_NAME)) .forEach(entry -> { if (entry.getValue().getRejectedExecutionHandler() instanceof AbortPolicyWithReport) { MetricThreadPoolExhaustedListener metricThreadPoolExhaustedListener = new MetricThreadPoolExhaustedListener(entry.getKey(), threadRejectMetricsCountSampler); ((AbortPolicyWithReport) entry.getValue().getRejectedExecutionHandler()) .addThreadPoolExhaustedEventListener(metricThreadPoolExhaustedListener); } }); } private void addRpcExecutors() { if (this.dataStore == null) { this.dataStore = collector .getApplicationModel() .getExtensionLoader(DataStore.class) .getDefaultExtension(); } if (dataStore != null) { dataStore.addListener(this); Map<String, Object> executors = dataStore.get(EXECUTOR_SERVICE_COMPONENT_KEY); for (Map.Entry<String, Object> entry : executors.entrySet()) { ExecutorService executor = (ExecutorService) entry.getValue(); if (executor instanceof ThreadPoolExecutor) { this.addExecutors(SERVER_THREAD_POOL_PREFIX + entry.getKey(), executor); } } executors = dataStore.get(CONSUMER_SHARED_EXECUTOR_SERVICE_COMPONENT_KEY); for (Map.Entry<String, Object> entry : executors.entrySet()) { ExecutorService executor = (ExecutorService) entry.getValue(); if (executor instanceof ThreadPoolExecutor) { this.addExecutors(CLIENT_THREAD_POOL_PREFIX + entry.getKey(), executor); } } } } private void addFrameworkExecutors() { try { if (this.frameworkExecutorRepository == null) { this.frameworkExecutorRepository = collector.getApplicationModel().getBeanFactory().getBean(FrameworkExecutorRepository.class); } } catch (Exception ex) { logger.warn( COMMON_METRICS_COLLECTOR_EXCEPTION, "", "", "ThreadPoolMetricsSampler! frameworkExecutorRepository non-init"); } if (this.frameworkExecutorRepository == null) { return; } this.addExecutors("poolRouterExecutor", frameworkExecutorRepository.getPoolRouterExecutor()); this.addExecutors("metadataRetryExecutor", frameworkExecutorRepository.getMetadataRetryExecutor()); this.addExecutors("internalServiceExecutor", frameworkExecutorRepository.getInternalServiceExecutor()); this.addExecutors( "connectivityScheduledExecutor", frameworkExecutorRepository.getConnectivityScheduledExecutor()); this.addExecutors( "cacheRefreshingScheduledExecutor", frameworkExecutorRepository.getCacheRefreshingScheduledExecutor()); this.addExecutors("sharedExecutor", frameworkExecutorRepository.getSharedExecutor()); this.addExecutors("sharedScheduledExecutor", frameworkExecutorRepository.getSharedScheduledExecutor()); this.addExecutors("mappingRefreshingExecutor", frameworkExecutorRepository.getMappingRefreshingExecutor()); } @Override public boolean calSamplesChanged() { // CAS to get and reset the flag in an atomic operation return samplesChanged.compareAndSet(true, false); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/MetricsNameCountSampler.java
dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/MetricsNameCountSampler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.collector.sample; import org.apache.dubbo.common.utils.ConcurrentHashSet; import org.apache.dubbo.metrics.collector.DefaultMetricsCollector; import org.apache.dubbo.metrics.model.Metric; import org.apache.dubbo.metrics.model.MetricsCategory; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.model.sample.MetricSample; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; public abstract class MetricsNameCountSampler<S, K, M extends Metric> extends SimpleMetricsCountSampler<S, K, M> { protected final DefaultMetricsCollector collector; private final AtomicBoolean samplesChanged = new AtomicBoolean(true); protected final Set<K> metricNames = new ConcurrentHashSet<>(); protected final MetricsCategory metricsCategory; protected final MetricsKey metricsKey; public MetricsNameCountSampler( DefaultMetricsCollector collector, MetricsCategory metricsCategory, MetricsKey metricsKey) { this.metricsCategory = metricsCategory; this.metricsKey = metricsKey; this.collector = collector; this.collector.addSampler(this); } public void addMetricName(K name) { this.metricNames.add(name); this.samplesChanged.set(true); } @Override public List<MetricSample> sample() { List<MetricSample> metricSamples = new ArrayList<>(); metricNames.forEach(name -> collect(metricSamples, name)); return metricSamples; } private void collect(List<MetricSample> samples, K metricName) { getCount(metricName) .filter(e -> !e.isEmpty()) .ifPresent(map -> map.forEach((k, v) -> samples.add(provideMetricsSample(k, v, metricsKey, metricsCategory)))); } protected abstract MetricSample provideMetricsSample( M metric, AtomicLong count, MetricsKey metricsKey, MetricsCategory metricsCategory); @Override public boolean calSamplesChanged() { // CAS to get and reset the flag in an atomic operation return samplesChanged.compareAndSet(true, false); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/MetricsSampler.java
dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/MetricsSampler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.collector.sample; import org.apache.dubbo.metrics.model.sample.MetricSample; import java.util.List; public interface MetricsSampler { List<MetricSample> sample(); /** * Check if samples have been changed. * Note that this method will reset the changed flag to false using CAS. * * @return true if samples have been changed */ boolean calSamplesChanged(); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/service/DefaultMetricsService.java
dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/service/DefaultMetricsService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.service; import org.apache.dubbo.metrics.collector.MetricsCollector; import org.apache.dubbo.metrics.model.MetricsCategory; import org.apache.dubbo.metrics.model.sample.GaugeMetricSample; import org.apache.dubbo.metrics.model.sample.MetricSample; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Default implementation of {@link MetricsService} */ public class DefaultMetricsService implements MetricsService { @SuppressWarnings("rawtypes") protected final List<MetricsCollector> collectors = new ArrayList<>(); public DefaultMetricsService(ApplicationModel applicationModel) { collectors.addAll(applicationModel.getBeanFactory().getBeansOfType(MetricsCollector.class)); } @Override public Map<MetricsCategory, List<MetricsEntity>> getMetricsByCategories(List<MetricsCategory> categories) { return getMetricsByCategories(null, categories); } @Override public Map<MetricsCategory, List<MetricsEntity>> getMetricsByCategories( String serviceUniqueName, List<MetricsCategory> categories) { return getMetricsByCategories(serviceUniqueName, null, null, categories); } @Override public Map<MetricsCategory, List<MetricsEntity>> getMetricsByCategories( String serviceUniqueName, String methodName, Class<?>[] parameterTypes, List<MetricsCategory> categories) { Map<MetricsCategory, List<MetricsEntity>> result = new HashMap<>(); for (MetricsCollector<?> collector : collectors) { List<MetricSample> samples = collector.collect(); for (MetricSample sample : samples) { if (categories.contains(sample.getCategory())) { List<MetricsEntity> entities = result.computeIfAbsent(sample.getCategory(), k -> new ArrayList<>()); entities.add(sampleToEntity(sample)); } } } return result; } @SuppressWarnings({"unchecked", "rawtypes"}) private MetricsEntity sampleToEntity(MetricSample sample) { MetricsEntity entity = new MetricsEntity(); entity.setName(sample.getName()); entity.setTags(sample.getTags()); entity.setCategory(sample.getCategory()); switch (sample.getType()) { case GAUGE: GaugeMetricSample gaugeSample = (GaugeMetricSample) sample; entity.setValue(gaugeSample.getApply().applyAsDouble(gaugeSample.getValue())); break; case COUNTER: case LONG_TASK_TIMER: case TIMER: case DISTRIBUTION_SUMMARY: default: break; } return entity; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/filter/MetricsProviderFilter.java
dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/filter/MetricsProviderFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.filter; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.rpc.BaseFilter; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; @Activate( group = {PROVIDER}, order = Integer.MIN_VALUE + 100) public class MetricsProviderFilter extends MetricsFilter implements Filter, BaseFilter.Listener { public MetricsProviderFilter() {} @Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { return super.invoke(invoker, invocation, true); } @Override public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) { super.onResponse(appResponse, invoker, invocation, true); } @Override public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) { super.onError(t, invoker, invocation, true); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/filter/MetricsFilter.java
dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/filter/MetricsFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.filter; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.config.MetricsConfig; import org.apache.dubbo.metrics.collector.DefaultMetricsCollector; import org.apache.dubbo.metrics.event.MetricsDispatcher; import org.apache.dubbo.metrics.event.MetricsEventBus; import org.apache.dubbo.metrics.event.RequestEvent; import org.apache.dubbo.metrics.model.MethodMetric; import org.apache.dubbo.metrics.model.MetricsSupport; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ScopeModelAware; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR; import static org.apache.dubbo.metrics.DefaultConstants.METRIC_FILTER_EVENT; import static org.apache.dubbo.metrics.DefaultConstants.METRIC_THROWABLE; public class MetricsFilter implements ScopeModelAware { private ApplicationModel applicationModel; private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(MetricsFilter.class); private boolean rpcMetricsEnable; private String appName; private MetricsDispatcher metricsDispatcher; private DefaultMetricsCollector defaultMetricsCollector; private boolean serviceLevel; @Override public void setApplicationModel(ApplicationModel applicationModel) { this.applicationModel = applicationModel; this.rpcMetricsEnable = applicationModel .getApplicationConfigManager() .getMetrics() .map(MetricsConfig::getEnableRpc) .orElse(false); this.appName = applicationModel.tryGetApplicationName(); this.metricsDispatcher = applicationModel.getBeanFactory().getBean(MetricsDispatcher.class); this.defaultMetricsCollector = applicationModel.getBeanFactory().getBean(DefaultMetricsCollector.class); serviceLevel = MethodMetric.isServiceLevel(applicationModel); } public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { return invoke(invoker, invocation, PROVIDER.equals(MetricsSupport.getSide(invocation))); } public Result invoke(Invoker<?> invoker, Invocation invocation, boolean isProvider) throws RpcException { if (rpcMetricsEnable) { try { RequestEvent requestEvent = RequestEvent.toRequestEvent( applicationModel, appName, metricsDispatcher, defaultMetricsCollector, invocation, isProvider ? PROVIDER : CONSUMER, serviceLevel); MetricsEventBus.before(requestEvent); invocation.put(METRIC_FILTER_EVENT, requestEvent); } catch (Throwable t) { LOGGER.warn(INTERNAL_ERROR, "", "", "Error occurred when invoke.", t); } } return invoker.invoke(invocation); } public void onResponse(Result result, Invoker<?> invoker, Invocation invocation) { if (rpcMetricsEnable) { onResponse(result, invoker, invocation, PROVIDER.equals(MetricsSupport.getSide(invocation))); } } public void onResponse(Result result, Invoker<?> invoker, Invocation invocation, boolean isProvider) { Object eventObj = invocation.get(METRIC_FILTER_EVENT); if (eventObj != null) { try { MetricsEventBus.after((RequestEvent) eventObj, result); } catch (Throwable t) { LOGGER.warn(INTERNAL_ERROR, "", "", "Error occurred when onResponse.", t); } } } public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) { if (rpcMetricsEnable) { onError(t, invoker, invocation, PROVIDER.equals(MetricsSupport.getSide(invocation))); } } public void onError(Throwable t, Invoker<?> invoker, Invocation invocation, boolean isProvider) { Object eventObj = invocation.get(METRIC_FILTER_EVENT); if (eventObj != null) { try { RequestEvent requestEvent = (RequestEvent) eventObj; requestEvent.putAttachment(METRIC_THROWABLE, t); MetricsEventBus.error(requestEvent); } catch (Throwable throwable) { LOGGER.warn(INTERNAL_ERROR, "", "", "Error occurred when onResponse.", throwable); } } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/report/DefaultMetricsReporterFactory.java
dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/report/DefaultMetricsReporterFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.report; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.model.ApplicationModel; public class DefaultMetricsReporterFactory extends AbstractMetricsReporterFactory { private final ApplicationModel applicationModel; public DefaultMetricsReporterFactory(ApplicationModel applicationModel) { super(applicationModel); this.applicationModel = applicationModel; } @Override public MetricsReporter createMetricsReporter(URL url) { return new DefaultMetricsReporter(url, applicationModel); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/report/AbstractMetricsReporter.java
dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/report/AbstractMetricsReporter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.report; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; import org.apache.dubbo.common.lang.ShutdownHookCallbacks; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.NamedThreadFactory; import org.apache.dubbo.metrics.MetricsGlobalRegistry; import org.apache.dubbo.metrics.collector.AggregateMetricsCollector; import org.apache.dubbo.metrics.collector.HistogramMetricsCollector; import org.apache.dubbo.metrics.collector.MetricsCollector; import org.apache.dubbo.metrics.model.sample.CounterMetricSample; import org.apache.dubbo.metrics.model.sample.GaugeMetricSample; import org.apache.dubbo.metrics.model.sample.MetricSample; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import io.micrometer.core.instrument.FunctionCounter; import io.micrometer.core.instrument.Gauge; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.Tag; import io.micrometer.core.instrument.binder.MeterBinder; import io.micrometer.core.instrument.binder.jvm.ClassLoaderMetrics; import io.micrometer.core.instrument.binder.jvm.JvmGcMetrics; import io.micrometer.core.instrument.binder.jvm.JvmMemoryMetrics; import io.micrometer.core.instrument.binder.jvm.JvmThreadMetrics; import io.micrometer.core.instrument.binder.system.ProcessorMetrics; import io.micrometer.core.instrument.binder.system.UptimeMetrics; import io.micrometer.core.instrument.composite.CompositeMeterRegistry; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_METRICS_COLLECTOR_EXCEPTION; import static org.apache.dubbo.common.constants.MetricsConstants.COLLECTOR_SYNC_PERIOD_KEY; import static org.apache.dubbo.common.constants.MetricsConstants.ENABLE_COLLECTOR_SYNC_KEY; import static org.apache.dubbo.common.constants.MetricsConstants.ENABLE_JVM_METRICS_KEY; /** * AbstractMetricsReporter. */ public abstract class AbstractMetricsReporter implements MetricsReporter { private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbstractMetricsReporter.class); private final AtomicBoolean initialized = new AtomicBoolean(false); protected final URL url; @SuppressWarnings("rawtypes") protected final List<MetricsCollector> collectors = new ArrayList<>(); // Avoid instances being gc due to weak references protected final List<MeterBinder> instanceHolder = new ArrayList<>(); protected final CompositeMeterRegistry compositeRegistry; private final ApplicationModel applicationModel; private ScheduledExecutorService collectorSyncJobExecutor = null; private static final int DEFAULT_SCHEDULE_INITIAL_DELAY = 5; private static final int DEFAULT_SCHEDULE_PERIOD = 60; protected AbstractMetricsReporter(URL url, ApplicationModel applicationModel) { this.url = url; this.applicationModel = applicationModel; this.compositeRegistry = MetricsGlobalRegistry.getCompositeRegistry(applicationModel); } @Override public void init() { if (initialized.compareAndSet(false, true)) { addJvmMetrics(); initCollectors(); scheduleMetricsCollectorSyncJob(); doInit(); registerDubboShutdownHook(); } } protected void addMeterRegistry(MeterRegistry registry) { compositeRegistry.add(registry); } protected ApplicationModel getApplicationModel() { return applicationModel; } private void addJvmMetrics() { boolean enableJvmMetrics = url.getParameter(ENABLE_JVM_METRICS_KEY, false); if (enableJvmMetrics) { new ClassLoaderMetrics().bindTo(compositeRegistry); new JvmMemoryMetrics().bindTo(compositeRegistry); @SuppressWarnings("java:S2095") // Do not change JvmGcMetrics to try-with-resources as the JvmGcMetrics will not be available after // (auto-)closing. // See https://github.com/micrometer-metrics/micrometer/issues/1492 JvmGcMetrics jvmGcMetrics = new JvmGcMetrics(); jvmGcMetrics.bindTo(compositeRegistry); Runtime.getRuntime().addShutdownHook(new Thread(jvmGcMetrics::close)); bindTo(new ProcessorMetrics()); new JvmThreadMetrics().bindTo(compositeRegistry); bindTo(new UptimeMetrics()); } } private void bindTo(MeterBinder binder) { binder.bindTo(compositeRegistry); instanceHolder.add(binder); } @SuppressWarnings("rawtypes") private void initCollectors() { ScopeBeanFactory beanFactory = applicationModel.getBeanFactory(); beanFactory.getOrRegisterBean(AggregateMetricsCollector.class); beanFactory.getOrRegisterBean(HistogramMetricsCollector.class); List<MetricsCollector> otherCollectors = beanFactory.getBeansOfType(MetricsCollector.class); collectors.addAll(otherCollectors); } private void scheduleMetricsCollectorSyncJob() { boolean enableCollectorSync = url.getParameter(ENABLE_COLLECTOR_SYNC_KEY, true); if (enableCollectorSync) { int collectSyncPeriod = url.getParameter(COLLECTOR_SYNC_PERIOD_KEY, DEFAULT_SCHEDULE_PERIOD); NamedThreadFactory threadFactory = new NamedThreadFactory("metrics-collector-sync-job", true); collectorSyncJobExecutor = Executors.newScheduledThreadPool(1, threadFactory); collectorSyncJobExecutor.scheduleWithFixedDelay( this::resetIfSamplesChanged, DEFAULT_SCHEDULE_INITIAL_DELAY, collectSyncPeriod, TimeUnit.SECONDS); } } @SuppressWarnings({"unchecked"}) public void resetIfSamplesChanged() { collectors.forEach(collector -> { if (!collector.calSamplesChanged()) { // Metrics has not been changed since last time, no need to reload return; } // Collect all the samples and register them to the micrometer registry List<MetricSample> samples = collector.collect(); for (MetricSample sample : samples) { try { registerSample(sample); } catch (Exception e) { logger.error( COMMON_METRICS_COLLECTOR_EXCEPTION, "", "", "error occurred when synchronize metrics collector.", e); } } }); } @SuppressWarnings({"rawtypes"}) private void registerSample(MetricSample sample) { switch (sample.getType()) { case GAUGE: registerGaugeSample((GaugeMetricSample) sample); break; case COUNTER: registerCounterSample((CounterMetricSample) sample); case TIMER: case LONG_TASK_TIMER: case DISTRIBUTION_SUMMARY: // TODO break; default: break; } } @SuppressWarnings({"rawtypes"}) private void registerCounterSample(CounterMetricSample sample) { FunctionCounter.builder(sample.getName(), sample.getValue(), Number::doubleValue) .description(sample.getDescription()) .tags(getTags(sample)) .register(compositeRegistry); } @SuppressWarnings({"unchecked", "rawtypes"}) private void registerGaugeSample(GaugeMetricSample sample) { Gauge.builder(sample.getName(), sample.getValue(), sample.getApply()) .description(sample.getDescription()) .tags(getTags(sample)) .register(compositeRegistry); } private static List<Tag> getTags(MetricSample gaugeSample) { List<Tag> tags = new ArrayList<>(); gaugeSample.getTags().forEach((k, v) -> { if (v == null) { v = ""; } tags.add(Tag.of(k, v)); }); return tags; } private void registerDubboShutdownHook() { applicationModel.getBeanFactory().getBean(ShutdownHookCallbacks.class).addCallback(this::destroy); } public void destroy() { if (collectorSyncJobExecutor != null) { collectorSyncJobExecutor.shutdownNow(); } doDestroy(); } protected abstract void doInit(); protected abstract void doDestroy(); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/report/DefaultMetricsReporter.java
dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/report/DefaultMetricsReporter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.report; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import io.micrometer.core.instrument.Counter; import io.micrometer.core.instrument.Gauge; import io.micrometer.core.instrument.Tag; import io.micrometer.core.instrument.Timer; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; public class DefaultMetricsReporter extends AbstractMetricsReporter { SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); protected DefaultMetricsReporter(URL url, ApplicationModel applicationModel) { super(url, applicationModel); } @Override public String getResponse() { return null; } @Override public String getResponseWithName(String metricsName) { Map<String, List<Tag>> metricsTags = new HashMap<>(); Map<String, Object> metricsValue = new HashMap<>(); StringBuilder sb = new StringBuilder(); meterRegistry.getMeters().stream() .filter(meter -> { if (meter == null || meter.getId() == null || meter.getId().getName() == null) { return false; } if (metricsName != null) { return meter.getId().getName().contains(metricsName); } return true; }) .forEach(meter -> { Object value = null; if (meter instanceof Counter) { Counter counter = (Counter) meter; value = counter.count(); } if (meter instanceof Gauge) { Gauge gauge = (Gauge) meter; value = gauge.value(); } if (meter instanceof Timer) { Timer timer = (Timer) meter; value = timer.totalTime(TimeUnit.MILLISECONDS); } metricsTags.put(meter.getId().getName(), meter.getId().getTags()); metricsValue.put(meter.getId().getName(), value); }); metricsValue.forEach((key, value) -> { sb.append(key).append("{"); List<Tag> tags = metricsTags.get(key); if (tags != null && tags.size() > 0) { tags.forEach(tag -> { sb.append(tag.getKey()).append("=").append(tag.getValue()).append(","); }); } sb.append("} ").append(value).append(System.lineSeparator()); }); return sb.toString(); } @Override protected void doInit() { addMeterRegistry(meterRegistry); } @Override protected void doDestroy() {} }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/report/nop/NopMetricsReporterFactory.java
dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/report/nop/NopMetricsReporterFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.report.nop; import org.apache.dubbo.common.URL; import org.apache.dubbo.metrics.report.MetricsReporter; import org.apache.dubbo.metrics.report.MetricsReporterFactory; /** * MetricsReporterFactory to create NopMetricsReporter. */ public class NopMetricsReporterFactory implements MetricsReporterFactory { @Override public MetricsReporter createMetricsReporter(URL url) { return new NopMetricsReporter(url); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/report/nop/NopMetricsReporter.java
dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/report/nop/NopMetricsReporter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.report.nop; import org.apache.dubbo.common.URL; import org.apache.dubbo.metrics.report.MetricsReporter; /** * Metrics reporter without any operations. */ public class NopMetricsReporter implements MetricsReporter { public NopMetricsReporter(URL url) {} @Override public void init() {} @Override public void resetIfSamplesChanged() {} @Override public String getResponse() { return null; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/aot/DefaultMetricsReflectionTypeDescriberRegistrar.java
dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/aot/DefaultMetricsReflectionTypeDescriberRegistrar.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.aot; import org.apache.dubbo.aot.api.MemberCategory; import org.apache.dubbo.aot.api.ReflectionTypeDescriberRegistrar; import org.apache.dubbo.aot.api.TypeDescriber; import org.apache.dubbo.metrics.collector.HistogramMetricsCollector; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class DefaultMetricsReflectionTypeDescriberRegistrar implements ReflectionTypeDescriberRegistrar { @Override public List<TypeDescriber> getTypeDescribers() { List<TypeDescriber> typeDescribers = new ArrayList<>(); typeDescribers.add(buildTypeDescriberWithDeclaredConstructors(HistogramMetricsCollector.class)); return typeDescribers; } private TypeDescriber buildTypeDescriberWithDeclaredConstructors(Class<?> cl) { Set<MemberCategory> memberCategories = new HashSet<>(); memberCategories.add(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS); return new TypeDescriber( cl.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/event/RequestEvent.java
dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/event/RequestEvent.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.event; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; import org.apache.dubbo.metrics.MetricsConstants; import org.apache.dubbo.metrics.collector.DefaultMetricsCollector; import org.apache.dubbo.metrics.exception.MetricsNeverHappenException; import org.apache.dubbo.metrics.model.MethodMetric; import org.apache.dubbo.metrics.model.MetricsSupport; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.model.key.MetricsLevel; import org.apache.dubbo.metrics.model.key.TypeWrapper; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.model.ApplicationModel; import static org.apache.dubbo.metrics.DefaultConstants.METRIC_THROWABLE; import static org.apache.dubbo.metrics.MetricsConstants.ATTACHMENT_KEY_SERVICE; import static org.apache.dubbo.metrics.model.key.MetricsKey.METRIC_REQUESTS; import static org.apache.dubbo.metrics.model.key.MetricsKey.METRIC_REQUESTS_SUCCEED; import static org.apache.dubbo.metrics.model.key.MetricsKey.METRIC_REQUEST_BUSINESS_FAILED; /** * Request related events */ public class RequestEvent extends TimeCounterEvent { private static final TypeWrapper REQUEST_EVENT = new TypeWrapper( MetricsLevel.SERVICE, METRIC_REQUESTS, METRIC_REQUESTS_SUCCEED, METRIC_REQUEST_BUSINESS_FAILED); private static final TypeWrapper REQUEST_ERROR_EVENT = new TypeWrapper(MetricsLevel.METHOD, MetricsKey.METRIC_REQUESTS); public RequestEvent( ApplicationModel applicationModel, String appName, MetricsDispatcher metricsDispatcher, DefaultMetricsCollector collector, TypeWrapper TYPE_WRAPPER) { super(applicationModel, appName, metricsDispatcher, TYPE_WRAPPER); if (collector == null) { ScopeBeanFactory beanFactory = applicationModel.getBeanFactory(); if (!beanFactory.isDestroyed()) { collector = beanFactory.getBean(DefaultMetricsCollector.class); } } super.setAvailable(collector != null && collector.isCollectEnabled()); } public static RequestEvent toRequestEvent( ApplicationModel applicationModel, String appName, MetricsDispatcher metricsDispatcher, DefaultMetricsCollector collector, Invocation invocation, String side, boolean serviceLevel) { MethodMetric methodMetric = new MethodMetric(applicationModel, invocation, serviceLevel); RequestEvent requestEvent = new RequestEvent(applicationModel, appName, metricsDispatcher, collector, REQUEST_EVENT); requestEvent.putAttachment(MetricsConstants.INVOCATION, invocation); requestEvent.putAttachment(MetricsConstants.METHOD_METRICS, methodMetric); requestEvent.putAttachment(ATTACHMENT_KEY_SERVICE, MetricsSupport.getInterfaceName(invocation)); requestEvent.putAttachment(MetricsConstants.INVOCATION_SIDE, side); return requestEvent; } @Override public void customAfterPost(Object postResult) { if (postResult == null) { return; } if (!(postResult instanceof Result)) { throw new MetricsNeverHappenException( "Result type error, postResult:" + postResult.getClass().getName()); } super.putAttachment(METRIC_THROWABLE, ((Result) postResult).getException()); } /** * Acts on MetricsClusterFilter to monitor exceptions that occur before request execution */ public static RequestEvent toRequestErrorEvent( ApplicationModel applicationModel, String appName, MetricsDispatcher metricsDispatcher, Invocation invocation, String side, int code, boolean serviceLevel) { RequestEvent event = new RequestEvent(applicationModel, appName, metricsDispatcher, null, REQUEST_ERROR_EVENT); event.putAttachment(ATTACHMENT_KEY_SERVICE, MetricsSupport.getInterfaceName(invocation)); event.putAttachment(MetricsConstants.INVOCATION_SIDE, side); event.putAttachment(MetricsConstants.INVOCATION, invocation); event.putAttachment(MetricsConstants.INVOCATION_REQUEST_ERROR, code); event.putAttachment( MetricsConstants.METHOD_METRICS, new MethodMetric(applicationModel, invocation, serviceLevel)); return event; } public boolean isRequestErrorEvent() { return super.getAttachmentValue(MetricsConstants.INVOCATION_REQUEST_ERROR) != null; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/event/DefaultSubDispatcher.java
dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/event/DefaultSubDispatcher.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.event; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.metrics.MetricsConstants; import org.apache.dubbo.metrics.collector.DefaultMetricsCollector; import org.apache.dubbo.metrics.collector.MethodMetricsCollector; import org.apache.dubbo.metrics.listener.AbstractMetricsKeyListener; import org.apache.dubbo.metrics.listener.MetricsListener; import org.apache.dubbo.metrics.model.MetricsSupport; import org.apache.dubbo.metrics.model.key.CategoryOverall; import org.apache.dubbo.metrics.model.key.MetricsCat; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.model.key.MetricsLevel; import org.apache.dubbo.metrics.model.key.MetricsPlaceValue; import static org.apache.dubbo.metrics.DefaultConstants.METRIC_THROWABLE; import static org.apache.dubbo.metrics.model.key.MetricsKey.METRIC_REQUESTS_SERVICE_UNAVAILABLE_FAILED; @SuppressWarnings({"unchecked", "rawtypes"}) public final class DefaultSubDispatcher extends SimpleMetricsEventMulticaster { public DefaultSubDispatcher(DefaultMetricsCollector collector) { CategoryOverall categoryOverall = initMethodRequest(); super.addListener(categoryOverall.getPost().getEventFunc().apply(collector)); super.addListener(categoryOverall.getFinish().getEventFunc().apply(collector)); super.addListener(categoryOverall.getError().getEventFunc().apply(collector)); super.addListener(new MetricsListener<RequestEvent>() { @Override public boolean isSupport(MetricsEvent event) { return event instanceof RequestEvent && ((RequestEvent) event).isRequestErrorEvent(); } private final MetricsPlaceValue dynamicPlaceType = MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD); @Override public void onEvent(RequestEvent event) { MetricsSupport.increment( METRIC_REQUESTS_SERVICE_UNAVAILABLE_FAILED, dynamicPlaceType, (MethodMetricsCollector) collector, event); } }); } private CategoryOverall initMethodRequest() { return new CategoryOverall( null, new MetricsCat( MetricsKey.METRIC_REQUESTS, (key, placeType, collector) -> AbstractMetricsKeyListener.onEvent(key, event -> { MetricsPlaceValue dynamicPlaceType = MetricsPlaceValue.of( event.getAttachmentValue(MetricsConstants.INVOCATION_SIDE), MetricsLevel.METHOD); MetricsSupport.increment(key, dynamicPlaceType, (MethodMetricsCollector) collector, event); MetricsSupport.increment( MetricsKey.METRIC_REQUESTS_PROCESSING, dynamicPlaceType, (MethodMetricsCollector) collector, event); })), new MetricsCat( MetricsKey.METRIC_REQUESTS_SUCCEED, (key, placeType, collector) -> AbstractMetricsKeyListener.onFinish(key, event -> { MetricsPlaceValue dynamicPlaceType = MetricsPlaceValue.of( event.getAttachmentValue(MetricsConstants.INVOCATION_SIDE), MetricsLevel.METHOD); MetricsSupport.dec( MetricsKey.METRIC_REQUESTS_PROCESSING, dynamicPlaceType, collector, event); Object throwableObj = event.getAttachmentValue(METRIC_THROWABLE); MetricsKey targetKey; if (throwableObj == null) { targetKey = key; } else { targetKey = MetricsSupport.getMetricsKey((Throwable) throwableObj); MetricsSupport.increment( MetricsKey.METRIC_REQUESTS_TOTAL_FAILED, dynamicPlaceType, (MethodMetricsCollector) collector, event); } MetricsSupport.incrAndAddRt( targetKey, dynamicPlaceType, (MethodMetricsCollector) collector, event); })), new MetricsCat( MetricsKey.METRIC_REQUEST_BUSINESS_FAILED, (key, placeType, collector) -> AbstractMetricsKeyListener.onError(key, event -> { MetricsKey targetKey = MetricsSupport.getMetricsKey(event.getAttachmentValue(METRIC_THROWABLE)); // Dynamic metricsKey && dynamicPlaceType MetricsPlaceValue dynamicPlaceType = MetricsPlaceValue.of( event.getAttachmentValue(MetricsConstants.INVOCATION_SIDE), MetricsLevel.METHOD); MetricsSupport.increment( MetricsKey.METRIC_REQUESTS_TOTAL_FAILED, dynamicPlaceType, (MethodMetricsCollector) collector, event); MetricsSupport.dec( MetricsKey.METRIC_REQUESTS_PROCESSING, dynamicPlaceType, collector, event); MetricsSupport.incrAndAddRt( targetKey, dynamicPlaceType, (MethodMetricsCollector) collector, event); }))); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/register/HistogramMetricRegister.java
dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/register/HistogramMetricRegister.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.register; import org.apache.dubbo.config.nested.HistogramConfig; import org.apache.dubbo.metrics.sample.HistogramMetricSample; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.Tag; import io.micrometer.core.instrument.Timer; public class HistogramMetricRegister implements MetricRegister<HistogramMetricSample, Timer> { private final MeterRegistry registry; private final HistogramConfig config; public HistogramMetricRegister(MeterRegistry registry, HistogramConfig config) { this.registry = registry; this.config = config; } @Override public Timer register(HistogramMetricSample sample) { List<Tag> tags = new ArrayList<>(); sample.getTags().forEach((k, v) -> { if (v == null) { v = ""; } tags.add(Tag.of(k, v)); }); Timer.Builder builder = Timer.builder(sample.getName()) .description(sample.getDescription()) .tags(tags); if (Boolean.TRUE.equals(config.getEnabledPercentiles())) { builder.publishPercentileHistogram(true); } if (config.getPercentiles() != null) { builder.publishPercentiles(config.getPercentiles()); } if (config.getBucketsMs() != null) { builder.serviceLevelObjectives( Arrays.stream(config.getBucketsMs()).map(Duration::ofMillis).toArray(Duration[]::new)); } if (config.getMinExpectedMs() != null) { builder.minimumExpectedValue(Duration.ofMillis(config.getMinExpectedMs())); } if (config.getMaxExpectedMs() != null) { builder.maximumExpectedValue(Duration.ofMillis(config.getMaxExpectedMs())); } if (config.getDistributionStatisticExpiryMin() != null) { builder.distributionStatisticExpiry(Duration.ofMinutes(config.getDistributionStatisticExpiryMin())); } return builder.register(registry); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/register/MetricRegister.java
dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/register/MetricRegister.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.register; import org.apache.dubbo.metrics.model.sample.MetricSample; import io.micrometer.core.instrument.Meter; public interface MetricRegister<S extends MetricSample, M extends Meter> { M register(S sample); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/sample/HistogramMetricSample.java
dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/sample/HistogramMetricSample.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.sample; import org.apache.dubbo.metrics.model.MetricsCategory; import org.apache.dubbo.metrics.model.sample.MetricSample; import java.util.Map; public class HistogramMetricSample extends MetricSample { public HistogramMetricSample(String name, String description, Map<String, String> tags, MetricsCategory category) { super(name, description, tags, Type.TIMER, category); } public HistogramMetricSample( String name, String description, Map<String, String> tags, Type type, MetricsCategory category, String baseUnit) { super(name, description, tags, type, category, baseUnit); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/monitor/support/MonitorClusterFilter.java
dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/monitor/support/MonitorClusterFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.monitor.support; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.rpc.cluster.filter.ClusterFilter; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER; @Deprecated @Activate(group = {CONSUMER}) public class MonitorClusterFilter extends MonitorFilter implements ClusterFilter {}
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java
dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.monitor.support; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.monitor.Monitor; import org.apache.dubbo.monitor.MonitorFactory; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.model.ProviderModel; import org.apache.dubbo.rpc.model.ServiceModel; import org.apache.dubbo.rpc.support.RpcUtils; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicInteger; import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.METHOD_KEY; import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_MONITOR_EXCEPTION; import static org.apache.dubbo.monitor.Constants.CONCURRENT_KEY; import static org.apache.dubbo.monitor.Constants.COUNT_PROTOCOL; import static org.apache.dubbo.monitor.Constants.ELAPSED_KEY; import static org.apache.dubbo.monitor.Constants.FAILURE_KEY; import static org.apache.dubbo.monitor.Constants.SUCCESS_KEY; import static org.apache.dubbo.rpc.Constants.INPUT_KEY; import static org.apache.dubbo.rpc.Constants.OUTPUT_KEY; /** * MonitorFilter. (SPI, Singleton, ThreadSafe) */ @Deprecated @Activate(group = {PROVIDER}) public class MonitorFilter implements Filter, Filter.Listener { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MonitorFilter.class); private static final String MONITOR_FILTER_START_TIME = "monitor_filter_start_time"; private static final String MONITOR_REMOTE_HOST_STORE = "monitor_remote_host_store"; /** * The Concurrent counter */ private final ConcurrentMap<String, AtomicInteger> concurrents = new ConcurrentHashMap<>(); /** * The MonitorFactory */ private MonitorFactory monitorFactory; public void setMonitorFactory(MonitorFactory monitorFactory) { this.monitorFactory = monitorFactory; } /** * The invocation interceptor,it will collect the invoke data about this invocation and send it to monitor center * * @param invoker service * @param invocation invocation. * @return {@link Result} the invoke result * @throws RpcException */ @Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { if (invoker.getUrl().hasAttribute(MONITOR_KEY)) { invocation.put(MONITOR_FILTER_START_TIME, System.currentTimeMillis()); invocation.put( MONITOR_REMOTE_HOST_STORE, RpcContext.getServiceContext().getRemoteHost()); // count up getConcurrent(invoker, invocation).incrementAndGet(); } ServiceModel serviceModel = invoker.getUrl().getServiceModel(); if (serviceModel instanceof ProviderModel) { ((ProviderModel) serviceModel).updateLastInvokeTime(); } // proceed invocation chain return invoker.invoke(invocation); } /** * concurrent counter * * @param invoker * @param invocation * @return */ private AtomicInteger getConcurrent(Invoker<?> invoker, Invocation invocation) { String key = invoker.getInterface().getName() + "." + RpcUtils.getMethodName(invocation); return ConcurrentHashMapUtils.computeIfAbsent(concurrents, key, k -> new AtomicInteger()); } @Override public void onResponse(Result result, Invoker<?> invoker, Invocation invocation) { if (invoker.getUrl().hasAttribute(MONITOR_KEY)) { Long startTime = (Long) invocation.get(MONITOR_FILTER_START_TIME); if (startTime != null) { collect( invoker, invocation, result, (String) invocation.get(MONITOR_REMOTE_HOST_STORE), startTime, false); } // count down getConcurrent(invoker, invocation).decrementAndGet(); } } @Override public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) { if (invoker.getUrl().hasAttribute(MONITOR_KEY)) { Long startTime = (Long) invocation.get(MONITOR_FILTER_START_TIME); if (startTime != null) { collect(invoker, invocation, null, (String) invocation.get(MONITOR_REMOTE_HOST_STORE), startTime, true); } // count down getConcurrent(invoker, invocation).decrementAndGet(); } } /** * The collector logic, it will be handled by the default monitor * * @param invoker * @param invocation * @param result the invocation result * @param remoteHost the remote host address * @param start the timestamp the invocation begin * @param error if there is an error on the invocation */ private void collect( Invoker<?> invoker, Invocation invocation, Result result, String remoteHost, long start, boolean error) { try { Object monitorUrl; monitorUrl = invoker.getUrl().getAttribute(MONITOR_KEY); if (monitorUrl instanceof URL) { Monitor monitor = monitorFactory.getMonitor((URL) monitorUrl); if (monitor == null) { return; } URL statisticsUrl = createStatisticsUrl(invoker, invocation, result, remoteHost, start, error); monitor.collect(statisticsUrl.toSerializableURL()); } } catch (Throwable t) { logger.warn( COMMON_MONITOR_EXCEPTION, "", "", "Failed to monitor count service " + invoker.getUrl() + ", cause: " + t.getMessage(), t); } } /** * Create statistics url * * @param invoker * @param invocation * @param result * @param remoteHost * @param start * @param error * @return */ private URL createStatisticsUrl( Invoker<?> invoker, Invocation invocation, Result result, String remoteHost, long start, boolean error) { // ---- service statistics ---- // invocation cost long elapsed = System.currentTimeMillis() - start; // current concurrent count int concurrent = getConcurrent(invoker, invocation).get(); String application = invoker.getUrl().getApplication(); // service name String service = invoker.getInterface().getName(); // method name String method = RpcUtils.getMethodName(invocation); String group = invoker.getUrl().getGroup(); String version = invoker.getUrl().getVersion(); int localPort; String remoteKey, remoteValue; if (CONSUMER_SIDE.equals(invoker.getUrl().getSide())) { // ---- for service consumer ---- localPort = 0; remoteKey = PROVIDER; remoteValue = invoker.getUrl().getAddress(); } else { // ---- for service provider ---- localPort = invoker.getUrl().getPort(); remoteKey = CONSUMER; remoteValue = remoteHost; } String input = "", output = ""; if (invocation.getAttachment(INPUT_KEY) != null) { input = invocation.getAttachment(INPUT_KEY); } if (result != null && result.getAttachment(OUTPUT_KEY) != null) { output = result.getAttachment(OUTPUT_KEY); } return new ServiceConfigURL( COUNT_PROTOCOL, NetUtils.getLocalHost(), localPort, service + PATH_SEPARATOR + method, APPLICATION_KEY, application, INTERFACE_KEY, service, METHOD_KEY, method, remoteKey, remoteValue, error ? FAILURE_KEY : SUCCESS_KEY, "1", ELAPSED_KEY, String.valueOf(elapsed), CONCURRENT_KEY, String.valueOf(concurrent), INPUT_KEY, input, OUTPUT_KEY, output, GROUP_KEY, group, VERSION_KEY, version); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-config-center/src/test/java/org/apache/dubbo/metrics/collector/ConfigCenterMetricsCollectorTest.java
dubbo-metrics/dubbo-metrics-config-center/src/test/java/org/apache/dubbo/metrics/collector/ConfigCenterMetricsCollectorTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.collector; import org.apache.dubbo.common.config.configcenter.ConfigChangeType; import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.metrics.config.collector.ConfigCenterMetricsCollector; import org.apache.dubbo.metrics.model.sample.GaugeMetricSample; import org.apache.dubbo.metrics.model.sample.MetricSample; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import java.util.List; import java.util.Map; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_APPLICATION_NAME; import static org.apache.dubbo.metrics.MetricsConstants.SELF_INCREMENT_SIZE; class ConfigCenterMetricsCollectorTest { private FrameworkModel frameworkModel; private ApplicationModel applicationModel; @BeforeEach public void setup() { frameworkModel = FrameworkModel.defaultModel(); applicationModel = frameworkModel.newApplication(); ApplicationConfig config = new ApplicationConfig(); config.setName("MockMetrics"); applicationModel.getApplicationConfigManager().setApplication(config); } @AfterEach public void teardown() { applicationModel.destroy(); } @Test void increase4Initialized() { ConfigCenterMetricsCollector collector = new ConfigCenterMetricsCollector(applicationModel); collector.setCollectEnabled(true); String applicationName = applicationModel.getApplicationName(); collector.increase("key", "group", "nacos", ConfigChangeType.ADDED.name(), 1); collector.increase("key", "group", "nacos", ConfigChangeType.ADDED.name(), 1); List<MetricSample> samples = collector.collect(); for (MetricSample sample : samples) { Assertions.assertTrue(sample instanceof GaugeMetricSample); GaugeMetricSample<Long> gaugeSample = (GaugeMetricSample) sample; Map<String, String> tags = gaugeSample.getTags(); Assertions.assertEquals(gaugeSample.applyAsLong(), 2); Assertions.assertEquals(tags.get(TAG_APPLICATION_NAME), applicationName); } } @Test void increaseUpdated() { ConfigCenterMetricsCollector collector = new ConfigCenterMetricsCollector(applicationModel); collector.setCollectEnabled(true); String applicationName = applicationModel.getApplicationName(); ConfigChangedEvent event = new ConfigChangedEvent("key", "group", null, ConfigChangeType.ADDED); collector.increase( event.getKey(), event.getGroup(), "apollo", ConfigChangeType.ADDED.name(), SELF_INCREMENT_SIZE); collector.increase( event.getKey(), event.getGroup(), "apollo", ConfigChangeType.ADDED.name(), SELF_INCREMENT_SIZE); List<MetricSample> samples = collector.collect(); for (MetricSample sample : samples) { Assertions.assertTrue(sample instanceof GaugeMetricSample); GaugeMetricSample<Long> gaugeSample = (GaugeMetricSample) sample; Map<String, String> tags = gaugeSample.getTags(); Assertions.assertEquals(gaugeSample.applyAsLong(), 2); Assertions.assertEquals(tags.get(TAG_APPLICATION_NAME), applicationName); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/ConfigCenterMetricsConstants.java
dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/ConfigCenterMetricsConstants.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.config; public interface ConfigCenterMetricsConstants { String ATTACHMENT_KEY_CONFIG_FILE = "configFileKey"; String ATTACHMENT_KEY_CONFIG_GROUP = "configGroup"; String ATTACHMENT_KEY_CONFIG_PROTOCOL = "configProtocol"; String ATTACHMENT_KEY_CHANGE_TYPE = "configChangeType"; }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/collector/ConfigCenterMetricsCollector.java
dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/collector/ConfigCenterMetricsCollector.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.config.collector; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.metrics.collector.CombMetricsCollector; import org.apache.dubbo.metrics.collector.MetricsCollector; import org.apache.dubbo.metrics.config.event.ConfigCenterEvent; import org.apache.dubbo.metrics.config.event.ConfigCenterSubDispatcher; import org.apache.dubbo.metrics.model.ConfigCenterMetric; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.model.sample.GaugeMetricSample; import org.apache.dubbo.metrics.model.sample.MetricSample; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import static org.apache.dubbo.metrics.model.MetricsCategory.CONFIGCENTER; /** * Config center implementation of {@link MetricsCollector} */ @Activate public class ConfigCenterMetricsCollector extends CombMetricsCollector<ConfigCenterEvent> { private Boolean collectEnabled = null; private final ApplicationModel applicationModel; private final AtomicBoolean samplesChanged = new AtomicBoolean(true); private final ConcurrentHashMap<ConfigCenterMetric, AtomicLong> updatedMetrics = new ConcurrentHashMap<>(); public ConfigCenterMetricsCollector(ApplicationModel applicationModel) { super(null); this.applicationModel = applicationModel; super.setEventMulticaster(new ConfigCenterSubDispatcher(this)); } public void setCollectEnabled(Boolean collectEnabled) { if (collectEnabled != null) { this.collectEnabled = collectEnabled; } } @Override public boolean isCollectEnabled() { if (collectEnabled == null) { ConfigManager configManager = applicationModel.getApplicationConfigManager(); configManager.getMetrics().ifPresent(metricsConfig -> setCollectEnabled(metricsConfig.getEnableMetadata())); } return Optional.ofNullable(collectEnabled).orElse(false); } public void increase(String key, String group, String protocol, String changeTypeName, int size) { if (!isCollectEnabled()) { return; } ConfigCenterMetric metric = new ConfigCenterMetric(applicationModel.getApplicationName(), key, group, protocol, changeTypeName); AtomicLong metrics = updatedMetrics.get(metric); if (metrics == null) { metrics = ConcurrentHashMapUtils.computeIfAbsent(updatedMetrics, metric, k -> new AtomicLong(0L)); samplesChanged.set(true); } metrics.addAndGet(size); } @Override public List<MetricSample> collect() { // Add metrics to reporter List<MetricSample> list = new ArrayList<>(); if (!isCollectEnabled()) { return list; } updatedMetrics.forEach((k, v) -> list.add(new GaugeMetricSample<>( MetricsKey.CONFIGCENTER_METRIC_TOTAL, k.getTags(), CONFIGCENTER, v, AtomicLong::get))); return list; } @Override public boolean calSamplesChanged() { // CAS to get and reset the flag in an atomic operation return samplesChanged.compareAndSet(true, false); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/event/ConfigCenterEvent.java
dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/event/ConfigCenterEvent.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.config.event; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; import org.apache.dubbo.metrics.config.collector.ConfigCenterMetricsCollector; import org.apache.dubbo.metrics.event.TimeCounterEvent; import org.apache.dubbo.metrics.model.key.MetricsLevel; import org.apache.dubbo.metrics.model.key.TypeWrapper; import org.apache.dubbo.rpc.model.ApplicationModel; import static org.apache.dubbo.metrics.MetricsConstants.ATTACHMENT_KEY_SIZE; import static org.apache.dubbo.metrics.config.ConfigCenterMetricsConstants.ATTACHMENT_KEY_CHANGE_TYPE; import static org.apache.dubbo.metrics.config.ConfigCenterMetricsConstants.ATTACHMENT_KEY_CONFIG_FILE; import static org.apache.dubbo.metrics.config.ConfigCenterMetricsConstants.ATTACHMENT_KEY_CONFIG_GROUP; import static org.apache.dubbo.metrics.config.ConfigCenterMetricsConstants.ATTACHMENT_KEY_CONFIG_PROTOCOL; import static org.apache.dubbo.metrics.model.key.MetricsKey.CONFIGCENTER_METRIC_TOTAL; /** * Registry related events * Triggered in three types of configuration centers (apollo, zk, nacos) */ public class ConfigCenterEvent extends TimeCounterEvent { public static final String NACOS_PROTOCOL = "nacos"; public static final String APOLLO_PROTOCOL = "apollo"; public static final String ZK_PROTOCOL = "zookeeper"; public ConfigCenterEvent(ApplicationModel applicationModel, TypeWrapper typeWrapper) { super(applicationModel, typeWrapper); ScopeBeanFactory beanFactory = applicationModel.getBeanFactory(); ConfigCenterMetricsCollector collector; if (!beanFactory.isDestroyed()) { collector = beanFactory.getBean(ConfigCenterMetricsCollector.class); super.setAvailable(collector != null && collector.isCollectEnabled()); } } public static ConfigCenterEvent toChangeEvent( ApplicationModel applicationModel, String key, String group, String protocol, String changeType, int count) { ConfigCenterEvent configCenterEvent = new ConfigCenterEvent( applicationModel, new TypeWrapper(MetricsLevel.CONFIG, CONFIGCENTER_METRIC_TOTAL)); configCenterEvent.putAttachment(ATTACHMENT_KEY_CONFIG_FILE, key); configCenterEvent.putAttachment(ATTACHMENT_KEY_CONFIG_GROUP, group); configCenterEvent.putAttachment(ATTACHMENT_KEY_CONFIG_PROTOCOL, protocol); configCenterEvent.putAttachment(ATTACHMENT_KEY_CHANGE_TYPE, changeType); configCenterEvent.putAttachment(ATTACHMENT_KEY_SIZE, count); return configCenterEvent; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/event/ConfigCenterSubDispatcher.java
dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/event/ConfigCenterSubDispatcher.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.config.event; import org.apache.dubbo.metrics.config.collector.ConfigCenterMetricsCollector; import org.apache.dubbo.metrics.event.MetricsEvent; import org.apache.dubbo.metrics.event.SimpleMetricsEventMulticaster; import org.apache.dubbo.metrics.event.TimeCounterEvent; import org.apache.dubbo.metrics.listener.AbstractMetricsKeyListener; import org.apache.dubbo.metrics.model.key.MetricsKey; import static org.apache.dubbo.metrics.MetricsConstants.ATTACHMENT_KEY_SIZE; import static org.apache.dubbo.metrics.config.ConfigCenterMetricsConstants.ATTACHMENT_KEY_CHANGE_TYPE; import static org.apache.dubbo.metrics.config.ConfigCenterMetricsConstants.ATTACHMENT_KEY_CONFIG_FILE; import static org.apache.dubbo.metrics.config.ConfigCenterMetricsConstants.ATTACHMENT_KEY_CONFIG_GROUP; import static org.apache.dubbo.metrics.config.ConfigCenterMetricsConstants.ATTACHMENT_KEY_CONFIG_PROTOCOL; public final class ConfigCenterSubDispatcher extends SimpleMetricsEventMulticaster { public ConfigCenterSubDispatcher(ConfigCenterMetricsCollector collector) { super.addListener(new AbstractMetricsKeyListener(MetricsKey.CONFIGCENTER_METRIC_TOTAL) { @Override public boolean isSupport(MetricsEvent event) { return event instanceof ConfigCenterEvent; } @Override public void onEvent(TimeCounterEvent event) { collector.increase( event.getAttachmentValue(ATTACHMENT_KEY_CONFIG_FILE), event.getAttachmentValue(ATTACHMENT_KEY_CONFIG_GROUP), event.getAttachmentValue(ATTACHMENT_KEY_CONFIG_PROTOCOL), event.getAttachmentValue(ATTACHMENT_KEY_CHANGE_TYPE), event.getAttachmentValue(ATTACHMENT_KEY_SIZE)); } }); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsCollectorTest.java
dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsCollectorTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.registry.metrics.collector; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.metrics.event.MetricsDispatcher; import org.apache.dubbo.metrics.event.MetricsEventBus; import org.apache.dubbo.metrics.model.TimePair; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper; import org.apache.dubbo.metrics.model.sample.GaugeMetricSample; import org.apache.dubbo.metrics.model.sample.MetricSample; import org.apache.dubbo.metrics.registry.RegistryMetricsConstants; import org.apache.dubbo.metrics.registry.collector.RegistryMetricsCollector; import org.apache.dubbo.metrics.registry.event.RegistryEvent; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_APPLICATION_NAME; import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.APP_LEVEL_KEYS; import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.OP_TYPE_REGISTER; import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.OP_TYPE_REGISTER_SERVICE; import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.OP_TYPE_SUBSCRIBE_SERVICE; import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.REGISTER_LEVEL_KEYS; class RegistryMetricsCollectorTest { private ApplicationModel applicationModel; private RegistryMetricsCollector collector; @BeforeEach public void setup() { FrameworkModel frameworkModel = FrameworkModel.defaultModel(); applicationModel = frameworkModel.newApplication(); ApplicationConfig config = new ApplicationConfig(); config.setName("MockMetrics"); applicationModel.getApplicationConfigManager().setApplication(config); applicationModel.getBeanFactory().getOrRegisterBean(MetricsDispatcher.class); collector = applicationModel.getBeanFactory().getOrRegisterBean(RegistryMetricsCollector.class); collector.setCollectEnabled(true); } @AfterEach public void teardown() { applicationModel.destroy(); } @Test void testRegisterMetrics() { List<String> registryClusterNames = new ArrayList<>(); registryClusterNames.add("reg1"); RegistryEvent registryEvent = RegistryEvent.toRegisterEvent(applicationModel, registryClusterNames); MetricsEventBus.post(registryEvent, () -> { List<MetricSample> metricSamples = collector.collect(); // push success +1 -> other default 0 = APP_LEVEL_KEYS.size() Assertions.assertEquals(APP_LEVEL_KEYS.size() + REGISTER_LEVEL_KEYS.size(), metricSamples.size()); Assertions.assertTrue( metricSamples.stream().allMatch(metricSample -> metricSample instanceof GaugeMetricSample)); Assertions.assertTrue(metricSamples.stream() .anyMatch(metricSample -> ((GaugeMetricSample) metricSample).applyAsDouble() == 1)); return null; }); // push finish rt +1 List<MetricSample> metricSamples = collector.collect(); // APP_LEVEL_KEYS.size() + rt(5) = 12 Assertions.assertEquals(APP_LEVEL_KEYS.size() + REGISTER_LEVEL_KEYS.size() + 5, metricSamples.size()); long c1 = registryEvent.getTimePair().calc(); registryEvent = RegistryEvent.toRegisterEvent(applicationModel, registryClusterNames); TimePair lastTimePair = registryEvent.getTimePair(); MetricsEventBus.post( registryEvent, () -> { try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } return null; }, Objects::nonNull); // push error rt +1 long c2 = lastTimePair.calc(); metricSamples = collector.collect(); // num(total+success+error) + rt(5) Assertions.assertEquals(APP_LEVEL_KEYS.size() + REGISTER_LEVEL_KEYS.size() + 5, metricSamples.size()); // calc rt for (MetricSample sample : metricSamples) { Map<String, String> tags = sample.getTags(); Assertions.assertEquals(tags.get(TAG_APPLICATION_NAME), applicationModel.getApplicationName()); } @SuppressWarnings("rawtypes") Map<String, Long> sampleMap = metricSamples.stream() .collect(Collectors.toMap(MetricSample::getName, k -> ((GaugeMetricSample) k).applyAsLong())); Assertions.assertEquals( sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_LAST, OP_TYPE_REGISTER).targetKey()), lastTimePair.calc()); Assertions.assertEquals( sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MIN, OP_TYPE_REGISTER).targetKey()), Math.min(c1, c2)); Assertions.assertEquals( sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MAX, OP_TYPE_REGISTER).targetKey()), Math.max(c1, c2)); Assertions.assertEquals( sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_AVG, OP_TYPE_REGISTER).targetKey()), (c1 + c2) / 2); Assertions.assertEquals( sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_SUM, OP_TYPE_REGISTER).targetKey()), c1 + c2); } @Test void testServicePushMetrics() { String serviceName = "demo.gameService"; List<String> rcNames = new ArrayList<>(); rcNames.add("demo1"); RegistryEvent registryEvent = RegistryEvent.toRsEvent(applicationModel, serviceName, 2, rcNames); MetricsEventBus.post(registryEvent, () -> { List<MetricSample> metricSamples = collector.collect(); // push success +1 Assertions.assertEquals(RegistryMetricsConstants.APP_LEVEL_KEYS.size() + 1, metricSamples.size()); // Service num only 1 and contains tag of interface Assertions.assertEquals( 1, metricSamples.stream() .filter(metricSample -> serviceName.equals(metricSample.getTags().get("interface"))) .count()); return null; }); // push finish rt +1 List<MetricSample> metricSamples = collector.collect(); // App(7) + rt(5) + service(total/success) = 14 Assertions.assertEquals(RegistryMetricsConstants.APP_LEVEL_KEYS.size() + 5 + 2, metricSamples.size()); long c1 = registryEvent.getTimePair().calc(); registryEvent = RegistryEvent.toRsEvent(applicationModel, serviceName, 2, rcNames); TimePair lastTimePair = registryEvent.getTimePair(); MetricsEventBus.post( registryEvent, () -> { try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } return null; }, Objects::nonNull); // push error rt +1 long c2 = lastTimePair.calc(); metricSamples = collector.collect(); // App(7) + rt(5) + service(total/success/failed) = 15 Assertions.assertEquals(RegistryMetricsConstants.APP_LEVEL_KEYS.size() + 5 + 3, metricSamples.size()); // calc rt for (MetricSample sample : metricSamples) { Map<String, String> tags = sample.getTags(); Assertions.assertEquals(tags.get(TAG_APPLICATION_NAME), applicationModel.getApplicationName()); } @SuppressWarnings("rawtypes") Map<String, Long> sampleMap = metricSamples.stream() .collect(Collectors.toMap(MetricSample::getName, k -> ((GaugeMetricSample) k).applyAsLong())); Assertions.assertEquals( sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_LAST, OP_TYPE_REGISTER_SERVICE).targetKey()), lastTimePair.calc()); Assertions.assertEquals( sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MIN, OP_TYPE_REGISTER_SERVICE).targetKey()), Math.min(c1, c2)); Assertions.assertEquals( sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MAX, OP_TYPE_REGISTER_SERVICE).targetKey()), Math.max(c1, c2)); Assertions.assertEquals( sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_AVG, OP_TYPE_REGISTER_SERVICE).targetKey()), (c1 + c2) / 2); Assertions.assertEquals( sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_SUM, OP_TYPE_REGISTER_SERVICE).targetKey()), c1 + c2); } @Test void testServiceSubscribeMetrics() { String serviceName = "demo.gameService"; RegistryEvent subscribeEvent = RegistryEvent.toSsEvent(applicationModel, serviceName, Collections.singletonList("demo1")); MetricsEventBus.post(subscribeEvent, () -> { List<MetricSample> metricSamples = collector.collect(); Assertions.assertTrue( metricSamples.stream().allMatch(metricSample -> metricSample instanceof GaugeMetricSample)); Assertions.assertTrue(metricSamples.stream() .anyMatch(metricSample -> ((GaugeMetricSample) metricSample).applyAsDouble() == 1)); // App(default=7) + (service success +1) Assertions.assertEquals(RegistryMetricsConstants.APP_LEVEL_KEYS.size() + 1, metricSamples.size()); // Service num only 1 and contains tag of interface Assertions.assertEquals( 1, metricSamples.stream() .filter(metricSample -> serviceName.equals(metricSample.getTags().get("interface"))) .count()); return null; }); // push finish rt +1 List<MetricSample> metricSamples = collector.collect(); // App(7) + rt(5) + service(total/success) = 14 Assertions.assertEquals(RegistryMetricsConstants.APP_LEVEL_KEYS.size() + 5 + 2, metricSamples.size()); long c1 = subscribeEvent.getTimePair().calc(); subscribeEvent = RegistryEvent.toSsEvent(applicationModel, serviceName, Collections.singletonList("demo1")); TimePair lastTimePair = subscribeEvent.getTimePair(); MetricsEventBus.post( subscribeEvent, () -> { try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } return null; }, Objects::nonNull); // push error rt +1 long c2 = lastTimePair.calc(); metricSamples = collector.collect(); // App(7) + rt(5) + service(total/success/failed) = 15 Assertions.assertEquals(RegistryMetricsConstants.APP_LEVEL_KEYS.size() + 5 + 3, metricSamples.size()); // calc rt for (MetricSample sample : metricSamples) { Map<String, String> tags = sample.getTags(); Assertions.assertEquals(tags.get(TAG_APPLICATION_NAME), applicationModel.getApplicationName()); } @SuppressWarnings("rawtypes") Map<String, Long> sampleMap = metricSamples.stream() .collect(Collectors.toMap(MetricSample::getName, k -> ((GaugeMetricSample) k).applyAsLong())); Assertions.assertEquals( sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_LAST, OP_TYPE_SUBSCRIBE_SERVICE).targetKey()), lastTimePair.calc()); Assertions.assertEquals( sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MIN, OP_TYPE_SUBSCRIBE_SERVICE).targetKey()), Math.min(c1, c2)); Assertions.assertEquals( sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MAX, OP_TYPE_SUBSCRIBE_SERVICE).targetKey()), Math.max(c1, c2)); Assertions.assertEquals( sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_AVG, OP_TYPE_SUBSCRIBE_SERVICE).targetKey()), (c1 + c2) / 2); Assertions.assertEquals( sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_SUM, OP_TYPE_SUBSCRIBE_SERVICE).targetKey()), c1 + c2); } @Test public void testNotify() { Map<String, Integer> lastNumMap = new HashMap<>(); MetricsEventBus.post(RegistryEvent.toNotifyEvent(applicationModel), () -> { try { Thread.sleep(50L); } catch (InterruptedException e) { e.printStackTrace(); } // 1 different services lastNumMap.put("demo.service1", 3); lastNumMap.put("demo.service2", 4); lastNumMap.put("demo.service3", 5); return lastNumMap; }); List<MetricSample> metricSamples = collector.collect(); // App(7) + num(service*3) + rt(5) = 9 Assertions.assertEquals((RegistryMetricsConstants.APP_LEVEL_KEYS.size() + 3 + 5), metricSamples.size()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsSampleTest.java
dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsSampleTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.registry.metrics.collector; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper; import org.apache.dubbo.metrics.model.sample.GaugeMetricSample; import org.apache.dubbo.metrics.model.sample.MetricSample; import org.apache.dubbo.metrics.registry.collector.RegistryMetricsCollector; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_APPLICATION_NAME; import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.OP_TYPE_REGISTER; class RegistryMetricsSampleTest { private ApplicationModel applicationModel; @BeforeEach public void setup() { FrameworkModel frameworkModel = FrameworkModel.defaultModel(); applicationModel = frameworkModel.newApplication(); ApplicationConfig config = new ApplicationConfig(); config.setName("MockMetrics"); applicationModel.getApplicationConfigManager().setApplication(config); } @AfterEach public void teardown() { applicationModel.destroy(); } @Test void testRegisterMetrics() {} @Test void testRTMetrics() { RegistryMetricsCollector collector = new RegistryMetricsCollector(applicationModel); collector.setCollectEnabled(true); String applicationName = applicationModel.getApplicationName(); collector.addServiceRt(applicationName, OP_TYPE_REGISTER.getType(), 10L); collector.addServiceRt(applicationName, OP_TYPE_REGISTER.getType(), 0L); List<MetricSample> samples = collector.collect(); for (MetricSample sample : samples) { Map<String, String> tags = sample.getTags(); Assertions.assertEquals(tags.get(TAG_APPLICATION_NAME), applicationName); } @SuppressWarnings("rawtypes") Map<String, Long> sampleMap = samples.stream() .collect(Collectors.toMap(MetricSample::getName, k -> ((GaugeMetricSample) k).applyAsLong())); Assertions.assertEquals( sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_LAST, OP_TYPE_REGISTER).targetKey()), 0L); Assertions.assertEquals( sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MIN, OP_TYPE_REGISTER).targetKey()), 0L); Assertions.assertEquals( sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MAX, OP_TYPE_REGISTER).targetKey()), 10L); Assertions.assertEquals( sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_AVG, OP_TYPE_REGISTER).targetKey()), 5L); Assertions.assertEquals( sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_SUM, OP_TYPE_REGISTER).targetKey()), 10L); } @Test void testListener() { RegistryMetricsCollector collector = new RegistryMetricsCollector(applicationModel); collector.setCollectEnabled(true); collector.increment(MetricsKey.REGISTER_METRIC_REQUESTS); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsTest.java
dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.registry.metrics.collector; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.MetricsConfig; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.config.nested.AggregationConfig; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.model.sample.GaugeMetricSample; import org.apache.dubbo.metrics.model.sample.MetricSample; import org.apache.dubbo.metrics.registry.collector.RegistryMetricsCollector; import org.apache.dubbo.metrics.registry.event.RegistryEvent; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; import java.util.Optional; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; public class RegistryMetricsTest { ApplicationModel applicationModel; RegistryMetricsCollector collector; String REGISTER = "register"; @BeforeEach void setUp() { this.applicationModel = getApplicationModel(); this.collector = getTestCollector(this.applicationModel); this.collector.setCollectEnabled(true); } @Test void testRegisterRequestsCount() { for (int i = 0; i < 10; i++) { RegistryEvent event = applicationRegister(); if (i % 2 == 0) { eventSuccess(event); } else { eventFailed(event); } } List<MetricSample> samples = collector.collect(); GaugeMetricSample<?> succeedRequests = getSample(MetricsKey.REGISTER_METRIC_REQUESTS_SUCCEED.getName(), samples); GaugeMetricSample<?> failedRequests = getSample(MetricsKey.REGISTER_METRIC_REQUESTS_FAILED.getName(), samples); GaugeMetricSample<?> totalRequests = getSample(MetricsKey.REGISTER_METRIC_REQUESTS.getName(), samples); Assertions.assertEquals(5L, succeedRequests.applyAsLong()); Assertions.assertEquals(5L, failedRequests.applyAsLong()); Assertions.assertEquals(10L, totalRequests.applyAsLong()); } @Test void testLastResponseTime() { long waitTime = 2000; RegistryEvent event = applicationRegister(); await(waitTime); eventSuccess(event); GaugeMetricSample<?> sample = getSample(MetricsKey.METRIC_RT_LAST.getNameByType(REGISTER), collector.collect()); // 20% deviation is allowed Assertions.assertTrue(considerEquals(waitTime, sample.applyAsLong(), 0.2)); RegistryEvent event1 = applicationRegister(); await(waitTime / 2); eventSuccess(event1); sample = getSample(MetricsKey.METRIC_RT_LAST.getNameByType(REGISTER), collector.collect()); Assertions.assertTrue(considerEquals((double) waitTime / 2, sample.applyAsLong(), 0.2)); RegistryEvent event2 = applicationRegister(); await(waitTime); eventFailed(event2); sample = getSample(MetricsKey.METRIC_RT_LAST.getNameByType(REGISTER), collector.collect()); Assertions.assertTrue(considerEquals((double) waitTime, sample.applyAsLong(), 0.2)); } @Test void testMinResponseTime() throws InterruptedException { long waitTime = 2000L; RegistryEvent event = applicationRegister(); await(waitTime); eventSuccess(event); RegistryEvent event1 = applicationRegister(); await(waitTime); RegistryEvent event2 = applicationRegister(); await(waitTime); eventSuccess(event1); eventSuccess(event2); GaugeMetricSample<?> sample = getSample(MetricsKey.METRIC_RT_MIN.getNameByType(REGISTER), collector.collect()); Assertions.assertTrue(considerEquals(waitTime, sample.applyAsLong(), 0.2)); RegistryEvent event3 = applicationRegister(); Thread.sleep(waitTime / 2); eventSuccess(event3); sample = getSample(MetricsKey.METRIC_RT_MIN.getNameByType(REGISTER), collector.collect()); Assertions.assertTrue(considerEquals((double) waitTime / 2, sample.applyAsLong(), 0.2)); } @Test void testMaxResponseTime() { long waitTime = 1000L; RegistryEvent event = applicationRegister(); await(waitTime); eventSuccess(event); GaugeMetricSample<?> sample = getSample(MetricsKey.METRIC_RT_MAX.getNameByType(REGISTER), collector.collect()); Assertions.assertTrue(considerEquals(waitTime, sample.applyAsLong(), 0.2)); RegistryEvent event1 = applicationRegister(); await(waitTime * 2); eventSuccess(event1); sample = getSample(MetricsKey.METRIC_RT_MAX.getNameByType(REGISTER), collector.collect()); Assertions.assertTrue(considerEquals(waitTime * 2, sample.applyAsLong(), 0.2)); sample = getSample(MetricsKey.METRIC_RT_MAX.getNameByType(REGISTER), collector.collect()); RegistryEvent event2 = applicationRegister(); eventSuccess(event2); Assertions.assertTrue(considerEquals(waitTime * 2, sample.applyAsLong(), 0.2)); } @Test void testSumResponseTime() { long waitTime = 1000; RegistryEvent event = applicationRegister(); RegistryEvent event1 = applicationRegister(); RegistryEvent event2 = applicationRegister(); await(waitTime); eventSuccess(event); eventFailed(event1); GaugeMetricSample<?> sample = getSample(MetricsKey.METRIC_RT_SUM.getNameByType(REGISTER), collector.collect()); Assertions.assertTrue(considerEquals(waitTime * 2, sample.applyAsLong(), 0.2)); await(waitTime); eventSuccess(event2); sample = getSample(MetricsKey.METRIC_RT_SUM.getNameByType(REGISTER), collector.collect()); Assertions.assertTrue(considerEquals(waitTime * 4, sample.applyAsLong(), 0.2)); } @Test void testAvgResponseTime() { long waitTime = 1000; RegistryEvent event = applicationRegister(); RegistryEvent event1 = applicationRegister(); RegistryEvent event2 = applicationRegister(); await(waitTime); eventSuccess(event); eventFailed(event1); GaugeMetricSample<?> sample = getSample(MetricsKey.METRIC_RT_AVG.getNameByType(REGISTER), collector.collect()); Assertions.assertTrue(considerEquals(waitTime, sample.applyAsLong(), 0.2)); await(waitTime); eventSuccess(event2); sample = getSample(MetricsKey.METRIC_RT_AVG.getNameByType(REGISTER), collector.collect()); Assertions.assertTrue(considerEquals((double) waitTime * 4 / 3, sample.applyAsLong(), 0.2)); } @Test void testServiceRegisterCount() { for (int i = 0; i < 10; i++) { RegistryEvent event = serviceRegister(); if (i % 2 == 0) { eventSuccess(event); } else { eventFailed(event); } } List<MetricSample> samples = collector.collect(); GaugeMetricSample<?> succeedRequests = getSample(MetricsKey.SERVICE_REGISTER_METRIC_REQUESTS_SUCCEED.getName(), samples); GaugeMetricSample<?> failedRequests = getSample(MetricsKey.SERVICE_REGISTER_METRIC_REQUESTS_FAILED.getName(), samples); GaugeMetricSample<?> totalRequests = getSample(MetricsKey.SERVICE_REGISTER_METRIC_REQUESTS.getName(), samples); Assertions.assertEquals(5L, succeedRequests.applyAsLong()); Assertions.assertEquals(5L, failedRequests.applyAsLong()); Assertions.assertEquals(10L, totalRequests.applyAsLong()); } @Test void testServiceSubscribeCount() { for (int i = 0; i < 10; i++) { RegistryEvent event = serviceSubscribe(); if (i % 2 == 0) { eventSuccess(event); } else { eventFailed(event); } } List<MetricSample> samples = collector.collect(); GaugeMetricSample<?> succeedRequests = getSample(MetricsKey.SUBSCRIBE_METRIC_NUM_SUCCEED.getName(), samples); GaugeMetricSample<?> failedRequests = getSample(MetricsKey.SUBSCRIBE_METRIC_NUM_FAILED.getName(), samples); GaugeMetricSample<?> totalRequests = getSample(MetricsKey.SUBSCRIBE_METRIC_NUM.getName(), samples); Assertions.assertEquals(5L, succeedRequests.applyAsLong()); Assertions.assertEquals(5L, failedRequests.applyAsLong()); Assertions.assertEquals(10L, totalRequests.applyAsLong()); } GaugeMetricSample<?> getSample(String name, List<MetricSample> samples) { return (GaugeMetricSample<?>) samples.stream() .filter(metricSample -> metricSample.getName().equals(name)) .findFirst() .orElseThrow(NoSuchElementException::new); } RegistryEvent applicationRegister() { RegistryEvent event = registerEvent(); collector.onEvent(event); return event; } RegistryEvent serviceRegister() { RegistryEvent event = rsEvent(); collector.onEvent(event); return event; } RegistryEvent serviceSubscribe() { RegistryEvent event = subscribeEvent(); collector.onEvent(event); return event; } boolean considerEquals(double expected, double trueValue, double allowedErrorRatio) { return Math.abs(1 - expected / trueValue) <= allowedErrorRatio; } void eventSuccess(RegistryEvent event) { collector.onEventFinish(event); } void eventFailed(RegistryEvent event) { collector.onEventError(event); } RegistryEvent registerEvent() { List<String> registryClusterNames = new ArrayList<>(); registryClusterNames.add("reg1"); RegistryEvent event = RegistryEvent.toRegisterEvent(applicationModel, registryClusterNames); event.setAvailable(true); return event; } RegistryEvent rsEvent() { List<String> rcNames = new ArrayList<>(); rcNames.add("demo1"); RegistryEvent event = RegistryEvent.toRsEvent(applicationModel, "TestServiceInterface1", 1, rcNames); event.setAvailable(true); return event; } RegistryEvent subscribeEvent() { RegistryEvent event = RegistryEvent.toSubscribeEvent(applicationModel, "registryClusterName_test"); event.setAvailable(true); return event; } ApplicationModel getApplicationModel() { return spy(new FrameworkModel().newApplication()); } void await(long millis) { CountDownLatch latch = new CountDownLatch(1); ScheduledFuture<?> future = TimeController.executor.schedule(latch::countDown, millis, TimeUnit.MILLISECONDS); try { latch.await(); } catch (InterruptedException e) { future.cancel(true); Thread.currentThread().interrupt(); } } RegistryMetricsCollector getTestCollector(ApplicationModel applicationModel) { ApplicationConfig applicationConfig = new ApplicationConfig("TestApp"); ConfigManager configManager = spy(new ConfigManager(applicationModel)); MetricsConfig metricsConfig = spy(new MetricsConfig()); configManager.setApplication(applicationConfig); configManager.setMetrics(metricsConfig); when(metricsConfig.getAggregation()).thenReturn(new AggregationConfig()); when(applicationModel.getApplicationConfigManager()).thenReturn(configManager); when(applicationModel.NotExistApplicationConfig()).thenReturn(false); when(configManager.getApplication()).thenReturn(Optional.of(applicationConfig)); return new RegistryMetricsCollector(applicationModel); } /** * make the control of thread sleep time more precise */ static class TimeController { private static final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); public static void sleep(long milliseconds) { CountDownLatch latch = new CountDownLatch(1); ScheduledFuture<?> future = executor.schedule(latch::countDown, milliseconds, TimeUnit.MILLISECONDS); try { latch.await(); } catch (InterruptedException e) { future.cancel(true); Thread.currentThread().interrupt(); } } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryStatCompositeTest.java
dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryStatCompositeTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.registry.metrics.collector; import org.apache.dubbo.common.constants.RegistryConstants; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.metrics.data.ApplicationStatComposite; import org.apache.dubbo.metrics.data.BaseStatComposite; import org.apache.dubbo.metrics.data.RtStatComposite; import org.apache.dubbo.metrics.data.ServiceStatComposite; import org.apache.dubbo.metrics.model.ApplicationMetric; import org.apache.dubbo.metrics.model.Metric; import org.apache.dubbo.metrics.model.MetricsCategory; import org.apache.dubbo.metrics.model.container.LongContainer; import org.apache.dubbo.metrics.model.sample.GaugeMetricSample; import org.apache.dubbo.metrics.model.sample.MetricSample; import org.apache.dubbo.metrics.registry.RegistryMetricsConstants; import org.apache.dubbo.metrics.registry.collector.RegistryStatComposite; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.atomic.AtomicLong; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.metrics.model.key.MetricsKey.METRIC_RT_AVG; import static org.apache.dubbo.metrics.model.key.MetricsKey.METRIC_RT_MAX; import static org.apache.dubbo.metrics.model.key.MetricsKey.METRIC_RT_MIN; import static org.apache.dubbo.metrics.model.key.MetricsKey.REGISTER_METRIC_REQUESTS; import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.OP_TYPE_NOTIFY; import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.OP_TYPE_REGISTER; import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.OP_TYPE_REGISTER_SERVICE; import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.OP_TYPE_SUBSCRIBE; import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.OP_TYPE_SUBSCRIBE_SERVICE; public class RegistryStatCompositeTest { private ApplicationModel applicationModel; private String applicationName; private BaseStatComposite statComposite; private RegistryStatComposite regStatComposite; @BeforeEach public void setup() { FrameworkModel frameworkModel = FrameworkModel.defaultModel(); applicationModel = frameworkModel.newApplication(); ApplicationConfig application = new ApplicationConfig(); application.setName("App1"); applicationModel.getApplicationConfigManager().setApplication(application); applicationName = applicationModel.getApplicationName(); statComposite = new BaseStatComposite(applicationModel) { @Override protected void init(ApplicationStatComposite applicationStatComposite) { super.init(applicationStatComposite); applicationStatComposite.init(RegistryMetricsConstants.APP_LEVEL_KEYS); } @Override protected void init(ServiceStatComposite serviceStatComposite) { super.init(serviceStatComposite); serviceStatComposite.initWrapper(RegistryMetricsConstants.SERVICE_LEVEL_KEYS); } @Override protected void init(RtStatComposite rtStatComposite) { super.init(rtStatComposite); rtStatComposite.init( OP_TYPE_REGISTER, OP_TYPE_SUBSCRIBE, OP_TYPE_NOTIFY, OP_TYPE_REGISTER_SERVICE, OP_TYPE_SUBSCRIBE_SERVICE); } }; regStatComposite = new RegistryStatComposite(applicationModel); } @Test void testInit() { Assertions.assertEquals( statComposite .getApplicationStatComposite() .getApplicationNumStats() .size(), RegistryMetricsConstants.APP_LEVEL_KEYS.size()); // (rt)5 * (applicationRegister,subscribe,notify,applicationRegister.service,subscribe.service) Assertions.assertEquals( 5 * 5, statComposite.getRtStatComposite().getRtStats().size()); statComposite .getApplicationStatComposite() .getApplicationNumStats() .values() .forEach((v -> Assertions.assertEquals(v.get(), new AtomicLong(0L).get()))); statComposite.getRtStatComposite().getRtStats().forEach(rtContainer -> { for (Map.Entry<Metric, ? extends Number> entry : rtContainer.entrySet()) { Assertions.assertEquals(0L, rtContainer.getValueSupplier().apply(entry.getKey())); } }); } @Test void testIncrement() { regStatComposite.incrMetricsNum(REGISTER_METRIC_REQUESTS, "beijing"); ApplicationMetric applicationMetric = new ApplicationMetric(applicationModel); applicationMetric.setExtraInfo( Collections.singletonMap(RegistryConstants.REGISTRY_CLUSTER_KEY.toLowerCase(), "beijing")); Assertions.assertEquals( 1L, regStatComposite .getAppStats() .get(REGISTER_METRIC_REQUESTS) .get(applicationMetric) .get()); } @Test void testCalcRt() { statComposite.calcApplicationRt(OP_TYPE_NOTIFY.getType(), 10L); Assertions.assertTrue(statComposite.getRtStatComposite().getRtStats().stream() .anyMatch(longContainer -> longContainer.specifyType(OP_TYPE_NOTIFY.getType()))); Optional<LongContainer<? extends Number>> subContainer = statComposite.getRtStatComposite().getRtStats().stream() .filter(longContainer -> longContainer.specifyType(OP_TYPE_NOTIFY.getType())) .findFirst(); subContainer.ifPresent(v -> Assertions.assertEquals( 10L, v.get(new ApplicationMetric(applicationModel)).longValue())); } @Test @SuppressWarnings("rawtypes") void testCalcServiceKeyRt() { String serviceKey = "TestService"; String registryOpType = OP_TYPE_REGISTER_SERVICE.getType(); Long responseTime1 = 100L; Long responseTime2 = 200L; statComposite.calcServiceKeyRt(serviceKey, registryOpType, responseTime1); statComposite.calcServiceKeyRt(serviceKey, registryOpType, responseTime2); List<MetricSample> exportedRtMetrics = statComposite.export(MetricsCategory.RT); GaugeMetricSample minSample = (GaugeMetricSample) exportedRtMetrics.stream() .filter(sample -> sample.getTags().containsValue(applicationName)) .filter(sample -> sample.getName().equals(METRIC_RT_MIN.getNameByType("register.service"))) .findFirst() .orElse(null); GaugeMetricSample maxSample = (GaugeMetricSample) exportedRtMetrics.stream() .filter(sample -> sample.getTags().containsValue(applicationName)) .filter(sample -> sample.getName().equals(METRIC_RT_MAX.getNameByType("register.service"))) .findFirst() .orElse(null); GaugeMetricSample avgSample = (GaugeMetricSample) exportedRtMetrics.stream() .filter(sample -> sample.getTags().containsValue(applicationName)) .filter(sample -> sample.getName().equals(METRIC_RT_AVG.getNameByType("register.service"))) .findFirst() .orElse(null); Assertions.assertNotNull(minSample); Assertions.assertNotNull(maxSample); Assertions.assertNotNull(avgSample); Assertions.assertEquals(responseTime1, minSample.applyAsLong()); Assertions.assertEquals(responseTime2, maxSample.applyAsLong()); Assertions.assertEquals((responseTime1 + responseTime2) / 2, avgSample.applyAsLong()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/RegistryMetricsConstants.java
dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/RegistryMetricsConstants.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.registry; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper; import org.apache.dubbo.metrics.model.key.MetricsLevel; import org.apache.dubbo.metrics.model.key.MetricsPlaceValue; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.apache.dubbo.metrics.model.key.MetricsKey.DIRECTORY_METRIC_NUM_ALL; import static org.apache.dubbo.metrics.model.key.MetricsKey.DIRECTORY_METRIC_NUM_DISABLE; import static org.apache.dubbo.metrics.model.key.MetricsKey.DIRECTORY_METRIC_NUM_TO_RECONNECT; import static org.apache.dubbo.metrics.model.key.MetricsKey.DIRECTORY_METRIC_NUM_VALID; import static org.apache.dubbo.metrics.model.key.MetricsKey.NOTIFY_METRIC_NUM_LAST; import static org.apache.dubbo.metrics.model.key.MetricsKey.NOTIFY_METRIC_REQUESTS; import static org.apache.dubbo.metrics.model.key.MetricsKey.REGISTER_METRIC_REQUESTS; import static org.apache.dubbo.metrics.model.key.MetricsKey.REGISTER_METRIC_REQUESTS_FAILED; import static org.apache.dubbo.metrics.model.key.MetricsKey.REGISTER_METRIC_REQUESTS_SUCCEED; import static org.apache.dubbo.metrics.model.key.MetricsKey.SERVICE_REGISTER_METRIC_REQUESTS; import static org.apache.dubbo.metrics.model.key.MetricsKey.SERVICE_REGISTER_METRIC_REQUESTS_FAILED; import static org.apache.dubbo.metrics.model.key.MetricsKey.SERVICE_REGISTER_METRIC_REQUESTS_SUCCEED; import static org.apache.dubbo.metrics.model.key.MetricsKey.SERVICE_SUBSCRIBE_METRIC_NUM; import static org.apache.dubbo.metrics.model.key.MetricsKey.SERVICE_SUBSCRIBE_METRIC_NUM_FAILED; import static org.apache.dubbo.metrics.model.key.MetricsKey.SERVICE_SUBSCRIBE_METRIC_NUM_SUCCEED; import static org.apache.dubbo.metrics.model.key.MetricsKey.SUBSCRIBE_METRIC_NUM; import static org.apache.dubbo.metrics.model.key.MetricsKey.SUBSCRIBE_METRIC_NUM_FAILED; import static org.apache.dubbo.metrics.model.key.MetricsKey.SUBSCRIBE_METRIC_NUM_SUCCEED; public interface RegistryMetricsConstants { String ATTACHMENT_REGISTRY_KEY = "registryKey"; String ATTACHMENT_REGISTRY_SINGLE_KEY = "registrySingleKey"; MetricsPlaceValue OP_TYPE_REGISTER = MetricsPlaceValue.of("register", MetricsLevel.APP); MetricsPlaceValue OP_TYPE_SUBSCRIBE = MetricsPlaceValue.of("subscribe", MetricsLevel.APP); MetricsPlaceValue OP_TYPE_NOTIFY = MetricsPlaceValue.of("notify", MetricsLevel.APP); MetricsPlaceValue OP_TYPE_DIRECTORY = MetricsPlaceValue.of("directory", MetricsLevel.APP); MetricsPlaceValue OP_TYPE_REGISTER_SERVICE = MetricsPlaceValue.of("register.service", MetricsLevel.REGISTRY); MetricsPlaceValue OP_TYPE_SUBSCRIBE_SERVICE = MetricsPlaceValue.of("subscribe.service", MetricsLevel.SERVICE); // App-level List<MetricsKey> APP_LEVEL_KEYS = Collections.singletonList(NOTIFY_METRIC_REQUESTS); // Registry-level List<MetricsKey> REGISTER_LEVEL_KEYS = Arrays.asList( REGISTER_METRIC_REQUESTS, REGISTER_METRIC_REQUESTS_SUCCEED, REGISTER_METRIC_REQUESTS_FAILED, SUBSCRIBE_METRIC_NUM, SUBSCRIBE_METRIC_NUM_SUCCEED, SUBSCRIBE_METRIC_NUM_FAILED); // Service-level List<MetricsKeyWrapper> SERVICE_LEVEL_KEYS = Arrays.asList( new MetricsKeyWrapper(NOTIFY_METRIC_NUM_LAST, OP_TYPE_NOTIFY), new MetricsKeyWrapper(SERVICE_REGISTER_METRIC_REQUESTS, OP_TYPE_REGISTER_SERVICE), new MetricsKeyWrapper(SERVICE_REGISTER_METRIC_REQUESTS_SUCCEED, OP_TYPE_REGISTER_SERVICE), new MetricsKeyWrapper(SERVICE_REGISTER_METRIC_REQUESTS_FAILED, OP_TYPE_REGISTER_SERVICE), new MetricsKeyWrapper(SERVICE_SUBSCRIBE_METRIC_NUM, OP_TYPE_SUBSCRIBE_SERVICE), new MetricsKeyWrapper(SERVICE_SUBSCRIBE_METRIC_NUM_SUCCEED, OP_TYPE_SUBSCRIBE_SERVICE), new MetricsKeyWrapper(SERVICE_SUBSCRIBE_METRIC_NUM_FAILED, OP_TYPE_SUBSCRIBE_SERVICE), new MetricsKeyWrapper(DIRECTORY_METRIC_NUM_VALID, OP_TYPE_DIRECTORY), new MetricsKeyWrapper(DIRECTORY_METRIC_NUM_TO_RECONNECT, OP_TYPE_DIRECTORY), new MetricsKeyWrapper(DIRECTORY_METRIC_NUM_DISABLE, OP_TYPE_DIRECTORY), new MetricsKeyWrapper(DIRECTORY_METRIC_NUM_ALL, OP_TYPE_DIRECTORY)); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/collector/RegistryMetricsCollector.java
dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/collector/RegistryMetricsCollector.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.registry.collector; import org.apache.dubbo.common.constants.RegistryConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.metrics.collector.CombMetricsCollector; import org.apache.dubbo.metrics.collector.MetricsCollector; import org.apache.dubbo.metrics.data.ApplicationStatComposite; import org.apache.dubbo.metrics.data.BaseStatComposite; import org.apache.dubbo.metrics.data.RtStatComposite; import org.apache.dubbo.metrics.data.ServiceStatComposite; import org.apache.dubbo.metrics.model.ApplicationMetric; import org.apache.dubbo.metrics.model.MetricsCategory; import org.apache.dubbo.metrics.model.ServiceKeyMetric; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper; import org.apache.dubbo.metrics.model.sample.MetricSample; import org.apache.dubbo.metrics.registry.RegistryMetricsConstants; import org.apache.dubbo.metrics.registry.event.RegistryEvent; import org.apache.dubbo.metrics.registry.event.RegistrySubDispatcher; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.OP_TYPE_NOTIFY; import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.OP_TYPE_REGISTER; import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.OP_TYPE_REGISTER_SERVICE; import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.OP_TYPE_SUBSCRIBE; import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.OP_TYPE_SUBSCRIBE_SERVICE; /** * Registry implementation of {@link MetricsCollector} */ @Activate public class RegistryMetricsCollector extends CombMetricsCollector<RegistryEvent> { private Boolean collectEnabled = null; private final ApplicationModel applicationModel; private final RegistryStatComposite internalStat; public RegistryMetricsCollector(ApplicationModel applicationModel) { super(new BaseStatComposite(applicationModel) { @Override protected void init(ApplicationStatComposite applicationStatComposite) { super.init(applicationStatComposite); applicationStatComposite.init(RegistryMetricsConstants.APP_LEVEL_KEYS); } @Override protected void init(ServiceStatComposite serviceStatComposite) { super.init(serviceStatComposite); serviceStatComposite.initWrapper(RegistryMetricsConstants.SERVICE_LEVEL_KEYS); } @Override protected void init(RtStatComposite rtStatComposite) { super.init(rtStatComposite); rtStatComposite.init( OP_TYPE_REGISTER, OP_TYPE_SUBSCRIBE, OP_TYPE_NOTIFY, OP_TYPE_REGISTER_SERVICE, OP_TYPE_SUBSCRIBE_SERVICE); } }); super.setEventMulticaster(new RegistrySubDispatcher(this)); internalStat = new RegistryStatComposite(applicationModel); this.applicationModel = applicationModel; } public void setCollectEnabled(Boolean collectEnabled) { if (collectEnabled != null) { this.collectEnabled = collectEnabled; } } @Override public boolean isCollectEnabled() { if (collectEnabled == null) { ConfigManager configManager = applicationModel.getApplicationConfigManager(); configManager.getMetrics().ifPresent(metricsConfig -> setCollectEnabled(metricsConfig.getEnableRegistry())); } return Optional.ofNullable(collectEnabled).orElse(false); } @Override public List<MetricSample> collect() { List<MetricSample> list = new ArrayList<>(); if (!isCollectEnabled()) { return list; } list.addAll(super.export(MetricsCategory.REGISTRY)); list.addAll(internalStat.export(MetricsCategory.REGISTRY)); return list; } public void incrMetricsNum(MetricsKey metricsKey, List<String> registryClusterNames) { registryClusterNames.forEach(name -> internalStat.incrMetricsNum(metricsKey, name)); } public void incrRegisterFinishNum( MetricsKey metricsKey, String registryOpType, List<String> registryClusterNames, Long responseTime) { registryClusterNames.forEach(name -> { ApplicationMetric applicationMetric = new ApplicationMetric(applicationModel); applicationMetric.setExtraInfo( Collections.singletonMap(RegistryConstants.REGISTRY_CLUSTER_KEY.toLowerCase(), name)); internalStat.incrMetricsNum(metricsKey, name); getStats().getRtStatComposite().calcServiceKeyRt(registryOpType, responseTime, applicationMetric); }); } public void incrServiceRegisterNum( MetricsKeyWrapper wrapper, String serviceKey, List<String> registryClusterNames, int size) { registryClusterNames.forEach(name -> stats.incrementServiceKey( wrapper, serviceKey, Collections.singletonMap(RegistryConstants.REGISTRY_CLUSTER_KEY.toLowerCase(), name), size)); } public void incrServiceRegisterFinishNum( MetricsKeyWrapper wrapper, String serviceKey, List<String> registryClusterNames, int size, Long responseTime) { registryClusterNames.forEach(name -> { Map<String, String> extraInfo = Collections.singletonMap(RegistryConstants.REGISTRY_CLUSTER_KEY.toLowerCase(), name); ServiceKeyMetric serviceKeyMetric = new ServiceKeyMetric(applicationModel, serviceKey); serviceKeyMetric.setExtraInfo(extraInfo); stats.incrementServiceKey(wrapper, serviceKey, extraInfo, size); getStats().getRtStatComposite().calcServiceKeyRt(wrapper.getType(), responseTime, serviceKeyMetric); }); } public void setNum(MetricsKeyWrapper metricsKey, String serviceKey, int num, Map<String, String> attachments) { this.stats.setServiceKey(metricsKey, serviceKey, num, attachments); } @Override public boolean calSamplesChanged() { // Should ensure that all the stat's samplesChanged have been compareAndSet, and cannot flip the `or` logic boolean changed = stats.calSamplesChanged(); changed = internalStat.calSamplesChanged() || changed; return changed; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/collector/RegistryStatComposite.java
dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/collector/RegistryStatComposite.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.registry.collector; import org.apache.dubbo.common.constants.RegistryConstants; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import org.apache.dubbo.metrics.model.ApplicationMetric; import org.apache.dubbo.metrics.model.MetricsCategory; import org.apache.dubbo.metrics.model.MetricsSupport; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.model.sample.GaugeMetricSample; import org.apache.dubbo.metrics.model.sample.MetricSample; import org.apache.dubbo.metrics.registry.RegistryMetricsConstants; import org.apache.dubbo.metrics.report.AbstractMetricsExport; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import static org.apache.dubbo.metrics.MetricsConstants.SELF_INCREMENT_SIZE; public class RegistryStatComposite extends AbstractMetricsExport { private final ConcurrentHashMap<MetricsKey, ConcurrentHashMap<ApplicationMetric, AtomicLong>> appStats = new ConcurrentHashMap<>(); private final AtomicBoolean samplesChanged = new AtomicBoolean(true); public RegistryStatComposite(ApplicationModel applicationModel) { super(applicationModel); init(RegistryMetricsConstants.REGISTER_LEVEL_KEYS); } public void init(List<MetricsKey> appKeys) { if (CollectionUtils.isEmpty(appKeys)) { return; } appKeys.forEach(appKey -> { appStats.put(appKey, new ConcurrentHashMap<>()); }); samplesChanged.set(true); } @Override public List<MetricSample> export(MetricsCategory category) { List<MetricSample> list = new ArrayList<>(); for (MetricsKey metricsKey : appStats.keySet()) { Map<ApplicationMetric, AtomicLong> stringAtomicLongMap = appStats.get(metricsKey); for (ApplicationMetric registerKeyMetric : stringAtomicLongMap.keySet()) { list.add(new GaugeMetricSample<>( metricsKey, registerKeyMetric.getTags(), category, stringAtomicLongMap, value -> value.get( registerKeyMetric) .get())); } } return list; } public void incrMetricsNum(MetricsKey metricsKey, String name) { if (!appStats.containsKey(metricsKey)) { return; } ApplicationMetric applicationMetric = new ApplicationMetric(getApplicationModel()); applicationMetric.setExtraInfo( Collections.singletonMap(RegistryConstants.REGISTRY_CLUSTER_KEY.toLowerCase(), name)); ConcurrentHashMap<ApplicationMetric, AtomicLong> stats = appStats.get(metricsKey); AtomicLong metrics = stats.get(applicationMetric); if (metrics == null) { metrics = ConcurrentHashMapUtils.computeIfAbsent(stats, applicationMetric, k -> new AtomicLong(0L)); samplesChanged.set(true); } metrics.getAndAdd(SELF_INCREMENT_SIZE); MetricsSupport.fillZero(appStats); } public ConcurrentHashMap<MetricsKey, ConcurrentHashMap<ApplicationMetric, AtomicLong>> getAppStats() { return appStats; } @Override public boolean calSamplesChanged() { // CAS to get and reset the flag in an atomic operation return samplesChanged.compareAndSet(true, false); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistrySpecListener.java
dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistrySpecListener.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.metrics.registry.event; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.metrics.collector.CombMetricsCollector; import org.apache.dubbo.metrics.event.MetricsEvent; import org.apache.dubbo.metrics.listener.AbstractMetricsKeyListener; import org.apache.dubbo.metrics.listener.MetricsApplicationListener; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper; import org.apache.dubbo.metrics.model.key.MetricsPlaceValue; import org.apache.dubbo.metrics.registry.RegistryMetricsConstants; import org.apache.dubbo.metrics.registry.collector.RegistryMetricsCollector; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import static org.apache.dubbo.metrics.MetricsConstants.ATTACHMENT_DIRECTORY_MAP; import static org.apache.dubbo.metrics.MetricsConstants.ATTACHMENT_KEY_LAST_NUM_MAP; import static org.apache.dubbo.metrics.MetricsConstants.ATTACHMENT_KEY_SERVICE; import static org.apache.dubbo.metrics.MetricsConstants.ATTACHMENT_KEY_SIZE; import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.OP_TYPE_DIRECTORY; import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.OP_TYPE_NOTIFY; import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.OP_TYPE_REGISTER; /** * Different from the general-purpose listener constructor {@link MetricsApplicationListener} , * it provides registry custom listeners */ public class RegistrySpecListener { /** * Perform auto-increment on the monitored key, * Can use a custom listener instead of this generic operation */ public static AbstractMetricsKeyListener onPost(MetricsKey metricsKey, CombMetricsCollector<?> collector) { return AbstractMetricsKeyListener.onEvent( metricsKey, event -> ((RegistryMetricsCollector) collector).incrMetricsNum(metricsKey, getRgs(event))); } public static AbstractMetricsKeyListener onFinish(MetricsKey metricsKey, CombMetricsCollector<?> collector) { return AbstractMetricsKeyListener.onFinish(metricsKey, event -> ((RegistryMetricsCollector) collector) .incrRegisterFinishNum( metricsKey, OP_TYPE_REGISTER.getType(), getRgs(event), event.getTimePair().calc())); } public static AbstractMetricsKeyListener onError(MetricsKey metricsKey, CombMetricsCollector<?> collector) { return AbstractMetricsKeyListener.onError(metricsKey, event -> ((RegistryMetricsCollector) collector) .incrRegisterFinishNum( metricsKey, OP_TYPE_REGISTER.getType(), getRgs(event), event.getTimePair().calc())); } public static AbstractMetricsKeyListener onPostOfService( MetricsKey metricsKey, MetricsPlaceValue placeType, CombMetricsCollector<?> collector) { return AbstractMetricsKeyListener.onEvent(metricsKey, event -> ((RegistryMetricsCollector) collector) .incrServiceRegisterNum( new MetricsKeyWrapper(metricsKey, placeType), getServiceKey(event), getRgs(event), getSize(event))); } public static AbstractMetricsKeyListener onFinishOfService( MetricsKey metricsKey, MetricsPlaceValue placeType, CombMetricsCollector<?> collector) { return AbstractMetricsKeyListener.onFinish(metricsKey, event -> ((RegistryMetricsCollector) collector) .incrServiceRegisterFinishNum( new MetricsKeyWrapper(metricsKey, placeType), getServiceKey(event), getRgs(event), getSize(event), event.getTimePair().calc())); } public static AbstractMetricsKeyListener onErrorOfService( MetricsKey metricsKey, MetricsPlaceValue placeType, CombMetricsCollector<?> collector) { return AbstractMetricsKeyListener.onError(metricsKey, event -> ((RegistryMetricsCollector) collector) .incrServiceRegisterFinishNum( new MetricsKeyWrapper(metricsKey, placeType), getServiceKey(event), getRgs(event), getSize(event), event.getTimePair().calc())); } /** * Every time an event is triggered, multiple serviceKey related to notify are increment */ public static AbstractMetricsKeyListener onFinishOfNotify( MetricsKey metricsKey, MetricsPlaceValue placeType, CombMetricsCollector<?> collector) { return AbstractMetricsKeyListener.onFinish(metricsKey, event -> { collector.addServiceRt( event.appName(), placeType.getType(), event.getTimePair().calc()); Map<String, Integer> lastNumMap = Collections.unmodifiableMap(event.getAttachmentValue(ATTACHMENT_KEY_LAST_NUM_MAP)); lastNumMap.forEach((k, v) -> collector.setNum(new MetricsKeyWrapper(metricsKey, OP_TYPE_NOTIFY), k, v)); }); } /** * Every time an event is triggered, multiple fixed key related to directory are increment, which has nothing to do with the monitored key */ public static AbstractMetricsKeyListener onPostOfDirectory( MetricsKey metricsKey, CombMetricsCollector<?> collector) { return AbstractMetricsKeyListener.onEvent(metricsKey, event -> { Map<MetricsKey, Map<String, Integer>> summaryMap = event.getAttachmentValue(ATTACHMENT_DIRECTORY_MAP); Map<String, String> otherAttachments = new HashMap<>(); for (Map.Entry<String, Object> entry : event.getAttachments().entrySet()) { if (entry.getValue() instanceof String) { otherAttachments.put(entry.getKey().toLowerCase(Locale.ROOT), (String) entry.getValue()); } } summaryMap.forEach((summaryKey, map) -> map.forEach((k, v) -> { if (CollectionUtils.isEmptyMap(otherAttachments)) { collector.setNum(new MetricsKeyWrapper(summaryKey, OP_TYPE_DIRECTORY), k, v); } else { ((RegistryMetricsCollector) collector) .setNum(new MetricsKeyWrapper(summaryKey, OP_TYPE_DIRECTORY), k, v, otherAttachments); } })); }); } /** * Get the number of multiple registries */ public static List<String> getRgs(MetricsEvent event) { return event.getAttachmentValue(RegistryMetricsConstants.ATTACHMENT_REGISTRY_KEY); } /** * Get the exposed number of the protocol */ public static int getSize(MetricsEvent event) { return event.getAttachmentValue(ATTACHMENT_KEY_SIZE); } public static String getServiceKey(MetricsEvent event) { return event.getAttachmentValue(ATTACHMENT_KEY_SERVICE); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false