index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata
Create_ds/dubbo/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(true); } @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(); } }
8,000
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata
Create_ds/dubbo/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); } }
8,001
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata
Create_ds/dubbo/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; } }
8,002
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo
Create_ds/dubbo/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() {} }
8,003
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo
Create_ds/dubbo/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()); } }
8,004
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/metrics
Create_ds/dubbo/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.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")); } @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); } }
8,005
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/metrics/model
Create_ds/dubbo/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()); } }
8,006
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/metrics/model
Create_ds/dubbo/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); } }
8,007
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/metrics
Create_ds/dubbo/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); } }
8,008
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics
Create_ds/dubbo/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); 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 System.out.println(Math.abs(1 - p95 / manualP95)); 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; } } }
8,009
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics
Create_ds/dubbo/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.config.ApplicationConfig; 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"); applicationModel.getApplicationConfigManager().setApplication(config); 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); 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) = 8 Assertions.assertEquals(8, metricSamples.size()); 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) = 5 Assertions.assertEquals(10, 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); } }
8,010
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics
Create_ds/dubbo/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()); } } } } }
8,011
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector
Create_ds/dubbo/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.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.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.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(3, executors.size()); Assertions.assertTrue(executors.containsKey("DubboServerHandler-server1")); Assertions.assertTrue(executors.containsKey("DubboClientHandler-client1")); Assertions.assertTrue(executors.containsKey("sharedExecutor")); serverExecutor.shutdown(); clientExecutor.shutdown(); } }
8,012
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics
Create_ds/dubbo/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.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(); 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)); } @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)); } } }
8,013
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/observation/ObservationReceiverFilterTest.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.observation; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.AppResponse; 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.ApplicationModel; import io.micrometer.common.KeyValues; import io.micrometer.core.tck.MeterRegistryAssert; import io.micrometer.tracing.Span; import io.micrometer.tracing.Tracer; import io.micrometer.tracing.test.simple.SpansAssert; import org.assertj.core.api.BDDAssertions; class ObservationReceiverFilterTest extends AbstractObservationFilterTest { @Override public SampleTestRunnerConsumer yourCode() { return (buildingBlocks, meterRegistry) -> { setupConfig(); setupAttachments(buildingBlocks.getTracer()); invoker = new AssertingInvoker(buildingBlocks.getTracer()); ObservationReceiverFilter senderFilter = (ObservationReceiverFilter) filter; senderFilter.invoke(invoker, invocation); senderFilter.onResponse(null, invoker, invocation); MeterRegistryAssert.then(meterRegistry) .hasMeterWithNameAndTags( "rpc.server.duration", KeyValues.of( "rpc.method", "mockMethod", "rpc.service", "DemoService", "rpc.system", "apache_dubbo")); SpansAssert.then(buildingBlocks.getFinishedSpans()) .hasASpanWithNameIgnoreCase("DemoService/mockMethod", spanAssert -> spanAssert .hasTag("rpc.method", "mockMethod") .hasTag("rpc.service", "DemoService") .hasTag("rpc.system", "apache_dubbo")); }; } void setupAttachments(Tracer tracer) { RpcContext.getServerAttachment() .setUrl(URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&side=consumer")); RpcContext.getServerAttachment().setMethodName("foo"); RpcContext.getServerAttachment().setRemoteAddress("foo.bar.com", 8080); RpcContext.getServerAttachment() .setAttachment("X-B3-TraceId", tracer.currentSpan().context().traceId()); RpcContext.getServerAttachment() .setAttachment("X-B3-SpanId", tracer.currentSpan().context().spanId()); RpcContext.getServerAttachment().setAttachment("X-B3-Sampled", "1"); } @Override Filter createFilter(ApplicationModel applicationModel) { return new ObservationReceiverFilter(applicationModel); } static class AssertingInvoker implements Invoker { private final String expectedTraceId; private final String parentSpanId; private final Tracer tracer; AssertingInvoker(Tracer tracer) { this.tracer = tracer; this.expectedTraceId = tracer.currentSpan().context().traceId(); this.parentSpanId = tracer.currentSpan().context().spanId(); } @Override public URL getUrl() { return null; } @Override public boolean isAvailable() { return true; } @Override public void destroy() {} @Override public Class getInterface() { return AssertingInvoker.class; } @Override public Result invoke(Invocation invocation) throws RpcException { Span span = this.tracer.currentSpan(); BDDAssertions.then(span.context().traceId()) .as("Should propagate the trace id from the attributes") .isEqualTo(this.expectedTraceId); BDDAssertions.then(span.context().spanId()) .as("A child span must be created") .isNotEqualTo(this.parentSpanId); return new AppResponse("OK"); } } }
8,014
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/observation/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.metrics.observation; 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; } }
8,015
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/observation/AbstractObservationFilterTest.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.observation; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.TracingConfig; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.BaseFilter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.model.ApplicationModel; import io.micrometer.tracing.test.SampleTestRunner; import org.junit.jupiter.api.AfterEach; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; abstract class AbstractObservationFilterTest extends SampleTestRunner { ApplicationModel applicationModel; RpcInvocation invocation; BaseFilter filter; Invoker<?> invoker = mock(Invoker.class); static final String INTERFACE_NAME = "org.apache.dubbo.MockInterface"; static final String METHOD_NAME = "mockMethod"; static final String GROUP = "mockGroup"; static final String VERSION = "1.0.0"; @AfterEach public void teardown() { if (applicationModel != null) { applicationModel.destroy(); } } abstract BaseFilter createFilter(ApplicationModel applicationModel); void setupConfig() { ApplicationConfig config = new ApplicationConfig(); config.setName("MockObservations"); applicationModel = ApplicationModel.defaultModel(); applicationModel.getApplicationConfigManager().setApplication(config); invocation = new RpcInvocation(new MockInvocation()); invocation.addInvokedInvoker(invoker); applicationModel.getBeanFactory().registerBean(getObservationRegistry()); TracingConfig tracingConfig = new TracingConfig(); tracingConfig.setEnabled(true); applicationModel.getApplicationConfigManager().setTracing(tracingConfig); filter = createFilter(applicationModel); given(invoker.invoke(invocation)).willReturn(new AppResponse("success")); initParam(); } private void initParam() { invocation.setTargetServiceUniqueName(GROUP + "/" + INTERFACE_NAME + ":" + VERSION); invocation.setMethodName(METHOD_NAME); invocation.setParameterTypes(new Class[] {String.class}); } }
8,016
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo
Create_ds/dubbo/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.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleModel; import org.apache.dubbo.rpc.model.ScopeModelInitializer; public class MetricsScopeModelInitializer implements ScopeModelInitializer { @Override public void initializeFrameworkModel(FrameworkModel frameworkModel) {} @Override public void initializeApplicationModel(ApplicationModel applicationModel) { ScopeBeanFactory beanFactory = applicationModel.getBeanFactory(); beanFactory.registerBean(MetricsDispatcher.class); } @Override public void initializeModuleModel(ModuleModel moduleModel) {} }
8,017
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo
Create_ds/dubbo/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; } }
8,018
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo
Create_ds/dubbo/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); }
8,019
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics
Create_ds/dubbo/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.Map; 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 Map<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(true); } @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 = methodTypeCounter.computeIfAbsent(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 = methodTypeCounter.computeIfAbsent(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); } }
8,020
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics
Create_ds/dubbo/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; } }
8,021
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics
Create_ds/dubbo/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.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 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)); samplers.add(applicationSampler); samplers.add(threadPoolSampler); samplesChanged.set(true); 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; } 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; } }
8,022
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector
Create_ds/dubbo/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; } }
8,023
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector
Create_ds/dubbo/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.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_NAME; import static org.apache.dubbo.config.Constants.SERVER_THREAD_POOL_NAME; import static org.apache.dubbo.metrics.model.MetricsCategory.THREAD_POOL; public class ThreadPoolMetricsSampler implements MetricsSampler { 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; } public void addExecutors(String name, ExecutorService executorService) { Optional.ofNullable(executorService) .filter(Objects::nonNull) .filter(e -> e instanceof ThreadPoolExecutor) .map(e -> (ThreadPoolExecutor) e) .ifPresent(threadPoolExecutor -> { sampleThreadPoolExecutor.put(name, threadPoolExecutor); 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; } 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.dataStore == null) { this.dataStore = collector .getApplicationModel() .getExtensionLoader(DataStore.class) .getDefaultExtension(); } if (dataStore != null) { 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_NAME + "-" + 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_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()); } } @Override public boolean calSamplesChanged() { // CAS to get and reset the flag in an atomic operation return samplesChanged.compareAndSet(true, false); } }
8,024
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector
Create_ds/dubbo/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(); }
8,025
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector
Create_ds/dubbo/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.ConcurrentMap; import java.util.concurrent.atomic.AtomicLong; public interface MetricsCountSampler<S, K, M extends Metric> extends MetricsSampler { void inc(S source, K metricName); Optional<ConcurrentMap<M, AtomicLong>> getCount(K metricName); }
8,026
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector
Create_ds/dubbo/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.metrics.model.Metric; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; 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 ConcurrentMap<M, AtomicLong> EMPTY_COUNT = new ConcurrentHashMap<>(); private final Map<K, ConcurrentMap<M, AtomicLong>> metricCounter = new ConcurrentHashMap<>(); @Override public void inc(S source, K metricName) { getAtomicCounter(source, metricName).incrementAndGet(); } @Override public Optional<ConcurrentMap<M, AtomicLong>> getCount(K metricName) { return Optional.ofNullable(metricCounter.get(metricName) == null ? EMPTY_COUNT : metricCounter.get(metricName)); } protected void initMetricsCounter(S source, K metricsName) { getAtomicCounter(source, metricsName); } 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); Map<M, AtomicLong> metricAtomic = metricCounter.get(metricsName); if (metricAtomic == null) { metricAtomic = metricCounter.computeIfAbsent(metricsName, k -> new ConcurrentHashMap<>()); } Assert.notNull(sampleConfigure.getMetric(), "metrics is null"); AtomicLong atomicCounter = metricAtomic.get(sampleConfigure.getMetric()); if (atomicCounter == null) { atomicCounter = metricAtomic.computeIfAbsent(sampleConfigure.getMetric(), k -> new AtomicLong()); } return atomicCounter; } }
8,027
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector
Create_ds/dubbo/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.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.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.ArrayList; import java.util.List; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; 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<>(); private final AtomicBoolean samplesChanged = new AtomicBoolean(true); public ThreadRejectMetricsCountSampler(DefaultMetricsCollector collector) { this.collector = collector; this.collector.addSampler(this); } public void addMetricName(String name) { this.metricNames.add(name); this.initMetricsCounter(name, name); samplesChanged.set(true); } @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())); } @Override public boolean calSamplesChanged() { // CAS to get and reset the flag in an atomic operation return samplesChanged.compareAndSet(true, false); } }
8,028
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector
Create_ds/dubbo/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); } }
8,029
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics
Create_ds/dubbo/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); } }
8,030
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics
Create_ds/dubbo/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); }
8,031
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics
Create_ds/dubbo/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); } }
8,032
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics
Create_ds/dubbo/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() {} }
8,033
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics
Create_ds/dubbo/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); } }
8,034
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics
Create_ds/dubbo/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(); }
8,035
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/report
Create_ds/dubbo/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); } }
8,036
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/report
Create_ds/dubbo/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; } }
8,037
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics
Create_ds/dubbo/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(true); 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) { 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) { 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); } } } }
8,038
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics
Create_ds/dubbo/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); } }
8,039
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics
Create_ds/dubbo/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; } }
8,040
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics
Create_ds/dubbo/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; } }
8,041
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics
Create_ds/dubbo/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); }))); } }
8,042
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/observation/ObservationReceiverFilter.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.observation; 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 org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ScopeModelAware; import io.micrometer.observation.Observation; import io.micrometer.observation.ObservationRegistry; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; /** * A {@link Filter} that creates an {@link Observation} around the incoming message. */ @Activate(group = PROVIDER, order = -1, onClass = "io.micrometer.observation.NoopObservationRegistry") public class ObservationReceiverFilter implements Filter, BaseFilter.Listener, ScopeModelAware { private ObservationRegistry observationRegistry; private DubboServerObservationConvention serverObservationConvention; public ObservationReceiverFilter(ApplicationModel applicationModel) { applicationModel.getApplicationConfigManager().getTracing().ifPresent(cfg -> { if (Boolean.TRUE.equals(cfg.getEnabled())) { observationRegistry = applicationModel.getBeanFactory().getBean(ObservationRegistry.class); serverObservationConvention = applicationModel.getBeanFactory().getBean(DubboServerObservationConvention.class); } }); } @Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { if (observationRegistry == null) { return invoker.invoke(invocation); } final DubboServerContext receiverContext = new DubboServerContext(invoker, invocation); final Observation observation = DubboObservationDocumentation.SERVER.observation( this.serverObservationConvention, DefaultDubboServerObservationConvention.getInstance(), () -> receiverContext, observationRegistry); invocation.put(Observation.class, observation.start()); return observation.scoped(() -> invoker.invoke(invocation)); } @Override public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) { final Observation observation = getObservation(invocation); if (observation == null) { return; } observation.stop(); } @Override public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) { final Observation observation = getObservation(invocation); if (observation == null) { return; } observation.error(t); observation.stop(); } private Observation getObservation(Invocation invocation) { return (Observation) invocation.get(Observation.class); } }
8,043
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics
Create_ds/dubbo/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()); } }
8,044
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics
Create_ds/dubbo/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.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; import com.google.common.collect.Lists; 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() { RegistryEvent registryEvent = RegistryEvent.toRegisterEvent(applicationModel, Lists.newArrayList("reg1")); 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, Lists.newArrayList("reg1")); 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 = Lists.newArrayList("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()); } }
8,045
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics
Create_ds/dubbo/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.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 com.google.common.collect.Lists; 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() { RegistryEvent event = RegistryEvent.toRegisterEvent(applicationModel, Lists.newArrayList("reg1")); event.setAvailable(true); return event; } RegistryEvent rsEvent() { List<String> rcNames = Lists.newArrayList("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(); } } } }
8,046
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics
Create_ds/dubbo/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); } }
8,047
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics
Create_ds/dubbo/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)); }
8,048
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry
Create_ds/dubbo/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(true); } @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; } }
8,049
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry
Create_ds/dubbo/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.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 Map<MetricsKey, Map<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)); Map<ApplicationMetric, AtomicLong> stats = appStats.get(metricsKey); AtomicLong metrics = stats.get(applicationMetric); if (metrics == null) { metrics = stats.computeIfAbsent(applicationMetric, k -> new AtomicLong(0L)); samplesChanged.set(true); } metrics.getAndAdd(SELF_INCREMENT_SIZE); MetricsSupport.fillZero(appStats); } public Map<MetricsKey, Map<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); } }
8,050
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry
Create_ds/dubbo/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); } }
8,051
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistrySubDispatcher.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.metrics.event.SimpleMetricsEventMulticaster; import org.apache.dubbo.metrics.listener.MetricsApplicationListener; 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.registry.collector.RegistryMetricsCollector; import java.util.Arrays; import java.util.List; 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; 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 final class RegistrySubDispatcher extends SimpleMetricsEventMulticaster { public RegistrySubDispatcher(RegistryMetricsCollector 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_REGISTER = new CategoryOverall( OP_TYPE_REGISTER, MCat.APPLICATION_REGISTER_POST, MCat.APPLICATION_REGISTER_FINISH, MCat.APPLICATION_REGISTER_ERROR); CategoryOverall APPLICATION_SUBSCRIBE = new CategoryOverall( OP_TYPE_SUBSCRIBE, MCat.APPLICATION_SUBSCRIBE_POST, MCat.APPLICATION_SUBSCRIBE_FINISH, MCat.APPLICATION_SUBSCRIBE_ERROR); CategoryOverall APPLICATION_NOTIFY = new CategoryOverall(OP_TYPE_NOTIFY, MCat.APPLICATION_NOTIFY_POST, MCat.APPLICATION_NOTIFY_FINISH, null); CategoryOverall SERVICE_DIRECTORY = new CategoryOverall(OP_TYPE_DIRECTORY, MCat.APPLICATION_DIRECTORY_POST, null, null); CategoryOverall SERVICE_REGISTER = new CategoryOverall( OP_TYPE_REGISTER_SERVICE, MCat.SERVICE_REGISTER_POST, MCat.SERVICE_REGISTER_FINISH, MCat.SERVICE_REGISTER_ERROR); CategoryOverall SERVICE_SUBSCRIBE = new CategoryOverall( OP_TYPE_SUBSCRIBE_SERVICE, MCat.SERVICE_SUBSCRIBE_POST, MCat.SERVICE_SUBSCRIBE_FINISH, MCat.SERVICE_SUBSCRIBE_ERROR); List<CategoryOverall> ALL = Arrays.asList( APPLICATION_REGISTER, APPLICATION_SUBSCRIBE, APPLICATION_NOTIFY, SERVICE_DIRECTORY, SERVICE_REGISTER, 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 { // MetricsRegisterListener MetricsCat APPLICATION_REGISTER_POST = new MetricsCat(MetricsKey.REGISTER_METRIC_REQUESTS, RegistrySpecListener::onPost); MetricsCat APPLICATION_REGISTER_FINISH = new MetricsCat(MetricsKey.REGISTER_METRIC_REQUESTS_SUCCEED, RegistrySpecListener::onFinish); MetricsCat APPLICATION_REGISTER_ERROR = new MetricsCat(MetricsKey.REGISTER_METRIC_REQUESTS_FAILED, RegistrySpecListener::onError); // MetricsSubscribeListener MetricsCat APPLICATION_SUBSCRIBE_POST = new MetricsCat(MetricsKey.SUBSCRIBE_METRIC_NUM, RegistrySpecListener::onPost); MetricsCat APPLICATION_SUBSCRIBE_FINISH = new MetricsCat(MetricsKey.SUBSCRIBE_METRIC_NUM_SUCCEED, RegistrySpecListener::onFinish); MetricsCat APPLICATION_SUBSCRIBE_ERROR = new MetricsCat(MetricsKey.SUBSCRIBE_METRIC_NUM_FAILED, RegistrySpecListener::onError); // MetricsNotifyListener MetricsCat APPLICATION_NOTIFY_POST = new MetricsCat(MetricsKey.NOTIFY_METRIC_REQUESTS, MetricsApplicationListener::onPostEventBuild); MetricsCat APPLICATION_NOTIFY_FINISH = new MetricsCat(MetricsKey.NOTIFY_METRIC_NUM_LAST, RegistrySpecListener::onFinishOfNotify); MetricsCat APPLICATION_DIRECTORY_POST = new MetricsCat(MetricsKey.DIRECTORY_METRIC_NUM_VALID, RegistrySpecListener::onPostOfDirectory); // MetricsServiceRegisterListener MetricsCat SERVICE_REGISTER_POST = new MetricsCat(MetricsKey.SERVICE_REGISTER_METRIC_REQUESTS, RegistrySpecListener::onPostOfService); MetricsCat SERVICE_REGISTER_FINISH = new MetricsCat( MetricsKey.SERVICE_REGISTER_METRIC_REQUESTS_SUCCEED, RegistrySpecListener::onFinishOfService); MetricsCat SERVICE_REGISTER_ERROR = new MetricsCat( MetricsKey.SERVICE_REGISTER_METRIC_REQUESTS_FAILED, RegistrySpecListener::onErrorOfService); // MetricsServiceSubscribeListener MetricsCat SERVICE_SUBSCRIBE_POST = new MetricsCat(MetricsKey.SERVICE_SUBSCRIBE_METRIC_NUM, RegistrySpecListener::onPostOfService); MetricsCat SERVICE_SUBSCRIBE_FINISH = new MetricsCat( MetricsKey.SERVICE_SUBSCRIBE_METRIC_NUM_SUCCEED, RegistrySpecListener::onFinishOfService); MetricsCat SERVICE_SUBSCRIBE_ERROR = new MetricsCat(MetricsKey.SERVICE_SUBSCRIBE_METRIC_NUM_FAILED, RegistrySpecListener::onErrorOfService); } }
8,052
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistryEvent.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.beans.factory.ScopeBeanFactory; import org.apache.dubbo.metrics.event.TimeCounterEvent; 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.metrics.registry.RegistryMetricsConstants; import org.apache.dubbo.metrics.registry.collector.RegistryMetricsCollector; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Collections; import java.util.List; 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; /** * Registry related events */ public class RegistryEvent extends TimeCounterEvent { public RegistryEvent(ApplicationModel applicationModel, TypeWrapper typeWrapper) { super(applicationModel, typeWrapper); ScopeBeanFactory beanFactory = getSource().getBeanFactory(); RegistryMetricsCollector collector; if (!beanFactory.isDestroyed()) { collector = beanFactory.getBean(RegistryMetricsCollector.class); super.setAvailable(collector != null && collector.isCollectEnabled()); } } private static final TypeWrapper REGISTER_EVENT = new TypeWrapper( MetricsLevel.APP, MetricsKey.REGISTER_METRIC_REQUESTS, MetricsKey.REGISTER_METRIC_REQUESTS_SUCCEED, MetricsKey.REGISTER_METRIC_REQUESTS_FAILED); public static RegistryEvent toRegisterEvent(ApplicationModel applicationModel, List<String> registryClusterNames) { RegistryEvent registryEvent = new RegistryEvent(applicationModel, REGISTER_EVENT); registryEvent.putAttachment(RegistryMetricsConstants.ATTACHMENT_REGISTRY_KEY, registryClusterNames); return registryEvent; } private static final TypeWrapper SUBSCRIBE_EVENT = new TypeWrapper( MetricsLevel.APP, MetricsKey.SUBSCRIBE_METRIC_NUM, MetricsKey.SUBSCRIBE_METRIC_NUM_SUCCEED, MetricsKey.SUBSCRIBE_METRIC_NUM_FAILED); public static RegistryEvent toSubscribeEvent(ApplicationModel applicationModel, String registryClusterName) { RegistryEvent ddEvent = new RegistryEvent(applicationModel, SUBSCRIBE_EVENT); ddEvent.putAttachment( RegistryMetricsConstants.ATTACHMENT_REGISTRY_KEY, Collections.singletonList(registryClusterName)); return ddEvent; } private static final TypeWrapper NOTIFY_EVENT = new TypeWrapper( MetricsLevel.APP, MetricsKey.NOTIFY_METRIC_REQUESTS, MetricsKey.NOTIFY_METRIC_NUM_LAST, (MetricsKey) null); public static RegistryEvent toNotifyEvent(ApplicationModel applicationModel) { return new RegistryEvent(applicationModel, NOTIFY_EVENT) { @Override public void customAfterPost(Object postResult) { super.putAttachment(ATTACHMENT_KEY_LAST_NUM_MAP, postResult); } }; } private static final TypeWrapper RS_EVENT = new TypeWrapper( MetricsLevel.SERVICE, MetricsKey.SERVICE_REGISTER_METRIC_REQUESTS, MetricsKey.SERVICE_REGISTER_METRIC_REQUESTS_SUCCEED, MetricsKey.SERVICE_REGISTER_METRIC_REQUESTS_FAILED); public static RegistryEvent toRsEvent( ApplicationModel applicationModel, String serviceKey, int size, List<String> serviceDiscoveryNames) { RegistryEvent ddEvent = new RegistryEvent(applicationModel, RS_EVENT); ddEvent.putAttachment(ATTACHMENT_KEY_SERVICE, serviceKey); ddEvent.putAttachment(ATTACHMENT_KEY_SIZE, size); ddEvent.putAttachment(RegistryMetricsConstants.ATTACHMENT_REGISTRY_KEY, serviceDiscoveryNames); return ddEvent; } private static final TypeWrapper SS_EVENT = new TypeWrapper( MetricsLevel.SERVICE, MetricsKey.SERVICE_SUBSCRIBE_METRIC_NUM, MetricsKey.SERVICE_SUBSCRIBE_METRIC_NUM_SUCCEED, MetricsKey.SERVICE_SUBSCRIBE_METRIC_NUM_FAILED); public static RegistryEvent toSsEvent( ApplicationModel applicationModel, String serviceKey, List<String> serviceDiscoveryNames) { RegistryEvent ddEvent = new RegistryEvent(applicationModel, SS_EVENT); ddEvent.putAttachment(ATTACHMENT_KEY_SERVICE, serviceKey); ddEvent.putAttachment(ATTACHMENT_KEY_SIZE, 1); ddEvent.putAttachment(RegistryMetricsConstants.ATTACHMENT_REGISTRY_KEY, serviceDiscoveryNames); return ddEvent; } private static final TypeWrapper DIRECTORY_EVENT = new TypeWrapper(MetricsLevel.APP, MetricsKey.DIRECTORY_METRIC_NUM_VALID, null, null); public static RegistryEvent refreshDirectoryEvent( ApplicationModel applicationModel, Map<MetricsKey, Map<String, Integer>> summaryMap, Map<String, String> attachments) { RegistryEvent registryEvent = new RegistryEvent(applicationModel, DIRECTORY_EVENT); registryEvent.putAttachment(ATTACHMENT_DIRECTORY_MAP, summaryMap); registryEvent.putAttachments(attachments); return registryEvent; } }
8,053
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics
Create_ds/dubbo/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; @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(); } @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 { HttpServer 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); } } }
8,054
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics
Create_ds/dubbo/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; @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(); } @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); try { Thread.sleep(5000); } catch (InterruptedException e) { throw new RuntimeException(e); } 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 { HttpServer 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); } } @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); } } }
8,055
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics
Create_ds/dubbo/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); } }
8,056
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-prometheus/src/main/java/org/apache/dubbo/metrics
Create_ds/dubbo/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; } }
8,057
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-prometheus/src/main/java/org/apache/dubbo/metrics
Create_ds/dubbo/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"); } }
8,058
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-prometheus/src/main/java/org/apache/dubbo/metrics
Create_ds/dubbo/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 ""; } }
8,059
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-prometheus/src/main/java/org/apache/dubbo/metrics
Create_ds/dubbo/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(); } }
8,060
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-config-center/src/test/java/org/apache/dubbo/metrics
Create_ds/dubbo/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); } } }
8,061
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics
Create_ds/dubbo/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"; }
8,062
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config
Create_ds/dubbo/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.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.Map; 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 Map<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(true); } 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 = updatedMetrics.computeIfAbsent(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); } }
8,063
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config
Create_ds/dubbo/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; } }
8,064
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config
Create_ds/dubbo/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)); } }); } }
8,065
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/MetricsSupportTest.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.config.ApplicationConfig; import org.apache.dubbo.metrics.model.MetricsSupport; 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.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.apache.dubbo.metrics.model.key.MetricsKey.METRIC_REQUESTS; public class MetricsSupportTest { @Test void testFillZero() { ApplicationModel applicationModel = FrameworkModel.defaultModel().newApplication(); ApplicationConfig config = new ApplicationConfig(); config.setName("MockMetrics"); applicationModel.getApplicationConfigManager().setApplication(config); Map<MetricsKeyWrapper, Map<ServiceKeyMetric, AtomicLong>> data = new HashMap<>(); MetricsKeyWrapper key1 = new MetricsKeyWrapper( METRIC_REQUESTS, MetricsPlaceValue.of(CommonConstants.PROVIDER, MetricsLevel.METHOD)); MetricsKeyWrapper key2 = new MetricsKeyWrapper( METRIC_REQUESTS, MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD)); ServiceKeyMetric sm1 = new ServiceKeyMetric(applicationModel, "a.b.c"); ServiceKeyMetric sm2 = new ServiceKeyMetric(applicationModel, "a.b.d"); data.computeIfAbsent(key1, k -> new HashMap<>()).put(sm1, new AtomicLong(1)); data.computeIfAbsent(key1, k -> new HashMap<>()).put(sm2, new AtomicLong(1)); data.put(key2, new HashMap<>()); Assertions.assertEquals( 2, data.values().stream().mapToLong(map -> map.values().size()).sum()); MetricsSupport.fillZero(data); Assertions.assertEquals( 4, data.values().stream().mapToLong(map -> map.values().size()).sum()); } }
8,066
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/aggregate/SlidingWindowTest.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.concurrent.atomic.LongAdder; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.RepeatedTest; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; class SlidingWindowTest { static final int paneCount = 10; static final long intervalInMs = 2000; TestSlidingWindow window; @BeforeEach void setup() { window = new TestSlidingWindow(paneCount, intervalInMs); } @RepeatedTest(1000) void testCurrentPane() { assertNull(window.currentPane(/* invalid time*/ -1L)); long timeInMs = System.currentTimeMillis(); Pane<LongAdder> currentPane = window.currentPane(timeInMs); assertNotNull(currentPane); // reuse test assertEquals(currentPane, window.currentPane(timeInMs + window.getPaneIntervalInMs() * paneCount)); } @Test void testGetPaneData() { assertNull(window.getPaneValue(/* invalid time*/ -1L)); window.currentPane(); assertNotNull(window.getPaneValue(System.currentTimeMillis())); assertNull(window.getPaneValue(System.currentTimeMillis() + window.getPaneIntervalInMs())); } @Test void testNewEmptyValue() { assertEquals(0L, window.newEmptyValue(System.currentTimeMillis()).sum()); } @Test void testResetPaneTo() { Pane<LongAdder> currentPane = window.currentPane(); currentPane.getValue().add(2); currentPane.getValue().add(1); assertEquals(3, currentPane.getValue().sum()); window.resetPaneTo(currentPane, System.currentTimeMillis()); assertEquals(0, currentPane.getValue().sum()); currentPane.getValue().add(1); assertEquals(1, currentPane.getValue().sum()); } @Test void testCalculatePaneStart() { long time = System.currentTimeMillis(); assertTrue(window.calculatePaneStart(time) <= time); assertTrue(time < window.calculatePaneStart(time) + window.getPaneIntervalInMs()); } @Test void testIsPaneDeprecated() { Pane<LongAdder> currentPane = window.currentPane(); currentPane.setStartInMs(1000000L); assertTrue(window.isPaneDeprecated(currentPane)); } @Test void testList() { window.currentPane(); assertTrue(0 < window.list().size()); } @Test void testValues() { window.currentPane().getValue().add(10); long sum = 0; for (LongAdder value : window.values()) { sum += value.sum(); } assertEquals(10, sum); } @Test void testGetIntervalInMs() { assertEquals(intervalInMs, window.getIntervalInMs()); } @Test void testGetPaneIntervalInMs() { assertEquals(intervalInMs / paneCount, window.getPaneIntervalInMs()); } private static class TestSlidingWindow extends SlidingWindow<LongAdder> { public TestSlidingWindow(int paneCount, long intervalInMs) { super(paneCount, intervalInMs); } @Override public LongAdder newEmptyValue(long timeMillis) { return new LongAdder(); } @Override protected Pane<LongAdder> resetPaneTo(Pane<LongAdder> pane, long startInMs) { pane.setStartInMs(startInMs); pane.getValue().reset(); return pane; } } }
8,067
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/aggregate/PaneTest.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.concurrent.atomic.LongAdder; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; class PaneTest { @Test void testIntervalInMs() { Pane<?> pane = mock(Pane.class); when(pane.getIntervalInMs()).thenReturn(100L); assertEquals(100L, pane.getIntervalInMs()); } @Test void testStartInMs() { Pane<?> pane = mock(Pane.class); long startTime = System.currentTimeMillis(); when(pane.getStartInMs()).thenReturn(startTime); assertEquals(startTime, pane.getStartInMs()); } @Test void testEndInMs() { long startTime = System.currentTimeMillis(); Pane<?> pane = new Pane<>(10, startTime, new Object()); assertEquals(startTime + 10, pane.getEndInMs()); } @Test @SuppressWarnings("unchecked") void testValue() { Pane<LongAdder> pane = mock(Pane.class); LongAdder count = new LongAdder(); when(pane.getValue()).thenReturn(count); assertEquals(count, pane.getValue()); when(pane.getValue()).thenReturn(null); assertNotEquals(count, pane.getValue()); } @Test void testIsTimeInWindow() { Pane<?> pane = new Pane<>(10, System.currentTimeMillis(), new Object()); assertTrue(pane.isTimeInWindow(System.currentTimeMillis())); assertFalse(pane.isTimeInWindow(System.currentTimeMillis() + 10)); } }
8,068
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/aggregate/TimeWindowCounterTest.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.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class TimeWindowCounterTest { @Test void test() { TimeWindowCounter counter = new TimeWindowCounter(10, 1); counter.increment(); Assertions.assertEquals(1, counter.get()); counter.decrement(); Assertions.assertEquals(0, counter.get()); counter.increment(); counter.increment(); Assertions.assertEquals(2, counter.get()); Assertions.assertTrue(counter.bucketLivedSeconds() <= 1); } }
8,069
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/aggregate/TimeWindowAggregatorTest.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.concurrent.TimeUnit; import org.junit.Test; import org.junit.jupiter.api.Assertions; public class TimeWindowAggregatorTest { @Test public void testTimeWindowAggregator() { TimeWindowAggregator aggregator = new TimeWindowAggregator(5, 5); // First time window, time range: 0 - 5 seconds aggregator.add(10); aggregator.add(20); aggregator.add(30); SampleAggregatedEntry entry1 = aggregator.get(); Assertions.assertEquals(20, entry1.getAvg()); Assertions.assertEquals(60, entry1.getTotal()); Assertions.assertEquals(3, entry1.getCount()); Assertions.assertEquals(30, entry1.getMax()); Assertions.assertEquals(10, entry1.getMin()); // Second time window, time range: 5 - 10 seconds try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } aggregator.add(15); aggregator.add(25); aggregator.add(35); SampleAggregatedEntry entry2 = aggregator.get(); Assertions.assertEquals(25, entry2.getAvg()); Assertions.assertEquals(75, entry2.getTotal()); Assertions.assertEquals(3, entry2.getCount()); Assertions.assertEquals(35, entry2.getMax()); Assertions.assertEquals(15, entry2.getMin()); // Third time window, time range: 10 - 15 seconds try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } aggregator.add(12); aggregator.add(22); aggregator.add(32); SampleAggregatedEntry entry3 = aggregator.get(); Assertions.assertEquals(22, entry3.getAvg()); Assertions.assertEquals(66, entry3.getTotal()); Assertions.assertEquals(3, entry3.getCount()); Assertions.assertEquals(32, entry3.getMax()); Assertions.assertEquals(12, entry3.getMin()); } }
8,070
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/aggregate/TimeWindowQuantileTest.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.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.RepeatedTest; import org.junit.jupiter.api.Test; class TimeWindowQuantileTest { @Test void test() { TimeWindowQuantile quantile = new TimeWindowQuantile(100, 10, 1); for (int i = 1; i <= 100; i++) { quantile.add(i); } Assertions.assertEquals(quantile.quantile(0.01), 2); Assertions.assertEquals(quantile.quantile(0.99), 100); } @Test @RepeatedTest(100) void testMulti() { ExecutorService executorService = Executors.newFixedThreadPool(200); TimeWindowQuantile quantile = new TimeWindowQuantile(100, 10, 120); int index = 0; while (index < 100) { for (int i = 0; i < 100; i++) { int finalI = i; Assertions.assertDoesNotThrow(() -> quantile.add(finalI)); executorService.execute(() -> quantile.add(finalI)); } index++; // try { // Thread.sleep(1); // } catch (InterruptedException e) { // e.printStackTrace(); // } } executorService.shutdown(); } }
8,071
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/model/ApplicationMetricTest.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.model; import org.apache.dubbo.common.Version; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Map; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.MetricsConstants.*; import static org.apache.dubbo.common.utils.NetUtils.getLocalHost; import static org.apache.dubbo.common.utils.NetUtils.getLocalHostName; import static org.apache.dubbo.metrics.model.key.MetricsKey.METADATA_GIT_COMMITID_METRIC; import static org.junit.jupiter.api.Assertions.*; class ApplicationMetricTest { @Test void getApplicationModel() { ApplicationMetric applicationMetric = new ApplicationMetric(ApplicationModel.defaultModel()); Assertions.assertNotNull(applicationMetric.getApplicationModel()); } @Test void getApplicationName() { ApplicationModel applicationModel = ApplicationModel.defaultModel(); String mockMetrics = "MockMetrics"; applicationModel .getApplicationConfigManager() .setApplication(new org.apache.dubbo.config.ApplicationConfig(mockMetrics)); ApplicationMetric applicationMetric = new ApplicationMetric(applicationModel); Assertions.assertNotNull(applicationMetric); Assertions.assertEquals(mockMetrics, applicationMetric.getApplicationName()); } @Test void getTags() { ApplicationModel applicationModel = ApplicationModel.defaultModel(); String mockMetrics = "MockMetrics"; applicationModel .getApplicationConfigManager() .setApplication(new org.apache.dubbo.config.ApplicationConfig(mockMetrics)); ApplicationMetric applicationMetric = new ApplicationMetric(applicationModel); Map<String, String> tags = applicationMetric.getTags(); Assertions.assertEquals(tags.get(TAG_IP), getLocalHost()); Assertions.assertEquals(tags.get(TAG_HOSTNAME), getLocalHostName()); Assertions.assertEquals(tags.get(TAG_APPLICATION_NAME), applicationModel.getApplicationName()); Assertions.assertEquals(tags.get(METADATA_GIT_COMMITID_METRIC.getName()), Version.getLastCommitId()); } @Test void gitTags() { ApplicationModel applicationModel = ApplicationModel.defaultModel(); String mockMetrics = "MockMetrics"; applicationModel .getApplicationConfigManager() .setApplication(new org.apache.dubbo.config.ApplicationConfig(mockMetrics)); ApplicationMetric applicationMetric = new ApplicationMetric(applicationModel); Map<String, String> tags = applicationMetric.getTags(); Assertions.assertEquals(tags.get(METADATA_GIT_COMMITID_METRIC.getName()), Version.getLastCommitId()); } @Test void hostTags() { ApplicationModel applicationModel = ApplicationModel.defaultModel(); String mockMetrics = "MockMetrics"; applicationModel .getApplicationConfigManager() .setApplication(new org.apache.dubbo.config.ApplicationConfig(mockMetrics)); ApplicationMetric applicationMetric = new ApplicationMetric(applicationModel); Map<String, String> tags = applicationMetric.getTags(); Assertions.assertEquals(tags.get(TAG_IP), getLocalHost()); Assertions.assertEquals(tags.get(TAG_HOSTNAME), getLocalHostName()); } @Test void getExtraInfo() {} @Test void setExtraInfo() {} @Test void testEquals() {} @Test void testHashCode() {} }
8,072
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/event/SimpleMetricsEventMulticasterTest.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.config.ApplicationConfig; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.metrics.listener.AbstractMetricsListener; import org.apache.dubbo.metrics.listener.MetricsLifeListener; import org.apache.dubbo.rpc.model.ApplicationModel; 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.EXECUTOR_MANAGEMENT_MODE_DEFAULT; public class SimpleMetricsEventMulticasterTest { private SimpleMetricsEventMulticaster eventMulticaster; private Object[] objects; private final Object obj = new Object(); private TimeCounterEvent requestEvent; @BeforeEach public void setup() { eventMulticaster = new SimpleMetricsEventMulticaster(); objects = new Object[] {obj}; eventMulticaster.addListener(new AbstractMetricsListener<MetricsEvent>() { @Override public void onEvent(MetricsEvent event) { objects[0] = new Object(); } }); ApplicationModel applicationModel = ApplicationModel.defaultModel(); ApplicationConfig applicationConfig = new ApplicationConfig("provider-app"); applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT); applicationModel.getApplicationConfigManager().setApplication(applicationConfig); ConfigManager configManager = new ConfigManager(applicationModel); configManager.setApplication(applicationConfig); applicationModel.setConfigManager(configManager); requestEvent = new TimeCounterEvent(applicationModel, null) {}; } @Test void testPublishFinishEvent() { // do nothing with no MetricsLifeListener eventMulticaster.publishFinishEvent(requestEvent); Assertions.assertSame(obj, objects[0]); // do onEventFinish with MetricsLifeListener eventMulticaster.addListener((new MetricsLifeListener<TimeCounterEvent>() { @Override public boolean isSupport(MetricsEvent event) { return event instanceof TimeCounterEvent; } @Override public void onEvent(TimeCounterEvent event) {} @Override public void onEventFinish(TimeCounterEvent event) { objects[0] = new Object(); } @Override public void onEventError(TimeCounterEvent event) {} })); eventMulticaster.publishFinishEvent(requestEvent); Assertions.assertNotSame(obj, objects[0]); } }
8,073
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/observation/DefaultDubboServerObservationConventionTest.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.observation; import org.apache.dubbo.metrics.observation.utils.ObservationConventionUtils; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcInvocation; import io.micrometer.common.KeyValues; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @SuppressWarnings("deprecation") public class DefaultDubboServerObservationConventionTest { static DubboServerObservationConvention dubboServerObservationConvention = DefaultDubboServerObservationConvention.getInstance(); @Test void testGetName() { Assertions.assertEquals("rpc.server.duration", dubboServerObservationConvention.getName()); } @Test void testGetLowCardinalityKeyValues() throws NoSuchFieldException, IllegalAccessException { RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("testMethod"); invocation.setAttachment("interface", "com.example.TestService"); invocation.setTargetServiceUniqueName("targetServiceName1"); Invoker<?> invoker = ObservationConventionUtils.getMockInvokerWithUrl(); invocation.setInvoker(invoker); DubboServerContext context = new DubboServerContext(invoker, invocation); KeyValues keyValues = dubboServerObservationConvention.getLowCardinalityKeyValues(context); Assertions.assertEquals("testMethod", ObservationConventionUtils.getValueForKey(keyValues, "rpc.method")); Assertions.assertEquals( "targetServiceName1", ObservationConventionUtils.getValueForKey(keyValues, "rpc.service")); Assertions.assertEquals("apache_dubbo", ObservationConventionUtils.getValueForKey(keyValues, "rpc.system")); } @Test void testGetContextualName() { RpcInvocation invocation = new RpcInvocation(); Invoker<?> invoker = ObservationConventionUtils.getMockInvokerWithUrl(); invocation.setMethodName("testMethod"); invocation.setServiceName("com.example.TestService"); DubboClientContext context = new DubboClientContext(invoker, invocation); DefaultDubboClientObservationConvention convention = new DefaultDubboClientObservationConvention(); String contextualName = convention.getContextualName(context); Assertions.assertEquals("com.example.TestService/testMethod", contextualName); } }
8,074
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/observation/DefaultDubboClientObservationConventionTest.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.observation; import org.apache.dubbo.metrics.observation.utils.ObservationConventionUtils; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcInvocation; import io.micrometer.common.KeyValues; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class DefaultDubboClientObservationConventionTest { static DubboClientObservationConvention dubboClientObservationConvention = DefaultDubboClientObservationConvention.getInstance(); @Test void testGetName() { Assertions.assertEquals("rpc.client.duration", dubboClientObservationConvention.getName()); } @Test void testGetLowCardinalityKeyValues() throws NoSuchFieldException, IllegalAccessException { RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("testMethod"); invocation.setAttachment("interface", "com.example.TestService"); invocation.setTargetServiceUniqueName("targetServiceName1"); Invoker<?> invoker = ObservationConventionUtils.getMockInvokerWithUrl(); invocation.setInvoker(invoker); DubboClientContext context = new DubboClientContext(invoker, invocation); KeyValues keyValues = dubboClientObservationConvention.getLowCardinalityKeyValues(context); Assertions.assertEquals("testMethod", ObservationConventionUtils.getValueForKey(keyValues, "rpc.method")); Assertions.assertEquals( "targetServiceName1", ObservationConventionUtils.getValueForKey(keyValues, "rpc.service")); Assertions.assertEquals("apache_dubbo", ObservationConventionUtils.getValueForKey(keyValues, "rpc.system")); } @Test void testGetContextualName() { RpcInvocation invocation = new RpcInvocation(); Invoker<?> invoker = ObservationConventionUtils.getMockInvokerWithUrl(); invocation.setMethodName("testMethod"); invocation.setServiceName("com.example.TestService"); DubboClientContext context = new DubboClientContext(invoker, invocation); DefaultDubboClientObservationConvention convention = new DefaultDubboClientObservationConvention(); String contextualName = convention.getContextualName(context); Assertions.assertEquals("com.example.TestService/testMethod", contextualName); } }
8,075
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/observation
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/observation/utils/ObservationConventionUtils.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.observation.utils; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invoker; import java.lang.reflect.Field; import io.micrometer.common.KeyValue; import io.micrometer.common.KeyValues; import org.mockito.Mockito; public class ObservationConventionUtils { public static Invoker<?> getMockInvokerWithUrl() { URL url = URL.valueOf( "dubbo://127.0.0.1:12345/com.example.TestService?anyhost=true&application=test&category=providers&dubbo=2.0.2&generic=false&interface=com.example.TestService&methods=testMethod&pid=26716&side=provider&timestamp=1633863896653"); Invoker<?> invoker = Mockito.mock(Invoker.class); Mockito.when(invoker.getUrl()).thenReturn(url); return invoker; } public static String getValueForKey(KeyValues keyValues, Object key) throws NoSuchFieldException, IllegalAccessException { Field f = KeyValues.class.getDeclaredField("keyValues"); f.setAccessible(true); KeyValue[] kv = (KeyValue[]) f.get(keyValues); for (KeyValue keyValue : kv) { if (keyValue.getKey().equals(key)) { return keyValue.getValue(); } } return null; } }
8,076
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/MetricsConstants.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; public interface MetricsConstants { String INVOCATION = "metric_filter_invocation"; String METHOD_METRICS = "metric_filter_method_metrics"; String INVOCATION_METRICS_COUNTER = "metric_filter_invocation_counter"; String INVOCATION_SIDE = "metric_filter_side"; String INVOCATION_REQUEST_ERROR = "metric_request_error"; String ATTACHMENT_KEY_SERVICE = "serviceKey"; String ATTACHMENT_KEY_SIZE = "size"; String ATTACHMENT_KEY_LAST_NUM_MAP = "lastNumMap"; String ATTACHMENT_DIRECTORY_MAP = "dirNum"; int SELF_INCREMENT_SIZE = 1; }
8,077
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
Create_ds/dubbo/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()); }); } }
8,078
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
Create_ds/dubbo/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); } }; } }
8,079
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
Create_ds/dubbo/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) {} }
8,080
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/MetricsListener.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; /** * Metrics Listener. */ public interface MetricsListener<E extends MetricsEvent> { boolean isSupport(MetricsEvent event); /** * notify event. * * @param event BaseMetricsEvent */ void onEvent(E event); }
8,081
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
Create_ds/dubbo/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.ReflectionUtils; import org.apache.dubbo.metrics.event.MetricsEvent; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public abstract class AbstractMetricsListener<E extends MetricsEvent> implements MetricsListener<E> { private final Map<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 = eventMatchCache.computeIfAbsent( event.getClass(), clazz -> ReflectionUtils.match(getClass(), AbstractMetricsListener.class, event)); return event.isAvailable() && eventMatch; } @Override public abstract void onEvent(E event); }
8,082
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
Create_ds/dubbo/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)); } }
8,083
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
Create_ds/dubbo/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); } } }
8,084
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/Pane.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; /** * The pane represents a window over a period of time. * * @param <T> The type of value the pane statistics. */ public class Pane<T> { /** * Time interval of the pane in milliseconds. */ private final long intervalInMs; /** * Start timestamp of the pane in milliseconds. */ private volatile long startInMs; /** * End timestamp of the pane in milliseconds. * <p> * endInMs = startInMs + intervalInMs */ private volatile long endInMs; /** * Pane statistics value. */ private T value; /** * @param intervalInMs interval of the pane in milliseconds. * @param startInMs start timestamp of the pane in milliseconds. * @param value the pane value. */ public Pane(long intervalInMs, long startInMs, T value) { this.intervalInMs = intervalInMs; this.startInMs = startInMs; this.endInMs = this.startInMs + this.intervalInMs; this.value = value; } /** * Get the interval of the pane in milliseconds. * * @return the interval of the pane in milliseconds. */ public long getIntervalInMs() { return this.intervalInMs; } /** * Get start timestamp of the pane in milliseconds. * * @return the start timestamp of the pane in milliseconds. */ public long getStartInMs() { return this.startInMs; } /** * Get end timestamp of the pane in milliseconds. * * @return the end timestamp of the pane in milliseconds. */ public long getEndInMs() { return this.endInMs; } /** * Get the pane statistics value. * * @return the pane statistics value. */ public T getValue() { return this.value; } /** * Set the new start timestamp to the pane, for reset the instance. * * @param newStartInMs the new start timestamp. */ public void setStartInMs(long newStartInMs) { this.startInMs = newStartInMs; this.endInMs = this.startInMs + this.intervalInMs; } /** * Set new value to the pane, for reset the instance. * * @param newData the new value. */ public void setValue(T newData) { this.value = newData; } /** * Check whether given timestamp is in current pane. * * @param timeMillis timestamp in milliseconds. * @return true if the given time is in current pane, otherwise false */ public boolean isTimeInWindow(long timeMillis) { // [) return startInMs <= timeMillis && timeMillis < endInMs; } }
8,085
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
Create_ds/dubbo/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; } } }
8,086
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/TimeWindowQuantile.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 com.tdunning.math.stats.TDigest; /** * Wrapper around TDigest. */ public class TimeWindowQuantile { private final double compression; private final DigestSlidingWindow slidingWindow; public TimeWindowQuantile(double compression, int bucketNum, int timeWindowSeconds) { this.compression = compression; this.slidingWindow = new DigestSlidingWindow(compression, bucketNum, TimeUnit.SECONDS.toMillis(timeWindowSeconds)); } public double quantile(double q) { TDigest mergeDigest = new DubboMergingDigest(compression); List<TDigest> validWindows = this.slidingWindow.values(); for (TDigest window : validWindows) { mergeDigest.add(window); } // This may return Double.NaN, and it's correct behavior. // see: https://github.com/prometheus/client_golang/issues/85 return mergeDigest.quantile(q); } public void add(double value) { this.slidingWindow.currentPane().getValue().add(value); } /** * Sliding window of type TDigest. */ private static class DigestSlidingWindow extends SlidingWindow<TDigest> { private final double compression; public DigestSlidingWindow(double compression, int sampleCount, long intervalInMs) { super(sampleCount, intervalInMs); this.compression = compression; } @Override public TDigest newEmptyValue(long timeMillis) { return new DubboMergingDigest(compression); } @Override protected Pane<TDigest> resetPaneTo(final Pane<TDigest> pane, long startTime) { pane.setStartInMs(startTime); pane.setValue(new DubboMergingDigest(compression)); return pane; } } }
8,087
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
Create_ds/dubbo/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; } }
8,088
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/DubboMergingDigest.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 org.apache.dubbo.metrics.exception.MetricsNeverHappenException; import com.tdunning.math.stats.Centroid; import com.tdunning.math.stats.ScaleFunction; import com.tdunning.math.stats.Sort; import com.tdunning.math.stats.TDigest; import java.nio.ByteBuffer; import java.util.AbstractCollection; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.concurrent.atomic.AtomicInteger; /** * Maintains a t-digest by collecting new points in a buffer that is then sorted occasionally and merged * into a sorted array that contains previously computed centroids. * <p> * This can be very fast because the cost of sorting and merging is amortized over several insertion. If * we keep N centroids total and have the input array is k long, then the amortized cost is something like * <p> * N/k + log k * <p> * These costs even out when N/k = log k. Balancing costs is often a good place to start in optimizing an * algorithm. For different values of compression factor, the following table shows estimated asymptotic * values of N and suggested values of k: * <table> * <thead> * <tr><td>Compression</td><td>N</td><td>k</td></tr> * </thead> * <tbody> * <tr><td>50</td><td>78</td><td>25</td></tr> * <tr><td>100</td><td>157</td><td>42</td></tr> * <tr><td>200</td><td>314</td><td>73</td></tr> * </tbody> * <caption>Sizing considerations for t-digest</caption> * </table> * <p> * The virtues of this kind of t-digest implementation include: * <ul> * <li>No allocation is required after initialization</li> * <li>The data structure automatically compresses existing centroids when possible</li> * <li>No Java object overhead is incurred for centroids since data is kept in primitive arrays</li> * </ul> * <p> * The current implementation takes the liberty of using ping-pong buffers for implementing the merge resulting * in a substantial memory penalty, but the complexity of an in place merge was not considered as worthwhile * since even with the overhead, the memory cost is less than 40 bytes per centroid which is much less than half * what the AVLTreeDigest uses and no dynamic allocation is required at all. */ public class DubboMergingDigest extends DubboAbstractTDigest { private int mergeCount = 0; private final double publicCompression; private final double compression; // points to the first unused centroid private final AtomicInteger lastUsedCell = new AtomicInteger(0); // sum_i weight[i] See also unmergedWeight private double totalWeight = 0; // number of points that have been added to each merged centroid private final double[] weight; // mean of points added to each merged centroid private final double[] mean; // history of all data added to centroids (for testing purposes) private List<List<Double>> data = null; double min = Double.POSITIVE_INFINITY; double max = Double.NEGATIVE_INFINITY; // sum_i tempWeight[i] private AtomicInteger unmergedWeight = new AtomicInteger(0); // this is the index of the next temporary centroid // this is a more Java-like convention than lastUsedCell uses private final AtomicInteger tempUsed = new AtomicInteger(0); private final double[] tempWeight; private final double[] tempMean; private List<List<Double>> tempData = null; // array used for sorting the temp centroids. This is a field // to avoid allocations during operation private final int[] order; // if true, alternate upward and downward merge passes public boolean useAlternatingSort = true; // if true, use higher working value of compression during construction, then reduce on presentation public boolean useTwoLevelCompression = true; // this forces centroid merging based on size limit rather than // based on accumulated k-index. This can be much faster since we // scale functions are more expensive than the corresponding // weight limits. public static boolean useWeightLimit = true; /** * Allocates a buffer merging t-digest. This is the normally used constructor that * allocates default sized internal arrays. Other versions are available, but should * only be used for special cases. * * @param compression The compression factor */ @SuppressWarnings("WeakerAccess") public DubboMergingDigest(double compression) { this(compression, -1); } /** * If you know the size of the temporary buffer for incoming points, you can use this entry point. * * @param compression Compression factor for t-digest. Same as 1/\delta in the paper. * @param bufferSize How many samples to retain before merging. */ @SuppressWarnings("WeakerAccess") public DubboMergingDigest(double compression, int bufferSize) { // we can guarantee that we only need ceiling(compression). this(compression, bufferSize, -1); } /** * Fully specified constructor. Normally only used for deserializing a buffer t-digest. * * @param compression Compression factor * @param bufferSize Number of temporary centroids * @param size Size of main buffer */ @SuppressWarnings("WeakerAccess") public DubboMergingDigest(double compression, int bufferSize, int size) { // ensure compression >= 10 // default size = 2 * ceil(compression) // default bufferSize = 5 * size // scale = max(2, bufferSize / size - 1) // compression, publicCompression = sqrt(scale-1)*compression, compression // ensure size > 2 * compression + weightLimitFudge // ensure bufferSize > 2*size // force reasonable value. Anything less than 10 doesn't make much sense because // too few centroids are retained if (compression < 10) { compression = 10; } // the weight limit is too conservative about sizes and can require a bit of extra room double sizeFudge = 0; if (useWeightLimit) { sizeFudge = 10; if (compression < 30) sizeFudge += 20; } // default size size = (int) Math.max(2 * compression + sizeFudge, size); // default buffer if (bufferSize == -1) { // TODO update with current numbers // having a big buffer is good for speed // experiments show bufferSize = 1 gives half the performance of bufferSize=10 // bufferSize = 2 gives 40% worse performance than 10 // but bufferSize = 5 only costs about 5-10% // // compression factor time(us) // 50 1 0.275799 // 50 2 0.151368 // 50 5 0.108856 // 50 10 0.102530 // 100 1 0.215121 // 100 2 0.142743 // 100 5 0.112278 // 100 10 0.107753 // 200 1 0.210972 // 200 2 0.148613 // 200 5 0.118220 // 200 10 0.112970 // 500 1 0.219469 // 500 2 0.158364 // 500 5 0.127552 // 500 10 0.121505 bufferSize = 5 * size; } // ensure enough space in buffer if (bufferSize <= 2 * size) { bufferSize = 2 * size; } // scale is the ratio of extra buffer to the final size // we have to account for the fact that we copy all live centroids into the incoming space double scale = Math.max(1, bufferSize / size - 1); //noinspection ConstantConditions if (!useTwoLevelCompression) { scale = 1; } // publicCompression is how many centroids the user asked for // compression is how many we actually keep this.publicCompression = compression; this.compression = Math.sqrt(scale) * publicCompression; // changing the compression could cause buffers to be too small, readjust if so if (size < this.compression + sizeFudge) { size = (int) Math.ceil(this.compression + sizeFudge); } // ensure enough space in buffer (possibly again) if (bufferSize <= 2 * size) { bufferSize = 2 * size; } weight = new double[size]; mean = new double[size]; tempWeight = new double[bufferSize]; tempMean = new double[bufferSize]; order = new int[bufferSize]; lastUsedCell.set(0); } public double getMin() { return min; } public double getMax() { return max; } /** * Over-ride the min and max values for testing purposes */ @SuppressWarnings("SameParameterValue") void setMinMax(double min, double max) { this.min = min; this.max = max; } /** * Turns on internal data recording. */ @Override public TDigest recordAllData() { super.recordAllData(); data = new ArrayList<>(); tempData = new ArrayList<>(); return this; } @Override void add(double x, int w, Centroid base) { add(x, w, base.data()); } @Override public void add(double x, int w) { add(x, w, (List<Double>) null); } private void add(double x, int w, List<Double> history) { if (Double.isNaN(x)) { throw new IllegalArgumentException("Cannot add NaN to t-digest"); } int where; synchronized (this) { // There is a small probability of entering here if (tempUsed.get() >= tempWeight.length - lastUsedCell.get() - 1) { mergeNewValues(); } where = tempUsed.getAndIncrement(); tempWeight[where] = w; tempMean[where] = x; unmergedWeight.addAndGet(w); } if (x < min) { min = x; } if (x > max) { max = x; } if (data != null) { if (tempData == null) { tempData = new ArrayList<>(); } while (tempData.size() <= where) { tempData.add(new ArrayList<Double>()); } if (history == null) { history = Collections.singletonList(x); } tempData.get(where).addAll(history); } } @Override public void add(List<? extends TDigest> others) { throw new MetricsNeverHappenException("Method not used"); } private void mergeNewValues() { mergeNewValues(false, compression); } private void mergeNewValues(boolean force, double compression) { if (totalWeight == 0 && unmergedWeight.get() == 0) { // seriously nothing to do return; } if (force || unmergedWeight.get() > 0) { // note that we run the merge in reverse every other merge to avoid left-to-right bias in merging merge(tempMean, tempWeight, tempUsed.get(), tempData, order, unmergedWeight.get(), useAlternatingSort & mergeCount % 2 == 1, compression); mergeCount++; tempUsed.set(0); unmergedWeight.set(0); if (data != null) { tempData = new ArrayList<>(); } } } private void merge(double[] incomingMean, double[] incomingWeight, int incomingCount, List<List<Double>> incomingData, int[] incomingOrder, double unmergedWeight, boolean runBackwards, double compression) { // when our incoming buffer fills up, we combine our existing centroids with the incoming data, // and then reduce the centroids by merging if possible assert lastUsedCell.get() <= 0 || weight[0] == 1; assert lastUsedCell.get() <= 0 || weight[lastUsedCell.get() - 1] == 1; System.arraycopy(mean, 0, incomingMean, incomingCount, lastUsedCell.get()); System.arraycopy(weight, 0, incomingWeight, incomingCount, lastUsedCell.get()); incomingCount += lastUsedCell.get(); if (incomingData != null) { for (int i = 0; i < lastUsedCell.get(); i++) { assert data != null; incomingData.add(data.get(i)); } data = new ArrayList<>(); } if (incomingOrder == null) { incomingOrder = new int[incomingCount]; } Sort.stableSort(incomingOrder, incomingMean, incomingCount); totalWeight += unmergedWeight; // option to run backwards is to help investigate bias in errors if (runBackwards) { Sort.reverse(incomingOrder, 0, incomingCount); } // start by copying the least incoming value to the normal buffer lastUsedCell.set(0); mean[lastUsedCell.get()] = incomingMean[incomingOrder[0]]; weight[lastUsedCell.get()] = incomingWeight[incomingOrder[0]]; double wSoFar = 0; if (data != null) { assert incomingData != null; data.add(incomingData.get(incomingOrder[0])); } // weight will contain all zeros after this loop double normalizer = scale.normalizer(compression, totalWeight); double k1 = scale.k(0, normalizer); double wLimit = totalWeight * scale.q(k1 + 1, normalizer); for (int i = 1; i < incomingCount; i++) { int ix = incomingOrder[i]; double proposedWeight = weight[lastUsedCell.get()] + incomingWeight[ix]; double projectedW = wSoFar + proposedWeight; boolean addThis; if (useWeightLimit) { double q0 = wSoFar / totalWeight; double q2 = (wSoFar + proposedWeight) / totalWeight; addThis = proposedWeight <= totalWeight * Math.min(scale.max(q0, normalizer), scale.max(q2, normalizer)); } else { addThis = projectedW <= wLimit; } if (i == 1 || i == incomingCount - 1) { // force last centroid to never merge addThis = false; } if (addThis) { // next point will fit // so merge into existing centroid weight[lastUsedCell.get()] += incomingWeight[ix]; mean[lastUsedCell.get()] = mean[lastUsedCell.get()] + (incomingMean[ix] - mean[lastUsedCell.get()]) * incomingWeight[ix] / weight[lastUsedCell.get()]; incomingWeight[ix] = 0; if (data != null) { while (data.size() <= lastUsedCell.get()) { data.add(new ArrayList<Double>()); } assert incomingData != null; assert data.get(lastUsedCell.get()) != incomingData.get(ix); data.get(lastUsedCell.get()).addAll(incomingData.get(ix)); } } else { // didn't fit ... move to next output, copy out first centroid wSoFar += weight[lastUsedCell.get()]; if (!useWeightLimit) { k1 = scale.k(wSoFar / totalWeight, normalizer); wLimit = totalWeight * scale.q(k1 + 1, normalizer); } lastUsedCell.getAndIncrement(); mean[lastUsedCell.get()] = incomingMean[ix]; weight[lastUsedCell.get()] = incomingWeight[ix]; incomingWeight[ix] = 0; if (data != null) { assert incomingData != null; assert data.size() == lastUsedCell.get(); data.add(incomingData.get(ix)); } } } // points to next empty cell lastUsedCell.getAndIncrement(); // sanity check double sum = 0; for (int i = 0; i < lastUsedCell.get(); i++) { sum += weight[i]; } assert sum == totalWeight; if (runBackwards) { Sort.reverse(mean, 0, lastUsedCell.get()); Sort.reverse(weight, 0, lastUsedCell.get()); if (data != null) { Collections.reverse(data); } } assert weight[0] == 1; assert weight[lastUsedCell.get() - 1] == 1; if (totalWeight > 0) { min = Math.min(min, mean[0]); max = Math.max(max, mean[lastUsedCell.get() - 1]); } } /** * Merges any pending inputs and compresses the data down to the public setting. * Note that this typically loses a bit of precision and thus isn't a thing to * be doing all the time. It is best done only when we want to show results to * the outside world. */ @Override public void compress() { mergeNewValues(true, publicCompression); } @Override public long size() { return (long) (totalWeight + unmergedWeight.get()); } @Override public double cdf(double x) { if (Double.isNaN(x) || Double.isInfinite(x)) { throw new IllegalArgumentException(String.format("Invalid value: %f", x)); } mergeNewValues(); if (lastUsedCell.get() == 0) { // no data to examine return Double.NaN; } else if (lastUsedCell.get() == 1) { // exactly one centroid, should have max==min double width = max - min; if (x < min) { return 0; } else if (x > max) { return 1; } else if (x - min <= width) { // min and max are too close together to do any viable interpolation return 0.5; } else { // interpolate if somehow we have weight > 0 and max != min return (x - min) / (max - min); } } else { int n = lastUsedCell.get(); if (x < min) { return 0; } if (x > max) { return 1; } // check for the left tail if (x < mean[0]) { // note that this is different than mean[0] > min // ... this guarantees we divide by non-zero number and interpolation works if (mean[0] - min > 0) { // must be a sample exactly at min if (x == min) { return 0.5 / totalWeight; } else { return (1 + (x - min) / (mean[0] - min) * (weight[0] / 2 - 1)) / totalWeight; } } else { // this should be redundant with the check x < min return 0; } } assert x >= mean[0]; // and the right tail if (x > mean[n - 1]) { if (max - mean[n - 1] > 0) { if (x == max) { return 1 - 0.5 / totalWeight; } else { // there has to be a single sample exactly at max double dq = (1 + (max - x) / (max - mean[n - 1]) * (weight[n - 1] / 2 - 1)) / totalWeight; return 1 - dq; } } else { return 1; } } // we know that there are at least two centroids and mean[0] < x < mean[n-1] // that means that there are either one or more consecutive centroids all at exactly x // or there are consecutive centroids, c0 < x < c1 double weightSoFar = 0; for (int it = 0; it < n - 1; it++) { // weightSoFar does not include weight[it] yet if (mean[it] == x) { // we have one or more centroids == x, treat them as one // dw will accumulate the weight of all of the centroids at x double dw = 0; while (it < n && mean[it] == x) { dw += weight[it]; it++; } return (weightSoFar + dw / 2) / totalWeight; } else if (mean[it] <= x && x < mean[it + 1]) { // landed between centroids ... check for floating point madness if (mean[it + 1] - mean[it] > 0) { // note how we handle singleton centroids here // the point is that for singleton centroids, we know that their entire // weight is exactly at the centroid and thus shouldn't be involved in // interpolation double leftExcludedW = 0; double rightExcludedW = 0; if (weight[it] == 1) { if (weight[it + 1] == 1) { // two singletons means no interpolation // left singleton is in, right is out return (weightSoFar + 1) / totalWeight; } else { leftExcludedW = 0.5; } } else if (weight[it + 1] == 1) { rightExcludedW = 0.5; } double dw = (weight[it] + weight[it + 1]) / 2; // can't have double singleton (handled that earlier) assert dw > 1; assert (leftExcludedW + rightExcludedW) <= 0.5; // adjust endpoints for any singleton double left = mean[it]; double right = mean[it + 1]; double dwNoSingleton = dw - leftExcludedW - rightExcludedW; // adjustments have only limited effect on endpoints assert dwNoSingleton > dw / 2; assert right - left > 0; double base = weightSoFar + weight[it] / 2 + leftExcludedW; return (base + dwNoSingleton * (x - left) / (right - left)) / totalWeight; } else { // this is simply caution against floating point madness // it is conceivable that the centroids will be different // but too near to allow safe interpolation double dw = (weight[it] + weight[it + 1]) / 2; return (weightSoFar + dw) / totalWeight; } } else { weightSoFar += weight[it]; } } if (x == mean[n - 1]) { return 1 - 0.5 / totalWeight; } else { throw new IllegalStateException("Can't happen ... loop fell through"); } } } @Override public double quantile(double q) { if (q < 0 || q > 1) { throw new IllegalArgumentException("q should be in [0,1], got " + q); } mergeNewValues(); if (lastUsedCell.get() == 0) { // no centroids means no data, no way to get a quantile return Double.NaN; } else if (lastUsedCell.get() == 1) { // with one data point, all quantiles lead to Rome return mean[0]; } // we know that there are at least two centroids now int n = lastUsedCell.get(); // if values were stored in a sorted array, index would be the offset we are interested in final double index = q * totalWeight; // beyond the boundaries, we return min or max // usually, the first centroid will have unit weight so this will make it moot if (index < 1) { return min; } // if the left centroid has more than one sample, we still know // that one sample occurred at min so we can do some interpolation if (weight[0] > 1 && index < weight[0] / 2) { // there is a single sample at min so we interpolate with less weight return min + (index - 1) / (weight[0] / 2 - 1) * (mean[0] - min); } // usually the last centroid will have unit weight so this test will make it moot if (index > totalWeight - 1) { return max; } // if the right-most centroid has more than one sample, we still know // that one sample occurred at max so we can do some interpolation if (weight[n - 1] > 1 && totalWeight - index <= weight[n - 1] / 2) { return max - (totalWeight - index - 1) / (weight[n - 1] / 2 - 1) * (max - mean[n - 1]); } // in between extremes we interpolate between centroids double weightSoFar = weight[0] / 2; for (int i = 0; i < n - 1; i++) { double dw = (weight[i] + weight[i + 1]) / 2; if (weightSoFar + dw > index) { // centroids i and i+1 bracket our current point // check for unit weight double leftUnit = 0; if (weight[i] == 1) { if (index - weightSoFar < 0.5) { // within the singleton's sphere return mean[i]; } else { leftUnit = 0.5; } } double rightUnit = 0; if (weight[i + 1] == 1) { if (weightSoFar + dw - index <= 0.5) { // no interpolation needed near singleton return mean[i + 1]; } rightUnit = 0.5; } double z1 = index - weightSoFar - leftUnit; double z2 = weightSoFar + dw - index - rightUnit; return weightedAverage(mean[i], z2, mean[i + 1], z1); } weightSoFar += dw; } // we handled singleton at end up above assert weight[n - 1] > 1; assert index <= totalWeight; assert index >= totalWeight - weight[n - 1] / 2; // weightSoFar = totalWeight - weight[n-1]/2 (very nearly) // so we interpolate out to max value ever seen double z1 = index - totalWeight - weight[n - 1] / 2.0; double z2 = weight[n - 1] / 2 - z1; return weightedAverage(mean[n - 1], z1, max, z2); } @Override public int centroidCount() { mergeNewValues(); return lastUsedCell.get(); } @Override public Collection<Centroid> centroids() { // we don't actually keep centroid structures around so we have to fake it compress(); return new AbstractCollection<Centroid>() { @Override public Iterator<Centroid> iterator() { return new Iterator<Centroid>() { int i = 0; @Override public boolean hasNext() { return i < lastUsedCell.get(); } @Override public Centroid next() { if (!hasNext()) { throw new NoSuchElementException(); } Centroid rc = new Centroid(mean[i], (int) weight[i]); List<Double> datas = data != null ? data.get(i) : null; if (datas != null) { datas.forEach(rc::insertData); } i++; return rc; } @Override public void remove() { throw new UnsupportedOperationException("Default operation"); } }; } @Override public int size() { return lastUsedCell.get(); } }; } @Override public double compression() { return publicCompression; } @Override public int byteSize() { compress(); // format code, compression(float), buffer-size(int), temp-size(int), #centroids-1(int), // then two doubles per centroid return lastUsedCell.get() * 16 + 32; } @Override public int smallByteSize() { compress(); // format code(int), compression(float), buffer-size(short), temp-size(short), #centroids-1(short), // then two floats per centroid return lastUsedCell.get() * 8 + 30; } @SuppressWarnings("WeakerAccess") public ScaleFunction getScaleFunction() { return scale; } @Override public void setScaleFunction(ScaleFunction scaleFunction) { super.setScaleFunction(scaleFunction); } public enum Encoding { VERBOSE_ENCODING(1), SMALL_ENCODING(2); private final int code; Encoding(int code) { this.code = code; } } @Override public void asBytes(ByteBuffer buf) { compress(); buf.putInt(DubboMergingDigest.Encoding.VERBOSE_ENCODING.code); buf.putDouble(min); buf.putDouble(max); buf.putDouble(publicCompression); buf.putInt(lastUsedCell.get()); for (int i = 0; i < lastUsedCell.get(); i++) { buf.putDouble(weight[i]); buf.putDouble(mean[i]); } } @Override public void asSmallBytes(ByteBuffer buf) { compress(); buf.putInt(DubboMergingDigest.Encoding.SMALL_ENCODING.code); // 4 buf.putDouble(min); // + 8 buf.putDouble(max); // + 8 buf.putFloat((float) publicCompression); // + 4 buf.putShort((short) mean.length); // + 2 buf.putShort((short) tempMean.length); // + 2 buf.putShort((short) lastUsedCell.get()); // + 2 = 30 for (int i = 0; i < lastUsedCell.get(); i++) { buf.putFloat((float) weight[i]); buf.putFloat((float) mean[i]); } } @Override public String toString() { return "MergingDigest" + "-" + getScaleFunction() + "-" + (useWeightLimit ? "weight" : "kSize") + "-" + (useAlternatingSort ? "alternating" : "stable") + "-" + (useTwoLevelCompression ? "twoLevel" : "oneLevel"); } }
8,089
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/TimeWindowAggregator.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.AtomicReference; import java.util.concurrent.atomic.DoubleAccumulator; import java.util.concurrent.atomic.LongAdder; public class TimeWindowAggregator { private final SnapshotSlidingWindow slidingWindow; public TimeWindowAggregator(int bucketNum, int timeWindowSeconds) { this.slidingWindow = new SnapshotSlidingWindow(bucketNum, TimeUnit.SECONDS.toMillis(timeWindowSeconds)); } public SnapshotSlidingWindow getSlidingWindow() { return slidingWindow; } public void add(double value) { SnapshotObservation sample = this.slidingWindow.currentPane().getValue(); sample.add(value); } public SampleAggregatedEntry get() { SampleAggregatedEntry aggregatedEntry = new SampleAggregatedEntry(); double total = 0L; long count = 0; double max = Double.MIN_VALUE; double min = Double.MAX_VALUE; List<SnapshotObservation> windows = this.slidingWindow.values(); for (SnapshotObservation window : windows) { total += window.getTotal(); count += window.getCount(); max = Math.max(max, window.getMax()); min = Math.min(min, window.getMin()); } if (count > 0) { double avg = total / count; aggregatedEntry.setAvg(Math.round(avg * 100.0) / 100.0); } else { aggregatedEntry.setAvg(0); } aggregatedEntry.setMax(max == Double.MIN_VALUE ? 0 : max); aggregatedEntry.setMin(min == Double.MAX_VALUE ? 0 : min); aggregatedEntry.setTotal(total); aggregatedEntry.setCount(count); return aggregatedEntry; } public static class SnapshotSlidingWindow extends SlidingWindow<SnapshotObservation> { public SnapshotSlidingWindow(int sampleCount, long intervalInMs) { super(sampleCount, intervalInMs); } @Override public SnapshotObservation newEmptyValue(long timeMillis) { return new SnapshotObservation(); } @Override protected Pane<SnapshotObservation> resetPaneTo(final Pane<SnapshotObservation> pane, long startTime) { pane.setStartInMs(startTime); pane.getValue().reset(); return pane; } } public static class SnapshotObservation { private final AtomicReference<Double> min = new AtomicReference<>(Double.MAX_VALUE); private final AtomicReference<Double> max = new AtomicReference<>(0d); private final DoubleAccumulator total = new DoubleAccumulator((x, y) -> x + y, 0); private final LongAdder count = new LongAdder(); public void add(double sample) { total.accumulate(sample); count.increment(); updateMin(sample); updateMax(sample); } private void updateMin(double sample) { Double curMin; do { curMin = min.get(); } while (sample < curMin && !min.compareAndSet(curMin, sample)); } private void updateMax(double sample) { Double curMax; do { curMax = max.get(); if (sample <= curMax) { return; } } while (!max.compareAndSet(curMax, sample)); } public void reset() { min.set(Double.MAX_VALUE); max.set(0d); count.reset(); total.reset(); } public double getMin() { return min.get(); } public double getMax() { return max.get(); } public Double getTotal() { return total.get(); } public long getCount() { return count.sum(); } } }
8,090
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/SampleAggregatedEntry.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; public class SampleAggregatedEntry { private Long count; private double max; private double min; private double avg; private double total; public Long getCount() { return count; } public void setCount(Long count) { this.count = count; } public double getMax() { return max; } public void setMax(double max) { this.max = max; } public double getMin() { return min; } public void setMin(double min) { this.min = min; } public double getAvg() { return avg; } public void setAvg(double avg) { this.avg = avg; } public double getTotal() { return total; } public void setTotal(double total) { this.total = total; } }
8,091
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/ApplicationMetricsCollector.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.metrics.event.TimeCounterEvent; import org.apache.dubbo.metrics.model.key.MetricsKey; /** * Application-level collector. * registration center, configuration center and other scenarios * * @Params <T> metrics type */ public interface ApplicationMetricsCollector<E extends TimeCounterEvent> extends MetricsCollector<E> { void increment(MetricsKey metricsKey); void addApplicationRt(String registryOpType, Long responseTime); }
8,092
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/ServiceMetricsCollector.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.metrics.event.TimeCounterEvent; import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper; import org.apache.dubbo.rpc.Invocation; /** * Service-level collector. * registration center, configuration center and other scenarios */ public interface ServiceMetricsCollector<E extends TimeCounterEvent> extends MetricsCollector<E> { void increment(String serviceKey, MetricsKeyWrapper wrapper, int size); void setNum(MetricsKeyWrapper metricsKey, String serviceKey, int num); void addServiceRt(String serviceKey, String registryOpType, Long responseTime); void addServiceRt(Invocation invocation, String registryOpType, Long responseTime); }
8,093
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/MethodMetricsCollector.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.metrics.event.TimeCounterEvent; import org.apache.dubbo.metrics.model.MethodMetric; import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper; import org.apache.dubbo.rpc.Invocation; /** * Method-level metrics collection for rpc invocation scenarios */ public interface MethodMetricsCollector<E extends TimeCounterEvent> extends MetricsCollector<E> { void increment(MethodMetric methodMetric, MetricsKeyWrapper wrapper, int size); void addMethodRt(Invocation invocation, String registryOpType, Long responseTime); void init(Invocation invocation, MetricsKeyWrapper wrapper); }
8,094
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/CombMetricsCollector.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.metrics.data.BaseStatComposite; import org.apache.dubbo.metrics.event.MetricsEventMulticaster; import org.apache.dubbo.metrics.event.TimeCounterEvent; import org.apache.dubbo.metrics.listener.AbstractMetricsListener; import org.apache.dubbo.metrics.model.MethodMetric; import org.apache.dubbo.metrics.model.MetricsCategory; 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.rpc.Invocation; import java.util.List; import static org.apache.dubbo.metrics.MetricsConstants.SELF_INCREMENT_SIZE; public abstract class CombMetricsCollector<E extends TimeCounterEvent> extends AbstractMetricsListener<E> implements ApplicationMetricsCollector<E>, ServiceMetricsCollector<E>, MethodMetricsCollector<E> { protected final BaseStatComposite stats; private MetricsEventMulticaster eventMulticaster; public CombMetricsCollector(BaseStatComposite stats) { this.stats = stats; } protected void setEventMulticaster(MetricsEventMulticaster eventMulticaster) { this.eventMulticaster = eventMulticaster; } @Override public void setNum(MetricsKeyWrapper metricsKey, String serviceKey, int num) { this.stats.setServiceKey(metricsKey, serviceKey, num); } @Override public void increment(MetricsKey metricsKey) { this.stats.incrementApp(metricsKey, SELF_INCREMENT_SIZE); } public void increment(String serviceKey, MetricsKeyWrapper metricsKeyWrapper, int size) { this.stats.incrementServiceKey(metricsKeyWrapper, serviceKey, size); } @Override public void addApplicationRt(String registryOpType, Long responseTime) { stats.calcApplicationRt(registryOpType, responseTime); } @Override public void addServiceRt(String serviceKey, String registryOpType, Long responseTime) { stats.calcServiceKeyRt(serviceKey, registryOpType, responseTime); } @Override public void addServiceRt(Invocation invocation, String registryOpType, Long responseTime) { stats.calcServiceKeyRt(invocation, registryOpType, responseTime); } @Override public void addMethodRt(Invocation invocation, String registryOpType, Long responseTime) { stats.calcMethodKeyRt(invocation, registryOpType, responseTime); } @Override public void increment(MethodMetric methodMetric, MetricsKeyWrapper wrapper, int size) { this.stats.incrementMethodKey(wrapper, methodMetric, size); } @Override public void init(Invocation invocation, MetricsKeyWrapper wrapper) { this.stats.initMethodKey(wrapper, invocation); } protected List<MetricSample> export(MetricsCategory category) { return stats.export(category); } public MetricsEventMulticaster getEventMulticaster() { return eventMulticaster; } @Override public void onEvent(TimeCounterEvent event) { eventMulticaster.publishEvent(event); } @Override public void onEventFinish(TimeCounterEvent event) { eventMulticaster.publishFinishEvent(event); } @Override public void onEventError(TimeCounterEvent event) { eventMulticaster.publishErrorEvent(event); } protected BaseStatComposite getStats() { return stats; } }
8,095
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/MetricsCollector.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.extension.SPI; import org.apache.dubbo.metrics.event.MetricsEvent; import org.apache.dubbo.metrics.event.TimeCounterEvent; import org.apache.dubbo.metrics.listener.MetricsLifeListener; import org.apache.dubbo.metrics.model.sample.MetricSample; import java.util.List; /** * Metrics Collector. * An interface of collector to collect framework internal metrics. */ @SPI public interface MetricsCollector<E extends TimeCounterEvent> extends MetricsLifeListener<E> { default boolean isCollectEnabled() { return false; } /** * Collect metrics as {@link MetricSample} * * @return List of MetricSample */ List<MetricSample> collect(); /** * 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(); default void initMetrics(MetricsEvent event) {} ; }
8,096
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/stat/MetricsStatHandler.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.stat; import org.apache.dubbo.metrics.event.MetricsEvent; import org.apache.dubbo.metrics.model.MethodMetric; import org.apache.dubbo.rpc.Invocation; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; public interface MetricsStatHandler { Map<MethodMetric, AtomicLong> get(); MetricsEvent increase(String applicationName, Invocation invocation); MetricsEvent decrease(String applicationName, Invocation invocation); MetricsEvent addApplication(String applicationName); }
8,097
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ThreadPoolMetric.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.model; import org.apache.dubbo.common.utils.ConfigUtils; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.concurrent.ThreadPoolExecutor; 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_PID; 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 ThreadPoolMetric implements Metric { private String applicationName; private String threadPoolName; private ThreadPoolExecutor threadPoolExecutor; public ThreadPoolMetric(String applicationName, String threadPoolName, ThreadPoolExecutor threadPoolExecutor) { this.applicationName = applicationName; this.threadPoolExecutor = threadPoolExecutor; this.threadPoolName = threadPoolName; } public String getThreadPoolName() { return threadPoolName; } public void setThreadPoolName(String threadPoolName) { this.threadPoolName = threadPoolName; } public ThreadPoolExecutor getThreadPoolExecutor() { return threadPoolExecutor; } public void setThreadPoolExecutor(ThreadPoolExecutor threadPoolExecutor) { this.threadPoolExecutor = threadPoolExecutor; } 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; ThreadPoolMetric that = (ThreadPoolMetric) 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; } public double getCorePoolSize() { return threadPoolExecutor.getCorePoolSize(); } public double getLargestPoolSize() { return threadPoolExecutor.getLargestPoolSize(); } public double getMaximumPoolSize() { return threadPoolExecutor.getMaximumPoolSize(); } public double getActiveCount() { return threadPoolExecutor.getActiveCount(); } public double getPoolSize() { return threadPoolExecutor.getPoolSize(); } public double getQueueSize() { return threadPoolExecutor.getQueue().size(); } }
8,098
0
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MethodMetric.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.model; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.MetricsConfig; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.metrics.model.key.MetricsLevel; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.support.RpcUtils; import java.util.Map; import java.util.Objects; import java.util.Optional; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_GROUP_KEY; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_VERSION_KEY; /** * Metric class for method. */ public class MethodMetric extends ServiceKeyMetric { private String side; private final String methodName; private String group; private String version; public MethodMetric(ApplicationModel applicationModel, Invocation invocation, boolean serviceLevel) { super(applicationModel, MetricsSupport.getInterfaceName(invocation)); this.side = MetricsSupport.getSide(invocation); this.group = MetricsSupport.getGroup(invocation); this.version = MetricsSupport.getVersion(invocation); this.methodName = serviceLevel ? null : RpcUtils.getMethodName(invocation); } public static boolean isServiceLevel(ApplicationModel applicationModel) { if (applicationModel == null) { return false; } ConfigManager applicationConfigManager = applicationModel.getApplicationConfigManager(); if (applicationConfigManager == null) { return false; } Optional<MetricsConfig> metrics = applicationConfigManager.getMetrics(); if (!metrics.isPresent()) { return false; } String rpcLevel = metrics.map(MetricsConfig::getRpcLevel).orElse(MetricsLevel.METHOD.name()); rpcLevel = StringUtils.isBlank(rpcLevel) ? MetricsLevel.METHOD.name() : rpcLevel; return MetricsLevel.SERVICE.name().equalsIgnoreCase(rpcLevel); } public String getGroup() { return group; } public void setGroup(String group) { this.group = group; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public Map<String, String> getTags() { Map<String, String> tags = MetricsSupport.methodTags(getApplicationModel(), getServiceKey(), methodName); tags.put(TAG_GROUP_KEY, group); tags.put(TAG_VERSION_KEY, version); return tags; } public String getMethodName() { return methodName; } public String getSide() { return side; } public void setSide(String side) { this.side = side; } @Override public String toString() { return "MethodMetric{" + "applicationName='" + getApplicationName() + '\'' + ", side='" + side + '\'' + ", interfaceName='" + getServiceKey() + '\'' + ", methodName='" + methodName + '\'' + ", group='" + group + '\'' + ", version='" + version + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MethodMetric that = (MethodMetric) o; return Objects.equals(getApplicationModel(), that.getApplicationModel()) && Objects.equals(side, that.side) && Objects.equals(getServiceKey(), that.getServiceKey()) && Objects.equals(methodName, that.methodName) && Objects.equals(group, that.group) && Objects.equals(version, that.version); } private volatile int hashCode = 0; @Override public int hashCode() { if (hashCode == 0) { hashCode = Objects.hash(getApplicationModel(), side, getServiceKey(), methodName, group, version); } return hashCode; } }
8,099