This is an automated email from the ASF dual-hosted git repository.

albumenj pushed a commit to branch 3.2
in repository https://gitbox.apache.org/repos/asf/dubbo.git


The following commit(s) were added to refs/heads/3.2 by this push:
     new 12febcfbf5 adding the reject task indicator for thread pool burying 
point(#11706) (#11916)
12febcfbf5 is described below

commit 12febcfbf505c926070686a4d4318812b1ed1938
Author: robin977 <[email protected]>
AuthorDate: Sat Mar 25 15:42:33 2023 +0800

    adding the reject task indicator for thread pool burying point(#11706) 
(#11916)
    
    * adding the reject task indicator for thread pool burying point(#11706)
    
    * adding the reject task indicator for thread pool burying point(#11706)
    
    * dd switch configuration for thread pool indicator burying point (#11788)
    
    * revert code (add switch configuration for thread pool indicator burying 
point) (#11788)
    
    ---------
    
    Co-authored-by: robin <[email protected]>
---
 .../org/apache/dubbo/common/utils/NetUtils.java    |  11 +-
 .../org/apache/dubbo/metrics/model/MetricsKey.java |   1 +
 .../metrics/model/ThreadPoolRejectMetric.java      |  82 +++++++++++
 .../metrics/collector/DefaultMetricsCollector.java |   7 +-
 .../sample/MetricThreadPoolExhaustedListener.java  |  43 ++++++
 .../collector/sample/ThreadPoolMetricsSampler.java |  11 +-
 .../sample/ThreadRejectMetricsCountSampler.java    |  84 +++++++++++
 .../PrometheusMetricsThreadPoolTest.java           | 163 +++++++++++++++++++++
 8 files changed, 395 insertions(+), 7 deletions(-)

diff --git 
a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/NetUtils.java 
b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/NetUtils.java
index 58f902f599..d33fcea5b0 100644
--- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/NetUtils.java
+++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/NetUtils.java
@@ -23,7 +23,6 @@ import org.apache.dubbo.common.logger.Logger;
 import org.apache.dubbo.common.logger.LoggerFactory;
 import org.apache.dubbo.common.logger.support.FailsafeLogger;
 import org.apache.dubbo.rpc.model.ScopeModel;
-
 import java.io.IOException;
 import java.net.Inet4Address;
 import java.net.Inet6Address;
@@ -251,6 +250,8 @@ public final class NetUtils {
 
     private static volatile String HOST_ADDRESS;
 
+    private static volatile String HOST_NAME;
+
     private static volatile String HOST_ADDRESS_V6;
 
     public static String getLocalHost() {
@@ -585,11 +586,15 @@ public final class NetUtils {
     }
 
     public static String getLocalHostName() {
+        if (HOST_NAME != null) {
+            return HOST_NAME;
+        }
         try {
-            return InetAddress.getLocalHost().getHostName();
+            HOST_NAME= InetAddress.getLocalHost().getHostName();
         } catch (UnknownHostException e) {
-            return getLocalAddress().getHostName();
+            HOST_NAME= 
Optional.ofNullable(getLocalAddress()).map(k->k.getHostName()).orElse(null);
         }
+        return HOST_NAME;
     }
 
     /**
diff --git 
a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsKey.java
 
b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsKey.java
index fbf3a5e1fd..2592f706cd 100644
--- 
a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsKey.java
+++ 
b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsKey.java
@@ -81,6 +81,7 @@ public enum MetricsKey {
     THREAD_POOL_ACTIVE_SIZE("dubbo.thread.pool.active.size", "Thread Pool 
Active Size"),
     THREAD_POOL_THREAD_COUNT("dubbo.thread.pool.thread.count", "Thread Pool 
Thread Count"),
     THREAD_POOL_QUEUE_SIZE("dubbo.thread.pool.queue.size", "Thread Pool Queue 
Size"),
+    THREAD_POOL_THREAD_REJECT_COUNT("dubbo.thread.pool.reject.thread.count", 
"Thread Pool Reject Thread Count"),
 
     // metadata push metrics key
     METADATA_PUSH_METRIC_NUM("dubbo.metadata.push.num.total", "Total Push 
Num"),
diff --git 
a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ThreadPoolRejectMetric.java
 
b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ThreadPoolRejectMetric.java
new file mode 100644
index 0000000000..8706070847
--- /dev/null
+++ 
b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ThreadPoolRejectMetric.java
@@ -0,0 +1,82 @@
+/*
+ * 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.model;
+
+import org.apache.dubbo.common.utils.ConfigUtils;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
+import static org.apache.dubbo.common.utils.NetUtils.getLocalHost;
+import static org.apache.dubbo.common.utils.NetUtils.getLocalHostName;
+import static org.apache.dubbo.common.constants.MetricsConstants.TAG_PID;
+import static 
org.apache.dubbo.common.constants.MetricsConstants.TAG_APPLICATION_NAME;
+import static 
org.apache.dubbo.common.constants.MetricsConstants.TAG_THREAD_NAME;
+import static org.apache.dubbo.common.constants.MetricsConstants.TAG_HOSTNAME;
+import static org.apache.dubbo.common.constants.MetricsConstants.TAG_IP;
+
+public class ThreadPoolRejectMetric implements Metric{
+    private String applicationName;
+
+    private String threadPoolName;
+
+    public ThreadPoolRejectMetric(String applicationName, String 
threadPoolName) {
+        this.applicationName = applicationName;
+        this.threadPoolName = threadPoolName;
+    }
+
+    public String getThreadPoolName() {
+        return threadPoolName;
+    }
+
+    public void setThreadPoolName(String threadPoolName) {
+        this.threadPoolName = threadPoolName;
+    }
+
+    public String getApplicationName() {
+        return applicationName;
+    }
+
+    public void setApplicationName(String applicationName) {
+        this.applicationName = applicationName;
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) return true;
+        if (o == null || getClass() != o.getClass()) return false;
+        ThreadPoolRejectMetric that = (ThreadPoolRejectMetric) o;
+        return Objects.equals(applicationName, that.applicationName) &&
+            Objects.equals(threadPoolName, that.threadPoolName);
+    }
+
+    @Override
+    public int hashCode() {
+        return Objects.hash(applicationName, threadPoolName);
+    }
+
+    public Map<String, String> getTags() {
+        Map<String, String> tags = new HashMap<>();
+        tags.put(TAG_IP, getLocalHost());
+        tags.put(TAG_PID, ConfigUtils.getPid()+"");
+        tags.put(TAG_HOSTNAME, getLocalHostName());
+        tags.put(TAG_APPLICATION_NAME, applicationName);
+        tags.put(TAG_THREAD_NAME, threadPoolName);
+        return tags;
+    }
+
+}
diff --git 
a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/DefaultMetricsCollector.java
 
b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/DefaultMetricsCollector.java
index 059e4abca7..56a0d5f9db 100644
--- 
a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/DefaultMetricsCollector.java
+++ 
b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/DefaultMetricsCollector.java
@@ -16,7 +16,6 @@
  */
 
 package org.apache.dubbo.metrics.collector;
-
 import org.apache.dubbo.metrics.collector.sample.MethodMetricsSampler;
 import org.apache.dubbo.metrics.collector.sample.MetricsCountSampleConfigurer;
 import org.apache.dubbo.metrics.collector.sample.MetricsSampler;
@@ -29,11 +28,9 @@ import org.apache.dubbo.metrics.model.ApplicationMetric;
 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.atomic.AtomicLong;
-
 import static org.apache.dubbo.metrics.model.MetricsCategory.APPLICATION;
 import static 
org.apache.dubbo.metrics.model.MetricsKey.APPLICATION_METRIC_INFO;
 
@@ -43,6 +40,7 @@ import static 
org.apache.dubbo.metrics.model.MetricsKey.APPLICATION_METRIC_INFO;
 public class DefaultMetricsCollector implements MetricsCollector {
 
     private boolean collectEnabled = false;
+
     private final SimpleMetricsEventMulticaster eventMulticaster;
     private final MethodMetricsSampler methodSampler = new 
MethodMetricsSampler(this);
     private final ThreadPoolMetricsSampler threadPoolSampler = new 
ThreadPoolMetricsSampler(this);
@@ -57,6 +55,9 @@ public class DefaultMetricsCollector implements 
MetricsCollector {
         samplers.add(threadPoolSampler);
     }
 
+    public void addSampler(MetricsSampler sampler){
+        samplers.add(sampler);
+    }
     public void setApplicationName(String applicationName) {
         this.applicationName = applicationName;
     }
diff --git 
a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/MetricThreadPoolExhaustedListener.java
 
b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/MetricThreadPoolExhaustedListener.java
new file mode 100644
index 0000000000..2a77b70542
--- /dev/null
+++ 
b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/MetricThreadPoolExhaustedListener.java
@@ -0,0 +1,43 @@
+/*
+ * 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;
+    }
+    @Override
+    public void onEvent(ThreadPoolExhaustedEvent event) {
+        threadRejectMetricsCountSampler.addMetricName(threadPoolExecutorName);
+        
threadRejectMetricsCountSampler.incOnEvent(threadPoolExecutorName,threadPoolExecutorName);
+    }
+}
diff --git 
a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/ThreadPoolMetricsSampler.java
 
b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/ThreadPoolMetricsSampler.java
index adc4118d4f..d3f5eb6a1d 100644
--- 
a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/ThreadPoolMetricsSampler.java
+++ 
b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/ThreadPoolMetricsSampler.java
@@ -20,6 +20,7 @@ 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.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.MetricsKey;
@@ -122,10 +123,18 @@ public class ThreadPoolMetricsSampler implements 
MetricsSampler {
                     this.addExecutors(CLIENT_THREAD_POOL_NAME + "-" + 
entry.getKey(), executor);
                 }
             }
+
+            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);
+                }
+            });
         }
         if (this.frameworkExecutorRepository != null) {
             this.addExecutors("sharedExecutor", 
frameworkExecutorRepository.getSharedExecutor());
-           }
+        }
     }
 
 }
diff --git 
a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/ThreadRejectMetricsCountSampler.java
 
b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/ThreadRejectMetricsCountSampler.java
new file mode 100644
index 0000000000..5edc6dafe2
--- /dev/null
+++ 
b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/ThreadRejectMetricsCountSampler.java
@@ -0,0 +1,84 @@
+/*
+ * 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.MetricsKey;
+import org.apache.dubbo.metrics.model.ThreadPoolRejectMetric;
+import org.apache.dubbo.metrics.model.sample.GaugeMetricSample;
+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.AtomicLong;
+import java.util.function.ToDoubleFunction;
+import static org.apache.dubbo.metrics.model.MetricsCategory.THREAD_POOL;
+
+public class ThreadRejectMetricsCountSampler extends 
SimpleMetricsCountSampler<String, String, ThreadPoolRejectMetric> {
+
+    private final DefaultMetricsCollector collector;
+
+    private final Set<String> metricNames = new ConcurrentHashSet<>();
+    public ThreadRejectMetricsCountSampler(DefaultMetricsCollector collector) {
+        this.collector = collector;
+        this.collector.addSampler(this);
+    }
+
+    public void addMetricName(String name){
+        this.metricNames.add(name);
+    }
+
+    @Override
+    public List<MetricSample> sample() {
+        List<MetricSample> metricSamples = new ArrayList<>();
+        metricNames.stream().forEach(name->collect(metricSamples,name));
+        return metricSamples;
+    }
+
+
+    private void collect(List<MetricSample> list, String metricName) {
+        count(list, metricName, MetricsKey.THREAD_POOL_THREAD_REJECT_COUNT);
+    }
+
+    private <T extends Metric> void count(List<MetricSample> list, String 
metricName, MetricsKey metricsKey) {
+        getCount(metricName).filter(e -> !e.isEmpty())
+            .ifPresent(map -> map.forEach((k, v) ->
+                list.add(getGaugeMetricSample(metricsKey, k, THREAD_POOL, v, 
AtomicLong::get))));
+    }
+
+    private <T> GaugeMetricSample<T> getGaugeMetricSample(MetricsKey 
metricsKey,
+                                                          
ThreadPoolRejectMetric methodMetric,
+                                                          MetricsCategory 
metricsCategory,
+                                                          T value,
+                                                          ToDoubleFunction<T> 
apply) {
+        return new GaugeMetricSample<>(
+            metricsKey.getNameByType(methodMetric.getThreadPoolName()),
+            metricsKey.getDescription(),
+            methodMetric.getTags(),
+            metricsCategory,
+            value,
+            apply);
+    }
+
+    @Override
+    protected void countConfigure(MetricsCountSampleConfigurer<String, String, 
ThreadPoolRejectMetric> sampleConfigure) {
+        sampleConfigure.configureMetrics(configure -> new 
ThreadPoolRejectMetric(collector.getApplicationName(),configure.getSource()));
+    }
+}
diff --git 
a/dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsThreadPoolTest.java
 
b/dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsThreadPoolTest.java
new file mode 100644
index 0000000000..bb242ae35c
--- /dev/null
+++ 
b/dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsThreadPoolTest.java
@@ -0,0 +1,163 @@
+/*
+ * 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 com.sun.net.httpserver.HttpServer;
+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 org.apache.dubbo.rpc.model.FrameworkModel;
+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 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 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_THREAD_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.utils.NetUtils.getLocalHost;
+import static org.apache.dubbo.common.utils.NetUtils.getLocalHostName;
+
+
+public class PrometheusMetricsThreadPoolTest {
+
+    private FrameworkModel   frameworkModel;
+
+    private ApplicationModel applicationModel;
+
+    private MetricsConfig metricsConfig;
+
+    DefaultMetricsCollector metricsCollector;
+
+    @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);
+        frameworkModel = FrameworkModel.defaultModel();
+        metricsCollector = 
frameworkModel.getBeanFactory().getOrRegisterBean(DefaultMetricsCollector.class);
+    }
+
+    @AfterEach
+    public void teardown() {
+        applicationModel.destroy();
+    }
+
+    @Test
+    void testExporterThreadpoolName() {
+        int port = 30899;
+        PrometheusConfig prometheusConfig = new PrometheusConfig();
+        PrometheusConfig.Exporter exporter = new PrometheusConfig.Exporter();
+        exporter.setMetricsPort(port);
+        exporter.setEnabled(true);
+        exporter.setMetricsPath("/metrics");
+
+        prometheusConfig.setExporter(exporter);
+        metricsConfig.setPrometheus(prometheusConfig);
+        metricsConfig.setEnableJvmMetrics(false);
+        metricsCollector.setCollectEnabled(true);
+        metricsCollector.collectApplication(applicationModel);
+        PrometheusMetricsReporter reporter = new 
PrometheusMetricsReporter(metricsConfig.toUrl(), applicationModel);
+        reporter.init();
+        exportHttpServer(reporter,port);
+        try {
+            Thread.sleep(5000);
+        } catch (InterruptedException e) {
+            throw new RuntimeException(e);
+        }
+        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 {
+            HttpServer prometheusExporterHttpServer = HttpServer.create(new 
InetSocketAddress(port), 0);
+            prometheusExporterHttpServer.createContext("/metrics", 
httpExchange -> {
+                reporter.refreshData();
+                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);
+        }
+    }
+
+
+
+    @Test
+    @SuppressWarnings("rawtypes")
+    void testThreadPoolRejectMetrics() {
+        DefaultMetricsCollector collector = new DefaultMetricsCollector();
+        collector.setCollectEnabled(true);
+        collector.setApplicationName(applicationModel.getApplicationName());
+        String threadPoolExecutorName="DubboServerHandler-20816";
+        ThreadRejectMetricsCountSampler threadRejectMetricsCountSampler=new 
ThreadRejectMetricsCountSampler(collector);
+        
threadRejectMetricsCountSampler.incOnEvent(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);
+        }
+    }
+
+}

Reply via email to