diff --git a/.artifacts b/.artifacts index 5818a24e9ad..61dc29d220e 100644 --- a/.artifacts +++ b/.artifacts @@ -59,7 +59,7 @@ dubbo-metrics-prometheus dubbo-metrics-registry dubbo-metrics-config-center dubbo-metrics-netty -dubbo-metrics-event +dubbo-metrics-monitor dubbo-native dubbo-parent dubbo-plugin diff --git a/dubbo-cluster/pom.xml b/dubbo-cluster/pom.xml index f5136d52cfe..1c7e3332fec 100644 --- a/dubbo-cluster/pom.xml +++ b/dubbo-cluster/pom.xml @@ -75,18 +75,6 @@ ${project.parent.version} test - - org.apache.dubbo - dubbo-metrics-registry - ${project.parent.version} - compile - - - org.apache.dubbo - dubbo-metrics-default - ${project.parent.version} - true - io.micrometer micrometer-tracing-integration-test diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/AbstractDirectory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/AbstractDirectory.java index be68810f4ae..eef0600b406 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/AbstractDirectory.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/AbstractDirectory.java @@ -21,6 +21,7 @@ import org.apache.dubbo.common.config.Configuration; import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.constants.LoggerCodeConstants; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository; @@ -28,9 +29,6 @@ import org.apache.dubbo.common.utils.LockUtils; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.metrics.event.MetricsEventBus; -import org.apache.dubbo.metrics.model.key.MetricsKey; -import org.apache.dubbo.metrics.registry.event.RegistryEvent; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcContext; @@ -46,7 +44,6 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; -import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; @@ -393,14 +390,13 @@ public void checkConnectivity() { checkConnectivity(); } }); - MetricsEventBus.publish(RegistryEvent.refreshDirectoryEvent( - applicationModel, getSummary(), getDirectoryMeta())); + DubboEventBus.publish( + new DirectoryRefreshEvent(applicationModel, getSummary(), getDirectoryMeta())); }, reconnectTaskPeriod, TimeUnit.MILLISECONDS); } - MetricsEventBus.publish( - RegistryEvent.refreshDirectoryEvent(applicationModel, getSummary(), getDirectoryMeta())); + DubboEventBus.publish(new DirectoryRefreshEvent(applicationModel, getSummary(), getDirectoryMeta())); } /** @@ -416,8 +412,7 @@ public void refreshInvoker() { refreshInvokerInternal(); } }); - MetricsEventBus.publish( - RegistryEvent.refreshDirectoryEvent(applicationModel, getSummary(), getDirectoryMeta())); + DubboEventBus.publish(new DirectoryRefreshEvent(applicationModel, getSummary(), getDirectoryMeta())); } protected Map getDirectoryMeta() { @@ -452,8 +447,7 @@ public void addDisabledInvoker(Invoker invoker) { logger.info("Disable service address: " + invoker.getUrl() + "."); } }); - MetricsEventBus.publish( - RegistryEvent.refreshDirectoryEvent(applicationModel, getSummary(), getDirectoryMeta())); + DubboEventBus.publish(new DirectoryRefreshEvent(applicationModel, getSummary(), getDirectoryMeta())); } @Override @@ -468,8 +462,7 @@ public void recoverDisabledInvoker(Invoker invoker) { } } }); - MetricsEventBus.publish( - RegistryEvent.refreshDirectoryEvent(applicationModel, getSummary(), getDirectoryMeta())); + DubboEventBus.publish(new DirectoryRefreshEvent(applicationModel, getSummary(), getDirectoryMeta())); } protected final void refreshRouter(BitList> newlyInvokers, Runnable switchAction) { @@ -532,8 +525,7 @@ protected void setInvokers(BitList> invokers) { this.invokersInitialized = true; }); - MetricsEventBus.publish( - RegistryEvent.refreshDirectoryEvent(applicationModel, getSummary(), getDirectoryMeta())); + DubboEventBus.publish(new DirectoryRefreshEvent(applicationModel, getSummary(), getDirectoryMeta())); } protected void destroyInvokers() { @@ -550,8 +542,7 @@ private boolean addValidInvoker(Invoker invoker) { LockUtils.safeLock(invokerRefreshLock, LockUtils.DEFAULT_TIMEOUT, () -> { result.set(this.validInvokers.add(invoker)); }); - MetricsEventBus.publish( - RegistryEvent.refreshDirectoryEvent(applicationModel, getSummary(), getDirectoryMeta())); + DubboEventBus.publish(new DirectoryRefreshEvent(applicationModel, getSummary(), getDirectoryMeta())); return result.get(); } @@ -560,8 +551,7 @@ private boolean removeValidInvoker(Invoker invoker) { LockUtils.safeLock(invokerRefreshLock, LockUtils.DEFAULT_TIMEOUT, () -> { result.set(this.validInvokers.remove(invoker)); }); - MetricsEventBus.publish( - RegistryEvent.refreshDirectoryEvent(applicationModel, getSummary(), getDirectoryMeta())); + DubboEventBus.publish(new DirectoryRefreshEvent(applicationModel, getSummary(), getDirectoryMeta())); return result.get(); } @@ -581,14 +571,13 @@ protected String joinValidInvokerAddresses() { .collect(Collectors.joining(",")); } - private Map> getSummary() { - Map> summaryMap = new HashMap<>(); - - summaryMap.put(MetricsKey.DIRECTORY_METRIC_NUM_VALID, groupByServiceKey(getValidInvokers())); - summaryMap.put(MetricsKey.DIRECTORY_METRIC_NUM_DISABLE, groupByServiceKey(getDisabledInvokers())); - summaryMap.put(MetricsKey.DIRECTORY_METRIC_NUM_TO_RECONNECT, groupByServiceKey(getInvokersToReconnect())); - summaryMap.put(MetricsKey.DIRECTORY_METRIC_NUM_ALL, groupByServiceKey(getInvokers())); - return summaryMap; + private DirectoryRefreshEvent.Summary getSummary() { + DirectoryRefreshEvent.Summary summary = new DirectoryRefreshEvent.Summary(); + summary.directoryNumValidMap = groupByServiceKey(getValidInvokers()); + summary.directoryNumDisableMap = groupByServiceKey(getDisabledInvokers()); + summary.directoryNumToReConnectMap = groupByServiceKey(getInvokersToReconnect()); + summary.directoryNumAllMap = groupByServiceKey(getInvokers()); + return summary; } private Map groupByServiceKey(Collection> invokers) { diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/DirectoryRefreshEvent.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/DirectoryRefreshEvent.java new file mode 100644 index 00000000000..8cd8ae761c3 --- /dev/null +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/DirectoryRefreshEvent.java @@ -0,0 +1,62 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.rpc.cluster.directory; + +import org.apache.dubbo.common.event.DubboEvent; +import org.apache.dubbo.common.utils.TimePair; +import org.apache.dubbo.rpc.model.ApplicationModel; + +import java.util.Map; + +public class DirectoryRefreshEvent extends DubboEvent { + + private final TimePair timePair; + + private final Summary summary; + + private final Map attachments; + + public DirectoryRefreshEvent(ApplicationModel applicationModel, Summary summary, Map attachments) { + super(applicationModel); + this.summary = summary; + this.attachments = attachments; + this.timePair = TimePair.start(); + } + + public Summary getSummary() { + return summary; + } + + public Map getAttachments() { + return attachments; + } + + public TimePair getTimePair() { + return timePair; + } + + public static class Summary { + + public Map directoryNumValidMap; + + public Map directoryNumDisableMap; + + public Map directoryNumToReConnectMap; + + public Map directoryNumAllMap; + } +} diff --git a/dubbo-cluster/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.filter.ClusterFilter b/dubbo-cluster/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.filter.ClusterFilter index 4e0de2450af..b1494d9a906 100644 --- a/dubbo-cluster/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.filter.ClusterFilter +++ b/dubbo-cluster/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.filter.ClusterFilter @@ -1,4 +1,3 @@ consumercontext=org.apache.dubbo.rpc.cluster.filter.support.ConsumerContextFilter consumer-classloader=org.apache.dubbo.rpc.cluster.filter.support.ConsumerClassLoaderFilter -router-snapshot=org.apache.dubbo.rpc.cluster.router.RouterSnapshotFilter -metricsConsumerFilter=org.apache.dubbo.rpc.cluster.filter.support.MetricsConsumerFilter +router-snapshot=org.apache.dubbo.rpc.cluster.router.RouterSnapshotFilter \ No newline at end of file diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/StaticDirectoryTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/StaticDirectoryTest.java index d18bb8fe66f..a17ae0f74f2 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/StaticDirectoryTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/StaticDirectoryTest.java @@ -19,14 +19,12 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.Holder; import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.metrics.event.MetricsDispatcher; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.cluster.router.MockInvoker; import org.apache.dubbo.rpc.cluster.router.condition.ConditionStateRouterFactory; import org.apache.dubbo.rpc.cluster.router.state.BitList; import org.apache.dubbo.rpc.cluster.router.state.StateRouter; -import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.ArrayList; import java.util.List; @@ -70,7 +68,6 @@ void testStaticDirectory() { new RpcInvocation(), false, new Holder<>()); - ApplicationModel.defaultModel().getBeanFactory().registerBean(MetricsDispatcher.class); StaticDirectory staticDirectory = new StaticDirectory<>(filteredInvokers); boolean isAvailable = staticDirectory.isAvailable(); Assertions.assertTrue(isAvailable); diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterEngineTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterEngineTest.java index e2aff971362..67d2b9b26bd 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterEngineTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterEngineTest.java @@ -18,7 +18,6 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.metrics.event.MetricsDispatcher; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; @@ -31,7 +30,6 @@ import org.apache.dubbo.rpc.cluster.directory.StaticDirectory; import org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory; import org.apache.dubbo.rpc.cluster.support.AbstractClusterInvoker; -import org.apache.dubbo.rpc.model.ApplicationModel; import javax.script.ScriptEngineManager; @@ -63,7 +61,6 @@ class FileRouterEngineTest { @BeforeAll public static void setUpBeforeClass() throws Exception { - ApplicationModel.defaultModel().getBeanFactory().registerBean(MetricsDispatcher.class); System.setProperty(ENABLE_CONNECTIVITY_VALIDATION, "false"); } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java index 6cbed8481fc..05d5d05c97a 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java @@ -20,7 +20,6 @@ import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.metrics.event.MetricsDispatcher; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; @@ -34,7 +33,6 @@ import org.apache.dubbo.rpc.cluster.loadbalance.LeastActiveLoadBalance; import org.apache.dubbo.rpc.cluster.loadbalance.RandomLoadBalance; import org.apache.dubbo.rpc.cluster.loadbalance.RoundRobinLoadBalance; -import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.ArrayList; import java.util.Collections; @@ -109,7 +107,6 @@ public static void afterClass() { @SuppressWarnings({"unchecked"}) @BeforeEach public void setUp() throws Exception { - ApplicationModel.defaultModel().getBeanFactory().registerBean(MetricsDispatcher.class); Map attributes = new HashMap<>(); attributes.put("application", "abstractClusterInvokerTest"); url = url.putAttribute(REFER_KEY, attributes); diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ConnectivityValidationTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ConnectivityValidationTest.java index a2f6b1499fe..11f721bf0ac 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ConnectivityValidationTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ConnectivityValidationTest.java @@ -19,7 +19,6 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.utils.CollectionUtils; -import org.apache.dubbo.metrics.event.MetricsDispatcher; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; @@ -28,7 +27,6 @@ import org.apache.dubbo.rpc.cluster.Directory; import org.apache.dubbo.rpc.cluster.LoadBalance; import org.apache.dubbo.rpc.cluster.directory.StaticDirectory; -import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Collections; import java.util.HashSet; @@ -72,7 +70,6 @@ class ConnectivityValidationTest { @BeforeEach public void setup() { - ApplicationModel.defaultModel().getBeanFactory().registerBean(MetricsDispatcher.class); invoker1 = Mockito.mock(Invoker.class); invoker2 = Mockito.mock(Invoker.class); invoker3 = Mockito.mock(Invoker.class); diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailoverClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailoverClusterInvokerTest.java index bc48b8629c1..baeac3aafbb 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailoverClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailoverClusterInvokerTest.java @@ -17,7 +17,6 @@ package org.apache.dubbo.rpc.cluster.support; import org.apache.dubbo.common.URL; -import org.apache.dubbo.metrics.event.MetricsDispatcher; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Invocation; @@ -30,7 +29,6 @@ import org.apache.dubbo.rpc.cluster.SingleRouterChain; import org.apache.dubbo.rpc.cluster.directory.StaticDirectory; import org.apache.dubbo.rpc.cluster.router.state.BitList; -import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.protocol.AbstractInvoker; import java.util.ArrayList; @@ -67,7 +65,6 @@ class FailoverClusterInvokerTest { */ @BeforeEach public void setUp() throws Exception { - ApplicationModel.defaultModel().getBeanFactory().registerBean(MetricsDispatcher.class); dic = mock(Directory.class); given(dic.getUrl()).willReturn(url); diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/MockAbstractClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/MockAbstractClusterInvokerTest.java index 5a31ff663a6..bdf5b86e503 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/MockAbstractClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/MockAbstractClusterInvokerTest.java @@ -17,7 +17,6 @@ package org.apache.dubbo.rpc.cluster.support; import org.apache.dubbo.common.URL; -import org.apache.dubbo.metrics.event.MetricsDispatcher; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; @@ -26,7 +25,6 @@ import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.cluster.LoadBalance; import org.apache.dubbo.rpc.cluster.directory.StaticDirectory; -import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.ArrayList; import java.util.HashMap; @@ -89,7 +87,6 @@ public static void afterClass() { @SuppressWarnings({"unchecked"}) @BeforeEach public void setUp() throws Exception { - ApplicationModel.defaultModel().getBeanFactory().registerBean(MetricsDispatcher.class); Map attributes = new HashMap<>(); attributes.put("application", "abstractClusterInvokerTest"); url = url.putAttribute(REFER_KEY, attributes); diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvokerTest.java index cc4dbb94bc9..6ffef03bf3b 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvokerTest.java @@ -18,7 +18,6 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.metrics.event.MetricsDispatcher; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; @@ -29,7 +28,6 @@ import org.apache.dubbo.rpc.cluster.LoadBalance; import org.apache.dubbo.rpc.cluster.directory.StaticDirectory; import org.apache.dubbo.rpc.cluster.support.AbstractClusterInvoker; -import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.support.MockProtocol; import java.util.ArrayList; @@ -51,7 +49,6 @@ class MockClusterInvokerTest { @BeforeEach public void beforeMethod() { - ApplicationModel.defaultModel().getBeanFactory().registerBean(MetricsDispatcher.class); invokers.clear(); } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockProviderRpcExceptionTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockProviderRpcExceptionTest.java index 4851e1790b5..e63892b37c9 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockProviderRpcExceptionTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockProviderRpcExceptionTest.java @@ -18,7 +18,6 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.metrics.event.MetricsDispatcher; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.ProxyFactory; @@ -28,7 +27,6 @@ import org.apache.dubbo.rpc.cluster.LoadBalance; import org.apache.dubbo.rpc.cluster.directory.StaticDirectory; import org.apache.dubbo.rpc.cluster.support.AbstractClusterInvoker; -import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.ArrayList; import java.util.Arrays; @@ -48,7 +46,6 @@ class MockProviderRpcExceptionTest { @BeforeEach public void beforeMethod() { - ApplicationModel.defaultModel().getBeanFactory().registerBean(MetricsDispatcher.class); invokers.clear(); } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/ScopeClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/ScopeClusterInvokerTest.java index f04617e6687..d59188731e5 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/ScopeClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/ScopeClusterInvokerTest.java @@ -18,7 +18,6 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.metrics.event.MetricsDispatcher; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; @@ -67,9 +66,7 @@ class ScopeClusterInvokerTest { private final List> exporters = new ArrayList<>(); @BeforeEach - void beforeMonth() { - ApplicationModel.defaultModel().getBeanFactory().registerBean(MetricsDispatcher.class); - } + void beforeMonth() {} @AfterEach void after() throws Exception { diff --git a/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/ConfigCenterMetricsConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/Ordered.java similarity index 71% rename from dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/ConfigCenterMetricsConstants.java rename to dubbo-common/src/main/java/org/apache/dubbo/common/Ordered.java index 157df551d40..3c2d995296b 100644 --- a/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/ConfigCenterMetricsConstants.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/Ordered.java @@ -14,12 +14,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.metrics.config; +package org.apache.dubbo.common; -public interface ConfigCenterMetricsConstants { +public interface Ordered { - String ATTACHMENT_KEY_CONFIG_FILE = "configFileKey"; - String ATTACHMENT_KEY_CONFIG_GROUP = "configGroup"; - String ATTACHMENT_KEY_CONFIG_PROTOCOL = "configProtocol"; - String ATTACHMENT_KEY_CHANGE_TYPE = "configChangeType"; + int HIGHEST_PRECEDENCE = Integer.MIN_VALUE; + + int LOWEST_PRECEDENCE = Integer.MAX_VALUE; + + default int getOrder() { + return 0; + } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/ConfigCenterChangeEvent.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/ConfigCenterChangeEvent.java new file mode 100644 index 00000000000..f8c4658b459 --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/ConfigCenterChangeEvent.java @@ -0,0 +1,81 @@ +/* + * 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.common.config.configcenter; + +import org.apache.dubbo.common.event.DubboEvent; +import org.apache.dubbo.common.utils.TimePair; +import org.apache.dubbo.rpc.model.ApplicationModel; + +public class ConfigCenterChangeEvent extends DubboEvent { + + private final String key; + + private final String group; + + private final String protocol; + + private final ConfigChangeType changeType; + + private final int count; + + private final TimePair timePair; + + public ConfigCenterChangeEvent( + ApplicationModel source, String key, String group, String protocol, ConfigChangeType changeType) { + this(source, key, group, protocol, changeType, 1); + } + + public ConfigCenterChangeEvent( + ApplicationModel source, + String key, + String group, + String protocol, + ConfigChangeType changeType, + int count) { + super(source); + this.key = key; + this.group = group; + this.protocol = protocol; + this.changeType = changeType; + this.count = count; + this.timePair = TimePair.start(); + } + + public TimePair getTimePair() { + return timePair; + } + + public String getKey() { + return key; + } + + public String getGroup() { + return group; + } + + public String getProtocol() { + return protocol; + } + + public ConfigChangeType getChangeType() { + return changeType; + } + + public int getCount() { + return count; + } +} diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/event/AbstractDubboLifecycleListener.java b/dubbo-common/src/main/java/org/apache/dubbo/common/event/AbstractDubboLifecycleListener.java new file mode 100644 index 00000000000..6887c4d1f4d --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/event/AbstractDubboLifecycleListener.java @@ -0,0 +1,25 @@ +/* + * 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.common.event; + +/** + * Abstract Dubbo Lifecycle Listener. Abstract Dubbo Listener. Match the event type by generic type. + * + * @param the event to respond to + */ +public abstract class AbstractDubboLifecycleListener extends AbstractDubboListener + implements DubboLifecycleListener {} diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/AbstractMetricsListener.java b/dubbo-common/src/main/java/org/apache/dubbo/common/event/AbstractDubboListener.java similarity index 64% rename from dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/AbstractMetricsListener.java rename to dubbo-common/src/main/java/org/apache/dubbo/common/event/AbstractDubboListener.java index dce4a8b207a..a3c2dae4af0 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/AbstractMetricsListener.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/event/AbstractDubboListener.java @@ -14,27 +14,31 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.metrics.listener; +package org.apache.dubbo.common.event; import org.apache.dubbo.common.utils.ReflectionUtils; -import org.apache.dubbo.metrics.event.MetricsEvent; +import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -public abstract class AbstractMetricsListener implements MetricsListener { +/** + * Abstract Dubbo Listener. Match the event type by generic type. + * + * @param the event to respond to + */ +public abstract class AbstractDubboListener implements DubboListener { private final Map, 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); + public boolean support(Class eventClass) { + return eventMatchCache.computeIfAbsent(eventClass, clazz -> { + List> eventTypes = ReflectionUtils.getClassGenerics(getClass(), AbstractDubboListener.class); + return eventTypes.stream().allMatch(eventType -> eventType.isAssignableFrom(clazz)); + }); + } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/event/CustomAfterPost.java b/dubbo-common/src/main/java/org/apache/dubbo/common/event/CustomAfterPost.java new file mode 100644 index 00000000000..73507cb78dd --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/event/CustomAfterPost.java @@ -0,0 +1,29 @@ +/* + * 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.common.event; + +/** + * Custom method after post action and before publish after event + * + * @param The result type of post + * @since 3.3.0 + * @see DubboEventBus#after(DubboEvent, Object) + */ +public interface CustomAfterPost { + + void customAfterPost(R postResult); +} diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/event/DefaultDubboEventMulticaster.java b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DefaultDubboEventMulticaster.java new file mode 100644 index 00000000000..06a37292f10 --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DefaultDubboEventMulticaster.java @@ -0,0 +1,114 @@ +/* + * 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.common.event; + +import java.util.Collection; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArraySet; + +public class DefaultDubboEventMulticaster implements DubboLifecycleEventMulticaster { + + /** + * All registered subscribers, indexed by event type. + * + *

The {@link CopyOnWriteArraySet} values make it easy and relatively lightweight to get an + * immutable snapshot of all current subscribers to an event without any locking. + */ + private final Set> listeners = new CopyOnWriteArraySet<>(); + + final Map, Set>> listenerCache = new ConcurrentHashMap<>(64); + + /** + * Registers all subscriber methods on the given listener object. + * + * @param listener object whose subscriber methods should be registered. + */ + @Override + public void addListener(DubboListener listener) { + synchronized (this.listeners) { + this.listeners.add(listener); + listenerCache.clear(); + } + } + + /** + * Registers all subscriber methods on the given listener object. + * + * @param listener object whose subscriber methods should be registered. + */ + @Override + public void removeListener(DubboListener listener) { + synchronized (this.listeners) { + this.listeners.remove(listener); + listenerCache.clear(); + } + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public void publishEvent(DubboEvent event) { + for (DubboListener listener : getListeners(event.getClass())) { + listener.onEvent(event); + } + } + + /** + * Return the listeners for the given event type. + * + * @param eventType the type of event to find listeners for. + * @return a live {@link Collection} of listeners for the given event type. If no listeners are + * found, this method returns an empty collection. + */ + public Collection> getListeners(Class eventType) { + return listenerCache.computeIfAbsent(eventType, key -> { + Set> listeners = new CopyOnWriteArraySet<>(); + for (DubboListener listener : this.listeners) { + if (listener.support(eventType)) { + listeners.add(listener); + } + } + return listeners; + }); + } + + /** + * Remove a listener from the notification list. + * + * @param listener the listener to remove + */ + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public void publishBeforeEvent(DubboEvent event) { + for (DubboListener listener : getListeners(event.getClass())) { + if (listener instanceof DubboLifecycleListener) { + ((DubboLifecycleListener) listener).onEventBefore(event); + } + } + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public void publishErrorEvent(DubboEvent event) { + for (DubboListener listener : getListeners(event.getClass())) { + if (listener instanceof DubboLifecycleListener) { + ((DubboLifecycleListener) listener).onEventError(event); + } + } + } +} diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEvent.java b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEvent.java new file mode 100644 index 00000000000..3d3d0ff0902 --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEvent.java @@ -0,0 +1,43 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.common.event; + +import org.apache.dubbo.rpc.model.ApplicationModel; + +import java.util.EventObject; + +/** + * Dubbo Event Object + * + * @since 3.3.0 + */ +public class DubboEvent extends EventObject { + + /** + * Constructs a prototypical Event. + * + * @param source The object on which the Event initially occurred. + * @throws IllegalArgumentException if source is null. + */ + public DubboEvent(ApplicationModel source) { + super(source); + } + + public ApplicationModel getApplicationModel() { + return (ApplicationModel) getSource(); + } +} diff --git a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/MetricsEventBus.java b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEventBus.java similarity index 50% rename from dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/MetricsEventBus.java rename to dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEventBus.java index 7654c2d9020..66890853e48 100644 --- a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/MetricsEventBus.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEventBus.java @@ -14,12 +14,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.metrics.event; +package org.apache.dubbo.common.event; +import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; +import org.apache.dubbo.rpc.model.ApplicationModel; -import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.function.Supplier; @@ -27,24 +29,50 @@ /** * Dispatches events to listeners, and provides ways for listeners to register themselves. + * + * @see DubboEvent + * @see DubboListener + * @see DubboLifecycleEventMulticaster + * @since 3.3.0 */ -public class MetricsEventBus { +public class DubboEventBus { + + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DubboEventBus.class); + + private static final ConcurrentHashMap cachedMulticasterMap = + new ConcurrentHashMap<>(); + + private DubboEventBus() {} + + /** + * Registers all subscriber methods on {@code object} to receive events. + * + * @param listener object whose subscriber methods should be registered. + */ + public static void addListener(ApplicationModel applicationModel, DubboListener listener) { + getMulticaster(applicationModel).addListener(listener); + } - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MetricsEventBus.class); + /** + * Unregisters all subscriber methods on a registered {@code object}. + * + * @param listener object whose subscriber methods should be unregistered. + * @throws IllegalArgumentException if the object was not previously registered. + */ + public static void removeListener(ApplicationModel applicationModel, DubboListener listener) { + getMulticaster(applicationModel).removeListener(listener); + } /** * Posts an event to all registered subscribers and only once. * * @param event event to post. */ - public static void publish(MetricsEvent event) { + public static void publish(DubboEvent event) { if (event.getSource() == null) { return; } - MetricsEventMulticaster dispatcher = event.getMetricsEventMulticaster(); - Optional.ofNullable(dispatcher).ifPresent(d -> { - tryInvoke(() -> d.publishEvent(event)); - }); + tryInvoke(() -> getMulticaster(event.getApplicationModel()).publishEvent(event)); } /** @@ -55,7 +83,7 @@ public static void publish(MetricsEvent event) { * @param event event to post. * @param targetSupplier original processing result targetSupplier */ - public static T post(MetricsEvent event, Supplier targetSupplier) { + public static T post(DubboEvent event, Supplier targetSupplier) { return post(event, targetSupplier, null); } @@ -68,30 +96,29 @@ public static T post(MetricsEvent event, Supplier targetSupplier) { * @param Biz result type * @return Biz result */ - public static T post(MetricsEvent event, Supplier targetSupplier, Function trFunction) { + public static T post(DubboEvent event, Supplier targetSupplier, Function trFunction) { T result; tryInvoke(() -> before(event)); + try { + result = targetSupplier.get(); + } catch (Throwable e) { + tryInvoke(() -> error(event)); + throw e; + } if (trFunction == null) { - try { - result = targetSupplier.get(); - } catch (Throwable e) { - tryInvoke(() -> error(event)); - throw e; - } + tryInvoke(() -> after(event, result)); + return result; + } + // Custom failure status + if (trFunction.apply(result)) { tryInvoke(() -> after(event, result)); } else { - // Custom failure status - result = targetSupplier.get(); - if (trFunction.apply(result)) { - tryInvoke(() -> after(event, result)); - } else { - tryInvoke(() -> error(event)); - } + tryInvoke(() -> error(event)); } return result; } - public static void tryInvoke(Runnable runnable) { + private static void tryInvoke(Runnable runnable) { try { runnable.run(); } catch (Throwable e) { @@ -103,36 +130,28 @@ public static void tryInvoke(Runnable runnable) { * Applicable to the scene where execution and return are separated, * eventSaveRunner saves the event, so that the calculation rt is introverted */ - public static void before(MetricsEvent event) { - MetricsEventMulticaster dispatcher = validate(event); - - if (dispatcher == null) return; - tryInvoke(() -> dispatcher.publishEvent(event)); + public static void before(DubboEvent event) { + tryInvoke(() -> getMulticaster(event.getApplicationModel()).publishBeforeEvent(event)); } - public static void after(MetricsEvent event, Object result) { - MetricsEventMulticaster dispatcher = validate(event); - if (dispatcher == null) return; + @SuppressWarnings({"unchecked", "rawtypes"}) + public static void after(DubboEvent event, Object result) { tryInvoke(() -> { - event.customAfterPost(result); - dispatcher.publishFinishEvent((TimeCounterEvent) event); + if (event instanceof CustomAfterPost) { + ((CustomAfterPost) event).customAfterPost(result); + } + getMulticaster(event.getApplicationModel()).publishEvent(event); }); } - public static void error(MetricsEvent event) { - MetricsEventMulticaster dispatcher = validate(event); - if (dispatcher == null) return; - tryInvoke(() -> dispatcher.publishErrorEvent((TimeCounterEvent) event)); + public static void error(DubboEvent event) { + tryInvoke(() -> getMulticaster(event.getApplicationModel()).publishErrorEvent(event)); } - private static MetricsEventMulticaster validate(MetricsEvent event) { - MetricsEventMulticaster dispatcher = event.getMetricsEventMulticaster(); - if (dispatcher == null) { - return null; - } - if (!(event instanceof TimeCounterEvent)) { - return null; - } - return dispatcher; + private static DubboLifecycleEventMulticaster getMulticaster(ApplicationModel applicationModel) { + return cachedMulticasterMap.computeIfAbsent(applicationModel, t -> { + ScopeBeanFactory beanFactory = applicationModel.getBeanFactory(); + return beanFactory.getBean(DubboLifecycleEventMulticaster.class); + }); } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEventMulticaster.java b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEventMulticaster.java new file mode 100644 index 00000000000..ecfae62a689 --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboEventMulticaster.java @@ -0,0 +1,48 @@ +/* + * 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.common.event; + +/** + * Dispatches events to listeners, and provides ways for listeners to register themselves. + * + * @since 3.3.0 + * @see DubboEvent + * @see DubboListener + */ +public interface DubboEventMulticaster { + + /** + * Add a listener to be notified of all events. + * + * @param listener the listener to add + */ + void addListener(DubboListener listener); + + /** + * Add a listener to be notified of all events. + * + * @param listener the listener to add + */ + void removeListener(DubboListener listener); + + /** + * Publish the given event to all listeners. + * + * @param event the event to publish + */ + void publishEvent(DubboEvent event); +} diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/MetricsLifeListener.java b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboLifecycleEventMulticaster.java similarity index 73% rename from dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/MetricsLifeListener.java rename to dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboLifecycleEventMulticaster.java index 67dd2ad8fd6..836844a9745 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/MetricsLifeListener.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboLifecycleEventMulticaster.java @@ -14,16 +14,14 @@ * 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; +package org.apache.dubbo.common.event; /** - * Metrics Listener. + * Support publish before event and error event */ -public interface MetricsLifeListener extends MetricsListener { +public interface DubboLifecycleEventMulticaster extends DubboEventMulticaster { - default void onEventFinish(E event) {} + void publishBeforeEvent(DubboEvent event); - default void onEventError(E event) {} + void publishErrorEvent(DubboEvent event); } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboLifecycleListener.java b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboLifecycleListener.java new file mode 100644 index 00000000000..39b95df6bff --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboLifecycleListener.java @@ -0,0 +1,52 @@ +/* + * 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.common.event; + +/** + * Dubbo Lifecycle Listener. + */ +public interface DubboLifecycleListener extends DubboListener { + + @Override + default void onEvent(E event) { + this.onEventFinish(event); + } + + /** + * notify event. + * + * @param event BaseMetricsEvent + */ + default void onEventBefore(E event) {} + ; + + /** + * notify event. + * + * @param event BaseMetricsEvent + */ + default void onEventFinish(E event) {} + ; + + /** + * notify event. + * + * @param event BaseMetricsEvent + */ + default void onEventError(E event) {} + ; +} diff --git a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/listener/MetricsListener.java b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboListener.java similarity index 72% rename from dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/listener/MetricsListener.java rename to dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboListener.java index 048625fb02f..80279a74c74 100644 --- a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/listener/MetricsListener.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboListener.java @@ -14,16 +14,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.metrics.listener; +package org.apache.dubbo.common.event; -import org.apache.dubbo.metrics.event.MetricsEvent; +import java.util.EventListener; /** - * Metrics Listener. + * Dubbo Listener. */ -public interface MetricsListener { +public interface DubboListener extends EventListener { - boolean isSupport(MetricsEvent event); + /** + * if support event. + * + * @param eventClass the event to respond to + * @return if support + */ + boolean support(Class eventClass); /** * notify event. diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/MetricsDispatcher.java b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboMulticasterScopeModelInitializer.java similarity index 53% rename from dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/MetricsDispatcher.java rename to dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboMulticasterScopeModelInitializer.java index 1a976cf8753..24ab6ed0626 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/MetricsDispatcher.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/event/DubboMulticasterScopeModelInitializer.java @@ -14,30 +14,31 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.metrics.event; +package org.apache.dubbo.common.event; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; -import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.metrics.collector.MetricsCollector; import org.apache.dubbo.rpc.model.ApplicationModel; - -import java.util.List; +import org.apache.dubbo.rpc.model.FrameworkModel; +import org.apache.dubbo.rpc.model.ModuleModel; +import org.apache.dubbo.rpc.model.ScopeModelInitializer; /** - * Global spi event publisher + * Initialize {@link DubboLifecycleEventMulticaster} for {@link ApplicationModel} + * + * @see DubboLifecycleEventMulticaster + * @since 3.3.0 */ -public class MetricsDispatcher extends SimpleMetricsEventMulticaster { +public class DubboMulticasterScopeModelInitializer implements ScopeModelInitializer { - @SuppressWarnings({"rawtypes"}) - public MetricsDispatcher(ApplicationModel applicationModel) { + @Override + public void initializeFrameworkModel(FrameworkModel frameworkModel) {} + + @Override + public void initializeApplicationModel(ApplicationModel applicationModel) { ScopeBeanFactory beanFactory = applicationModel.getBeanFactory(); - ExtensionLoader extensionLoader = applicationModel.getExtensionLoader(MetricsCollector.class); - if (extensionLoader != null) { - List customizeCollectors = extensionLoader.getActivateExtensions(); - for (MetricsCollector customizeCollector : customizeCollectors) { - beanFactory.registerBean(customizeCollector); - } - customizeCollectors.forEach(this::addListener); - } + beanFactory.registerBean(DefaultDubboEventMulticaster.class); } + + @Override + public void initializeModuleModel(ModuleModel moduleModel) {} } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/OrderedObjectCompareUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/OrderedObjectCompareUtils.java new file mode 100644 index 00000000000..9e24f9d7bcf --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/OrderedObjectCompareUtils.java @@ -0,0 +1,40 @@ +/* + * 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.common.utils; + +import org.apache.dubbo.common.Ordered; + +public class OrderedObjectCompareUtils { + + public static int compareByOrder(Object o1, Object o2) { + boolean o1Ordered = o1 instanceof Ordered; + boolean o2Ordered = o2 instanceof Ordered; + if (!o1Ordered) { + if (!o2Ordered) { + return 0; + } else { + return -1; + } + } else { + if (!o2Ordered) { + return 1; + } else { + return Integer.compare(((Ordered) o1).getOrder(), ((Ordered) o2).getOrder()); + } + } + } +} diff --git a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/model/TimePair.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/TimePair.java similarity index 97% rename from dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/model/TimePair.java rename to dubbo-common/src/main/java/org/apache/dubbo/common/utils/TimePair.java index c00e96bbb74..32b75a45d35 100644 --- a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/model/TimePair.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/TimePair.java @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.metrics.model; +package org.apache.dubbo.common.utils; public class TimePair { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ApplicationModel.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ApplicationModel.java index 1971cf25e70..8474638ca2c 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ApplicationModel.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ApplicationModel.java @@ -25,6 +25,7 @@ import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.threadpool.manager.ExecutorRepository; import org.apache.dubbo.common.utils.Assert; +import org.apache.dubbo.common.utils.OrderedObjectCompareUtils; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.context.ConfigManager; @@ -123,9 +124,9 @@ protected ApplicationModel(FrameworkModel frameworkModel, boolean isInternal) { ExtensionLoader initializerExtensionLoader = this.getExtensionLoader(ScopeModelInitializer.class); Set initializers = initializerExtensionLoader.getSupportedExtensionInstances(); - for (ScopeModelInitializer initializer : initializers) { - initializer.initializeApplicationModel(this); - } + initializers.stream() + .sorted(OrderedObjectCompareUtils::compareByOrder) + .forEach(initializer -> initializer.initializeApplicationModel(this)); Assert.notNull(getApplicationServiceRepository(), "ApplicationServiceRepository can not be null"); Assert.notNull(getApplicationConfigManager(), "ApplicationConfigManager can not be null"); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/FrameworkModel.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/FrameworkModel.java index e5fb2b52ff4..bcd6ec3b3bc 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/FrameworkModel.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/FrameworkModel.java @@ -24,6 +24,7 @@ import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.resource.GlobalResourcesRepository; import org.apache.dubbo.common.utils.Assert; +import org.apache.dubbo.common.utils.OrderedObjectCompareUtils; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.metadata.definition.TypeDefinitionBuilder; @@ -94,9 +95,9 @@ public FrameworkModel() { ExtensionLoader initializerExtensionLoader = this.getExtensionLoader(ScopeModelInitializer.class); Set initializers = initializerExtensionLoader.getSupportedExtensionInstances(); - for (ScopeModelInitializer initializer : initializers) { - initializer.initializeFrameworkModel(this); - } + initializers.stream() + .sorted(OrderedObjectCompareUtils::compareByOrder) + .forEach(initializer -> initializer.initializeFrameworkModel(this)); internalApplicationModel = new ApplicationModel(this, true); internalApplicationModel diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ModuleModel.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ModuleModel.java index 9af38b04289..aea6c241cce 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ModuleModel.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ModuleModel.java @@ -28,6 +28,7 @@ import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.Assert; import org.apache.dubbo.common.utils.ClassUtils; +import org.apache.dubbo.common.utils.OrderedObjectCompareUtils; import org.apache.dubbo.config.context.ModuleConfigManager; import java.util.HashMap; @@ -72,9 +73,9 @@ protected ModuleModel(ApplicationModel applicationModel, boolean isInternal) { ExtensionLoader initializerExtensionLoader = this.getExtensionLoader(ScopeModelInitializer.class); Set initializers = initializerExtensionLoader.getSupportedExtensionInstances(); - for (ScopeModelInitializer initializer : initializers) { - initializer.initializeModuleModel(this); - } + initializers.stream() + .sorted(OrderedObjectCompareUtils::compareByOrder) + .forEach(initializer -> initializer.initializeModuleModel(this)); Assert.notNull(getServiceRepository(), "ModuleServiceRepository can not be null"); Assert.notNull(getConfigManager(), "ModuleConfigManager can not be null"); Assert.assertTrue(getConfigManager().isInitialized(), "ModuleConfigManager can not be initialized"); diff --git a/dubbo-common/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.model.ScopeModelInitializer b/dubbo-common/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.model.ScopeModelInitializer index fdd8f8be8a4..57bb7d1398c 100644 --- a/dubbo-common/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.model.ScopeModelInitializer +++ b/dubbo-common/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.model.ScopeModelInitializer @@ -1 +1,2 @@ dubbo-common=org.apache.dubbo.common.CommonScopeModelInitializer +dubbo-multicaster-init=org.apache.dubbo.common.event.DubboMulticasterScopeModelInitializer diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/event/DubboEventTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/event/DubboEventTest.java new file mode 100644 index 00000000000..bdceba3fdf1 --- /dev/null +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/event/DubboEventTest.java @@ -0,0 +1,210 @@ +/* + * 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.common.event; + +import org.apache.dubbo.rpc.model.ApplicationModel; +import org.apache.dubbo.rpc.model.FrameworkModel; +import org.apache.dubbo.rpc.model.ModuleModel; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class DubboEventTest { + + private FrameworkModel frameworkModel; + private ApplicationModel applicationModel; + private ModuleModel moduleModel; + + @BeforeEach + public void setUp() { + frameworkModel = new FrameworkModel(); + applicationModel = frameworkModel.newApplication(); + moduleModel = applicationModel.newModule(); + } + + @AfterEach + public void reset() { + frameworkModel.destroy(); + } + + @Test + public void testDubboListener() { + AtomicInteger num = new AtomicInteger(0); + List> classes = new ArrayList<>(); + DubboListener dubboListener = new DubboListener() { + @Override + public boolean support(Class eventClass) { + classes.add(eventClass); + return true; + } + + @Override + public void onEvent(DubboEvent event) { + num.incrementAndGet(); + } + }; + DubboEventBus.addListener(applicationModel, dubboListener); + + FirstDubboEvent firstDubboEvent = new FirstDubboEvent(applicationModel); + SecondDubboEvent secondDubboEvent = new SecondDubboEvent(applicationModel); + DubboEventBus.publish(firstDubboEvent); + DubboEventBus.publish(secondDubboEvent); + + Assertions.assertEquals(num.get(), 2); + Assertions.assertEquals(classes.size(), 2); + Assertions.assertTrue(classes.contains(FirstDubboEvent.class)); + Assertions.assertTrue(classes.contains(SecondDubboEvent.class)); + } + + @Test + public void testAbstractDubboListener() { + List eventList = new ArrayList<>(); + AbstractDubboListener dubboListener = new AbstractDubboListener() { + @Override + public void onEvent(FirstDubboEvent event) { + eventList.add(event); + } + }; + DubboEventBus.addListener(applicationModel, dubboListener); + + FirstDubboEvent firstDubboEvent = new FirstDubboEvent(applicationModel); + SecondDubboEvent secondDubboEvent = new SecondDubboEvent(applicationModel); + DubboEventBus.publish(firstDubboEvent); + DubboEventBus.publish(secondDubboEvent); + + Assertions.assertEquals(eventList.size(), 1); + Assertions.assertTrue(eventList.contains(firstDubboEvent)); + Assertions.assertFalse(eventList.contains(secondDubboEvent)); + } + + @Test + public void testAbstractDubboLifecycleListener() { + List beforeEventList = new ArrayList<>(); + List afterEventList = new ArrayList<>(); + List errorEventList = new ArrayList<>(); + AbstractDubboLifecycleListener dubboListener = + new AbstractDubboLifecycleListener() { + + @Override + public void onEventBefore(FirstDubboEvent event) { + beforeEventList.add(event); + } + + @Override + public void onEventFinish(FirstDubboEvent event) { + afterEventList.add(event); + } + + @Override + public void onEventError(FirstDubboEvent event) { + errorEventList.add(event); + } + }; + DubboEventBus.addListener(applicationModel, dubboListener); + + FirstDubboEvent firstDubboEvent = new FirstDubboEvent(applicationModel); + SecondDubboEvent secondDubboEvent = new SecondDubboEvent(applicationModel); + + DubboEventBus.post(firstDubboEvent, FirstDubboEvent.class::getName); + DubboEventBus.post(secondDubboEvent, SecondDubboEvent.class::getName); + + Assertions.assertEquals(beforeEventList.size(), 1); + Assertions.assertEquals(beforeEventList.get(0), firstDubboEvent); + Assertions.assertEquals(afterEventList.size(), 1); + Assertions.assertEquals(afterEventList.get(0), firstDubboEvent); + Assertions.assertEquals(errorEventList.size(), 0); + + beforeEventList.clear(); + afterEventList.clear(); + errorEventList.clear(); + + try { + DubboEventBus.post(firstDubboEvent, () -> { + throw new RuntimeException(); + }); + } catch (RuntimeException e) { + } + try { + DubboEventBus.post(secondDubboEvent, () -> { + throw new RuntimeException(); + }); + } catch (RuntimeException e) { + } + + Assertions.assertEquals(beforeEventList.size(), 1); + Assertions.assertEquals(beforeEventList.get(0), firstDubboEvent); + Assertions.assertEquals(afterEventList.size(), 0); + Assertions.assertEquals(errorEventList.size(), 1); + Assertions.assertEquals(errorEventList.get(0), firstDubboEvent); + + beforeEventList.clear(); + afterEventList.clear(); + errorEventList.clear(); + + DubboEventBus.post(firstDubboEvent, FirstDubboEvent.class::getName, result -> false); + DubboEventBus.post(secondDubboEvent, SecondDubboEvent.class::getName, result -> false); + + Assertions.assertEquals(beforeEventList.size(), 1); + Assertions.assertEquals(beforeEventList.get(0), firstDubboEvent); + Assertions.assertEquals(afterEventList.size(), 0); + Assertions.assertEquals(errorEventList.size(), 1); + Assertions.assertEquals(errorEventList.get(0), firstDubboEvent); + } + + @Test + public void testCustomAfterPostEventListener() { + SecondDubboEvent secondDubboEvent = new SecondDubboEvent(applicationModel); + + DubboEventBus.post(secondDubboEvent, SecondDubboEvent.class::getName); + List resultList = secondDubboEvent.getResultList(); + + Assertions.assertEquals(resultList.size(), 1); + Assertions.assertEquals(resultList.get(0), SecondDubboEvent.class.getName()); + } + + public static class FirstDubboEvent extends DubboEvent { + + public FirstDubboEvent(ApplicationModel source) { + super(source); + } + } + + public static class SecondDubboEvent extends DubboEvent implements CustomAfterPost { + + private final List resultList; + + public SecondDubboEvent(ApplicationModel source) { + super(source); + resultList = new ArrayList<>(); + } + + @Override + public void customAfterPost(String postResult) { + resultList.add(postResult); + } + + public List getResultList() { + return resultList; + } + } +} diff --git a/dubbo-config/dubbo-config-api/pom.xml b/dubbo-config/dubbo-config-api/pom.xml index 9ed360e9475..0b46d30253d 100644 --- a/dubbo-config/dubbo-config-api/pom.xml +++ b/dubbo-config/dubbo-config-api/pom.xml @@ -38,43 +38,7 @@ org.apache.dubbo - dubbo-metadata-api - ${project.parent.version} - - - - org.apache.dubbo - dubbo-metrics-api - ${project.parent.version} - - - - org.apache.dubbo - dubbo-metrics-default - ${project.parent.version} - - - - org.apache.dubbo - dubbo-metrics-registry - ${project.parent.version} - - - - org.apache.dubbo - dubbo-metrics-metadata - ${project.parent.version} - - - - org.apache.dubbo - dubbo-metrics-config-center - ${project.parent.version} - - - - org.apache.dubbo - dubbo-tracing + dubbo-metrics-monitor ${project.parent.version} diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/InitServiceMethodEvent.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/InitServiceMethodEvent.java new file mode 100644 index 00000000000..8055da3fe89 --- /dev/null +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/InitServiceMethodEvent.java @@ -0,0 +1,35 @@ +/* + * 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.config; + +import org.apache.dubbo.common.event.DubboEvent; +import org.apache.dubbo.rpc.Invocation; +import org.apache.dubbo.rpc.model.ApplicationModel; + +public class InitServiceMethodEvent extends DubboEvent { + + private final Invocation invocation; + + public InitServiceMethodEvent(ApplicationModel source, Invocation invocation) { + super(source); + this.invocation = invocation; + } + + public Invocation getInvocation() { + return invocation; + } +} diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java index 363eccd8b5e..baa7ee21173 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java @@ -22,6 +22,7 @@ import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.constants.RegisterTypeEnum; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -38,9 +39,6 @@ import org.apache.dubbo.config.support.Parameter; import org.apache.dubbo.config.utils.ConfigValidationUtils; import org.apache.dubbo.metadata.ServiceNameMapping; -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.registry.client.metadata.MetadataUtils; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invoker; @@ -628,7 +626,6 @@ private void initServiceMethodMetrics(URL url) { String[] methods = Optional.ofNullable(url.getParameter(METHODS_KEY)) .map(i -> i.split(",")) .orElse(new String[] {}); - boolean serviceLevel = MethodMetric.isServiceLevel(application.getApplicationModel()); Arrays.stream(methods).forEach(method -> { RpcInvocation invocation = new RpcInvocation( url.getServiceKey(), @@ -642,8 +639,7 @@ private void initServiceMethodMetrics(URL url) { null, null, null); - MetricsEventBus.publish( - MetricsInitEvent.toMetricsInitEvent(application.getApplicationModel(), invocation, serviceLevel)); + DubboEventBus.publish(new InitServiceMethodEvent(application.getApplicationModel(), invocation)); }); } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultApplicationDeployer.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultApplicationDeployer.java index 28940038881..8f806a6e648 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultApplicationDeployer.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultApplicationDeployer.java @@ -20,6 +20,7 @@ import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.config.Environment; import org.apache.dubbo.common.config.ReferenceCache; +import org.apache.dubbo.common.config.configcenter.ConfigCenterChangeEvent; import org.apache.dubbo.common.config.configcenter.ConfigChangeType; import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; import org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory; @@ -31,6 +32,7 @@ import org.apache.dubbo.common.deploy.DeployListener; import org.apache.dubbo.common.deploy.DeployState; import org.apache.dubbo.common.deploy.ModuleDeployer; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.lang.ShutdownHookCallbacks; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; @@ -44,22 +46,16 @@ import org.apache.dubbo.config.ConfigCenterConfig; import org.apache.dubbo.config.DubboShutdownHook; import org.apache.dubbo.config.MetadataReportConfig; -import org.apache.dubbo.config.MetricsConfig; import org.apache.dubbo.config.RegistryConfig; -import org.apache.dubbo.config.TracingConfig; import org.apache.dubbo.config.context.ConfigManager; +import org.apache.dubbo.config.deploy.event.ApplicationLoadedEvent; +import org.apache.dubbo.config.deploy.event.ApplicationStartedEvent; +import org.apache.dubbo.config.deploy.event.PreDestroyApplicationInstanceEvent; +import org.apache.dubbo.config.deploy.event.PrepareApplicationInstanceEvent; import org.apache.dubbo.config.utils.CompositeReferenceCache; import org.apache.dubbo.config.utils.ConfigValidationUtils; import org.apache.dubbo.metadata.report.MetadataReportFactory; import org.apache.dubbo.metadata.report.MetadataReportInstance; -import org.apache.dubbo.metrics.collector.DefaultMetricsCollector; -import org.apache.dubbo.metrics.config.event.ConfigCenterEvent; -import org.apache.dubbo.metrics.event.MetricsEventBus; -import org.apache.dubbo.metrics.report.DefaultMetricsReporterFactory; -import org.apache.dubbo.metrics.report.MetricsReporter; -import org.apache.dubbo.metrics.report.MetricsReporterFactory; -import org.apache.dubbo.metrics.service.MetricsServiceExporter; -import org.apache.dubbo.metrics.utils.MetricsSupportUtil; import org.apache.dubbo.registry.Registry; import org.apache.dubbo.registry.RegistryFactory; import org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils; @@ -70,8 +66,6 @@ import org.apache.dubbo.rpc.model.ProviderModel; import org.apache.dubbo.rpc.model.ScopeModel; import org.apache.dubbo.rpc.model.ScopeModelUtil; -import org.apache.dubbo.tracing.DubboObservationRegistry; -import org.apache.dubbo.tracing.utils.ObservationSupportUtil; import java.io.IOException; import java.util.ArrayList; @@ -95,14 +89,11 @@ import static org.apache.dubbo.common.config.ConfigurationUtils.parseProperties; import static org.apache.dubbo.common.constants.CommonConstants.REGISTRY_SPLIT_PATTERN; import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_METADATA_STORAGE_TYPE; -import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_METRICS_COLLECTOR_EXCEPTION; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_EXECUTE_DESTROY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_INIT_CONFIG_CENTER; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_START_MODEL; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_REFRESH_INSTANCE_ERROR; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_REGISTER_INSTANCE_ERROR; -import static org.apache.dubbo.common.constants.MetricsConstants.PROTOCOL_DEFAULT; -import static org.apache.dubbo.common.constants.MetricsConstants.PROTOCOL_PROMETHEUS; import static org.apache.dubbo.common.utils.StringUtils.isEmpty; import static org.apache.dubbo.common.utils.StringUtils.isNotEmpty; import static org.apache.dubbo.config.Constants.DEFAULT_APP_NAME; @@ -136,8 +127,6 @@ public class DefaultApplicationDeployer extends AbstractDeployer startFuture; private final DubboShutdownHook dubboShutdownHook; - private volatile MetricsServiceExporter metricsServiceExporter; - private final Object stateLock = new Object(); private final Object startLock = new Object(); private final Object destroyLock = new Object(); @@ -227,12 +216,7 @@ public void initialize() { initModuleDeployers(); - initMetricsReporter(); - - initMetricsService(); - - // @since 3.2.3 - initObservationRegistry(); + DubboEventBus.publish(new ApplicationLoadedEvent(applicationModel)); // @since 2.7.8 startMetadataCenter(); @@ -375,86 +359,6 @@ private void useRegistryAsConfigCenterIfNecessary() { } } - private void initMetricsService() { - this.metricsServiceExporter = - getExtensionLoader(MetricsServiceExporter.class).getDefaultExtension(); - metricsServiceExporter.init(); - } - - private void initMetricsReporter() { - if (!MetricsSupportUtil.isSupportMetrics()) { - return; - } - DefaultMetricsCollector collector = applicationModel.getBeanFactory().getBean(DefaultMetricsCollector.class); - Optional configOptional = configManager.getMetrics(); - // If no specific metrics type is configured and there is no Prometheus dependency in the dependencies. - MetricsConfig metricsConfig = configOptional.orElse(new MetricsConfig(applicationModel)); - if (PROTOCOL_PROMETHEUS.equals(metricsConfig.getProtocol()) && !MetricsSupportUtil.isSupportPrometheus()) { - return; - } - if (StringUtils.isBlank(metricsConfig.getProtocol())) { - metricsConfig.setProtocol( - MetricsSupportUtil.isSupportPrometheus() ? PROTOCOL_PROMETHEUS : PROTOCOL_DEFAULT); - } - collector.setCollectEnabled(true); - collector.collectApplication(); - collector.setThreadpoolCollectEnabled( - Optional.ofNullable(metricsConfig.getEnableThreadpool()).orElse(true)); - collector.setMetricsInitEnabled( - Optional.ofNullable(metricsConfig.getEnableMetricsInit()).orElse(true)); - MetricsReporterFactory metricsReporterFactory = - getExtensionLoader(MetricsReporterFactory.class).getAdaptiveExtension(); - MetricsReporter metricsReporter = null; - try { - metricsReporter = metricsReporterFactory.createMetricsReporter(metricsConfig.toUrl()); - } catch (IllegalStateException e) { - if (e.getMessage().startsWith("No such extension org.apache.dubbo.metrics.report.MetricsReporterFactory")) { - logger.warn(COMMON_METRICS_COLLECTOR_EXCEPTION, "", "", e.getMessage()); - return; - } else { - throw e; - } - } - metricsReporter.init(); - applicationModel.getBeanFactory().registerBean(metricsReporter); - // If the protocol is not the default protocol, the default protocol is also initialized. - if (!PROTOCOL_DEFAULT.equals(metricsConfig.getProtocol())) { - DefaultMetricsReporterFactory defaultMetricsReporterFactory = - new DefaultMetricsReporterFactory(applicationModel); - MetricsReporter defaultMetricsReporter = - defaultMetricsReporterFactory.createMetricsReporter(metricsConfig.toUrl()); - defaultMetricsReporter.init(); - applicationModel.getBeanFactory().registerBean(defaultMetricsReporter); - } - } - - /** - * init ObservationRegistry(Micrometer) - */ - private void initObservationRegistry() { - if (!ObservationSupportUtil.isSupportObservation()) { - if (logger.isDebugEnabled()) { - logger.debug( - "Not found micrometer-observation or plz check the version of micrometer-observation version if already introduced, need > 1.10.0"); - } - return; - } - if (!ObservationSupportUtil.isSupportTracing()) { - if (logger.isDebugEnabled()) { - logger.debug("Not found micrometer-tracing dependency, skip init ObservationRegistry."); - } - return; - } - Optional configOptional = configManager.getTracing(); - if (!configOptional.isPresent() || !configOptional.get().getEnabled()) { - return; - } - - DubboObservationRegistry dubboObservationRegistry = - new DubboObservationRegistry(applicationModel, configOptional.get()); - dubboObservationRegistry.initObservationRegistry(); - } - private boolean isUsedRegistryAsConfigCenter(RegistryConfig registryConfig) { return isUsedRegistryAsCenter( registryConfig, registryConfig::getUseAsConfigCenter, "config", DynamicConfigurationFactory.class); @@ -780,7 +684,7 @@ public void prepareApplicationInstance(ModuleModel moduleModel) { } // export MetricsService - exportMetricsService(); + DubboEventBus.publish(new PrepareApplicationInstanceEvent(applicationModel)); if (moduleModel.getDeployer().hasRegistryInteraction()) { ApplicationConfig applicationConfig = configManager.getApplicationOrElseThrow(); @@ -832,36 +736,6 @@ public void prepareInternalModule() { } } - private void exportMetricsService() { - boolean exportMetrics = applicationModel - .getApplicationConfigManager() - .getMetrics() - .map(MetricsConfig::getExportMetricsService) - .orElse(true); - if (exportMetrics) { - try { - metricsServiceExporter.export(); - } catch (Exception e) { - logger.error( - LoggerCodeConstants.COMMON_METRICS_COLLECTOR_EXCEPTION, - "", - "", - "exportMetricsService an exception occurred when handle starting event", - e); - } - } - } - - private void unexportMetricsService() { - if (metricsServiceExporter != null) { - try { - metricsServiceExporter.unexport(); - } catch (Exception ignored) { - // ignored - } - } - } - private boolean hasExportedServices() { for (ModuleModel moduleModel : applicationModel.getModuleModels()) { if (CollectionUtils.isNotEmpty(moduleModel.getConfigManager().getServices())) { @@ -940,20 +814,20 @@ private DynamicConfiguration prepareEnvironment(ConfigCenterConfig configCenter) environment.updateAppExternalConfigMap(appConfigMap); // Add metrics - MetricsEventBus.publish(ConfigCenterEvent.toChangeEvent( + DubboEventBus.publish(new ConfigCenterChangeEvent( applicationModel, configCenter.getConfigFile(), configCenter.getGroup(), configCenter.getProtocol(), - ConfigChangeType.ADDED.name(), + ConfigChangeType.ADDED, configMap.size())); if (isNotEmpty(appGroup)) { - MetricsEventBus.publish(ConfigCenterEvent.toChangeEvent( + DubboEventBus.publish(new ConfigCenterChangeEvent( applicationModel, appConfigFile, appGroup, configCenter.getProtocol(), - ConfigChangeType.ADDED.name(), + ConfigChangeType.ADDED, appConfigMap.size())); } } catch (IOException e) { @@ -1094,7 +968,7 @@ public void preDestroy() { unregisterServiceInstance(); - unexportMetricsService(); + DubboEventBus.publish(new PreDestroyApplicationInstanceEvent(applicationModel)); unRegisterShutdownHook(); if (asyncMetadataFuture != null) { @@ -1335,7 +1209,7 @@ private void onStarted() { return; } setStarted(); - startMetricsCollector(); + DubboEventBus.publish(new ApplicationStartedEvent(applicationModel)); if (logger.isInfoEnabled()) { logger.info(getIdentifier() + " is ready."); } @@ -1365,13 +1239,6 @@ private void onCompletion() { } } - private void startMetricsCollector() { - DefaultMetricsCollector collector = applicationModel.getBeanFactory().getBean(DefaultMetricsCollector.class); - if (Objects.nonNull(collector) && collector.isThreadpoolCollectEnabled()) { - collector.registryDefaultSample(); - } - } - private void completeStartFuture(boolean success) { if (startFuture != null) { startFuture.complete(success); diff --git a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/MetricsEventMulticaster.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/event/ApplicationLoadedEvent.java similarity index 70% rename from dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/MetricsEventMulticaster.java rename to dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/event/ApplicationLoadedEvent.java index 2f1381a7265..3c1468f71ae 100644 --- a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/MetricsEventMulticaster.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/event/ApplicationLoadedEvent.java @@ -14,17 +14,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.metrics.event; +package org.apache.dubbo.config.deploy.event; -import org.apache.dubbo.metrics.listener.MetricsListener; +import org.apache.dubbo.common.event.DubboEvent; +import org.apache.dubbo.rpc.model.ApplicationModel; -public interface MetricsEventMulticaster { +public class ApplicationLoadedEvent extends DubboEvent { - void addListener(MetricsListener listener); - - void publishEvent(MetricsEvent event); - - void publishFinishEvent(TimeCounterEvent event); - - void publishErrorEvent(TimeCounterEvent event); + public ApplicationLoadedEvent(ApplicationModel source) { + super(source); + } } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/event/ApplicationStartedEvent.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/event/ApplicationStartedEvent.java new file mode 100644 index 00000000000..298d5ef2a8f --- /dev/null +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/event/ApplicationStartedEvent.java @@ -0,0 +1,27 @@ +/* + * 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.config.deploy.event; + +import org.apache.dubbo.common.event.DubboEvent; +import org.apache.dubbo.rpc.model.ApplicationModel; + +public class ApplicationStartedEvent extends DubboEvent { + + public ApplicationStartedEvent(ApplicationModel source) { + super(source); + } +} diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/event/PreDestroyApplicationInstanceEvent.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/event/PreDestroyApplicationInstanceEvent.java new file mode 100644 index 00000000000..6e215575c9c --- /dev/null +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/event/PreDestroyApplicationInstanceEvent.java @@ -0,0 +1,27 @@ +/* + * 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.config.deploy.event; + +import org.apache.dubbo.common.event.DubboEvent; +import org.apache.dubbo.rpc.model.ApplicationModel; + +public class PreDestroyApplicationInstanceEvent extends DubboEvent { + + public PreDestroyApplicationInstanceEvent(ApplicationModel source) { + super(source); + } +} diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/event/PrepareApplicationInstanceEvent.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/event/PrepareApplicationInstanceEvent.java new file mode 100644 index 00000000000..cdead7419a7 --- /dev/null +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/event/PrepareApplicationInstanceEvent.java @@ -0,0 +1,27 @@ +/* + * 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.config.deploy.event; + +import org.apache.dubbo.common.event.DubboEvent; +import org.apache.dubbo.rpc.model.ApplicationModel; + +public class PrepareApplicationInstanceEvent extends DubboEvent { + + public PrepareApplicationInstanceEvent(ApplicationModel source) { + super(source); + } +} diff --git a/dubbo-config/dubbo-config-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metrics.service.MetricsServiceExporter b/dubbo-config/dubbo-config-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metrics.service.MetricsServiceExporter deleted file mode 100644 index 7edea936d57..00000000000 --- a/dubbo-config/dubbo-config-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metrics.service.MetricsServiceExporter +++ /dev/null @@ -1 +0,0 @@ -default=org.apache.dubbo.config.deploy.DefaultMetricsServiceExporter diff --git a/dubbo-config/dubbo-config-spring/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.common.metrics.service.MetricsServiceExporter b/dubbo-config/dubbo-config-spring/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.common.metrics.service.MetricsServiceExporter deleted file mode 100644 index 7edea936d57..00000000000 --- a/dubbo-config/dubbo-config-spring/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.common.metrics.service.MetricsServiceExporter +++ /dev/null @@ -1 +0,0 @@ -default=org.apache.dubbo.config.deploy.DefaultMetricsServiceExporter diff --git a/dubbo-configcenter/dubbo-configcenter-apollo/pom.xml b/dubbo-configcenter/dubbo-configcenter-apollo/pom.xml index 5a709b40e8f..6c1e0a0e370 100644 --- a/dubbo-configcenter/dubbo-configcenter-apollo/pom.xml +++ b/dubbo-configcenter/dubbo-configcenter-apollo/pom.xml @@ -39,21 +39,6 @@ dubbo-common ${project.parent.version} - - org.apache.dubbo - dubbo-metrics-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-metrics-default - ${project.parent.version} - - - org.apache.dubbo - dubbo-metrics-prometheus - ${project.parent.version} - com.ctrip.framework.apollo apollo-client @@ -64,10 +49,5 @@ ${apollo_mock_server_version} test - - org.apache.dubbo - dubbo-metrics-config-center - ${project.parent.version} - diff --git a/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloConstants.java b/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloConstants.java new file mode 100644 index 00000000000..58f7fa9b54e --- /dev/null +++ b/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloConstants.java @@ -0,0 +1,22 @@ +/* + * 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.configcenter.support.apollo; + +public interface ApolloConstants { + + String APOLLO_PROTOCOL = "apollo"; +} diff --git a/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfiguration.java index e355bb22da5..8079bb6e2c0 100644 --- a/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfiguration.java +++ b/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfiguration.java @@ -17,16 +17,16 @@ package org.apache.dubbo.configcenter.support.apollo; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.config.configcenter.ConfigCenterChangeEvent; import org.apache.dubbo.common.config.configcenter.ConfigChangeType; import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent; import org.apache.dubbo.common.config.configcenter.ConfigurationListener; import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.common.utils.SystemPropertyConfigUtils; -import org.apache.dubbo.metrics.config.event.ConfigCenterEvent; -import org.apache.dubbo.metrics.event.MetricsEventBus; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Arrays; @@ -58,7 +58,6 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_CLOSE_CONNECT_APOLLO; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_CONNECT_REGISTRY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_NOT_EFFECT_EMPTY_RULE_APOLLO; -import static org.apache.dubbo.metrics.MetricsConstants.SELF_INCREMENT_SIZE; /** * Apollo implementation, https://github.com/ctripcorp/apollo @@ -269,13 +268,12 @@ public void onChange(com.ctrip.framework.apollo.model.ConfigChangeEvent changeEv new ConfigChangedEvent(key, change.getNamespace(), change.getNewValue(), getChangeType(change)); listeners.forEach(listener -> listener.process(event)); - MetricsEventBus.publish(ConfigCenterEvent.toChangeEvent( + DubboEventBus.publish(new ConfigCenterChangeEvent( applicationModel, event.getKey(), event.getGroup(), - ConfigCenterEvent.APOLLO_PROTOCOL, - ConfigChangeType.ADDED.name(), - SELF_INCREMENT_SIZE)); + ApolloConstants.APOLLO_PROTOCOL, + ConfigChangeType.ADDED)); } } diff --git a/dubbo-configcenter/dubbo-configcenter-file/pom.xml b/dubbo-configcenter/dubbo-configcenter-file/pom.xml index c6c403fcfac..e7b6626bdbd 100644 --- a/dubbo-configcenter/dubbo-configcenter-file/pom.xml +++ b/dubbo-configcenter/dubbo-configcenter-file/pom.xml @@ -38,25 +38,5 @@ dubbo-common ${project.parent.version} - - org.apache.dubbo - dubbo-metrics-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-metrics-default - ${project.parent.version} - - - org.apache.dubbo - dubbo-metrics-prometheus - ${project.parent.version} - - - org.apache.dubbo - dubbo-metrics-config-center - ${project.parent.version} - diff --git a/dubbo-configcenter/dubbo-configcenter-nacos/pom.xml b/dubbo-configcenter/dubbo-configcenter-nacos/pom.xml index 991a961c5ff..def322c935a 100644 --- a/dubbo-configcenter/dubbo-configcenter-nacos/pom.xml +++ b/dubbo-configcenter/dubbo-configcenter-nacos/pom.xml @@ -38,26 +38,6 @@ com.alibaba.nacos nacos-client - - org.apache.dubbo - dubbo-metrics-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-metrics-default - ${project.parent.version} - - - org.apache.dubbo - dubbo-metrics-prometheus - ${project.parent.version} - - - org.apache.dubbo - dubbo-metrics-config-center - ${project.parent.version} - org.apache.logging.log4j log4j-slf4j-impl diff --git a/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosConstants.java b/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosConstants.java new file mode 100644 index 00000000000..0af21280242 --- /dev/null +++ b/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosConstants.java @@ -0,0 +1,22 @@ +/* + * 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.configcenter.support.nacos; + +public interface NacosConstants { + + String NACOS_PROTOCOL = "nacos"; +} diff --git a/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java index 74c530e2b07..c5dfde74943 100644 --- a/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java +++ b/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java @@ -17,19 +17,19 @@ package org.apache.dubbo.configcenter.support.nacos; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.config.configcenter.ConfigCenterChangeEvent; import org.apache.dubbo.common.config.configcenter.ConfigChangeType; import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent; import org.apache.dubbo.common.config.configcenter.ConfigItem; import org.apache.dubbo.common.config.configcenter.ConfigurationListener; import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; import org.apache.dubbo.common.constants.LoggerCodeConstants; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import org.apache.dubbo.common.utils.MD5Utils; import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.metrics.config.event.ConfigCenterEvent; -import org.apache.dubbo.metrics.event.MetricsEventBus; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Map; @@ -55,7 +55,6 @@ import static org.apache.dubbo.common.constants.RemotingConstants.BACKUP_KEY; import static org.apache.dubbo.common.utils.StringConstantFieldValuePredicate.of; import static org.apache.dubbo.common.utils.StringUtils.HYPHEN_CHAR; -import static org.apache.dubbo.metrics.MetricsConstants.SELF_INCREMENT_SIZE; /** * The nacos implementation of {@link DynamicConfiguration} @@ -362,13 +361,12 @@ public void innerReceive(String dataId, String group, String configInfo) { } listeners.forEach(listener -> listener.process(event)); - MetricsEventBus.publish(ConfigCenterEvent.toChangeEvent( + DubboEventBus.publish(new ConfigCenterChangeEvent( applicationModel, event.getKey(), event.getGroup(), - ConfigCenterEvent.NACOS_PROTOCOL, - ConfigChangeType.ADDED.name(), - SELF_INCREMENT_SIZE)); + NacosConstants.NACOS_PROTOCOL, + ConfigChangeType.ADDED)); } void addListener(ConfigurationListener configurationListener) { diff --git a/dubbo-configcenter/dubbo-configcenter-zookeeper/pom.xml b/dubbo-configcenter/dubbo-configcenter-zookeeper/pom.xml index c1deb8c3e5b..1596c474eb4 100644 --- a/dubbo-configcenter/dubbo-configcenter-zookeeper/pom.xml +++ b/dubbo-configcenter/dubbo-configcenter-zookeeper/pom.xml @@ -61,26 +61,6 @@ org.apache.zookeeper zookeeper - - org.apache.dubbo - dubbo-metrics-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-metrics-default - ${project.parent.version} - - - org.apache.dubbo - dubbo-metrics-prometheus - ${project.parent.version} - - - org.apache.dubbo - dubbo-metrics-config-center - ${project.parent.version} - diff --git a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperConstants.java b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperConstants.java new file mode 100644 index 00000000000..6cfffd767cc --- /dev/null +++ b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperConstants.java @@ -0,0 +1,22 @@ +/* + * 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.configcenter.support.zookeeper; + +public interface ZookeeperConstants { + + String ZK_PROTOCOL = "zookeeper"; +} diff --git a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDataListener.java b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDataListener.java index 508b9430a87..5217dd93ccb 100644 --- a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDataListener.java +++ b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDataListener.java @@ -16,12 +16,12 @@ */ package org.apache.dubbo.configcenter.support.zookeeper; +import org.apache.dubbo.common.config.configcenter.ConfigCenterChangeEvent; import org.apache.dubbo.common.config.configcenter.ConfigChangeType; import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent; import org.apache.dubbo.common.config.configcenter.ConfigurationListener; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.common.utils.CollectionUtils; -import org.apache.dubbo.metrics.config.event.ConfigCenterEvent; -import org.apache.dubbo.metrics.event.MetricsEventBus; import org.apache.dubbo.remoting.zookeeper.curator5.DataListener; import org.apache.dubbo.remoting.zookeeper.curator5.EventType; import org.apache.dubbo.rpc.model.ApplicationModel; @@ -29,8 +29,6 @@ import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; -import static org.apache.dubbo.metrics.MetricsConstants.SELF_INCREMENT_SIZE; - /** * one path has multi configurationListeners */ @@ -80,12 +78,11 @@ public void dataChanged(String path, Object value, EventType eventType) { listeners.forEach(listener -> listener.process(configChangeEvent)); } - MetricsEventBus.publish(ConfigCenterEvent.toChangeEvent( + DubboEventBus.publish(new ConfigCenterChangeEvent( applicationModel, configChangeEvent.getKey(), configChangeEvent.getGroup(), - ConfigCenterEvent.ZK_PROTOCOL, - ConfigChangeType.ADDED.name(), - SELF_INCREMENT_SIZE)); + ZookeeperConstants.ZK_PROTOCOL, + ConfigChangeType.ADDED)); } } diff --git a/dubbo-distribution/dubbo-all-shaded/pom.xml b/dubbo-distribution/dubbo-all-shaded/pom.xml index bc7ca34f7f5..1098bb08f5a 100644 --- a/dubbo-distribution/dubbo-all-shaded/pom.xml +++ b/dubbo-distribution/dubbo-all-shaded/pom.xml @@ -172,6 +172,13 @@ + + org.apache.dubbo + dubbo-metrics-monitor + ${project.version} + compile + true + org.apache.dubbo dubbo-metrics-api @@ -461,6 +468,7 @@ org.apache.dubbo:dubbo-metadata-report-nacos org.apache.dubbo:dubbo-metadata-report-redis org.apache.dubbo:dubbo-metadata-report-zookeeper + org.apache.dubbo:dubbo-metrics-monitor org.apache.dubbo:dubbo-metrics-api org.apache.dubbo:dubbo-metrics-default org.apache.dubbo:dubbo-metrics-registry diff --git a/dubbo-distribution/dubbo-all/pom.xml b/dubbo-distribution/dubbo-all/pom.xml index db8f34bf76a..f10033f10d7 100644 --- a/dubbo-distribution/dubbo-all/pom.xml +++ b/dubbo-distribution/dubbo-all/pom.xml @@ -160,7 +160,7 @@ org.apache.dubbo - dubbo-metrics-event + dubbo-metrics-monitor ${project.version} compile true @@ -497,7 +497,7 @@ org.apache.dubbo:dubbo-metadata-report-nacos org.apache.dubbo:dubbo-metadata-report-redis org.apache.dubbo:dubbo-metadata-report-zookeeper - org.apache.dubbo:dubbo-metrics-event + org.apache.dubbo:dubbo-metrics-monitor org.apache.dubbo:dubbo-metrics-api org.apache.dubbo:dubbo-metrics-default org.apache.dubbo:dubbo-metrics-registry diff --git a/dubbo-distribution/dubbo-bom/pom.xml b/dubbo-distribution/dubbo-bom/pom.xml index 47175873452..2209d927116 100644 --- a/dubbo-distribution/dubbo-bom/pom.xml +++ b/dubbo-distribution/dubbo-bom/pom.xml @@ -237,7 +237,7 @@ org.apache.dubbo - dubbo-metrics-event + dubbo-metrics-monitor ${project.version} diff --git a/dubbo-distribution/dubbo-core-spi/pom.xml b/dubbo-distribution/dubbo-core-spi/pom.xml index 43511a8c924..bf7c2f66591 100644 --- a/dubbo-distribution/dubbo-core-spi/pom.xml +++ b/dubbo-distribution/dubbo-core-spi/pom.xml @@ -125,6 +125,7 @@ org.apache.dubbo:dubbo-common org.apache.dubbo:dubbo-config-api org.apache.dubbo:dubbo-metadata-api + org.apache.dubbo:dubbo-metrics-monitor org.apache.dubbo:dubbo-metrics-api org.apache.dubbo:dubbo-metrics-default org.apache.dubbo:dubbo-tracing diff --git a/dubbo-metadata/dubbo-metadata-api/pom.xml b/dubbo-metadata/dubbo-metadata-api/pom.xml index 8fc6af86eae..c9352c930bb 100644 --- a/dubbo-metadata/dubbo-metadata-api/pom.xml +++ b/dubbo-metadata/dubbo-metadata-api/pom.xml @@ -44,25 +44,6 @@ ${project.parent.version} - - org.apache.dubbo - dubbo-metrics-api - ${project.parent.version} - compile - - - org.apache.dubbo - dubbo-metrics-default - ${project.parent.version} - compile - - - org.apache.dubbo - dubbo-metrics-metadata - ${project.parent.version} - compile - - org.apache.dubbo dubbo-native diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetadataEvent.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetadataEvent.java new file mode 100644 index 00000000000..181d1edbd54 --- /dev/null +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetadataEvent.java @@ -0,0 +1,35 @@ +/* + * 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.metadata.event; + +import org.apache.dubbo.common.event.DubboEvent; +import org.apache.dubbo.common.utils.TimePair; +import org.apache.dubbo.rpc.model.ApplicationModel; + +public abstract class MetadataEvent extends DubboEvent { + + private final TimePair timePair; + + public MetadataEvent(ApplicationModel source) { + super(source); + this.timePair = TimePair.start(); + } + + public TimePair getTimePair() { + return timePair; + } +} diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetadataPushEvent.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetadataPushEvent.java new file mode 100644 index 00000000000..2b4c2279050 --- /dev/null +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetadataPushEvent.java @@ -0,0 +1,26 @@ +/* + * 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.metadata.event; + +import org.apache.dubbo.rpc.model.ApplicationModel; + +public class MetadataPushEvent extends MetadataEvent { + + public MetadataPushEvent(ApplicationModel source) { + super(source); + } +} diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetadataServiceSubscribeEvent.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetadataServiceSubscribeEvent.java new file mode 100644 index 00000000000..bf5c7cc0781 --- /dev/null +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetadataServiceSubscribeEvent.java @@ -0,0 +1,33 @@ +/* + * 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.metadata.event; + +import org.apache.dubbo.rpc.model.ApplicationModel; + +public class MetadataServiceSubscribeEvent extends MetadataEvent { + + private final String serviceKey; + + public MetadataServiceSubscribeEvent(ApplicationModel source, String serviceKey) { + super(source); + this.serviceKey = serviceKey; + } + + public String getServiceKey() { + return serviceKey; + } +} diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetadataSubscribeEvent.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetadataSubscribeEvent.java new file mode 100644 index 00000000000..f9ac4ee93fb --- /dev/null +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/event/MetadataSubscribeEvent.java @@ -0,0 +1,26 @@ +/* + * 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.metadata.event; + +import org.apache.dubbo.rpc.model.ApplicationModel; + +public class MetadataSubscribeEvent extends MetadataEvent { + + public MetadataSubscribeEvent(ApplicationModel source) { + super(source); + } +} diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReport.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReport.java index f21e99b3dfd..cccc7f1a4c4 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReport.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReport.java @@ -17,6 +17,7 @@ package org.apache.dubbo.metadata.report.support; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; @@ -26,13 +27,12 @@ import org.apache.dubbo.common.utils.SystemPropertyConfigUtils; import org.apache.dubbo.metadata.definition.model.FullServiceDefinition; import org.apache.dubbo.metadata.definition.model.ServiceDefinition; +import org.apache.dubbo.metadata.event.MetadataServiceSubscribeEvent; import org.apache.dubbo.metadata.report.MetadataReport; import org.apache.dubbo.metadata.report.identifier.KeyTypeEnum; import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier; import org.apache.dubbo.metadata.report.identifier.ServiceMetadataIdentifier; import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier; -import org.apache.dubbo.metrics.event.MetricsEventBus; -import org.apache.dubbo.metrics.metadata.event.MetadataEvent; import org.apache.dubbo.rpc.model.ApplicationModel; import java.io.File; @@ -298,9 +298,9 @@ public void storeProviderMetadata( private void storeProviderMetadataTask( MetadataIdentifier providerMetadataIdentifier, ServiceDefinition serviceDefinition) { - MetadataEvent metadataEvent = MetadataEvent.toServiceSubscribeEvent( - applicationModel, providerMetadataIdentifier.getUniqueServiceName()); - MetricsEventBus.post( + MetadataServiceSubscribeEvent metadataEvent = + new MetadataServiceSubscribeEvent(applicationModel, providerMetadataIdentifier.getUniqueServiceName()); + DubboEventBus.post( metadataEvent, () -> { boolean result = true; @@ -329,7 +329,7 @@ private void storeProviderMetadataTask( } return result; }, - aBoolean -> aBoolean); + result -> result); } @Override diff --git a/dubbo-metrics/dubbo-metrics-api/pom.xml b/dubbo-metrics/dubbo-metrics-api/pom.xml index da9570a5d07..2c387a2cb05 100644 --- a/dubbo-metrics/dubbo-metrics-api/pom.xml +++ b/dubbo-metrics/dubbo-metrics-api/pom.xml @@ -36,11 +36,6 @@ dubbo-common ${project.parent.version} - - org.apache.dubbo - dubbo-metrics-event - ${project.parent.version} - org.apache.dubbo dubbo-rpc-api diff --git a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/MetricsConstants.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/MetricsConstants.java similarity index 100% rename from dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/MetricsConstants.java rename to dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/MetricsConstants.java diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/MetricsGlobalRegistry.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/MetricsGlobalRegistry.java similarity index 100% rename from dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/MetricsGlobalRegistry.java rename to dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/MetricsGlobalRegistry.java diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/ApplicationMetricsCollector.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/ApplicationMetricsCollector.java index 63c996d0c2a..02489cc3356 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/ApplicationMetricsCollector.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/ApplicationMetricsCollector.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.metrics.collector; -import org.apache.dubbo.metrics.event.TimeCounterEvent; import org.apache.dubbo.metrics.model.key.MetricsKey; /** @@ -25,7 +24,7 @@ * * @Params metrics type */ -public interface ApplicationMetricsCollector extends MetricsCollector { +public interface ApplicationMetricsCollector extends MetricsCollector { void increment(MetricsKey metricsKey); diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/CombMetricsCollector.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/CombMetricsCollector.java index becf811e9f8..8b7c8bf5aeb 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/CombMetricsCollector.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/CombMetricsCollector.java @@ -17,9 +17,6 @@ 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; @@ -31,20 +28,15 @@ import static org.apache.dubbo.metrics.MetricsConstants.SELF_INCREMENT_SIZE; -public abstract class CombMetricsCollector extends AbstractMetricsListener - implements ApplicationMetricsCollector, ServiceMetricsCollector, MethodMetricsCollector { +public abstract class CombMetricsCollector + implements ApplicationMetricsCollector, ServiceMetricsCollector, MethodMetricsCollector { 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); @@ -97,25 +89,6 @@ protected List 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; } diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/MethodMetricsCollector.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/MethodMetricsCollector.java index 03f1becd04c..74d4e266bf5 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/MethodMetricsCollector.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/MethodMetricsCollector.java @@ -16,7 +16,6 @@ */ 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; @@ -24,7 +23,7 @@ /** * Method-level metrics collection for rpc invocation scenarios */ -public interface MethodMetricsCollector extends MetricsCollector { +public interface MethodMetricsCollector extends MetricsCollector { void increment(MethodMetric methodMetric, MetricsKeyWrapper wrapper, int size); diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/MetricsCollector.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/MetricsCollector.java index 0d61468f045..3bc2bc458d2 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/MetricsCollector.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/MetricsCollector.java @@ -17,9 +17,6 @@ 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; @@ -29,7 +26,7 @@ * An interface of collector to collect framework internal metrics. */ @SPI -public interface MetricsCollector extends MetricsLifeListener { +public interface MetricsCollector { default boolean isCollectEnabled() { return false; @@ -49,7 +46,4 @@ default boolean isCollectEnabled() { * @return true if samples have been changed */ boolean calSamplesChanged(); - - default void initMetrics(MetricsEvent event) {} - ; } diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/ServiceMetricsCollector.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/ServiceMetricsCollector.java index 699236f3fb0..06020d72766 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/ServiceMetricsCollector.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/ServiceMetricsCollector.java @@ -16,7 +16,6 @@ */ 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; @@ -24,7 +23,7 @@ * Service-level collector. * registration center, configuration center and other scenarios */ -public interface ServiceMetricsCollector extends MetricsCollector { +public interface ServiceMetricsCollector extends MetricsCollector { void increment(String serviceKey, MetricsKeyWrapper wrapper, int size); diff --git a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/MetricsEvent.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/MetricsEvent.java similarity index 77% rename from dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/MetricsEvent.java rename to dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/MetricsEvent.java index 25a040d8588..51a89e1f7f1 100644 --- a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/MetricsEvent.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/MetricsEvent.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.metrics.event; -import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; +import org.apache.dubbo.common.event.DubboEvent; import org.apache.dubbo.metrics.exception.MetricsNeverHappenException; import org.apache.dubbo.metrics.model.key.TypeWrapper; import org.apache.dubbo.rpc.model.ApplicationModel; @@ -28,7 +28,7 @@ /** * BaseMetricsEvent. */ -public abstract class MetricsEvent { +public abstract class MetricsEvent extends DubboEvent { /** * Metric object. (eg. MethodMetric) @@ -38,19 +38,15 @@ public abstract class MetricsEvent { private boolean available = true; private final TypeWrapper typeWrapper; private final String appName; - private final MetricsEventMulticaster metricsEventMulticaster; private final Map attachments = new IdentityHashMap<>(8); public MetricsEvent(ApplicationModel source, TypeWrapper typeWrapper) { - this(source, null, null, typeWrapper); + this(source, null, typeWrapper); } - public MetricsEvent( - ApplicationModel source, - String appName, - MetricsEventMulticaster metricsEventMulticaster, - TypeWrapper typeWrapper) { + public MetricsEvent(ApplicationModel source, String appName, TypeWrapper typeWrapper) { + super(source); this.typeWrapper = typeWrapper; if (source == null) { this.source = ApplicationModel.defaultModel(); @@ -59,21 +55,6 @@ public MetricsEvent( } else { this.source = source; } - if (metricsEventMulticaster == null) { - if (this.source.isDestroyed()) { - this.metricsEventMulticaster = null; - } else { - ScopeBeanFactory beanFactory = this.source.getBeanFactory(); - if (beanFactory.isDestroyed()) { - this.metricsEventMulticaster = null; - } else { - MetricsEventMulticaster dispatcher = beanFactory.getBean(MetricsEventMulticaster.class); - this.metricsEventMulticaster = dispatcher; - } - } - } else { - this.metricsEventMulticaster = metricsEventMulticaster; - } if (appName == null) { this.appName = this.source.tryGetApplicationName(); } else { @@ -115,10 +96,6 @@ public ApplicationModel getSource() { return source; } - public MetricsEventMulticaster getMetricsEventMulticaster() { - return metricsEventMulticaster; - } - public String appName() { return appName; } diff --git a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/TimeCounterEvent.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/TimeCounterEvent.java similarity index 77% rename from dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/TimeCounterEvent.java rename to dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/TimeCounterEvent.java index 7cfb2c607f8..a29f6e904e9 100644 --- a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/TimeCounterEvent.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/TimeCounterEvent.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.metrics.event; -import org.apache.dubbo.metrics.model.TimePair; +import org.apache.dubbo.common.utils.TimePair; import org.apache.dubbo.metrics.model.key.TypeWrapper; import org.apache.dubbo.rpc.model.ApplicationModel; @@ -27,18 +27,14 @@ public abstract class TimeCounterEvent extends MetricsEvent { private final TimePair timePair; - public TimeCounterEvent(ApplicationModel source, TypeWrapper typeWrapper) { + public TimeCounterEvent(ApplicationModel source, TypeWrapper typeWrapper, TimePair timePair) { super(source, typeWrapper); - this.timePair = TimePair.start(); + this.timePair = timePair; } - public TimeCounterEvent( - ApplicationModel source, - String appName, - MetricsEventMulticaster metricsDispatcher, - TypeWrapper typeWrapper) { - super(source, appName, metricsDispatcher, typeWrapper); - this.timePair = TimePair.start(); + public TimeCounterEvent(ApplicationModel source, String appName, TypeWrapper typeWrapper, TimePair timePair) { + super(source, appName, typeWrapper); + this.timePair = timePair; } public TimePair getTimePair() { diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/SimpleMetricsEventMulticaster.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/TimeCounterEventMulticaster.java similarity index 58% rename from dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/SimpleMetricsEventMulticaster.java rename to dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/TimeCounterEventMulticaster.java index bfc8ae2b91e..40a2bc92213 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/SimpleMetricsEventMulticaster.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/TimeCounterEventMulticaster.java @@ -17,8 +17,7 @@ package org.apache.dubbo.metrics.event; import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.metrics.listener.MetricsLifeListener; -import org.apache.dubbo.metrics.listener.MetricsListener; +import org.apache.dubbo.metrics.listener.AbstractMetricsKeyListener; import java.util.ArrayList; import java.util.Collections; @@ -28,26 +27,23 @@ /** * A simple event publisher that defines lifecycle events and supports rt events */ -public class SimpleMetricsEventMulticaster implements MetricsEventMulticaster { - private final List> listeners = Collections.synchronizedList(new ArrayList<>()); +public class TimeCounterEventMulticaster { + private final List listeners = Collections.synchronizedList(new ArrayList<>()); - @Override - public void addListener(MetricsListener listener) { + public void addListener(AbstractMetricsKeyListener listener) { listeners.add(listener); } - @Override - @SuppressWarnings({"rawtypes", "unchecked"}) - public void publishEvent(MetricsEvent event) { + public void publishEvent(TimeCounterEvent event) { if (validateIfApplicationConfigExist(event)) return; - for (MetricsListener listener : listeners) { - if (listener.isSupport(event)) { + for (AbstractMetricsKeyListener listener : listeners) { + if (listener.support(event)) { listener.onEvent(event); } } } - private boolean validateIfApplicationConfigExist(MetricsEvent event) { + private boolean validateIfApplicationConfigExist(TimeCounterEvent event) { if (event.getSource() != null) { // Check if exist application config return StringUtils.isEmpty(event.appName()); @@ -55,27 +51,22 @@ private boolean validateIfApplicationConfigExist(MetricsEvent event) { return false; } - @Override - @SuppressWarnings({"unchecked"}) public void publishFinishEvent(TimeCounterEvent event) { publishTimeEvent(event, metricsLifeListener -> metricsLifeListener.onEventFinish(event)); } - @Override - @SuppressWarnings({"unchecked"}) public void publishErrorEvent(TimeCounterEvent event) { publishTimeEvent(event, metricsLifeListener -> metricsLifeListener.onEventError(event)); } - @SuppressWarnings({"rawtypes"}) - private void publishTimeEvent(MetricsEvent event, Consumer consumer) { - if (validateIfApplicationConfigExist(event)) return; - if (event instanceof TimeCounterEvent) { - ((TimeCounterEvent) event).getTimePair().end(); + private void publishTimeEvent(TimeCounterEvent event, Consumer consumer) { + if (validateIfApplicationConfigExist(event)) { + return; } - for (MetricsListener listener : listeners) { - if (listener instanceof MetricsLifeListener && listener.isSupport(event)) { - consumer.accept(((MetricsLifeListener) listener)); + event.getTimePair().end(); + for (AbstractMetricsKeyListener listener : listeners) { + if (listener.support(event)) { + consumer.accept(listener); } } } diff --git a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/exception/MetricsNeverHappenException.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/exception/MetricsNeverHappenException.java similarity index 100% rename from dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/exception/MetricsNeverHappenException.java rename to dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/exception/MetricsNeverHappenException.java diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/AbstractMetricsKeyListener.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/AbstractMetricsKeyListener.java index 516ce04ae4c..34c90cc2ff8 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/AbstractMetricsKeyListener.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/AbstractMetricsKeyListener.java @@ -16,20 +16,17 @@ */ package org.apache.dubbo.metrics.listener; -import org.apache.dubbo.metrics.event.MetricsEvent; -import org.apache.dubbo.metrics.event.MetricsEventBus; +import org.apache.dubbo.common.event.DubboEventBus; 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}, + * According to the event template of {@link DubboEventBus}, * build a consistent static method for general and custom monitoring consume methods - * */ -public abstract class AbstractMetricsKeyListener extends AbstractMetricsListener - implements MetricsLifeListener { +public abstract class AbstractMetricsKeyListener { private final MetricsKey metricsKey; @@ -40,14 +37,16 @@ public AbstractMetricsKeyListener(MetricsKey metricsKey) { /** * The MetricsKey type determines whether events are supported */ - @Override - public boolean isSupport(MetricsEvent event) { - return super.isSupport(event) && event.isAssignableFrom(metricsKey); + public boolean support(TimeCounterEvent event) { + return event.isAssignableFrom(metricsKey); } - @Override public void onEvent(TimeCounterEvent event) {} + public void onEventFinish(TimeCounterEvent event) {} + + public void onEventError(TimeCounterEvent event) {} + public static AbstractMetricsKeyListener onEvent(MetricsKey metricsKey, Consumer postFunc) { return new AbstractMetricsKeyListener(metricsKey) { diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/MetricsApplicationListener.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/MetricsApplicationListener.java index 018889ec2a8..2e9f4d8bbae 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/MetricsApplicationListener.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/MetricsApplicationListener.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.metrics.listener; -import org.apache.dubbo.metrics.collector.CombMetricsCollector; +import org.apache.dubbo.metrics.collector.ApplicationMetricsCollector; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.model.key.MetricsPlaceValue; @@ -24,11 +24,7 @@ * 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); - } +public class MetricsApplicationListener { /** * Perform auto-increment on the monitored key, @@ -38,7 +34,7 @@ public MetricsApplicationListener(MetricsKey metricsKey) { * @param collector Corresponding collector */ public static AbstractMetricsKeyListener onPostEventBuild( - MetricsKey metricsKey, CombMetricsCollector collector) { + MetricsKey metricsKey, ApplicationMetricsCollector collector) { return AbstractMetricsKeyListener.onEvent(metricsKey, event -> collector.increment(metricsKey)); } @@ -50,7 +46,7 @@ public static AbstractMetricsKeyListener onPostEventBuild( * @param collector Corresponding collector */ public static AbstractMetricsKeyListener onFinishEventBuild( - MetricsKey metricsKey, MetricsPlaceValue placeType, CombMetricsCollector collector) { + MetricsKey metricsKey, MetricsPlaceValue placeType, ApplicationMetricsCollector collector) { return AbstractMetricsKeyListener.onFinish(metricsKey, event -> { collector.increment(metricsKey); collector.addApplicationRt(placeType.getType(), event.getTimePair().calc()); @@ -61,7 +57,7 @@ public static AbstractMetricsKeyListener onFinishEventBuild( * Similar to onFinishEventBuild */ public static AbstractMetricsKeyListener onErrorEventBuild( - MetricsKey metricsKey, MetricsPlaceValue placeType, CombMetricsCollector collector) { + MetricsKey metricsKey, MetricsPlaceValue placeType, ApplicationMetricsCollector collector) { return AbstractMetricsKeyListener.onError(metricsKey, event -> { collector.increment(metricsKey); collector.addApplicationRt(placeType.getType(), event.getTimePair().calc()); diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/MetricsServiceListener.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/MetricsServiceListener.java index 49fa8c783f1..ec1215c0d83 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/MetricsServiceListener.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/MetricsServiceListener.java @@ -17,7 +17,6 @@ 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; @@ -27,26 +26,22 @@ * to produce an anonymous listener for general monitoring. * Similar to App-level */ -public class MetricsServiceListener extends AbstractMetricsKeyListener { - - public MetricsServiceListener(MetricsKey metricsKey) { - super(metricsKey); - } +public class MetricsServiceListener { public static AbstractMetricsKeyListener onPostEventBuild( - MetricsKey metricsKey, MetricsPlaceValue placeType, ServiceMetricsCollector collector) { + MetricsKey metricsKey, MetricsPlaceValue placeType, ServiceMetricsCollector collector) { return AbstractMetricsKeyListener.onEvent( metricsKey, event -> MetricsSupport.increment(metricsKey, placeType, collector, event)); } public static AbstractMetricsKeyListener onFinishEventBuild( - MetricsKey metricsKey, MetricsPlaceValue placeType, ServiceMetricsCollector collector) { + MetricsKey metricsKey, MetricsPlaceValue placeType, ServiceMetricsCollector collector) { return AbstractMetricsKeyListener.onFinish( metricsKey, event -> MetricsSupport.incrAndAddRt(metricsKey, placeType, collector, event)); } public static AbstractMetricsKeyListener onErrorEventBuild( - MetricsKey metricsKey, MetricsPlaceValue placeType, ServiceMetricsCollector collector) { + MetricsKey metricsKey, MetricsPlaceValue placeType, ServiceMetricsCollector collector) { return AbstractMetricsKeyListener.onError( metricsKey, event -> MetricsSupport.incrAndAddRt(metricsKey, placeType, collector, event)); } diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsSupport.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsSupport.java index dc7b9e5aa28..219198d1924 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsSupport.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsSupport.java @@ -213,10 +213,7 @@ public static String getVersion(Invocation invocation) { * Incr service num */ public static void increment( - MetricsKey metricsKey, - MetricsPlaceValue placeType, - ServiceMetricsCollector collector, - MetricsEvent event) { + MetricsKey metricsKey, MetricsPlaceValue placeType, ServiceMetricsCollector collector, MetricsEvent event) { collector.increment( event.getAttachmentValue(ATTACHMENT_KEY_SERVICE), new MetricsKeyWrapper(metricsKey, placeType), @@ -229,7 +226,7 @@ public static void increment( public static void incrAndAddRt( MetricsKey metricsKey, MetricsPlaceValue placeType, - ServiceMetricsCollector collector, + ServiceMetricsCollector collector, TimeCounterEvent event) { collector.increment( event.getAttachmentValue(ATTACHMENT_KEY_SERVICE), @@ -251,10 +248,7 @@ public static void incrAndAddRt( * Incr method num */ public static void increment( - MetricsKey metricsKey, - MetricsPlaceValue placeType, - MethodMetricsCollector collector, - MetricsEvent event) { + MetricsKey metricsKey, MetricsPlaceValue placeType, MethodMetricsCollector collector, MetricsEvent event) { collector.increment( event.getAttachmentValue(METHOD_METRICS), new MetricsKeyWrapper(metricsKey, placeType), @@ -262,10 +256,7 @@ public static void increment( } public static void init( - MetricsKey metricsKey, - MetricsPlaceValue placeType, - MethodMetricsCollector collector, - MetricsEvent event) { + MetricsKey metricsKey, MetricsPlaceValue placeType, MethodMetricsCollector collector, MetricsEvent event) { collector.init(event.getAttachmentValue(INVOCATION), new MetricsKeyWrapper(metricsKey, placeType)); } @@ -273,10 +264,7 @@ public static void init( * Dec method num */ public static void dec( - MetricsKey metricsKey, - MetricsPlaceValue placeType, - MethodMetricsCollector collector, - MetricsEvent event) { + MetricsKey metricsKey, MetricsPlaceValue placeType, MethodMetricsCollector collector, MetricsEvent event) { collector.increment( event.getAttachmentValue(METHOD_METRICS), new MetricsKeyWrapper(metricsKey, placeType), @@ -289,7 +277,7 @@ public static void dec( public static void incrAndAddRt( MetricsKey metricsKey, MetricsPlaceValue placeType, - MethodMetricsCollector collector, + MethodMetricsCollector collector, TimeCounterEvent event) { collector.increment( event.getAttachmentValue(METHOD_METRICS), diff --git a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/model/key/MetricsKey.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/MetricsKey.java similarity index 100% rename from dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/model/key/MetricsKey.java rename to dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/MetricsKey.java diff --git a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/model/key/MetricsLevel.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/MetricsLevel.java similarity index 100% rename from dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/model/key/MetricsLevel.java rename to dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/MetricsLevel.java diff --git a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/model/key/TypeWrapper.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/TypeWrapper.java similarity index 100% rename from dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/model/key/TypeWrapper.java rename to dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/TypeWrapper.java diff --git a/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/MetricsSupportTest.java b/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/MetricsSupportTest.java index 5ea95fdff7b..c3e0b07c831 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/MetricsSupportTest.java +++ b/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/MetricsSupportTest.java @@ -17,12 +17,14 @@ package org.apache.dubbo.metrics; import org.apache.dubbo.common.constants.CommonConstants; +import org.apache.dubbo.common.utils.Assert; 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.metrics.utils.MetricsSupportUtil; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; @@ -60,4 +62,10 @@ void testFillZero() { Assertions.assertEquals( 4, data.values().stream().mapToLong(map -> map.values().size()).sum()); } + + @Test + void isSupportPrometheus() { + boolean supportPrometheus = MetricsSupportUtil.isSupportPrometheus(); + Assert.assertTrue(!supportPrometheus, "MetricsSupportUtil.isSupportPrometheus() should return false"); + } } diff --git a/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/event/SimpleMetricsEventMulticasterTest.java b/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/event/SimpleDubboEventMulticasterTest.java similarity index 79% rename from dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/event/SimpleMetricsEventMulticasterTest.java rename to dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/event/SimpleDubboEventMulticasterTest.java index b101d944e43..9adf276a77b 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/event/SimpleMetricsEventMulticasterTest.java +++ b/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/event/SimpleDubboEventMulticasterTest.java @@ -16,10 +16,10 @@ */ package org.apache.dubbo.metrics.event; +import org.apache.dubbo.common.utils.TimePair; 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.metrics.listener.AbstractMetricsKeyListener; import org.apache.dubbo.rpc.model.ApplicationModel; import org.junit.jupiter.api.Assertions; @@ -28,20 +28,26 @@ import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT; -public class SimpleMetricsEventMulticasterTest { +public class SimpleDubboEventMulticasterTest { - private SimpleMetricsEventMulticaster eventMulticaster; + private TimeCounterEventMulticaster eventMulticaster; private Object[] objects; private final Object obj = new Object(); private TimeCounterEvent requestEvent; @BeforeEach public void setup() { - eventMulticaster = new SimpleMetricsEventMulticaster(); + eventMulticaster = new TimeCounterEventMulticaster(); objects = new Object[] {obj}; - eventMulticaster.addListener(new AbstractMetricsListener() { + eventMulticaster.addListener(new AbstractMetricsKeyListener(null) { + @Override - public void onEvent(MetricsEvent event) { + public boolean support(TimeCounterEvent event) { + return true; + } + + @Override + public void onEvent(TimeCounterEvent event) { objects[0] = new Object(); } }); @@ -52,7 +58,7 @@ public void onEvent(MetricsEvent event) { ConfigManager configManager = new ConfigManager(applicationModel); configManager.setApplication(applicationConfig); applicationModel.setConfigManager(configManager); - requestEvent = new TimeCounterEvent(applicationModel, null) {}; + requestEvent = new TimeCounterEvent(applicationModel, null, TimePair.start()) {}; } @Test @@ -63,11 +69,11 @@ void testPublishFinishEvent() { Assertions.assertSame(obj, objects[0]); // do onEventFinish with MetricsLifeListener - eventMulticaster.addListener((new MetricsLifeListener() { + eventMulticaster.addListener(new AbstractMetricsKeyListener(null) { @Override - public boolean isSupport(MetricsEvent event) { - return event instanceof TimeCounterEvent; + public boolean support(TimeCounterEvent event) { + return true; } @Override @@ -80,7 +86,7 @@ public void onEventFinish(TimeCounterEvent event) { @Override public void onEventError(TimeCounterEvent event) {} - })); + }); eventMulticaster.publishFinishEvent(requestEvent); Assertions.assertNotSame(obj, objects[0]); } diff --git a/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/collector/ConfigCenterMetricsCollector.java b/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/collector/ConfigCenterMetricsCollector.java index 3840862f68e..2aab5615412 100644 --- a/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/collector/ConfigCenterMetricsCollector.java +++ b/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/collector/ConfigCenterMetricsCollector.java @@ -16,11 +16,10 @@ */ package org.apache.dubbo.metrics.config.collector; +import org.apache.dubbo.common.event.DubboEventBus; 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; @@ -42,7 +41,7 @@ * Config center implementation of {@link MetricsCollector} */ @Activate -public class ConfigCenterMetricsCollector extends CombMetricsCollector { +public class ConfigCenterMetricsCollector implements MetricsCollector { private Boolean collectEnabled = null; private final ApplicationModel applicationModel; @@ -51,9 +50,9 @@ public class ConfigCenterMetricsCollector extends CombMetricsCollector updatedMetrics = new ConcurrentHashMap<>(); public ConfigCenterMetricsCollector(ApplicationModel applicationModel) { - super(null); this.applicationModel = applicationModel; - super.setEventMulticaster(new ConfigCenterSubDispatcher(this)); + // bind dispatcher + DubboEventBus.addListener(applicationModel, new ConfigCenterSubDispatcher(this)); } public void setCollectEnabled(Boolean collectEnabled) { diff --git a/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/event/ConfigCenterEvent.java b/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/event/ConfigCenterEvent.java deleted file mode 100644 index 58e9979f70b..00000000000 --- a/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/event/ConfigCenterEvent.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * 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; - } -} diff --git a/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/event/ConfigCenterSubDispatcher.java b/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/event/ConfigCenterSubDispatcher.java index 49eab005783..dba769c54d4 100644 --- a/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/event/ConfigCenterSubDispatcher.java +++ b/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/event/ConfigCenterSubDispatcher.java @@ -16,38 +16,25 @@ */ package org.apache.dubbo.metrics.config.event; +import org.apache.dubbo.common.config.configcenter.ConfigCenterChangeEvent; +import org.apache.dubbo.common.event.AbstractDubboListener; 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 AbstractDubboListener { -public final class ConfigCenterSubDispatcher extends SimpleMetricsEventMulticaster { + private ConfigCenterMetricsCollector collector; public ConfigCenterSubDispatcher(ConfigCenterMetricsCollector collector) { + this.collector = 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)); - } - }); + @Override + public void onEvent(ConfigCenterChangeEvent event) { + collector.increase( + event.getKey(), + event.getGroup(), + event.getProtocol(), + event.getChangeType().name(), + event.getCount()); } } diff --git a/dubbo-metrics/dubbo-metrics-config-center/src/test/java/org/apache/dubbo/metrics/collector/ConfigCenterMetricsCollectorTest.java b/dubbo-metrics/dubbo-metrics-config-center/src/test/java/org/apache/dubbo/metrics/collector/ConfigCenterMetricsCollectorTest.java index 35c44a94cad..7af2abb2631 100644 --- a/dubbo-metrics/dubbo-metrics-config-center/src/test/java/org/apache/dubbo/metrics/collector/ConfigCenterMetricsCollectorTest.java +++ b/dubbo-metrics/dubbo-metrics-config-center/src/test/java/org/apache/dubbo/metrics/collector/ConfigCenterMetricsCollectorTest.java @@ -16,8 +16,10 @@ */ package org.apache.dubbo.metrics.collector; +import org.apache.dubbo.common.config.configcenter.ConfigCenterChangeEvent; import org.apache.dubbo.common.config.configcenter.ConfigChangeType; import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.metrics.config.collector.ConfigCenterMetricsCollector; import org.apache.dubbo.metrics.model.sample.GaugeMetricSample; @@ -34,7 +36,6 @@ 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 { @@ -61,8 +62,12 @@ 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); + // collector.increase("key", "group", "nacos", ConfigChangeType.ADDED.name(), 1); + // collector.increase("key", "group", "nacos", ConfigChangeType.ADDED.name(), 1); + ConfigCenterChangeEvent configCenterChangeEvent = + new ConfigCenterChangeEvent(applicationModel, "key", "group", "nacos", ConfigChangeType.ADDED, 1); + DubboEventBus.publish(configCenterChangeEvent); + DubboEventBus.publish(configCenterChangeEvent); List samples = collector.collect(); for (MetricSample sample : samples) { @@ -83,11 +88,18 @@ void increaseUpdated() { 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); + // 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); + + ConfigCenterChangeEvent configCenterChangeEvent = new ConfigCenterChangeEvent( + applicationModel, event.getKey(), event.getGroup(), "apollo", ConfigChangeType.ADDED); + DubboEventBus.publish(configCenterChangeEvent); + DubboEventBus.publish(configCenterChangeEvent); List samples = collector.collect(); for (MetricSample sample : samples) { diff --git a/dubbo-metrics/dubbo-metrics-default/pom.xml b/dubbo-metrics/dubbo-metrics-default/pom.xml index 98fb0890137..d570d5da2e2 100644 --- a/dubbo-metrics/dubbo-metrics-default/pom.xml +++ b/dubbo-metrics/dubbo-metrics-default/pom.xml @@ -31,11 +31,21 @@ false + + org.apache.dubbo + dubbo-tracing + ${project.parent.version} + org.apache.dubbo dubbo-metrics-api ${project.parent.version} + + org.apache.dubbo + dubbo-config-api + ${project.parent.version} + org.apache.dubbo diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultMetricsServiceExporter.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/DefaultMetricsServiceExporter.java similarity index 99% rename from dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultMetricsServiceExporter.java rename to dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/DefaultMetricsServiceExporter.java index a3501102447..841e4cd8406 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultMetricsServiceExporter.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/DefaultMetricsServiceExporter.java @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.config.deploy; +package org.apache.dubbo.metrics; import org.apache.dubbo.common.constants.LoggerCodeConstants; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/MetricsScopeModelInitializer.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/MetricsScopeModelInitializer.java index 01e174ad0b3..562730d8e46 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/MetricsScopeModelInitializer.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/MetricsScopeModelInitializer.java @@ -16,14 +16,20 @@ */ package org.apache.dubbo.metrics; +import org.apache.dubbo.common.Ordered; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; -import org.apache.dubbo.metrics.event.MetricsDispatcher; +import org.apache.dubbo.common.event.DubboEventBus; +import org.apache.dubbo.common.event.DubboListener; +import org.apache.dubbo.common.extension.ExtensionLoader; +import org.apache.dubbo.metrics.collector.MetricsCollector; 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 { +import java.util.List; + +public class MetricsScopeModelInitializer implements ScopeModelInitializer, Ordered { @Override public void initializeFrameworkModel(FrameworkModel frameworkModel) {} @@ -31,9 +37,24 @@ public void initializeFrameworkModel(FrameworkModel frameworkModel) {} @Override public void initializeApplicationModel(ApplicationModel applicationModel) { ScopeBeanFactory beanFactory = applicationModel.getBeanFactory(); - beanFactory.registerBean(MetricsDispatcher.class); + ExtensionLoader extensionLoader = applicationModel.getExtensionLoader(MetricsCollector.class); + if (extensionLoader != null) { + List customizeCollectors = extensionLoader.getActivateExtensions(); + for (MetricsCollector customizeCollector : customizeCollectors) { + beanFactory.registerBean(customizeCollector); + } + } + MetricsServiceInitializer metricsServiceInitializer = new MetricsServiceInitializer(applicationModel); + for (DubboListener dubboListener : metricsServiceInitializer.getDubboListeners()) { + DubboEventBus.addListener(applicationModel, dubboListener); + } } @Override public void initializeModuleModel(ModuleModel moduleModel) {} + + @Override + public int getOrder() { + return 1; + } } diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/MetricsServiceInitializer.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/MetricsServiceInitializer.java new file mode 100644 index 00000000000..30f18d90393 --- /dev/null +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/MetricsServiceInitializer.java @@ -0,0 +1,178 @@ +/* + * 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.event.AbstractDubboListener; +import org.apache.dubbo.common.event.DubboListener; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; +import org.apache.dubbo.common.logger.LoggerFactory; +import org.apache.dubbo.common.utils.StringUtils; +import org.apache.dubbo.config.MetricsConfig; +import org.apache.dubbo.config.TracingConfig; +import org.apache.dubbo.config.deploy.event.ApplicationLoadedEvent; +import org.apache.dubbo.metrics.collector.DefaultMetricsCollector; +import org.apache.dubbo.metrics.listener.PreDestroyApplicationInstanceEventListener; +import org.apache.dubbo.metrics.listener.PrepareApplicationInstanceEventListener; +import org.apache.dubbo.metrics.report.DefaultMetricsReporterFactory; +import org.apache.dubbo.metrics.report.MetricsReporter; +import org.apache.dubbo.metrics.report.MetricsReporterFactory; +import org.apache.dubbo.metrics.service.MetricsServiceExporter; +import org.apache.dubbo.metrics.utils.MetricsSupportUtil; +import org.apache.dubbo.rpc.model.ApplicationModel; +import org.apache.dubbo.tracing.DubboObservationRegistry; +import org.apache.dubbo.tracing.utils.ObservationSupportUtil; + +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_METRICS_COLLECTOR_EXCEPTION; +import static org.apache.dubbo.common.constants.MetricsConstants.PROTOCOL_DEFAULT; +import static org.apache.dubbo.common.constants.MetricsConstants.PROTOCOL_PROMETHEUS; + +/** + * Initialize the metrics service. + */ +public class MetricsServiceInitializer { + + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(MetricsServiceInitializer.class); + + private final ApplicationModel applicationModel; + + private final MetricsServiceExporter metricsServiceExporter; + + private final DefaultMetricsCollector defaultCollector; + + private final List> dubboListeners; + + public MetricsServiceInitializer(ApplicationModel applicationModel) { + this.applicationModel = applicationModel; + this.defaultCollector = applicationModel.getBeanFactory().getBean(DefaultMetricsCollector.class); + this.metricsServiceExporter = applicationModel + .getExtensionLoader(MetricsServiceExporter.class) + .getDefaultExtension(); + dubboListeners = Arrays.asList( + new AbstractDubboListener() { + @Override + public void onEvent(ApplicationLoadedEvent event) { + + if (MetricsSupportUtil.isSupportMetrics()) { + MetricsConfig metricsConfig = initMetricsConfig(); + if (!PROTOCOL_PROMETHEUS.equals(metricsConfig.getProtocol()) + || MetricsSupportUtil.isSupportPrometheus()) { + initDefaultMetricsCollector(metricsConfig); + initMetricsReporter(metricsConfig); + } + } + + initMetricsService(); + + // @since 3.2.3 + initObservationRegistry(); + } + }, + new PrepareApplicationInstanceEventListener(), + new PreDestroyApplicationInstanceEventListener()); + } + + public List> getDubboListeners() { + return dubboListeners; + } + + private void initMetricsService() { + this.applicationModel.getBeanFactory().registerBean(this.metricsServiceExporter); + this.metricsServiceExporter.init(); + } + + private MetricsConfig initMetricsConfig() { + Optional configOptional = + applicationModel.getApplicationConfigManager().getMetrics(); + // If no specific metrics type is configured and there is no Prometheus dependency in the dependencies. + MetricsConfig metricsConfig = configOptional.orElse(new MetricsConfig(applicationModel)); + if (StringUtils.isBlank(metricsConfig.getProtocol())) { + metricsConfig.setProtocol( + MetricsSupportUtil.isSupportPrometheus() ? PROTOCOL_PROMETHEUS : PROTOCOL_DEFAULT); + } + return metricsConfig; + } + + private void initDefaultMetricsCollector(MetricsConfig metricsConfig) { + defaultCollector.setCollectEnabled(true); + defaultCollector.collectApplication(); + defaultCollector.setThreadpoolCollectEnabled( + Optional.ofNullable(metricsConfig.getEnableThreadpool()).orElse(true)); + defaultCollector.setMetricsInitEnabled( + Optional.ofNullable(metricsConfig.getEnableMetricsInit()).orElse(true)); + } + + private void initMetricsReporter(MetricsConfig metricsConfig) { + MetricsReporterFactory metricsReporterFactory = applicationModel + .getExtensionLoader(MetricsReporterFactory.class) + .getAdaptiveExtension(); + MetricsReporter metricsReporter = null; + try { + metricsReporter = metricsReporterFactory.createMetricsReporter(metricsConfig.toUrl()); + } catch (IllegalStateException e) { + if (e.getMessage().startsWith("No such extension org.apache.dubbo.metrics.report.MetricsReporterFactory")) { + logger.warn(COMMON_METRICS_COLLECTOR_EXCEPTION, "", "", e.getMessage()); + return; + } else { + throw e; + } + } + metricsReporter.init(); + applicationModel.getBeanFactory().registerBean(metricsReporter); + // If the protocol is not the default protocol, the default protocol is also initialized. + if (!PROTOCOL_DEFAULT.equals(metricsConfig.getProtocol())) { + DefaultMetricsReporterFactory defaultMetricsReporterFactory = + new DefaultMetricsReporterFactory(applicationModel); + MetricsReporter defaultMetricsReporter = + defaultMetricsReporterFactory.createMetricsReporter(metricsConfig.toUrl()); + defaultMetricsReporter.init(); + applicationModel.getBeanFactory().registerBean(defaultMetricsReporter); + } + } + + /** + * init ObservationRegistry(Micrometer) + */ + private void initObservationRegistry() { + if (!ObservationSupportUtil.isSupportObservation()) { + if (logger.isDebugEnabled()) { + logger.debug("Not found micrometer-observation or plz check the version of micrometer-observation " + + "version if already introduced, need > 1.10.0"); + } + return; + } + if (!ObservationSupportUtil.isSupportTracing()) { + if (logger.isDebugEnabled()) { + logger.debug("Not found micrometer-tracing dependency, skip init ObservationRegistry."); + } + return; + } + Optional configOptional = + applicationModel.getApplicationConfigManager().getTracing(); + if (!configOptional.isPresent() || !configOptional.get().getEnabled()) { + return; + } + + DubboObservationRegistry dubboObservationRegistry = + new DubboObservationRegistry(applicationModel, configOptional.get()); + dubboObservationRegistry.initObservationRegistry(); + } +} diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/AggregateMetricsCollector.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/AggregateMetricsCollector.java index 25ad926a6cc..3ddfa19e897 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/AggregateMetricsCollector.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/AggregateMetricsCollector.java @@ -16,7 +16,11 @@ */ package org.apache.dubbo.metrics.collector; +import org.apache.dubbo.common.event.AbstractDubboLifecycleListener; +import org.apache.dubbo.common.event.AbstractDubboListener; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; +import org.apache.dubbo.config.InitServiceMethodEvent; import org.apache.dubbo.config.MetricsConfig; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.config.nested.AggregationConfig; @@ -25,7 +29,8 @@ 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.event.MetricsInitEvent; +import org.apache.dubbo.metrics.event.RequestMetricsEvent; import org.apache.dubbo.metrics.model.MethodMetric; import org.apache.dubbo.metrics.model.MetricsSupport; import org.apache.dubbo.metrics.model.key.MetricsKey; @@ -57,7 +62,7 @@ * Aggregation metrics collector implementation of {@link MetricsCollector}. * This collector only enabled when metrics aggregation config is enabled. */ -public class AggregateMetricsCollector implements MetricsCollector { +public class AggregateMetricsCollector implements MetricsCollector { private int bucketNum = DEFAULT_BUCKET_NUM; private int timeWindowSeconds = DEFAULT_TIME_WINDOW_SECONDS; private int qpsTimeWindowMillSeconds = DEFAULT_QPS_TIME_WINDOW_MILL_SECONDS; @@ -88,7 +93,16 @@ public AggregateMetricsCollector(ApplicationModel applicationModel) { // only registered when aggregation is enabled. Optional optional = configManager.getMetrics(); if (optional.isPresent()) { - registerListener(); + // register listener for init metrics + DubboEventBus.addListener(applicationModel, new AbstractDubboListener() { + @Override + public void onEvent(InitServiceMethodEvent event) { + MetricsInitEvent metricsInitEvent = MetricsInitEvent.toMetricsInitEvent(event); + initMetrics(metricsInitEvent); + } + }); + DubboEventBus.addListener(applicationModel, new AggregateMetricsEventListener(this)); + // init collector AggregationConfig aggregation = optional.get().getAggregation(); this.bucketNum = Optional.ofNullable(aggregation.getBucketNum()).orElse(DEFAULT_BUCKET_NUM); this.timeWindowSeconds = @@ -124,97 +138,113 @@ public boolean isCollectEnabled() { return Optional.ofNullable(collectEnabled).orElse(true); } - @Override - public boolean isSupport(MetricsEvent event) { - return event instanceof RequestEvent; - } + public static class AggregateMetricsEventListener extends AbstractDubboLifecycleListener { - @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(); + private final AggregateMetricsCollector collector; + + public AggregateMetricsEventListener(AggregateMetricsCollector collector) { + this.collector = collector; } - } - @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); + @Override + public void onEventBefore(RequestMetricsEvent event) { + if (collector.enableQps) { + MethodMetric metric = calcWindowCounter(event, MetricsKey.METRIC_REQUESTS); + TimeWindowCounter qpsCounter = collector.qps.get(metric); + if (qpsCounter == null) { + qpsCounter = ConcurrentHashMapUtils.computeIfAbsent( + collector.qps, + metric, + methodMetric -> new TimeWindowCounter( + collector.bucketNum, + TimeUnit.MILLISECONDS.toSeconds(collector.qpsTimeWindowMillSeconds))); + collector.samplesChanged.set(true); + } + qpsCounter.increment(); + } } - calcWindowCounter(event, targetKey); - onRTEvent(event); - } - @Override - public void onEventError(RequestEvent event) { - if (enableRequest) { - MetricsKey targetKey = MetricsKey.METRIC_REQUESTS_FAILED; + @Override + public void onEventFinish(RequestMetricsEvent event) { + MetricsKey targetKey = MetricsKey.METRIC_REQUESTS_SUCCEED; 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); + @Override + public void onEventError(RequestMetricsEvent event) { + if (collector.enableRequest) { + MetricsKey targetKey = MetricsKey.METRIC_REQUESTS_FAILED; + Object throwableObj = event.getAttachmentValue(METRIC_THROWABLE); + if (throwableObj != null) { + targetKey = MetricsSupport.getAggMetricsKey((Throwable) throwableObj); + } + calcWindowCounter(event, targetKey); } - 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); + if (collector.enableRt || collector.enableRtPxx) { + onRTEvent(event); } - 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); + private void onRTEvent(RequestMetricsEvent event) { + MethodMetric metric = new MethodMetric( + event.getApplicationModel(), + event.getAttachmentValue(MetricsConstants.INVOCATION), + collector.serviceLevel); + long responseTime = event.getTimePair().calc(); + if (collector.enableRt) { + TimeWindowQuantile quantile = collector.rt.get(metric); + if (quantile == null) { + quantile = ConcurrentHashMapUtils.computeIfAbsent( + collector.rt, + metric, + k -> new TimeWindowQuantile( + DEFAULT_COMPRESSION, collector.bucketNum, collector.timeWindowSeconds)); + collector.samplesChanged.set(true); + } + quantile.add(responseTime); + } - ConcurrentMap counter = - methodTypeCounter.computeIfAbsent(metricsKeyWrapper, k -> new ConcurrentHashMap<>()); + if (collector.enableRtPxx) { + TimeWindowAggregator timeWindowAggregator = collector.rtAgr.get(metric); + if (timeWindowAggregator == null) { + timeWindowAggregator = ConcurrentHashMapUtils.computeIfAbsent( + collector.rtAgr, + metric, + methodMetric -> new TimeWindowAggregator(collector.bucketNum, collector.timeWindowSeconds)); + collector.samplesChanged.set(true); + } + timeWindowAggregator.add(responseTime); + } + } - TimeWindowCounter windowCounter = counter.get(metric); - if (windowCounter == null) { - windowCounter = ConcurrentHashMapUtils.computeIfAbsent( - counter, metric, methodMetric -> new TimeWindowCounter(bucketNum, timeWindowSeconds)); - samplesChanged.set(true); + private MethodMetric calcWindowCounter(RequestMetricsEvent event, MetricsKey targetKey) { + MetricsPlaceValue placeType = MetricsPlaceValue.of( + event.getAttachmentValue(MetricsConstants.INVOCATION_SIDE), MetricsLevel.SERVICE); + MetricsKeyWrapper metricsKeyWrapper = new MetricsKeyWrapper(targetKey, placeType); + MethodMetric metric = new MethodMetric( + event.getApplicationModel(), + event.getAttachmentValue(MetricsConstants.INVOCATION), + collector.serviceLevel); + + ConcurrentMap counter = + collector.methodTypeCounter.computeIfAbsent(metricsKeyWrapper, k -> new ConcurrentHashMap<>()); + + TimeWindowCounter windowCounter = counter.get(metric); + if (windowCounter == null) { + windowCounter = ConcurrentHashMapUtils.computeIfAbsent( + counter, + metric, + methodMetric -> new TimeWindowCounter(collector.bucketNum, collector.timeWindowSeconds)); + collector.samplesChanged.set(true); + } + windowCounter.increment(); + return metric; } - windowCounter.increment(); - return metric; } @Override @@ -336,15 +366,6 @@ private void collectRT(List list) { }); } - 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); diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/DefaultMetricsCollector.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/DefaultMetricsCollector.java index 52c182f16df..f6ee9c834e8 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/DefaultMetricsCollector.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/DefaultMetricsCollector.java @@ -17,7 +17,11 @@ package org.apache.dubbo.metrics.collector; import org.apache.dubbo.common.constants.CommonConstants; +import org.apache.dubbo.common.event.AbstractDubboListener; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.common.extension.Activate; +import org.apache.dubbo.config.InitServiceMethodEvent; +import org.apache.dubbo.config.deploy.event.ApplicationStartedEvent; import org.apache.dubbo.metrics.DefaultConstants; import org.apache.dubbo.metrics.MetricsConstants; import org.apache.dubbo.metrics.collector.sample.ErrorCodeSampler; @@ -31,8 +35,6 @@ 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; @@ -55,7 +57,7 @@ * Default implementation of {@link MetricsCollector} */ @Activate -public class DefaultMetricsCollector extends CombMetricsCollector { +public class DefaultMetricsCollector extends CombMetricsCollector { private boolean collectEnabled = false; @@ -73,12 +75,10 @@ public class DefaultMetricsCollector extends CombMetricsCollector private final List samplers = new ArrayList<>(); - private final List collectors = new ArrayList<>(); - - private final AtomicBoolean initialized = new AtomicBoolean(); - private final AtomicBoolean samplesChanged = new AtomicBoolean(); + public final DefaultSubDispatcher listener; + public DefaultMetricsCollector(ApplicationModel applicationModel) { super(new BaseStatComposite(applicationModel) { @Override @@ -95,7 +95,27 @@ protected void init(RtStatComposite rtStatComposite) { MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD)); } }); - super.setEventMulticaster(new DefaultSubDispatcher(this)); + + // add listener for init + DubboEventBus.addListener(applicationModel, new AbstractDubboListener() { + @Override + public void onEvent(InitServiceMethodEvent event) { + MetricsInitEvent metricsInitEvent = MetricsInitEvent.toMetricsInitEvent(event); + initMetrics(metricsInitEvent); + } + }); + DubboEventBus.addListener(applicationModel, new AbstractDubboListener() { + @Override + public void onEvent(ApplicationStartedEvent event) { + if (isThreadpoolCollectEnabled()) { + registryDefaultSample(); + } + } + }); + // add listener for metrics + listener = new DefaultSubDispatcher(this); + DubboEventBus.addListener(applicationModel, listener); + this.samplers.add(applicationSampler); this.samplers.add(threadPoolSampler); this.samplesChanged.set(true); @@ -169,28 +189,7 @@ public List collect() { 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) { + public void initMetrics(MetricsInitEvent event) { MetricsPlaceValue dynamicPlaceType = MetricsPlaceValue.of(event.getAttachmentValue(MetricsConstants.INVOCATION_SIDE), MetricsLevel.METHOD); INIT_DEFAULT_METHOD_KEYS.stream() diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/HistogramMetricsCollector.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/HistogramMetricsCollector.java index 807e31b2515..4793c0a0792 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/HistogramMetricsCollector.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/HistogramMetricsCollector.java @@ -16,14 +16,15 @@ */ package org.apache.dubbo.metrics.collector; +import org.apache.dubbo.common.event.AbstractDubboLifecycleListener; +import org.apache.dubbo.common.event.DubboEventBus; 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.event.RequestMetricsEvent; import org.apache.dubbo.metrics.model.MethodMetric; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.model.sample.MetricSample; @@ -40,8 +41,7 @@ import static org.apache.dubbo.metrics.model.MetricsCategory.RT; -public class HistogramMetricsCollector extends AbstractMetricsListener - implements MetricsCollector { +public class HistogramMetricsCollector implements MetricsCollector { private final ConcurrentHashMap rt = new ConcurrentHashMap<>(); private HistogramMetricRegister metricRegister; @@ -60,7 +60,7 @@ public HistogramMetricsCollector(ApplicationModel applicationModel) { || config.getHistogram() == null || config.getHistogram().getEnabled() == null || Boolean.TRUE.equals(config.getHistogram().getEnabled())) { - registerListener(); + DubboEventBus.addListener(applicationModel, new HistogramMetricsEventListener(this)); HistogramConfig histogram; if (config == null || config.getHistogram() == null) { @@ -79,41 +79,45 @@ public HistogramMetricsCollector(ApplicationModel applicationModel) { } } - private void registerListener() { - applicationModel - .getBeanFactory() - .getBean(DefaultMetricsCollector.class) - .getEventMulticaster() - .addListener(this); - } - - @Override - public void onEvent(RequestEvent event) {} + public static class HistogramMetricsEventListener extends AbstractDubboLifecycleListener { - @Override - public void onEventFinish(RequestEvent event) { - onRTEvent(event); - } + private final HistogramMetricsCollector collector; - @Override - public void onEventError(RequestEvent event) { - onRTEvent(event); - } + public HistogramMetricsEventListener(HistogramMetricsCollector collector) { + this.collector = collector; + } - private void onRTEvent(RequestEvent event) { - if (metricRegister != null) { - MethodMetric metric = new MethodMetric( - applicationModel, event.getAttachmentValue(MetricsConstants.INVOCATION), serviceLevel); - long responseTime = event.getTimePair().calc(); + @Override + public void onEventFinish(RequestMetricsEvent event) { + onRTEvent(event); + } - HistogramMetricSample sample = new HistogramMetricSample( - MetricsKey.METRIC_RT_HISTOGRAM.getNameByType(metric.getSide()), - MetricsKey.METRIC_RT_HISTOGRAM.getDescription(), - metric.getTags(), - RT); + @Override + public void onEventError(RequestMetricsEvent event) { + onRTEvent(event); + } - Timer timer = ConcurrentHashMapUtils.computeIfAbsent(rt, metric, k -> metricRegister.register(sample)); - timer.record(responseTime, TimeUnit.MILLISECONDS); + private void onRTEvent(RequestMetricsEvent event) { + if (!event.isAvailable()) { + return; + } + if (collector.metricRegister != null) { + MethodMetric metric = new MethodMetric( + collector.applicationModel, + event.getAttachmentValue(MetricsConstants.INVOCATION), + collector.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( + collector.rt, metric, k -> collector.metricRegister.register(sample)); + timer.record(responseTime, TimeUnit.MILLISECONDS); + } } } diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/event/DefaultSubDispatcher.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/event/DefaultSubDispatcher.java index ca84829f9ef..e89be70aca3 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/event/DefaultSubDispatcher.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/event/DefaultSubDispatcher.java @@ -17,11 +17,11 @@ package org.apache.dubbo.metrics.event; import org.apache.dubbo.common.constants.CommonConstants; +import org.apache.dubbo.common.event.AbstractDubboLifecycleListener; 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; @@ -32,35 +32,52 @@ 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 final class DefaultSubDispatcher extends AbstractDubboLifecycleListener { - public DefaultSubDispatcher(DefaultMetricsCollector collector) { + private final TimeCounterEventMulticaster multicaster; + + private final DefaultMetricsCollector collector; + public DefaultSubDispatcher(DefaultMetricsCollector collector) { + this.collector = collector; + multicaster = new TimeCounterEventMulticaster(); CategoryOverall categoryOverall = initMethodRequest(); - super.addListener(categoryOverall.getPost().getEventFunc().apply(collector)); - super.addListener(categoryOverall.getFinish().getEventFunc().apply(collector)); - super.addListener(categoryOverall.getError().getEventFunc().apply(collector)); + multicaster.addListener(categoryOverall.getPost().getEventFunc().apply(collector)); + multicaster.addListener(categoryOverall.getFinish().getEventFunc().apply(collector)); + multicaster.addListener(categoryOverall.getError().getEventFunc().apply(collector)); + } - super.addListener(new MetricsListener() { + @Override + public void onEventBefore(RequestMetricsEvent event) { + if (!event.isAvailable()) { + return; + } + this.multicaster.publishEvent(event); + } - @Override - public boolean isSupport(MetricsEvent event) { - return event instanceof RequestEvent && ((RequestEvent) event).isRequestErrorEvent(); - } + private final MetricsPlaceValue dynamicPlaceType = + MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD); - private final MetricsPlaceValue dynamicPlaceType = - MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD); + @Override + public void onEventFinish(RequestMetricsEvent event) { + if (event.isAvailable()) { + this.multicaster.publishFinishEvent(event); + } + if (event.isRequestErrorEvent()) { + MetricsSupport.increment( + METRIC_REQUESTS_SERVICE_UNAVAILABLE_FAILED, + dynamicPlaceType, + (MethodMetricsCollector) collector, + event); + } + } - @Override - public void onEvent(RequestEvent event) { - MetricsSupport.increment( - METRIC_REQUESTS_SERVICE_UNAVAILABLE_FAILED, - dynamicPlaceType, - (MethodMetricsCollector) collector, - event); - } - }); + @Override + public void onEventError(RequestMetricsEvent event) { + if (!event.isAvailable()) { + return; + } + this.multicaster.publishErrorEvent(event); } private CategoryOverall initMethodRequest() { diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/MetricsInitEvent.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/event/MetricsInitEvent.java similarity index 82% rename from dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/MetricsInitEvent.java rename to dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/event/MetricsInitEvent.java index 864cc3c1740..d898cbe53cc 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/MetricsInitEvent.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/event/MetricsInitEvent.java @@ -16,6 +16,8 @@ */ package org.apache.dubbo.metrics.event; +import org.apache.dubbo.common.utils.TimePair; +import org.apache.dubbo.config.InitServiceMethodEvent; import org.apache.dubbo.metrics.MetricsConstants; import org.apache.dubbo.metrics.model.MethodMetric; import org.apache.dubbo.metrics.model.MetricsSupport; @@ -32,11 +34,14 @@ public class MetricsInitEvent extends TimeCounterEvent { private static final TypeWrapper METRIC_EVENT = new TypeWrapper(MetricsLevel.SERVICE, METRIC_REQUESTS); public MetricsInitEvent(ApplicationModel source, TypeWrapper typeWrapper) { - super(source, typeWrapper); + super(source, typeWrapper, TimePair.start()); } - public static MetricsInitEvent toMetricsInitEvent( - ApplicationModel applicationModel, Invocation invocation, boolean serviceLevel) { + public static MetricsInitEvent toMetricsInitEvent(InitServiceMethodEvent event) { + ApplicationModel applicationModel = event.getApplicationModel(); + Invocation invocation = event.getInvocation(); + boolean serviceLevel = MethodMetric.isServiceLevel(event.getApplicationModel()); + MethodMetric methodMetric = new MethodMetric(applicationModel, invocation, serviceLevel); MetricsInitEvent initEvent = new MetricsInitEvent(applicationModel, METRIC_EVENT); initEvent.putAttachment(MetricsConstants.INVOCATION, invocation); diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/event/RequestEvent.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/event/RequestMetricsEvent.java similarity index 80% rename from dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/event/RequestEvent.java rename to dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/event/RequestMetricsEvent.java index 732aab1dce4..c0645765aeb 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/event/RequestEvent.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/event/RequestMetricsEvent.java @@ -17,6 +17,8 @@ package org.apache.dubbo.metrics.event; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; +import org.apache.dubbo.common.event.CustomAfterPost; +import org.apache.dubbo.common.utils.TimePair; import org.apache.dubbo.metrics.MetricsConstants; import org.apache.dubbo.metrics.collector.DefaultMetricsCollector; import org.apache.dubbo.metrics.exception.MetricsNeverHappenException; @@ -38,19 +40,18 @@ /** * Request related events */ -public class RequestEvent extends TimeCounterEvent { +public class RequestMetricsEvent extends TimeCounterEvent implements CustomAfterPost { 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( + public RequestMetricsEvent( ApplicationModel applicationModel, String appName, - MetricsDispatcher metricsDispatcher, DefaultMetricsCollector collector, TypeWrapper TYPE_WRAPPER) { - super(applicationModel, appName, metricsDispatcher, TYPE_WRAPPER); + super(applicationModel, appName, TYPE_WRAPPER, TimePair.start()); if (collector == null) { ScopeBeanFactory beanFactory = applicationModel.getBeanFactory(); if (!beanFactory.isDestroyed()) { @@ -60,22 +61,21 @@ public RequestEvent( super.setAvailable(collector != null && collector.isCollectEnabled()); } - public static RequestEvent toRequestEvent( + public static RequestMetricsEvent 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; + RequestMetricsEvent requestMetricsEvent = + new RequestMetricsEvent(applicationModel, appName, collector, REQUEST_EVENT); + requestMetricsEvent.putAttachment(MetricsConstants.INVOCATION, invocation); + requestMetricsEvent.putAttachment(MetricsConstants.METHOD_METRICS, methodMetric); + requestMetricsEvent.putAttachment(ATTACHMENT_KEY_SERVICE, MetricsSupport.getInterfaceName(invocation)); + requestMetricsEvent.putAttachment(MetricsConstants.INVOCATION_SIDE, side); + return requestMetricsEvent; } @Override @@ -93,15 +93,14 @@ public void customAfterPost(Object postResult) { /** * Acts on MetricsClusterFilter to monitor exceptions that occur before request execution */ - public static RequestEvent toRequestErrorEvent( + public static RequestMetricsEvent 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); + RequestMetricsEvent event = new RequestMetricsEvent(applicationModel, appName, null, REQUEST_ERROR_EVENT); event.putAttachment(ATTACHMENT_KEY_SERVICE, MetricsSupport.getInterfaceName(invocation)); event.putAttachment(MetricsConstants.INVOCATION_SIDE, side); event.putAttachment(MetricsConstants.INVOCATION, invocation); diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/MetricsConsumerFilter.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/filter/MetricsConsumerFilter.java similarity index 94% rename from dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/MetricsConsumerFilter.java rename to dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/filter/MetricsConsumerFilter.java index 7e3619094b4..5c21dc52342 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/MetricsConsumerFilter.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/filter/MetricsConsumerFilter.java @@ -14,10 +14,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.rpc.cluster.filter.support; +package org.apache.dubbo.metrics.filter; import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.metrics.filter.MetricsFilter; import org.apache.dubbo.rpc.BaseFilter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/filter/MetricsFilter.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/filter/MetricsFilter.java index 900dc7002b9..8f43011da4e 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/filter/MetricsFilter.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/filter/MetricsFilter.java @@ -16,13 +16,12 @@ */ package org.apache.dubbo.metrics.filter; +import org.apache.dubbo.common.event.DubboEventBus; 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.event.RequestMetricsEvent; import org.apache.dubbo.metrics.model.MethodMetric; import org.apache.dubbo.metrics.model.MetricsSupport; import org.apache.dubbo.rpc.Invocation; @@ -44,7 +43,6 @@ public class MetricsFilter implements ScopeModelAware { private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(MetricsFilter.class); private boolean rpcMetricsEnable; private String appName; - private MetricsDispatcher metricsDispatcher; private DefaultMetricsCollector defaultMetricsCollector; private boolean serviceLevel; @@ -57,7 +55,6 @@ public void setApplicationModel(ApplicationModel applicationModel) { .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); } @@ -69,15 +66,14 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept public Result invoke(Invoker invoker, Invocation invocation, boolean isProvider) throws RpcException { if (rpcMetricsEnable) { try { - RequestEvent requestEvent = RequestEvent.toRequestEvent( + RequestMetricsEvent requestEvent = RequestMetricsEvent.toRequestEvent( applicationModel, appName, - metricsDispatcher, defaultMetricsCollector, invocation, isProvider ? PROVIDER : CONSUMER, serviceLevel); - MetricsEventBus.before(requestEvent); + DubboEventBus.before(requestEvent); invocation.put(METRIC_FILTER_EVENT, requestEvent); } catch (Throwable t) { LOGGER.warn(INTERNAL_ERROR, "", "", "Error occurred when invoke.", t); @@ -94,7 +90,7 @@ public void onResponse(Result result, Invoker invoker, Invocation invocation, Object eventObj = invocation.get(METRIC_FILTER_EVENT); if (eventObj != null) { try { - MetricsEventBus.after((RequestEvent) eventObj, result); + DubboEventBus.after((RequestMetricsEvent) eventObj, result); } catch (Throwable t) { LOGGER.warn(INTERNAL_ERROR, "", "", "Error occurred when onResponse.", t); } @@ -109,9 +105,9 @@ public void onError(Throwable t, Invoker invoker, Invocation invocation, bool Object eventObj = invocation.get(METRIC_FILTER_EVENT); if (eventObj != null) { try { - RequestEvent requestEvent = (RequestEvent) eventObj; + RequestMetricsEvent requestEvent = (RequestMetricsEvent) eventObj; requestEvent.putAttachment(METRIC_THROWABLE, t); - MetricsEventBus.error(requestEvent); + DubboEventBus.error(requestEvent); } catch (Throwable throwable) { LOGGER.warn(INTERNAL_ERROR, "", "", "Error occurred when onResponse.", throwable); } diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/listener/PreDestroyApplicationInstanceEventListener.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/listener/PreDestroyApplicationInstanceEventListener.java new file mode 100644 index 00000000000..98cd8f5a01c --- /dev/null +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/listener/PreDestroyApplicationInstanceEventListener.java @@ -0,0 +1,37 @@ +/* + * 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.event.AbstractDubboListener; +import org.apache.dubbo.config.deploy.event.PreDestroyApplicationInstanceEvent; +import org.apache.dubbo.metrics.service.MetricsServiceExporter; + +public class PreDestroyApplicationInstanceEventListener + extends AbstractDubboListener { + @Override + public void onEvent(PreDestroyApplicationInstanceEvent event) { + MetricsServiceExporter metricsServiceExporter = + event.getApplicationModel().getBeanFactory().getBean(MetricsServiceExporter.class); + if (metricsServiceExporter != null) { + try { + metricsServiceExporter.unexport(); + } catch (Exception ignored) { + // ignored + } + } + } +} diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/listener/PrepareApplicationInstanceEventListener.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/listener/PrepareApplicationInstanceEventListener.java new file mode 100644 index 00000000000..e11f90cf615 --- /dev/null +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/listener/PrepareApplicationInstanceEventListener.java @@ -0,0 +1,54 @@ +/* + * 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.constants.LoggerCodeConstants; +import org.apache.dubbo.common.event.AbstractDubboListener; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; +import org.apache.dubbo.common.logger.LoggerFactory; +import org.apache.dubbo.config.MetricsConfig; +import org.apache.dubbo.config.deploy.event.PrepareApplicationInstanceEvent; +import org.apache.dubbo.metrics.service.MetricsServiceExporter; + +public class PrepareApplicationInstanceEventListener extends AbstractDubboListener { + + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(PrepareApplicationInstanceEventListener.class); + + @Override + public void onEvent(PrepareApplicationInstanceEvent event) { + MetricsServiceExporter metricsServiceExporter = + event.getApplicationModel().getBeanFactory().getBean(MetricsServiceExporter.class); + boolean exportMetrics = event.getApplicationModel() + .getApplicationConfigManager() + .getMetrics() + .map(MetricsConfig::getExportMetricsService) + .orElse(true); + if (exportMetrics && metricsServiceExporter != null) { + try { + metricsServiceExporter.export(); + } catch (Exception e) { + logger.error( + LoggerCodeConstants.COMMON_METRICS_COLLECTOR_EXCEPTION, + "", + "", + "exportMetricsService an" + " exception occurred when handle starting event", + e); + } + } + } +} diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/service/DefaultMetricsService.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/service/DefaultMetricsService.java index 2548bb81048..67110828457 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/service/DefaultMetricsService.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/service/DefaultMetricsService.java @@ -54,7 +54,7 @@ public Map> getMetricsByCategories( public Map> getMetricsByCategories( String serviceUniqueName, String methodName, Class[] parameterTypes, List categories) { Map> result = new HashMap<>(); - for (MetricsCollector collector : collectors) { + for (MetricsCollector collector : collectors) { List samples = collector.collect(); for (MetricSample sample : samples) { if (categories.contains(sample.getCategory())) { diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/service/MetricsServiceExporter.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/service/MetricsServiceExporter.java similarity index 100% rename from dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/service/MetricsServiceExporter.java rename to dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/service/MetricsServiceExporter.java diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/MetricsClusterFilter.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/MetricsClusterFilter.java index 35f9942fe4c..608b1c3d0ca 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/MetricsClusterFilter.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/MetricsClusterFilter.java @@ -16,11 +16,10 @@ */ package org.apache.dubbo.rpc.cluster.filter.support; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.metrics.collector.DefaultMetricsCollector; -import org.apache.dubbo.metrics.event.MetricsDispatcher; -import org.apache.dubbo.metrics.event.MetricsEventBus; -import org.apache.dubbo.metrics.event.RequestEvent; +import org.apache.dubbo.metrics.event.RequestMetricsEvent; import org.apache.dubbo.metrics.model.MethodMetric; import org.apache.dubbo.rpc.BaseFilter; import org.apache.dubbo.rpc.Invocation; @@ -40,7 +39,6 @@ public class MetricsClusterFilter implements ClusterFilter, BaseFilter.Listener, private ApplicationModel applicationModel; private DefaultMetricsCollector collector; private String appName; - private MetricsDispatcher metricsDispatcher; private boolean serviceLevel; @Override @@ -48,7 +46,6 @@ public void setApplicationModel(ApplicationModel applicationModel) { this.applicationModel = applicationModel; this.collector = applicationModel.getBeanFactory().getBean(DefaultMetricsCollector.class); this.appName = applicationModel.tryGetApplicationName(); - this.metricsDispatcher = applicationModel.getBeanFactory().getBean(MetricsDispatcher.class); this.serviceLevel = MethodMetric.isServiceLevel(applicationModel); } @@ -74,14 +71,8 @@ private void handleMethodException(Throwable t, Invocation invocation) { if (t instanceof RpcException) { RpcException e = (RpcException) t; if (e.isForbidden()) { - MetricsEventBus.publish(RequestEvent.toRequestErrorEvent( - applicationModel, - appName, - metricsDispatcher, - invocation, - CONSUMER_SIDE, - e.getCode(), - serviceLevel)); + DubboEventBus.publish(RequestMetricsEvent.toRequestErrorEvent( + applicationModel, appName, invocation, CONSUMER_SIDE, e.getCode(), serviceLevel)); } } } diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metrics.service.MetricsServiceExporter b/dubbo-metrics/dubbo-metrics-default/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metrics.service.MetricsServiceExporter new file mode 100644 index 00000000000..6d6fd48ad3f --- /dev/null +++ b/dubbo-metrics/dubbo-metrics-default/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metrics.service.MetricsServiceExporter @@ -0,0 +1 @@ +default=org.apache.dubbo.metrics.DefaultMetricsServiceExporter diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Filter b/dubbo-metrics/dubbo-metrics-default/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Filter index ecb9e24f278..08e822be301 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Filter +++ b/dubbo-metrics/dubbo-metrics-default/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Filter @@ -1,2 +1 @@ metrics-provider=org.apache.dubbo.metrics.filter.MetricsProviderFilter -monitor=org.apache.dubbo.monitor.support.MonitorFilter diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.filter.ClusterFilter b/dubbo-metrics/dubbo-metrics-default/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.filter.ClusterFilter index 3d5a3f49370..ca716e377a7 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.filter.ClusterFilter +++ b/dubbo-metrics/dubbo-metrics-default/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.filter.ClusterFilter @@ -1,2 +1,2 @@ metricsClusterFilter=org.apache.dubbo.rpc.cluster.filter.support.MetricsClusterFilter -monitor=org.apache.dubbo.monitor.support.MonitorClusterFilter +metricsConsumerFilter=org.apache.dubbo.metrics.filter.MetricsConsumerFilter diff --git a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/DefaultMetricsServiceTest.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/DefaultMetricsServiceTest.java index c61fd486209..cb8fe656416 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/DefaultMetricsServiceTest.java +++ b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/DefaultMetricsServiceTest.java @@ -17,6 +17,8 @@ package org.apache.dubbo.metrics; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; +import org.apache.dubbo.common.event.DefaultDubboEventMulticaster; +import org.apache.dubbo.common.event.DubboLifecycleEventMulticaster; import org.apache.dubbo.metrics.collector.MetricsCollector; import org.apache.dubbo.metrics.model.MetricsCategory; import org.apache.dubbo.metrics.model.sample.GaugeMetricSample; @@ -52,6 +54,7 @@ public void setUp() { when(applicationModel.getBeanFactory()).thenReturn(beanFactory); when(beanFactory.getBeansOfType(MetricsCollector.class)) .thenReturn(Collections.singletonList(metricsCollector)); + when(beanFactory.getBean(DubboLifecycleEventMulticaster.class)).thenReturn(new DefaultDubboEventMulticaster()); defaultMetricsService = new DefaultMetricsService(applicationModel); } diff --git a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/AggregateMetricsCollectorTest.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/AggregateMetricsCollectorTest.java index ef049eb49c6..c6fbfc0c517 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/AggregateMetricsCollectorTest.java +++ b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/AggregateMetricsCollectorTest.java @@ -19,8 +19,13 @@ 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.event.DefaultDubboEventMulticaster; +import org.apache.dubbo.common.event.DubboEventBus; +import org.apache.dubbo.common.event.DubboLifecycleEventMulticaster; +import org.apache.dubbo.common.event.DubboListener; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.ReflectionUtils; +import org.apache.dubbo.common.utils.TimePair; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.MetricsConfig; import org.apache.dubbo.config.context.ConfigManager; @@ -28,14 +33,10 @@ 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.event.RequestMetricsEvent; 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; @@ -82,7 +83,6 @@ class AggregateMetricsCollectorTest { private String version; private RpcInvocation invocation; private String side; - private MetricsDispatcher metricsDispatcher; private AggregateMetricsCollector collector; private MetricsFilter metricsFilter; @@ -111,7 +111,6 @@ public void setup() { 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); @@ -139,26 +138,25 @@ public void setup() { @Test void testListener() { - AggregateMetricsCollector metricsCollector = new AggregateMetricsCollector(applicationModel); - RequestEvent event = RequestEvent.toRequestEvent( + AggregateMetricsCollector.AggregateMetricsEventListener metricscollector = + new AggregateMetricsCollector.AggregateMetricsEventListener(collector); + RequestMetricsEvent event = RequestMetricsEvent.toRequestEvent( applicationModel, null, null, - null, invocation, MetricsSupport.getSide(invocation), MethodMetric.isServiceLevel(applicationModel)); - RequestEvent beforeEvent = RequestEvent.toRequestErrorEvent( + RequestMetricsEvent beforeEvent = RequestMetricsEvent.toRequestErrorEvent( applicationModel, null, - null, invocation, MetricsSupport.getSide(invocation), RpcException.FORBIDDEN_EXCEPTION, MethodMetric.isServiceLevel(applicationModel)); - Assertions.assertTrue(metricsCollector.isSupport(event)); - Assertions.assertTrue(metricsCollector.isSupport(beforeEvent)); + Assertions.assertTrue(metricscollector.support(event.getClass())); + Assertions.assertTrue(metricscollector.support(beforeEvent.getClass())); } @AfterEach @@ -206,6 +204,7 @@ void testRequestsMetrics() { @Test public void testQPS() { ApplicationModel applicationModel = mock(ApplicationModel.class); + ConfigManager configManager = mock(ConfigManager.class); MetricsConfig metricsConfig = mock(MetricsConfig.class); ScopeBeanFactory beanFactory = mock(ScopeBeanFactory.class); @@ -213,6 +212,7 @@ public void testQPS() { when(applicationModel.getApplicationConfigManager()).thenReturn(configManager); when(applicationModel.getBeanFactory()).thenReturn(beanFactory); + when(beanFactory.getBean(DubboLifecycleEventMulticaster.class)).thenReturn(new DefaultDubboEventMulticaster()); DefaultMetricsCollector defaultMetricsCollector = new DefaultMetricsCollector(applicationModel); when(beanFactory.getBean(DefaultMetricsCollector.class)).thenReturn(defaultMetricsCollector); when(configManager.getMetrics()).thenReturn(Optional.of(metricsConfig)); @@ -250,7 +250,6 @@ public void testQPS() { @Test public void testRtAggregation() { - metricsDispatcher.addListener(collector); ConfigManager configManager = applicationModel.getApplicationConfigManager(); MetricsConfig config = configManager.getMetrics().orElse(null); AggregationConfig aggregationConfig = new AggregationConfig(); @@ -263,21 +262,20 @@ public void testRtAggregation() { rtList.add(30L); for (Long requestTime : rtList) { - RequestEvent requestEvent = RequestEvent.toRequestEvent( + RequestMetricsEvent requestMetricsEvent = RequestMetricsEvent.toRequestEvent( applicationModel, null, null, - null, invocation, MetricsSupport.getSide(invocation), MethodMetric.isServiceLevel(applicationModel)); - TestRequestEvent testRequestEvent = - new TestRequestEvent(requestEvent.getSource(), requestEvent.getTypeWrapper()); + TestRequestMetricsEvent testRequestEvent = + new TestRequestMetricsEvent(requestMetricsEvent.getSource(), requestMetricsEvent.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); + DubboEventBus.post(testRequestEvent, () -> null); } List samples = collector.collect(); @@ -299,8 +297,6 @@ public void testRtAggregation() { @Test void testP95AndP99() throws InterruptedException { - - metricsDispatcher.addListener(collector); ConfigManager configManager = applicationModel.getApplicationConfigManager(); MetricsConfig config = configManager.getMetrics().orElse(null); AggregationConfig aggregationConfig = new AggregationConfig(); @@ -321,21 +317,20 @@ void testP95AndP99() throws InterruptedException { double manualP99 = requestTimes.get((int) Math.round(p99Index)); for (Long requestTime : requestTimes) { - RequestEvent requestEvent = RequestEvent.toRequestEvent( + RequestMetricsEvent requestMetricsEvent = RequestMetricsEvent.toRequestEvent( applicationModel, null, null, - null, invocation, MetricsSupport.getSide(invocation), MethodMetric.isServiceLevel(applicationModel)); - TestRequestEvent testRequestEvent = - new TestRequestEvent(requestEvent.getSource(), requestEvent.getTypeWrapper()); + TestRequestMetricsEvent testRequestEvent = + new TestRequestMetricsEvent(requestMetricsEvent.getSource(), requestMetricsEvent.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); + DubboEventBus.post(testRequestEvent, () -> null); } Thread.sleep(4000L); @@ -367,17 +362,17 @@ void testP95AndP99() throws InterruptedException { @Test void testGenericCache() { - List> classGenerics = - ReflectionUtils.getClassGenerics(AggregateMetricsCollector.class, MetricsListener.class); + List> classGenerics = ReflectionUtils.getClassGenerics( + AggregateMetricsCollector.AggregateMetricsEventListener.class, DubboListener.class); Assertions.assertTrue(CollectionUtils.isNotEmpty(classGenerics)); - Assertions.assertEquals(RequestEvent.class, classGenerics.get(0)); + Assertions.assertEquals(RequestMetricsEvent.class, classGenerics.get(0)); } - public static class TestRequestEvent extends RequestEvent { + public static class TestRequestMetricsEvent extends RequestMetricsEvent { private long rt; - public TestRequestEvent(ApplicationModel applicationModel, TypeWrapper typeWrapper) { - super(applicationModel, null, null, null, typeWrapper); + public TestRequestMetricsEvent(ApplicationModel applicationModel, TypeWrapper typeWrapper) { + super(applicationModel, null, null, typeWrapper); } public void setRt(long rt) { diff --git a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/CollectorInitTest.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/CollectorInitTest.java new file mode 100644 index 00000000000..9bc416dd6be --- /dev/null +++ b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/CollectorInitTest.java @@ -0,0 +1,48 @@ +/* + * 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.config.ApplicationConfig; +import org.apache.dubbo.rpc.model.ApplicationModel; +import org.apache.dubbo.rpc.model.FrameworkModel; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; + +public class CollectorInitTest { + + private ApplicationModel applicationModel; + + DefaultMetricsCollector defaultCollector; + + @BeforeEach + public void setUp() { + FrameworkModel frameworkModel = FrameworkModel.defaultModel(); + applicationModel = frameworkModel.newApplication(); + ApplicationConfig config = new ApplicationConfig(); + config.setName("MockMetrics"); + + applicationModel.getApplicationConfigManager().setApplication(config); + defaultCollector = applicationModel.getBeanFactory().getBean(DefaultMetricsCollector.class); + defaultCollector.setCollectEnabled(true); + } + + @AfterEach + public void teardown() { + applicationModel.destroy(); + } +} diff --git a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/DefaultCollectorTest.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/DefaultCollectorTest.java index 9105d1b518a..74c8502012f 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/DefaultCollectorTest.java +++ b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/DefaultCollectorTest.java @@ -22,8 +22,7 @@ import org.apache.dubbo.common.logger.LoggerFactory; 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.event.RequestMetricsEvent; import org.apache.dubbo.metrics.filter.MetricsFilter; import org.apache.dubbo.metrics.model.MethodMetric; import org.apache.dubbo.metrics.model.MetricsSupport; @@ -75,9 +74,6 @@ class DefaultCollectorTest { private RpcInvocation invocation; private String side; - MetricsDispatcher metricsDispatcher; - DefaultMetricsCollector defaultCollector; - MetricsFilter metricsFilter; @BeforeEach @@ -88,9 +84,6 @@ public void setup() { 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"; @@ -113,25 +106,23 @@ public void setup() { @Test void testListener() { DefaultMetricsCollector metricsCollector = new DefaultMetricsCollector(applicationModel); - RequestEvent event = RequestEvent.toRequestEvent( + RequestMetricsEvent event = RequestMetricsEvent.toRequestEvent( applicationModel, null, null, - null, invocation, MetricsSupport.getSide(invocation), MethodMetric.isServiceLevel(applicationModel)); - RequestEvent beforeEvent = RequestEvent.toRequestErrorEvent( + RequestMetricsEvent beforeEvent = RequestMetricsEvent.toRequestErrorEvent( applicationModel, null, - null, invocation, MetricsSupport.getSide(invocation), RpcException.FORBIDDEN_EXCEPTION, MethodMetric.isServiceLevel(applicationModel)); - Assertions.assertTrue(metricsCollector.isSupport(event)); - Assertions.assertTrue(metricsCollector.isSupport(beforeEvent)); + Assertions.assertTrue(metricsCollector.listener.support(event.getClass())); + Assertions.assertTrue(metricsCollector.listener.support(beforeEvent.getClass())); } @AfterEach @@ -145,7 +136,6 @@ public void teardown() { @Test void testRequestEventNoRt() { - applicationModel.getBeanFactory().getOrRegisterBean(MetricsDispatcher.class); DefaultMetricsCollector collector = applicationModel.getBeanFactory().getOrRegisterBean(DefaultMetricsCollector.class); collector.setCollectEnabled(true); @@ -164,7 +154,7 @@ void testRequestEventNoRt() { Result result = AsyncRpcResult.newDefaultAsyncResult(mockRpcResult, invocation); metricsFilter.onResponse(result, new TestMetricsInvoker(side), invocation); - RequestEvent eventObj = (RequestEvent) invocation.get(METRIC_FILTER_EVENT); + RequestMetricsEvent eventObj = (RequestMetricsEvent) invocation.get(METRIC_FILTER_EVENT); long c1 = eventObj.getTimePair().calc(); // push finish rt +1 @@ -216,7 +206,7 @@ void testRequestEventNoRt() { } metricsFilter.onError( new RpcException(RpcException.TIMEOUT_EXCEPTION, "timeout"), new TestMetricsInvoker(side), invocation); - eventObj = (RequestEvent) invocation.get(METRIC_FILTER_EVENT); + eventObj = (RequestMetricsEvent) invocation.get(METRIC_FILTER_EVENT); long c2 = eventObj.getTimePair().calc(); metricSamples = collector.collect(); diff --git a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/InitServiceMetricsTest.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/InitServiceMetricsTest.java index f036eb7dfa2..b9dcb8c52d7 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/InitServiceMetricsTest.java +++ b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/InitServiceMetricsTest.java @@ -17,13 +17,12 @@ package org.apache.dubbo.metrics.collector; import org.apache.dubbo.common.constants.CommonConstants; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.config.ApplicationConfig; +import org.apache.dubbo.config.InitServiceMethodEvent; 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; @@ -82,7 +81,7 @@ public void setup() { applicationModel.getApplicationConfigManager().setMetrics(metricsConfig); applicationModel.getApplicationConfigManager().setApplication(config); - defaultCollector = applicationModel.getBeanFactory().getBean(DefaultMetricsCollector.class); + defaultCollector = new DefaultMetricsCollector(applicationModel); defaultCollector.setCollectEnabled(true); aggregateMetricsCollector = @@ -101,8 +100,7 @@ public void setup() { RpcInvocation invocation = new RpcInvocation( serviceKey, null, methodName, interfaceName, protocolServiceKey, null, null, null, null, null, null); - MetricsEventBus.publish(MetricsInitEvent.toMetricsInitEvent( - applicationModel, invocation, MethodMetric.isServiceLevel(applicationModel))); + DubboEventBus.publish(new InitServiceMethodEvent(applicationModel, invocation)); } @AfterEach diff --git a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/sample/ThreadPoolMetricsSamplerTest.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/sample/ThreadPoolMetricsSamplerTest.java index d33fcc1070b..c36fc8bbdae 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/sample/ThreadPoolMetricsSamplerTest.java +++ b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/sample/ThreadPoolMetricsSamplerTest.java @@ -17,6 +17,9 @@ package org.apache.dubbo.metrics.collector.sample; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; +import org.apache.dubbo.common.event.DefaultDubboEventMulticaster; +import org.apache.dubbo.common.event.DubboLifecycleEventMulticaster; +import org.apache.dubbo.common.event.DubboMulticasterScopeModelInitializer; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.store.DataStore; import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository; @@ -49,6 +52,8 @@ public class ThreadPoolMetricsSamplerTest { ThreadPoolMetricsSampler sampler; + private DubboMulticasterScopeModelInitializer multicasterRegistry = new DubboMulticasterScopeModelInitializer(); + @BeforeEach void setUp() { DefaultMetricsCollector collector = new DefaultMetricsCollector(applicationModel); @@ -136,13 +141,15 @@ void testSample() { public void setUp2() { MockitoAnnotations.openMocks(this); + when(applicationModel.getBeanFactory()).thenReturn(scopeBeanFactory); + when(scopeBeanFactory.getBean(DubboLifecycleEventMulticaster.class)) + .thenReturn(new DefaultDubboEventMulticaster()); + 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); } diff --git a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/filter/MetricsFilterTest.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/filter/MetricsFilterTest.java index b668c770245..28909aa961b 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/filter/MetricsFilterTest.java +++ b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/filter/MetricsFilterTest.java @@ -18,11 +18,11 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; +import org.apache.dubbo.common.event.DubboEventBus; 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.event.RequestMetricsEvent; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper; import org.apache.dubbo.metrics.model.key.MetricsLevel; @@ -104,7 +104,7 @@ public void teardown() { @Test void testCollectDisabled() { given(invoker.invoke(invocation)).willReturn(new AppResponse("success")); - + initParam(); filter.invoke(invoker, invocation); Map metricsMap = getMetricsMap(); metricsMap.remove(MetricsKey.APPLICATION_METRIC_INFO.getName()); @@ -406,7 +406,7 @@ void testThrowable() { result.setException(new RuntimeException("failed")); Object eventObj = invocation.get(METRIC_FILTER_EVENT); if (eventObj != null) { - Assertions.assertDoesNotThrow(() -> MetricsEventBus.after((RequestEvent) eventObj, result)); + Assertions.assertDoesNotThrow(() -> DubboEventBus.after((RequestMetricsEvent) eventObj, result)); } } } diff --git a/dubbo-metrics/dubbo-metrics-metadata/pom.xml b/dubbo-metrics/dubbo-metrics-metadata/pom.xml index 1de43cac944..373586537fd 100644 --- a/dubbo-metrics/dubbo-metrics-metadata/pom.xml +++ b/dubbo-metrics/dubbo-metrics-metadata/pom.xml @@ -36,6 +36,11 @@ dubbo-metrics-api ${project.parent.version} + + org.apache.dubbo + dubbo-registry-api + ${project.parent.version} + org.apache.logging.log4j log4j-slf4j-impl diff --git a/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/collector/MetadataMetricsCollector.java b/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/collector/MetadataMetricsCollector.java index 82dcc7cd97d..d71a2792b66 100644 --- a/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/collector/MetadataMetricsCollector.java +++ b/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/collector/MetadataMetricsCollector.java @@ -16,6 +16,7 @@ */ package org.apache.dubbo.metrics.metadata.collector; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.metrics.collector.CombMetricsCollector; @@ -25,7 +26,6 @@ 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; @@ -43,7 +43,7 @@ * Registry implementation of {@link MetricsCollector} */ @Activate -public class MetadataMetricsCollector extends CombMetricsCollector { +public class MetadataMetricsCollector extends CombMetricsCollector { private Boolean collectEnabled = null; private final ApplicationModel applicationModel; @@ -68,8 +68,9 @@ protected void init(RtStatComposite rtStatComposite) { rtStatComposite.init(OP_TYPE_PUSH, OP_TYPE_SUBSCRIBE, OP_TYPE_STORE_PROVIDER_INTERFACE); } }); - super.setEventMulticaster(new MetadataSubDispatcher(this)); this.applicationModel = applicationModel; + + DubboEventBus.addListener(applicationModel, new MetadataSubDispatcher(this)); } public void setCollectEnabled(Boolean collectEnabled) { diff --git a/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataEvent.java b/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataMetricsEvent.java similarity index 57% rename from dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataEvent.java rename to dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataMetricsEvent.java index a14c6690526..b896619552e 100644 --- a/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataEvent.java +++ b/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataMetricsEvent.java @@ -17,6 +17,11 @@ package org.apache.dubbo.metrics.metadata.event; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; +import org.apache.dubbo.common.utils.TimePair; +import org.apache.dubbo.metadata.event.MetadataEvent; +import org.apache.dubbo.metadata.event.MetadataPushEvent; +import org.apache.dubbo.metadata.event.MetadataServiceSubscribeEvent; +import org.apache.dubbo.metadata.event.MetadataSubscribeEvent; import org.apache.dubbo.metrics.event.TimeCounterEvent; import org.apache.dubbo.metrics.metadata.collector.MetadataMetricsCollector; import org.apache.dubbo.metrics.model.key.MetricsLevel; @@ -37,9 +42,9 @@ /** * Registry related events */ -public class MetadataEvent extends TimeCounterEvent { - public MetadataEvent(ApplicationModel applicationModel, TypeWrapper typeWrapper) { - super(applicationModel, typeWrapper); +public class MetadataMetricsEvent extends TimeCounterEvent { + public MetadataMetricsEvent(ApplicationModel applicationModel, TypeWrapper typeWrapper, TimePair timePair) { + super(applicationModel, typeWrapper, timePair); ScopeBeanFactory beanFactory = applicationModel.getBeanFactory(); MetadataMetricsCollector collector; if (!beanFactory.isDestroyed()) { @@ -48,35 +53,56 @@ public MetadataEvent(ApplicationModel applicationModel, TypeWrapper typeWrapper) } } - public static MetadataEvent toPushEvent(ApplicationModel applicationModel) { - return new MetadataEvent( + public static MetadataMetricsEvent toPushEvent(ApplicationModel applicationModel, TimePair timePair) { + return new MetadataMetricsEvent( applicationModel, new TypeWrapper( MetricsLevel.APP, METADATA_PUSH_METRIC_NUM, METADATA_PUSH_METRIC_NUM_SUCCEED, - METADATA_PUSH_METRIC_NUM_FAILED)); + METADATA_PUSH_METRIC_NUM_FAILED), + timePair); } - public static MetadataEvent toSubscribeEvent(ApplicationModel applicationModel) { - return new MetadataEvent( + public static MetadataMetricsEvent toSubscribeEvent(ApplicationModel applicationModel, TimePair timePair) { + return new MetadataMetricsEvent( applicationModel, new TypeWrapper( MetricsLevel.APP, METADATA_SUBSCRIBE_METRIC_NUM, METADATA_SUBSCRIBE_METRIC_NUM_SUCCEED, - METADATA_SUBSCRIBE_METRIC_NUM_FAILED)); + METADATA_SUBSCRIBE_METRIC_NUM_FAILED), + timePair); } - public static MetadataEvent toServiceSubscribeEvent(ApplicationModel applicationModel, String serviceKey) { - MetadataEvent metadataEvent = new MetadataEvent( + public static MetadataMetricsEvent toServiceSubscribeEvent( + ApplicationModel applicationModel, String serviceKey, TimePair timePair) { + MetadataMetricsEvent metadataMetricsEvent = new MetadataMetricsEvent( applicationModel, new TypeWrapper( MetricsLevel.APP, STORE_PROVIDER_METADATA, STORE_PROVIDER_METADATA_SUCCEED, - STORE_PROVIDER_METADATA_FAILED)); - metadataEvent.putAttachment(ATTACHMENT_KEY_SERVICE, serviceKey); - return metadataEvent; + STORE_PROVIDER_METADATA_FAILED), + timePair); + metadataMetricsEvent.putAttachment(ATTACHMENT_KEY_SERVICE, serviceKey); + return metadataMetricsEvent; + } + + public static MetadataMetricsEvent convertEvent(MetadataEvent event) { + MetadataMetricsEvent metadataMetricsEvent; + if (event instanceof MetadataPushEvent) { + metadataMetricsEvent = MetadataMetricsEvent.toPushEvent(event.getApplicationModel(), event.getTimePair()); + } else if (event instanceof MetadataSubscribeEvent) { + metadataMetricsEvent = + MetadataMetricsEvent.toSubscribeEvent(event.getApplicationModel(), event.getTimePair()); + } else if (event instanceof MetadataServiceSubscribeEvent) { + MetadataServiceSubscribeEvent serviceEvent = (MetadataServiceSubscribeEvent) event; + metadataMetricsEvent = MetadataMetricsEvent.toServiceSubscribeEvent( + event.getApplicationModel(), serviceEvent.getServiceKey(), event.getTimePair()); + } else { + return null; + } + return metadataMetricsEvent; } } diff --git a/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataSubDispatcher.java b/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataSubDispatcher.java index bc7ec7fa0f1..93ab8d1615c 100644 --- a/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataSubDispatcher.java +++ b/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataSubDispatcher.java @@ -16,7 +16,11 @@ */ package org.apache.dubbo.metrics.metadata.event; -import org.apache.dubbo.metrics.event.SimpleMetricsEventMulticaster; +import org.apache.dubbo.common.event.AbstractDubboLifecycleListener; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; +import org.apache.dubbo.common.logger.LoggerFactory; +import org.apache.dubbo.metadata.event.MetadataEvent; +import org.apache.dubbo.metrics.event.TimeCounterEventMulticaster; import org.apache.dubbo.metrics.listener.MetricsApplicationListener; import org.apache.dubbo.metrics.listener.MetricsServiceListener; import org.apache.dubbo.metrics.metadata.collector.MetadataMetricsCollector; @@ -31,21 +35,57 @@ 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 final class MetadataSubDispatcher extends AbstractDubboLifecycleListener { - public MetadataSubDispatcher(MetadataMetricsCollector collector) { + ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MetadataSubDispatcher.class); + + private final TimeCounterEventMulticaster multicaster; + public MetadataSubDispatcher(MetadataMetricsCollector collector) { + this.multicaster = new TimeCounterEventMulticaster(); CategorySet.ALL.forEach(categorySet -> { - super.addListener(categorySet.getPost().getEventFunc().apply(collector)); + this.multicaster.addListener(categorySet.getPost().getEventFunc().apply(collector)); if (categorySet.getFinish() != null) { - super.addListener(categorySet.getFinish().getEventFunc().apply(collector)); + this.multicaster.addListener( + categorySet.getFinish().getEventFunc().apply(collector)); } if (categorySet.getError() != null) { - super.addListener(categorySet.getError().getEventFunc().apply(collector)); + this.multicaster.addListener( + categorySet.getError().getEventFunc().apply(collector)); } }); } + @Override + public void onEventBefore(MetadataEvent event) { + MetadataMetricsEvent metadataMetricsEvent = MetadataMetricsEvent.convertEvent(event); + if (metadataMetricsEvent == null) { + logger.debug("Unsupported event type: {}", event.getClass().getName()); + return; + } + this.multicaster.publishEvent(metadataMetricsEvent); + } + + @Override + public void onEventFinish(MetadataEvent event) { + MetadataMetricsEvent metadataMetricsEvent = MetadataMetricsEvent.convertEvent(event); + if (metadataMetricsEvent == null) { + logger.debug("Unsupported event type: {}", event.getClass().getName()); + return; + } + this.multicaster.publishFinishEvent(metadataMetricsEvent); + } + + @Override + public void onEventError(MetadataEvent event) { + MetadataMetricsEvent metadataMetricsEvent = MetadataMetricsEvent.convertEvent(event); + if (metadataMetricsEvent == null) { + logger.debug("Unsupported event type: {}", event.getClass().getName()); + return; + } + this.multicaster.publishErrorEvent(metadataMetricsEvent); + } + /** * A closer aggregation of MetricsCat, a summary collection of certain types of events */ diff --git a/dubbo-metrics/dubbo-metrics-metadata/src/test/java/org/apache/dubbo/metrics/metadata/MetadataMetricsCollectorTest.java b/dubbo-metrics/dubbo-metrics-metadata/src/test/java/org/apache/dubbo/metrics/metadata/MetadataMetricsCollectorTest.java index 8ee31a9e795..b870316a294 100644 --- a/dubbo-metrics/dubbo-metrics-metadata/src/test/java/org/apache/dubbo/metrics/metadata/MetadataMetricsCollectorTest.java +++ b/dubbo-metrics/dubbo-metrics-metadata/src/test/java/org/apache/dubbo/metrics/metadata/MetadataMetricsCollectorTest.java @@ -16,13 +16,15 @@ */ package org.apache.dubbo.metrics.metadata; +import org.apache.dubbo.common.event.DubboEvent; +import org.apache.dubbo.common.event.DubboEventBus; +import org.apache.dubbo.common.utils.TimePair; import org.apache.dubbo.config.ApplicationConfig; -import org.apache.dubbo.metrics.event.MetricsDispatcher; -import org.apache.dubbo.metrics.event.MetricsEvent; -import org.apache.dubbo.metrics.event.MetricsEventBus; +import org.apache.dubbo.metadata.event.MetadataPushEvent; +import org.apache.dubbo.metadata.event.MetadataServiceSubscribeEvent; +import org.apache.dubbo.metadata.event.MetadataSubscribeEvent; import org.apache.dubbo.metrics.metadata.collector.MetadataMetricsCollector; -import org.apache.dubbo.metrics.metadata.event.MetadataEvent; -import org.apache.dubbo.metrics.model.TimePair; +import org.apache.dubbo.metrics.metadata.event.MetadataSubDispatcher; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper; import org.apache.dubbo.metrics.model.sample.GaugeMetricSample; @@ -60,7 +62,6 @@ public void setup() { config.setName("MockMetrics"); applicationModel.getApplicationConfigManager().setApplication(config); - applicationModel.getBeanFactory().getOrRegisterBean(MetricsDispatcher.class); collector = applicationModel.getBeanFactory().getOrRegisterBean(MetadataMetricsCollector.class); collector.setCollectEnabled(true); @@ -68,10 +69,17 @@ public void setup() { @Test void testListener() { - MetadataEvent event = MetadataEvent.toPushEvent(applicationModel); - MetricsEvent otherEvent = new MetricsEvent(applicationModel, null, null, null) {}; - Assertions.assertTrue(collector.isSupport(event)); - Assertions.assertFalse(collector.isSupport(otherEvent)); + MetadataSubDispatcher dispatcher = new MetadataSubDispatcher(collector); + MetadataPushEvent event = new MetadataPushEvent(applicationModel); + MetadataSubscribeEvent subscribeEvent = new MetadataSubscribeEvent(applicationModel); + MetadataServiceSubscribeEvent serviceSubscribeEvent = + new MetadataServiceSubscribeEvent(applicationModel, "serviceKey"); + + DubboEvent otherEvent = new DubboEvent(applicationModel); + Assertions.assertTrue(dispatcher.support(event.getClass())); + Assertions.assertTrue(dispatcher.support(subscribeEvent.getClass())); + Assertions.assertTrue(dispatcher.support(serviceSubscribeEvent.getClass())); + Assertions.assertFalse(dispatcher.support(otherEvent.getClass())); } @AfterEach @@ -81,10 +89,8 @@ public void teardown() { @Test void testPushMetrics() { - // MetadataMetricsCollector collector = getCollector(); - - MetadataEvent pushEvent = MetadataEvent.toPushEvent(applicationModel); - MetricsEventBus.post(pushEvent, () -> { + MetadataPushEvent pushEvent = new MetadataPushEvent(applicationModel); + DubboEventBus.post(pushEvent, () -> { List metricSamples = collector.collect(); // push success +1 @@ -102,9 +108,9 @@ void testPushMetrics() { Assertions.assertEquals(MetadataMetricsConstants.APP_LEVEL_KEYS.size() + 5, metricSamples.size()); long c1 = pushEvent.getTimePair().calc(); - pushEvent = MetadataEvent.toPushEvent(applicationModel); + pushEvent = new MetadataPushEvent(applicationModel); TimePair lastTimePair = pushEvent.getTimePair(); - MetricsEventBus.post( + DubboEventBus.post( pushEvent, () -> { try { @@ -152,8 +158,8 @@ void testPushMetrics() { void testSubscribeMetrics() { // MetadataMetricsCollector collector = getCollector(); - MetadataEvent subscribeEvent = MetadataEvent.toSubscribeEvent(applicationModel); - MetricsEventBus.post(subscribeEvent, () -> { + MetadataSubscribeEvent subscribeEvent = new MetadataSubscribeEvent(applicationModel); + DubboEventBus.post(subscribeEvent, () -> { List metricSamples = collector.collect(); // push success +1 @@ -171,9 +177,9 @@ void testSubscribeMetrics() { // App(6) + rt(5) = 7 Assertions.assertEquals(MetadataMetricsConstants.APP_LEVEL_KEYS.size() + 5, metricSamples.size()); - subscribeEvent = MetadataEvent.toSubscribeEvent(applicationModel); + subscribeEvent = new MetadataSubscribeEvent(applicationModel); TimePair lastTimePair = subscribeEvent.getTimePair(); - MetricsEventBus.post( + DubboEventBus.post( subscribeEvent, () -> { try { @@ -223,8 +229,8 @@ void testStoreProviderMetadataMetrics() { // MetadataMetricsCollector collector = getCollector(); String serviceKey = "store.provider.test"; - MetadataEvent metadataEvent = MetadataEvent.toServiceSubscribeEvent(applicationModel, serviceKey); - MetricsEventBus.post(metadataEvent, () -> { + MetadataServiceSubscribeEvent metadataEvent = new MetadataServiceSubscribeEvent(applicationModel, serviceKey); + DubboEventBus.post(metadataEvent, () -> { List metricSamples = collector.collect(); // App(6) + service success(1) @@ -242,9 +248,9 @@ void testStoreProviderMetadataMetrics() { Assertions.assertEquals(MetadataMetricsConstants.APP_LEVEL_KEYS.size() + 2 + 5, metricSamples.size()); long c1 = metadataEvent.getTimePair().calc(); - metadataEvent = MetadataEvent.toServiceSubscribeEvent(applicationModel, serviceKey); + metadataEvent = new MetadataServiceSubscribeEvent(applicationModel, serviceKey); TimePair lastTimePair = metadataEvent.getTimePair(); - MetricsEventBus.post( + DubboEventBus.post( metadataEvent, () -> { try { @@ -299,11 +305,11 @@ void testStoreProviderMetadataMetrics() { void testMetadataPushNum() { for (int i = 0; i < 10; i++) { - MetadataEvent event = MetadataEvent.toPushEvent(applicationModel); + MetadataPushEvent event = new MetadataPushEvent(applicationModel); if (i % 2 == 0) { - MetricsEventBus.post(event, () -> true, r -> r); + DubboEventBus.post(event, () -> true, r -> r); } else { - MetricsEventBus.post(event, () -> false, r -> r); + DubboEventBus.post(event, () -> false, r -> r); } } @@ -322,11 +328,11 @@ void testMetadataPushNum() { void testSubscribeSum() { for (int i = 0; i < 10; i++) { - MetadataEvent event = MetadataEvent.toSubscribeEvent(applicationModel); + MetadataSubscribeEvent event = new MetadataSubscribeEvent(applicationModel); if (i % 2 == 0) { - MetricsEventBus.post(event, () -> true, r -> r); + DubboEventBus.post(event, () -> true, r -> r); } else { - MetricsEventBus.post(event, () -> false, r -> r); + DubboEventBus.post(event, () -> false, r -> r); } } diff --git a/dubbo-metrics/dubbo-metrics-event/pom.xml b/dubbo-metrics/dubbo-metrics-monitor/pom.xml similarity index 77% rename from dubbo-metrics/dubbo-metrics-event/pom.xml rename to dubbo-metrics/dubbo-metrics-monitor/pom.xml index abdaf820d5f..a761fccaf4a 100644 --- a/dubbo-metrics/dubbo-metrics-event/pom.xml +++ b/dubbo-metrics/dubbo-metrics-monitor/pom.xml @@ -23,20 +23,28 @@ ${revision} ../pom.xml - dubbo-metrics-event + dubbo-metrics-monitor jar ${project.artifactId} - The metrics event-related api module of dubbo project + The metrics module of dubbo project false - org.apache.dubbo dubbo-common ${project.parent.version} + + org.apache.dubbo + dubbo-cluster + ${project.parent.version} + + + org.apache.dubbo + dubbo-rpc-api + ${project.parent.version} + - diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/monitor/Constants.java b/dubbo-metrics/dubbo-metrics-monitor/src/main/java/org/apache/dubbo/monitor/Constants.java similarity index 100% rename from dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/monitor/Constants.java rename to dubbo-metrics/dubbo-metrics-monitor/src/main/java/org/apache/dubbo/monitor/Constants.java diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/monitor/Monitor.java b/dubbo-metrics/dubbo-metrics-monitor/src/main/java/org/apache/dubbo/monitor/Monitor.java similarity index 100% rename from dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/monitor/Monitor.java rename to dubbo-metrics/dubbo-metrics-monitor/src/main/java/org/apache/dubbo/monitor/Monitor.java diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/monitor/MonitorFactory.java b/dubbo-metrics/dubbo-metrics-monitor/src/main/java/org/apache/dubbo/monitor/MonitorFactory.java similarity index 100% rename from dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/monitor/MonitorFactory.java rename to dubbo-metrics/dubbo-metrics-monitor/src/main/java/org/apache/dubbo/monitor/MonitorFactory.java diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/monitor/MonitorService.java b/dubbo-metrics/dubbo-metrics-monitor/src/main/java/org/apache/dubbo/monitor/MonitorService.java similarity index 100% rename from dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/monitor/MonitorService.java rename to dubbo-metrics/dubbo-metrics-monitor/src/main/java/org/apache/dubbo/monitor/MonitorService.java diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/monitor/support/MonitorClusterFilter.java b/dubbo-metrics/dubbo-metrics-monitor/src/main/java/org/apache/dubbo/monitor/support/MonitorClusterFilter.java similarity index 100% rename from dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/monitor/support/MonitorClusterFilter.java rename to dubbo-metrics/dubbo-metrics-monitor/src/main/java/org/apache/dubbo/monitor/support/MonitorClusterFilter.java diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java b/dubbo-metrics/dubbo-metrics-monitor/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java similarity index 100% rename from dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java rename to dubbo-metrics/dubbo-metrics-monitor/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java diff --git a/dubbo-metrics/dubbo-metrics-monitor/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Filter b/dubbo-metrics/dubbo-metrics-monitor/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Filter new file mode 100644 index 00000000000..fbeff59d1df --- /dev/null +++ b/dubbo-metrics/dubbo-metrics-monitor/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Filter @@ -0,0 +1 @@ +monitor=org.apache.dubbo.monitor.support.MonitorFilter diff --git a/dubbo-metrics/dubbo-metrics-monitor/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.filter.ClusterFilter b/dubbo-metrics/dubbo-metrics-monitor/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.filter.ClusterFilter new file mode 100644 index 00000000000..454d429d93f --- /dev/null +++ b/dubbo-metrics/dubbo-metrics-monitor/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.filter.ClusterFilter @@ -0,0 +1 @@ +monitor=org.apache.dubbo.monitor.support.MonitorClusterFilter diff --git a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/monitor/support/MonitorFilterTest.java b/dubbo-metrics/dubbo-metrics-monitor/src/test/java/org/apache/dubbo/monitor/support/MonitorFilterTest.java similarity index 100% rename from dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/monitor/support/MonitorFilterTest.java rename to dubbo-metrics/dubbo-metrics-monitor/src/test/java/org/apache/dubbo/monitor/support/MonitorFilterTest.java diff --git a/dubbo-metrics/dubbo-metrics-netty/pom.xml b/dubbo-metrics/dubbo-metrics-netty/pom.xml index e3d1c50f97a..f66c44d15df 100644 --- a/dubbo-metrics/dubbo-metrics-netty/pom.xml +++ b/dubbo-metrics/dubbo-metrics-netty/pom.xml @@ -36,5 +36,10 @@ dubbo-metrics-api ${project.parent.version} + + org.apache.dubbo + dubbo-remoting-netty4 + ${project.parent.version} + diff --git a/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/collector/NettyMetricsCollector.java b/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/collector/NettyMetricsCollector.java index 0a30e63fe42..7e18c5f4d5e 100644 --- a/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/collector/NettyMetricsCollector.java +++ b/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/collector/NettyMetricsCollector.java @@ -16,6 +16,7 @@ */ package org.apache.dubbo.metrics.registry.collector; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.metrics.collector.CombMetricsCollector; @@ -27,7 +28,6 @@ import org.apache.dubbo.metrics.model.MetricsCategory; import org.apache.dubbo.metrics.model.sample.MetricSample; import org.apache.dubbo.metrics.registry.NettyMetricsConstants; -import org.apache.dubbo.metrics.registry.event.NettyEvent; import org.apache.dubbo.metrics.registry.event.NettySubDispatcher; import org.apache.dubbo.rpc.model.ApplicationModel; @@ -39,7 +39,7 @@ * Netty implementation of {@link MetricsCollector} */ @Activate -public class NettyMetricsCollector extends CombMetricsCollector { +public class NettyMetricsCollector extends CombMetricsCollector { private Boolean collectEnabled = null; private final ApplicationModel applicationModel; @@ -62,8 +62,8 @@ protected void init(RtStatComposite rtStatComposite) { super.init(rtStatComposite); } }); - super.setEventMulticaster(new NettySubDispatcher(this)); this.applicationModel = applicationModel; + DubboEventBus.addListener(applicationModel, new NettySubDispatcher(this)); } public void setCollectEnabled(Boolean collectEnabled) { diff --git a/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/event/NettyEvent.java b/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/event/NettyEvent.java deleted file mode 100644 index 9af8812b82a..00000000000 --- a/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/event/NettyEvent.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * 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.MetricsLevel; -import org.apache.dubbo.metrics.model.key.TypeWrapper; -import org.apache.dubbo.metrics.registry.collector.NettyMetricsCollector; -import org.apache.dubbo.rpc.model.ApplicationModel; - -import static org.apache.dubbo.metrics.MetricsConstants.NETTY_METRICS_MAP; - -/** - * Netty related events - */ -public class NettyEvent extends TimeCounterEvent { - public NettyEvent(ApplicationModel applicationModel, TypeWrapper typeWrapper) { - super(applicationModel, typeWrapper); - ScopeBeanFactory beanFactory = getSource().getBeanFactory(); - NettyMetricsCollector collector; - if (!beanFactory.isDestroyed()) { - collector = beanFactory.getBean(NettyMetricsCollector.class); - super.setAvailable(collector != null && collector.isCollectEnabled()); - } - } - - public static NettyEvent toNettyEvent(ApplicationModel applicationModel) { - return new NettyEvent(applicationModel, new TypeWrapper(MetricsLevel.APP, null, null, null)) { - @Override - public void customAfterPost(Object postResult) { - super.putAttachment(NETTY_METRICS_MAP, postResult); - } - }; - } -} diff --git a/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/event/NettyMetricsEvent.java b/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/event/NettyMetricsEvent.java new file mode 100644 index 00000000000..0d96030b200 --- /dev/null +++ b/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/event/NettyMetricsEvent.java @@ -0,0 +1,68 @@ +/* + * 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.common.utils.TimePair; +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.collector.NettyMetricsCollector; +import org.apache.dubbo.remoting.transport.netty4.NettyEvent; +import org.apache.dubbo.rpc.model.ApplicationModel; + +import java.util.HashMap; +import java.util.Map; + +import static org.apache.dubbo.metrics.MetricsConstants.NETTY_METRICS_MAP; + +/** + * Netty related events + */ +public class NettyMetricsEvent extends TimeCounterEvent { + public NettyMetricsEvent(ApplicationModel applicationModel, TypeWrapper typeWrapper) { + super(applicationModel, typeWrapper, TimePair.start()); + ScopeBeanFactory beanFactory = getSource().getBeanFactory(); + NettyMetricsCollector collector; + if (!beanFactory.isDestroyed()) { + collector = beanFactory.getBean(NettyMetricsCollector.class); + super.setAvailable(collector != null && collector.isCollectEnabled()); + } + } + + public static NettyMetricsEvent toNettyEvent(NettyEvent event) { + ApplicationModel applicationModel = event.getApplicationModel(); + NettyEvent.MetricsData postResult = event.getPostResult(); + + NettyMetricsEvent nettyMetricsEvent = + new NettyMetricsEvent(applicationModel, new TypeWrapper(MetricsLevel.APP, null, null, null)); + + Map dataMap = new HashMap<>(); + dataMap.put(MetricsKey.NETTY_ALLOCATOR_HEAP_MEMORY_USED.getName(), postResult.usedHeapMemory); + dataMap.put(MetricsKey.NETTY_ALLOCATOR_DIRECT_MEMORY_USED.getName(), postResult.usedDirectMemory); + dataMap.put(MetricsKey.NETTY_ALLOCATOR_HEAP_ARENAS_NUM.getName(), postResult.numHeapArenas); + dataMap.put(MetricsKey.NETTY_ALLOCATOR_DIRECT_ARENAS_NUM.getName(), postResult.numDirectArenas); + dataMap.put(MetricsKey.NETTY_ALLOCATOR_NORMAL_CACHE_SIZE.getName(), postResult.normalCacheSize); + dataMap.put(MetricsKey.NETTY_ALLOCATOR_SMALL_CACHE_SIZE.getName(), postResult.smallCacheSize); + dataMap.put(MetricsKey.NETTY_ALLOCATOR_THREAD_LOCAL_CACHES_NUM.getName(), postResult.numThreadLocalCaches); + dataMap.put(MetricsKey.NETTY_ALLOCATOR_CHUNK_SIZE.getName(), postResult.chunkSize); + nettyMetricsEvent.putAttachment(NETTY_METRICS_MAP, dataMap); + + return nettyMetricsEvent; + } +} diff --git a/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/event/NettySubDispatcher.java b/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/event/NettySubDispatcher.java index 5dfacadf299..90c08ab29ac 100644 --- a/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/event/NettySubDispatcher.java +++ b/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/event/NettySubDispatcher.java @@ -16,24 +16,28 @@ */ package org.apache.dubbo.metrics.registry.event; -import org.apache.dubbo.metrics.event.MetricsEvent; -import org.apache.dubbo.metrics.event.SimpleMetricsEventMulticaster; +import org.apache.dubbo.common.event.AbstractDubboLifecycleListener; import org.apache.dubbo.metrics.event.TimeCounterEvent; +import org.apache.dubbo.metrics.event.TimeCounterEventMulticaster; import org.apache.dubbo.metrics.listener.AbstractMetricsKeyListener; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.registry.collector.NettyMetricsCollector; +import org.apache.dubbo.remoting.transport.netty4.NettyEvent; import java.util.Collections; import java.util.Map; import static org.apache.dubbo.metrics.MetricsConstants.NETTY_METRICS_MAP; -public final class NettySubDispatcher extends SimpleMetricsEventMulticaster { +public final class NettySubDispatcher extends AbstractDubboLifecycleListener { + + private final TimeCounterEventMulticaster multicaster; public NettySubDispatcher(NettyMetricsCollector collector) { - super.addListener(new AbstractMetricsKeyListener(null) { + this.multicaster = new TimeCounterEventMulticaster(); + this.multicaster.addListener(new AbstractMetricsKeyListener(null) { @Override - public boolean isSupport(MetricsEvent event) { + public boolean support(TimeCounterEvent event) { return true; } @@ -47,4 +51,22 @@ public void onEventFinish(TimeCounterEvent event) { } }); } + + @Override + public void onEventBefore(NettyEvent event) { + NettyMetricsEvent nettyMetricsEvent = NettyMetricsEvent.toNettyEvent(event); + multicaster.publishEvent(nettyMetricsEvent); + } + + @Override + public void onEventFinish(NettyEvent event) { + NettyMetricsEvent nettyMetricsEvent = NettyMetricsEvent.toNettyEvent(event); + multicaster.publishFinishEvent(nettyMetricsEvent); + } + + @Override + public void onEventError(NettyEvent event) { + NettyMetricsEvent nettyMetricsEvent = NettyMetricsEvent.toNettyEvent(event); + multicaster.publishErrorEvent(nettyMetricsEvent); + } } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/deploy/DefaultApplicationDeployerTest.java b/dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics/prometheus/MetricsSupportPrometheusTest.java similarity index 97% rename from dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/deploy/DefaultApplicationDeployerTest.java rename to dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics/prometheus/MetricsSupportPrometheusTest.java index 6799c116ece..ff3ae772743 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/deploy/DefaultApplicationDeployerTest.java +++ b/dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics/prometheus/MetricsSupportPrometheusTest.java @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.config.deploy; +package org.apache.dubbo.metrics.prometheus; import org.apache.dubbo.common.utils.Assert; import org.apache.dubbo.config.MetricsConfig; diff --git a/dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporterTest.java b/dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporterTest.java index e8198a3d05f..746bd472abd 100644 --- a/dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporterTest.java +++ b/dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporterTest.java @@ -59,7 +59,8 @@ public void setup() { applicationModel = ApplicationModel.defaultModel(); metricsConfig.setProtocol(PROTOCOL_PROMETHEUS); frameworkModel = FrameworkModel.defaultModel(); - frameworkModel.getBeanFactory().getOrRegisterBean(DefaultMetricsCollector.class); + DefaultMetricsCollector defaultMetricsCollector = new DefaultMetricsCollector(applicationModel); + frameworkModel.getBeanFactory().registerBean(defaultMetricsCollector); } @AfterEach diff --git a/dubbo-metrics/dubbo-metrics-registry/pom.xml b/dubbo-metrics/dubbo-metrics-registry/pom.xml index b1287adfee5..2de15833695 100644 --- a/dubbo-metrics/dubbo-metrics-registry/pom.xml +++ b/dubbo-metrics/dubbo-metrics-registry/pom.xml @@ -36,6 +36,11 @@ dubbo-metrics-api ${project.parent.version} + + org.apache.dubbo + dubbo-registry-api + ${project.parent.version} + org.apache.logging.log4j log4j-slf4j-impl diff --git a/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/collector/RegistryMetricsCollector.java b/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/collector/RegistryMetricsCollector.java index c10bca41ddd..91561f7cc54 100644 --- a/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/collector/RegistryMetricsCollector.java +++ b/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/collector/RegistryMetricsCollector.java @@ -17,6 +17,7 @@ package org.apache.dubbo.metrics.registry.collector; import org.apache.dubbo.common.constants.RegistryConstants; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.metrics.collector.CombMetricsCollector; @@ -32,7 +33,6 @@ 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; @@ -52,12 +52,14 @@ * Registry implementation of {@link MetricsCollector} */ @Activate -public class RegistryMetricsCollector extends CombMetricsCollector { +public class RegistryMetricsCollector extends CombMetricsCollector { private Boolean collectEnabled = null; private final ApplicationModel applicationModel; private final RegistryStatComposite internalStat; + public final RegistrySubDispatcher dispatcher; + public RegistryMetricsCollector(ApplicationModel applicationModel) { super(new BaseStatComposite(applicationModel) { @Override @@ -83,7 +85,8 @@ protected void init(RtStatComposite rtStatComposite) { OP_TYPE_SUBSCRIBE_SERVICE); } }); - super.setEventMulticaster(new RegistrySubDispatcher(this)); + dispatcher = new RegistrySubDispatcher(this); + DubboEventBus.addListener(applicationModel, dispatcher); internalStat = new RegistryStatComposite(applicationModel); this.applicationModel = applicationModel; } diff --git a/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistryEvent.java b/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistryEvent.java deleted file mode 100644 index d122ecabc38..00000000000 --- a/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistryEvent.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * 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 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 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 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> summaryMap, - Map attachments) { - RegistryEvent registryEvent = new RegistryEvent(applicationModel, DIRECTORY_EVENT); - registryEvent.putAttachment(ATTACHMENT_DIRECTORY_MAP, summaryMap); - registryEvent.putAttachments(attachments); - return registryEvent; - } -} diff --git a/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistryMetricsEvent.java b/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistryMetricsEvent.java new file mode 100644 index 00000000000..22ed82ecb3c --- /dev/null +++ b/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistryMetricsEvent.java @@ -0,0 +1,198 @@ +/* + * 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.common.event.DubboEvent; +import org.apache.dubbo.common.utils.TimePair; +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.registry.client.event.RegistryNotifyEvent; +import org.apache.dubbo.registry.client.event.RegistryRegisterEvent; +import org.apache.dubbo.registry.client.event.RegistryRsEvent; +import org.apache.dubbo.registry.client.event.RegistrySsEvent; +import org.apache.dubbo.registry.client.event.RegistrySubscribeEvent; +import org.apache.dubbo.rpc.cluster.directory.DirectoryRefreshEvent; +import org.apache.dubbo.rpc.model.ApplicationModel; + +import java.util.Collections; +import java.util.HashMap; +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 RegistryMetricsEvent extends TimeCounterEvent { + public RegistryMetricsEvent(ApplicationModel applicationModel, TypeWrapper typeWrapper, TimePair timePair) { + super(applicationModel, typeWrapper, timePair); + 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 RegistryMetricsEvent toRegisterEvent( + ApplicationModel applicationModel, List registryClusterNames, TimePair timePair) { + RegistryMetricsEvent registryMetricsEvent = + new RegistryMetricsEvent(applicationModel, REGISTER_EVENT, timePair); + registryMetricsEvent.putAttachment(RegistryMetricsConstants.ATTACHMENT_REGISTRY_KEY, registryClusterNames); + return registryMetricsEvent; + } + + 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 RegistryMetricsEvent toSubscribeEvent( + ApplicationModel applicationModel, String registryClusterName, TimePair timePair) { + RegistryMetricsEvent ddEvent = new RegistryMetricsEvent(applicationModel, SUBSCRIBE_EVENT, timePair); + 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 RegistryMetricsEvent toNotifyEvent( + ApplicationModel applicationModel, Map postResult, TimePair timePair) { + RegistryMetricsEvent registryMetricsEvent = new RegistryMetricsEvent(applicationModel, NOTIFY_EVENT, timePair); + registryMetricsEvent.putAttachment(ATTACHMENT_KEY_LAST_NUM_MAP, postResult); + return registryMetricsEvent; + } + + 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 RegistryMetricsEvent toRsEvent( + ApplicationModel applicationModel, + String serviceKey, + int size, + List serviceDiscoveryNames, + TimePair timePair) { + RegistryMetricsEvent ddEvent = new RegistryMetricsEvent(applicationModel, RS_EVENT, timePair); + 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 RegistryMetricsEvent toSsEvent( + ApplicationModel applicationModel, + String serviceKey, + List serviceDiscoveryNames, + TimePair timePair) { + RegistryMetricsEvent ddEvent = new RegistryMetricsEvent(applicationModel, SS_EVENT, timePair); + 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 RegistryMetricsEvent refreshDirectoryEvent( + ApplicationModel applicationModel, + DirectoryRefreshEvent.Summary summary, + Map attachments, + TimePair timePair) { + Map> summaryMap = new HashMap<>(); + summaryMap.put(MetricsKey.DIRECTORY_METRIC_NUM_VALID, summary.directoryNumValidMap); + summaryMap.put(MetricsKey.DIRECTORY_METRIC_NUM_DISABLE, summary.directoryNumDisableMap); + summaryMap.put(MetricsKey.DIRECTORY_METRIC_NUM_TO_RECONNECT, summary.directoryNumToReConnectMap); + summaryMap.put(MetricsKey.DIRECTORY_METRIC_NUM_ALL, summary.directoryNumAllMap); + + RegistryMetricsEvent registryMetricsEvent = + new RegistryMetricsEvent(applicationModel, DIRECTORY_EVENT, timePair); + registryMetricsEvent.putAttachment(ATTACHMENT_DIRECTORY_MAP, summaryMap); + registryMetricsEvent.putAttachments(attachments); + return registryMetricsEvent; + } + + public static RegistryMetricsEvent convertEvent(DubboEvent event) { + if (event instanceof RegistryRegisterEvent) { + RegistryRegisterEvent registerEvent = (RegistryRegisterEvent) event; + return RegistryMetricsEvent.toRegisterEvent( + registerEvent.getApplicationModel(), + registerEvent.getRegistryClusterNames(), + registerEvent.getTimePair()); + } else if (event instanceof RegistrySubscribeEvent) { + RegistrySubscribeEvent subscribeEvent = (RegistrySubscribeEvent) event; + return RegistryMetricsEvent.toSubscribeEvent( + subscribeEvent.getApplicationModel(), + subscribeEvent.getRegistryClusterName(), + subscribeEvent.getTimePair()); + } else if (event instanceof RegistryNotifyEvent) { + RegistryNotifyEvent notifyEvent = (RegistryNotifyEvent) event; + return RegistryMetricsEvent.toNotifyEvent( + notifyEvent.getApplicationModel(), notifyEvent.getPostResult(), notifyEvent.getTimePair()); + } else if (event instanceof RegistryRsEvent) { + RegistryRsEvent rsEvent = (RegistryRsEvent) event; + return RegistryMetricsEvent.toRsEvent( + rsEvent.getApplicationModel(), + rsEvent.getServiceKey(), + rsEvent.getSize(), + rsEvent.getRegistryClusterNames(), + rsEvent.getTimePair()); + } else if (event instanceof RegistrySsEvent) { + RegistrySsEvent ssEvent = (RegistrySsEvent) event; + return RegistryMetricsEvent.toSsEvent( + ssEvent.getApplicationModel(), + ssEvent.getServiceKey(), + ssEvent.getRegistryClusterNames(), + ssEvent.getTimePair()); + } else if (event instanceof DirectoryRefreshEvent) { + DirectoryRefreshEvent refreshEvent = (DirectoryRefreshEvent) event; + return RegistryMetricsEvent.refreshDirectoryEvent( + refreshEvent.getApplicationModel(), + refreshEvent.getSummary(), + refreshEvent.getAttachments(), + refreshEvent.getTimePair()); + } + return null; + } +} diff --git a/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistrySpecListener.java b/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistrySpecListener.java index a28ec570f18..d45bda3de49 100644 --- a/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistrySpecListener.java +++ b/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistrySpecListener.java @@ -51,12 +51,12 @@ 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) { + 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) { + public static AbstractMetricsKeyListener onFinish(MetricsKey metricsKey, CombMetricsCollector collector) { return AbstractMetricsKeyListener.onFinish(metricsKey, event -> ((RegistryMetricsCollector) collector) .incrRegisterFinishNum( metricsKey, @@ -65,7 +65,7 @@ public static AbstractMetricsKeyListener onFinish(MetricsKey metricsKey, CombMet event.getTimePair().calc())); } - public static AbstractMetricsKeyListener onError(MetricsKey metricsKey, CombMetricsCollector collector) { + public static AbstractMetricsKeyListener onError(MetricsKey metricsKey, CombMetricsCollector collector) { return AbstractMetricsKeyListener.onError(metricsKey, event -> ((RegistryMetricsCollector) collector) .incrRegisterFinishNum( metricsKey, @@ -75,7 +75,7 @@ public static AbstractMetricsKeyListener onError(MetricsKey metricsKey, CombMetr } public static AbstractMetricsKeyListener onPostOfService( - MetricsKey metricsKey, MetricsPlaceValue placeType, CombMetricsCollector collector) { + MetricsKey metricsKey, MetricsPlaceValue placeType, CombMetricsCollector collector) { return AbstractMetricsKeyListener.onEvent(metricsKey, event -> ((RegistryMetricsCollector) collector) .incrServiceRegisterNum( new MetricsKeyWrapper(metricsKey, placeType), @@ -85,7 +85,7 @@ public static AbstractMetricsKeyListener onPostOfService( } public static AbstractMetricsKeyListener onFinishOfService( - MetricsKey metricsKey, MetricsPlaceValue placeType, CombMetricsCollector collector) { + MetricsKey metricsKey, MetricsPlaceValue placeType, CombMetricsCollector collector) { return AbstractMetricsKeyListener.onFinish(metricsKey, event -> ((RegistryMetricsCollector) collector) .incrServiceRegisterFinishNum( new MetricsKeyWrapper(metricsKey, placeType), @@ -96,7 +96,7 @@ public static AbstractMetricsKeyListener onFinishOfService( } public static AbstractMetricsKeyListener onErrorOfService( - MetricsKey metricsKey, MetricsPlaceValue placeType, CombMetricsCollector collector) { + MetricsKey metricsKey, MetricsPlaceValue placeType, CombMetricsCollector collector) { return AbstractMetricsKeyListener.onError(metricsKey, event -> ((RegistryMetricsCollector) collector) .incrServiceRegisterFinishNum( new MetricsKeyWrapper(metricsKey, placeType), @@ -110,7 +110,7 @@ public static AbstractMetricsKeyListener onErrorOfService( * Every time an event is triggered, multiple serviceKey related to notify are increment */ public static AbstractMetricsKeyListener onFinishOfNotify( - MetricsKey metricsKey, MetricsPlaceValue placeType, CombMetricsCollector collector) { + MetricsKey metricsKey, MetricsPlaceValue placeType, CombMetricsCollector collector) { return AbstractMetricsKeyListener.onFinish(metricsKey, event -> { collector.addServiceRt( event.appName(), placeType.getType(), event.getTimePair().calc()); @@ -123,8 +123,7 @@ public static AbstractMetricsKeyListener onFinishOfNotify( /** * 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) { + public static AbstractMetricsKeyListener onPostOfDirectory(MetricsKey metricsKey, CombMetricsCollector collector) { return AbstractMetricsKeyListener.onEvent(metricsKey, event -> { Map> summaryMap = event.getAttachmentValue(ATTACHMENT_DIRECTORY_MAP); Map otherAttachments = new HashMap<>(); diff --git a/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistrySubDispatcher.java b/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistrySubDispatcher.java index 458ed9d7afc..00ed7e0567c 100644 --- a/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistrySubDispatcher.java +++ b/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistrySubDispatcher.java @@ -16,15 +16,23 @@ */ package org.apache.dubbo.metrics.registry.event; -import org.apache.dubbo.metrics.event.SimpleMetricsEventMulticaster; +import org.apache.dubbo.common.event.DubboEvent; +import org.apache.dubbo.common.event.DubboLifecycleListener; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; +import org.apache.dubbo.common.logger.LoggerFactory; +import org.apache.dubbo.metrics.event.TimeCounterEventMulticaster; 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 org.apache.dubbo.registry.client.event.RegistryEvent; +import org.apache.dubbo.rpc.cluster.directory.DirectoryRefreshEvent; import java.util.Arrays; import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.OP_TYPE_DIRECTORY; import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.OP_TYPE_NOTIFY; @@ -33,21 +41,70 @@ 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 final class RegistrySubDispatcher implements DubboLifecycleListener { - public RegistrySubDispatcher(RegistryMetricsCollector collector) { + ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(RegistrySubDispatcher.class); + + private final RegistryMetricsCollector collector; + + private final TimeCounterEventMulticaster multicaster; + + private final Map, Boolean> eventMatchCache = new ConcurrentHashMap<>(); + public RegistrySubDispatcher(RegistryMetricsCollector collector) { + this.multicaster = new TimeCounterEventMulticaster(); + this.collector = collector; CategorySet.ALL.forEach(categorySet -> { - super.addListener(categorySet.getPost().getEventFunc().apply(collector)); + this.multicaster.addListener(categorySet.getPost().getEventFunc().apply(collector)); if (categorySet.getFinish() != null) { - super.addListener(categorySet.getFinish().getEventFunc().apply(collector)); + this.multicaster.addListener( + categorySet.getFinish().getEventFunc().apply(collector)); } if (categorySet.getError() != null) { - super.addListener(categorySet.getError().getEventFunc().apply(collector)); + this.multicaster.addListener( + categorySet.getError().getEventFunc().apply(collector)); } }); } + @Override + public boolean support(Class eventClass) { + return eventMatchCache.computeIfAbsent( + eventClass, + clazz -> RegistryEvent.class.isAssignableFrom(eventClass) + || DirectoryRefreshEvent.class.isAssignableFrom(eventClass)); + } + + @Override + public void onEventBefore(DubboEvent event) { + RegistryMetricsEvent metricsEvent = RegistryMetricsEvent.convertEvent(event); + if (metricsEvent == null) { + logger.debug("Unsupported event type: {}", event.getClass().getName()); + return; + } + this.multicaster.publishEvent(metricsEvent); + } + + @Override + public void onEventFinish(DubboEvent event) { + RegistryMetricsEvent metricsEvent = RegistryMetricsEvent.convertEvent(event); + if (metricsEvent == null) { + logger.debug("Unsupported event type: {}", event.getClass().getName()); + return; + } + this.multicaster.publishFinishEvent(metricsEvent); + } + + @Override + public void onEventError(DubboEvent event) { + RegistryMetricsEvent metricsEvent = RegistryMetricsEvent.convertEvent(event); + if (metricsEvent == null) { + logger.debug("Unsupported event type: {}", event.getClass().getName()); + return; + } + this.multicaster.publishErrorEvent(metricsEvent); + } + /** * A closer aggregation of MetricsCat, a summary collection of certain types of events */ diff --git a/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsCollectorTest.java b/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsCollectorTest.java index 442b9a7142c..a7ddee01960 100644 --- a/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsCollectorTest.java +++ b/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsCollectorTest.java @@ -16,17 +16,19 @@ */ package org.apache.dubbo.metrics.registry.metrics.collector; +import org.apache.dubbo.common.event.DubboEventBus; +import org.apache.dubbo.common.utils.TimePair; 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.registry.client.event.RegistryNotifyEvent; +import org.apache.dubbo.registry.client.event.RegistryRegisterEvent; +import org.apache.dubbo.registry.client.event.RegistryRsEvent; +import org.apache.dubbo.registry.client.event.RegistrySsEvent; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; @@ -63,7 +65,6 @@ public void setup() { config.setName("MockMetrics"); applicationModel.getApplicationConfigManager().setApplication(config); - applicationModel.getBeanFactory().getOrRegisterBean(MetricsDispatcher.class); collector = applicationModel.getBeanFactory().getOrRegisterBean(RegistryMetricsCollector.class); collector.setCollectEnabled(true); } @@ -76,8 +77,8 @@ public void teardown() { @Test void testRegisterMetrics() { - RegistryEvent registryEvent = RegistryEvent.toRegisterEvent(applicationModel, Lists.newArrayList("reg1")); - MetricsEventBus.post(registryEvent, () -> { + RegistryRegisterEvent registryEvent = new RegistryRegisterEvent(applicationModel, Lists.newArrayList("reg1")); + DubboEventBus.post(registryEvent, () -> { List 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()); @@ -94,9 +95,9 @@ void testRegisterMetrics() { 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")); + registryEvent = new RegistryRegisterEvent(applicationModel, Lists.newArrayList("reg1")); TimePair lastTimePair = registryEvent.getTimePair(); - MetricsEventBus.post( + DubboEventBus.post( registryEvent, () -> { try { @@ -147,8 +148,8 @@ void testServicePushMetrics() { String serviceName = "demo.gameService"; List rcNames = Lists.newArrayList("demo1"); - RegistryEvent registryEvent = RegistryEvent.toRsEvent(applicationModel, serviceName, 2, rcNames); - MetricsEventBus.post(registryEvent, () -> { + RegistryRsEvent registryEvent = new RegistryRsEvent(applicationModel, serviceName, 2, rcNames); + DubboEventBus.post(registryEvent, () -> { List metricSamples = collector.collect(); // push success +1 @@ -169,9 +170,9 @@ void testServicePushMetrics() { Assertions.assertEquals(RegistryMetricsConstants.APP_LEVEL_KEYS.size() + 5 + 2, metricSamples.size()); long c1 = registryEvent.getTimePair().calc(); - registryEvent = RegistryEvent.toRsEvent(applicationModel, serviceName, 2, rcNames); + registryEvent = new RegistryRsEvent(applicationModel, serviceName, 2, rcNames); TimePair lastTimePair = registryEvent.getTimePair(); - MetricsEventBus.post( + DubboEventBus.post( registryEvent, () -> { try { @@ -222,9 +223,9 @@ void testServiceSubscribeMetrics() { String serviceName = "demo.gameService"; - RegistryEvent subscribeEvent = - RegistryEvent.toSsEvent(applicationModel, serviceName, Collections.singletonList("demo1")); - MetricsEventBus.post(subscribeEvent, () -> { + RegistrySsEvent subscribeEvent = + new RegistrySsEvent(applicationModel, serviceName, Collections.singletonList("demo1")); + DubboEventBus.post(subscribeEvent, () -> { List metricSamples = collector.collect(); Assertions.assertTrue( metricSamples.stream().allMatch(metricSample -> metricSample instanceof GaugeMetricSample)); @@ -248,9 +249,9 @@ void testServiceSubscribeMetrics() { Assertions.assertEquals(RegistryMetricsConstants.APP_LEVEL_KEYS.size() + 5 + 2, metricSamples.size()); long c1 = subscribeEvent.getTimePair().calc(); - subscribeEvent = RegistryEvent.toSsEvent(applicationModel, serviceName, Collections.singletonList("demo1")); + subscribeEvent = new RegistrySsEvent(applicationModel, serviceName, Collections.singletonList("demo1")); TimePair lastTimePair = subscribeEvent.getTimePair(); - MetricsEventBus.post( + DubboEventBus.post( subscribeEvent, () -> { try { @@ -299,7 +300,7 @@ void testServiceSubscribeMetrics() { @Test public void testNotify() { Map lastNumMap = new HashMap<>(); - MetricsEventBus.post(RegistryEvent.toNotifyEvent(applicationModel), () -> { + DubboEventBus.post(new RegistryNotifyEvent(applicationModel), () -> { try { Thread.sleep(50L); } catch (InterruptedException e) { diff --git a/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsTest.java b/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsTest.java index db06191028c..a68be08887c 100644 --- a/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsTest.java +++ b/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsTest.java @@ -16,6 +16,9 @@ */ package org.apache.dubbo.metrics.registry.metrics.collector; +import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; +import org.apache.dubbo.common.event.DefaultDubboEventMulticaster; +import org.apache.dubbo.common.event.DubboLifecycleEventMulticaster; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.MetricsConfig; import org.apache.dubbo.config.context.ConfigManager; @@ -24,7 +27,10 @@ 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.registry.client.event.RegistryEvent; +import org.apache.dubbo.registry.client.event.RegistryRegisterEvent; +import org.apache.dubbo.registry.client.event.RegistryRsEvent; +import org.apache.dubbo.registry.client.event.RegistrySubscribeEvent; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; @@ -41,6 +47,7 @@ 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.spy; import static org.mockito.Mockito.when; @@ -56,6 +63,8 @@ public class RegistryMetricsTest { @BeforeEach void setUp() { this.applicationModel = getApplicationModel(); + ScopeBeanFactory beanFactory = Mockito.mock(ScopeBeanFactory.class); + when(beanFactory.getBean(DubboLifecycleEventMulticaster.class)).thenReturn(new DefaultDubboEventMulticaster()); this.collector = getTestCollector(this.applicationModel); this.collector.setCollectEnabled(true); } @@ -263,19 +272,19 @@ GaugeMetricSample getSample(String name, List samples) { RegistryEvent applicationRegister() { RegistryEvent event = registerEvent(); - collector.onEvent(event); + collector.dispatcher.onEventBefore(event); return event; } RegistryEvent serviceRegister() { RegistryEvent event = rsEvent(); - collector.onEvent(event); + collector.dispatcher.onEventBefore(event); return event; } RegistryEvent serviceSubscribe() { RegistryEvent event = subscribeEvent(); - collector.onEvent(event); + collector.dispatcher.onEventBefore(event); return event; } @@ -284,30 +293,24 @@ boolean considerEquals(double expected, double trueValue, double allowedErrorRat } void eventSuccess(RegistryEvent event) { - collector.onEventFinish(event); + collector.dispatcher.onEventFinish(event); } void eventFailed(RegistryEvent event) { - collector.onEventError(event); + collector.dispatcher.onEventError(event); } RegistryEvent registerEvent() { - RegistryEvent event = RegistryEvent.toRegisterEvent(applicationModel, Lists.newArrayList("reg1")); - event.setAvailable(true); - return event; + return new RegistryRegisterEvent(applicationModel, Lists.newArrayList("reg1")); } RegistryEvent rsEvent() { List rcNames = Lists.newArrayList("demo1"); - RegistryEvent event = RegistryEvent.toRsEvent(applicationModel, "TestServiceInterface1", 1, rcNames); - event.setAvailable(true); - return event; + return new RegistryRsEvent(applicationModel, "TestServiceInterface1", 1, rcNames); } - RegistryEvent subscribeEvent() { - RegistryEvent event = RegistryEvent.toSubscribeEvent(applicationModel, "registryClusterName_test"); - event.setAvailable(true); - return event; + RegistrySubscribeEvent subscribeEvent() { + return new RegistrySubscribeEvent(applicationModel, "registryClusterName_test"); } ApplicationModel getApplicationModel() { diff --git a/dubbo-metrics/dubbo-tracing/pom.xml b/dubbo-metrics/dubbo-tracing/pom.xml index 2979b08cd92..917881a98a3 100644 --- a/dubbo-metrics/dubbo-tracing/pom.xml +++ b/dubbo-metrics/dubbo-tracing/pom.xml @@ -51,7 +51,7 @@ org.apache.dubbo - dubbo-metrics-default + dubbo-metrics-api ${project.parent.version} diff --git a/dubbo-metrics/pom.xml b/dubbo-metrics/pom.xml index 2c2692f3f94..c6990b624cb 100644 --- a/dubbo-metrics/pom.xml +++ b/dubbo-metrics/pom.xml @@ -28,8 +28,8 @@ ${project.artifactId} The metrics module of dubbo project + dubbo-metrics-monitor dubbo-metrics-api - dubbo-metrics-event dubbo-metrics-default dubbo-metrics-registry dubbo-metrics-metadata diff --git a/dubbo-registry/dubbo-registry-api/pom.xml b/dubbo-registry/dubbo-registry-api/pom.xml index 3d407872364..7338687ecec 100644 --- a/dubbo-registry/dubbo-registry-api/pom.xml +++ b/dubbo-registry/dubbo-registry-api/pom.xml @@ -65,31 +65,6 @@ zookeeper test - - org.apache.dubbo - dubbo-metrics-api - ${project.parent.version} - compile - - - org.apache.dubbo - dubbo-metrics-default - ${project.parent.version} - compile - - - org.apache.dubbo - dubbo-metrics-metadata - ${project.parent.version} - compile - - - - org.apache.dubbo - dubbo-metrics-registry - ${project.parent.version} - compile - org.apache.dubbo diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/AbstractServiceDiscovery.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/AbstractServiceDiscovery.java index 48775813211..4fc29e20cc9 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/AbstractServiceDiscovery.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/AbstractServiceDiscovery.java @@ -17,17 +17,18 @@ package org.apache.dubbo.registry.client; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository; import org.apache.dubbo.common.utils.ConcurrentHashSet; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.metadata.MetadataInfo; +import org.apache.dubbo.metadata.event.MetadataPushEvent; +import org.apache.dubbo.metadata.event.MetadataSubscribeEvent; import org.apache.dubbo.metadata.report.MetadataReport; import org.apache.dubbo.metadata.report.MetadataReportInstance; import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier; -import org.apache.dubbo.metrics.event.MetricsEventBus; -import org.apache.dubbo.metrics.metadata.event.MetadataEvent; import org.apache.dubbo.registry.NotifyListener; import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener; import org.apache.dubbo.registry.client.metadata.MetadataUtils; @@ -244,8 +245,8 @@ public MetadataInfo getRemoteMetadata(String revision, List ins int triedTimes = 0; while (triedTimes < 3) { - metadata = MetricsEventBus.post( - MetadataEvent.toSubscribeEvent(applicationModel), + metadata = DubboEventBus.post( + new MetadataSubscribeEvent(applicationModel), () -> MetadataUtils.getRemoteMetadata(revision, instances, metadataReport), result -> result != MetadataInfo.EMPTY); @@ -383,7 +384,7 @@ protected void reportMetadata(MetadataInfo metadataInfo) { new SubscriberMetadataIdentifier(serviceName, metadataInfo.getRevision()); if ((DEFAULT_METADATA_STORAGE_TYPE.equals(metadataType) && metadataReport.shouldReportMetadata()) || REMOTE_METADATA_STORAGE_TYPE.equals(metadataType)) { - MetricsEventBus.post(MetadataEvent.toPushEvent(applicationModel), () -> { + DubboEventBus.post(new MetadataPushEvent(applicationModel), () -> { metadataReport.publishAppMetadata(identifier, metadataInfo); return null; }); diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistry.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistry.java index b86afee87d4..9188bec4254 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistry.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistry.java @@ -18,6 +18,7 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.RegistryConstants; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; @@ -27,9 +28,8 @@ import org.apache.dubbo.metadata.MappingChangedEvent; import org.apache.dubbo.metadata.MappingListener; import org.apache.dubbo.metadata.ServiceNameMapping; -import org.apache.dubbo.metrics.event.MetricsEventBus; -import org.apache.dubbo.metrics.registry.event.RegistryEvent; import org.apache.dubbo.registry.NotifyListener; +import org.apache.dubbo.registry.client.event.RegistrySsEvent; import org.apache.dubbo.registry.client.event.ServiceInstancesChangedEvent; import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener; import org.apache.dubbo.registry.support.FailbackRegistry; @@ -366,8 +366,8 @@ protected void subscribeURLs(URL url, NotifyListener listener, Set servi String serviceDiscoveryName = url.getParameter(RegistryConstants.REGISTRY_CLUSTER_KEY, url.getProtocol()); - MetricsEventBus.post( - RegistryEvent.toSsEvent( + DubboEventBus.post( + new RegistrySsEvent( url.getApplicationModel(), serviceKey, Collections.singletonList(serviceDiscoveryName)), () -> { serviceDiscovery.addServiceInstancesChangedListener(finalServiceInstancesChangedListener); diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RegistryEvent.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RegistryEvent.java new file mode 100644 index 00000000000..e9b6b2a2d93 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RegistryEvent.java @@ -0,0 +1,35 @@ +/* + * 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.registry.client.event; + +import org.apache.dubbo.common.event.DubboEvent; +import org.apache.dubbo.common.utils.TimePair; +import org.apache.dubbo.rpc.model.ApplicationModel; + +public class RegistryEvent extends DubboEvent { + + private final TimePair timePair; + + public RegistryEvent(ApplicationModel applicationModel) { + super(applicationModel); + this.timePair = TimePair.start(); + } + + public TimePair getTimePair() { + return timePair; + } +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RegistryNotifyEvent.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RegistryNotifyEvent.java new file mode 100644 index 00000000000..1816f7c566c --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RegistryNotifyEvent.java @@ -0,0 +1,40 @@ +/* + * 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.registry.client.event; + +import org.apache.dubbo.common.event.CustomAfterPost; +import org.apache.dubbo.rpc.model.ApplicationModel; + +import java.util.Map; + +public class RegistryNotifyEvent extends RegistryEvent implements CustomAfterPost> { + + private Map postResult; + + public RegistryNotifyEvent(ApplicationModel applicationModel) { + super(applicationModel); + } + + @Override + public void customAfterPost(Map postResult) { + this.postResult = postResult; + } + + public Map getPostResult() { + return postResult; + } +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RegistryRegisterEvent.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RegistryRegisterEvent.java new file mode 100644 index 00000000000..9273e627c96 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RegistryRegisterEvent.java @@ -0,0 +1,35 @@ +/* + * 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.registry.client.event; + +import org.apache.dubbo.rpc.model.ApplicationModel; + +import java.util.List; + +public class RegistryRegisterEvent extends RegistryEvent { + + private final List registryClusterNames; + + public RegistryRegisterEvent(ApplicationModel source, List registryClusterNames) { + super(source); + this.registryClusterNames = registryClusterNames; + } + + public List getRegistryClusterNames() { + return registryClusterNames; + } +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RegistryRsEvent.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RegistryRsEvent.java new file mode 100644 index 00000000000..d44631ec82d --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RegistryRsEvent.java @@ -0,0 +1,50 @@ +/* + * 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.registry.client.event; + +import org.apache.dubbo.rpc.model.ApplicationModel; + +import java.util.List; + +public class RegistryRsEvent extends RegistryEvent { + + private final List registryClusterNames; + + private final String serviceKey; + + private final int size; + + public RegistryRsEvent( + ApplicationModel applicationModel, String serviceKey, int size, List serviceDiscoveryNames) { + super(applicationModel); + this.registryClusterNames = serviceDiscoveryNames; + this.serviceKey = serviceKey; + this.size = size; + } + + public List getRegistryClusterNames() { + return registryClusterNames; + } + + public String getServiceKey() { + return serviceKey; + } + + public int getSize() { + return size; + } +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RegistrySsEvent.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RegistrySsEvent.java new file mode 100644 index 00000000000..4b61b3c95eb --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RegistrySsEvent.java @@ -0,0 +1,49 @@ +/* + * 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.registry.client.event; + +import org.apache.dubbo.rpc.model.ApplicationModel; + +import java.util.List; + +public class RegistrySsEvent extends RegistryEvent { + + private final List registryClusterNames; + + private final String serviceKey; + + private final int size; + + public RegistrySsEvent(ApplicationModel applicationModel, String serviceKey, List serviceDiscoveryNames) { + super(applicationModel); + this.registryClusterNames = serviceDiscoveryNames; + this.serviceKey = serviceKey; + this.size = 1; + } + + public List getRegistryClusterNames() { + return registryClusterNames; + } + + public String getServiceKey() { + return serviceKey; + } + + public int getSize() { + return size; + } +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RegistrySubscribeEvent.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RegistrySubscribeEvent.java new file mode 100644 index 00000000000..b2c07c8ecd8 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RegistrySubscribeEvent.java @@ -0,0 +1,33 @@ +/* + * 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.registry.client.event; + +import org.apache.dubbo.rpc.model.ApplicationModel; + +public class RegistrySubscribeEvent extends RegistryEvent { + + private final String registryClusterName; + + public RegistrySubscribeEvent(ApplicationModel source, String registryClusterName) { + super(source); + this.registryClusterName = registryClusterName; + } + + public String getRegistryClusterName() { + return registryClusterName; + } +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/listener/ServiceInstancesChangedListener.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/listener/ServiceInstancesChangedListener.java index ba5e7ac8035..fc642d63b72 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/listener/ServiceInstancesChangedListener.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/listener/ServiceInstancesChangedListener.java @@ -20,6 +20,7 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; import org.apache.dubbo.common.constants.CommonConstants; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository; @@ -27,12 +28,11 @@ import org.apache.dubbo.common.utils.ConcurrentHashSet; import org.apache.dubbo.metadata.MetadataInfo; import org.apache.dubbo.metadata.MetadataInfo.ServiceInfo; -import org.apache.dubbo.metrics.event.MetricsEventBus; -import org.apache.dubbo.metrics.registry.event.RegistryEvent; import org.apache.dubbo.registry.NotifyListener; import org.apache.dubbo.registry.client.DefaultServiceInstance; import org.apache.dubbo.registry.client.ServiceDiscovery; import org.apache.dubbo.registry.client.ServiceInstance; +import org.apache.dubbo.registry.client.event.RegistryNotifyEvent; import org.apache.dubbo.registry.client.event.RetryServiceInstancesChangedEvent; import org.apache.dubbo.registry.client.event.ServiceInstancesChangedEvent; import org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils; @@ -452,7 +452,7 @@ protected List getAddresses(ProtocolServiceKey protocolServiceKey, URL cons */ protected void notifyAddressChanged() { - MetricsEventBus.post(RegistryEvent.toNotifyEvent(applicationModel), () -> { + DubboEventBus.post(new RegistryNotifyEvent(applicationModel), () -> { Map lastNumMap = new HashMap<>(); // 1 different services listeners.forEach((serviceKey, listenerSet) -> { diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataUtils.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataUtils.java index bc26aad59f8..1e31549afcc 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataUtils.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataUtils.java @@ -18,6 +18,7 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.RegistryConstants; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -26,13 +27,12 @@ import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.metadata.MetadataInfo; import org.apache.dubbo.metadata.MetadataService; -import org.apache.dubbo.metrics.event.MetricsEventBus; -import org.apache.dubbo.metrics.registry.event.RegistryEvent; import org.apache.dubbo.registry.client.DefaultServiceInstance; import org.apache.dubbo.registry.client.DefaultServiceInstance.Endpoint; import org.apache.dubbo.registry.client.ServiceDiscovery; import org.apache.dubbo.registry.client.ServiceInstance; import org.apache.dubbo.registry.client.ServiceInstanceCustomizer; +import org.apache.dubbo.registry.client.event.RegistryRegisterEvent; import org.apache.dubbo.registry.support.RegistryManager; import org.apache.dubbo.rpc.model.ApplicationModel; @@ -211,8 +211,8 @@ public static void registerMetadataAndInstance(ApplicationModel applicationModel LOGGER.info("Start registering instance address to registry."); List serviceDiscoveries = registryManager.getServiceDiscoveries(); for (ServiceDiscovery serviceDiscovery : serviceDiscoveries) { - MetricsEventBus.post( - RegistryEvent.toRegisterEvent( + DubboEventBus.post( + new RegistryRegisterEvent( applicationModel, Collections.singletonList(getServiceDiscoveryName(serviceDiscovery))), () -> { // register service instance diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java index 703db627a16..c9a6b3b9702 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java @@ -20,6 +20,7 @@ import org.apache.dubbo.common.URLBuilder; import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; import org.apache.dubbo.common.constants.RegistryConstants; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -31,10 +32,9 @@ import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.common.utils.UrlUtils; -import org.apache.dubbo.metrics.event.MetricsEventBus; -import org.apache.dubbo.metrics.registry.event.RegistryEvent; import org.apache.dubbo.registry.AddressListener; import org.apache.dubbo.registry.Registry; +import org.apache.dubbo.registry.client.event.RegistrySubscribeEvent; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; @@ -147,7 +147,7 @@ public void subscribe(URL url) { .getParameter( RegistryConstants.REGISTRY_CLUSTER_KEY, registry.getUrl().getParameter(PROTOCOL_KEY)); - MetricsEventBus.post(RegistryEvent.toSubscribeEvent(applicationModel, registryClusterName), () -> { + DubboEventBus.post(new RegistrySubscribeEvent(applicationModel, registryClusterName), () -> { super.subscribe(url); return null; }); diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java index e8a6a680644..6e1d814f22f 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java @@ -20,6 +20,7 @@ import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; import org.apache.dubbo.common.constants.RegistryConstants; import org.apache.dubbo.common.deploy.ApplicationDeployer; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -31,13 +32,12 @@ import org.apache.dubbo.common.utils.NamedThreadFactory; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.common.utils.UrlUtils; -import org.apache.dubbo.metrics.event.MetricsEventBus; -import org.apache.dubbo.metrics.registry.event.RegistryEvent; import org.apache.dubbo.registry.NotifyListener; import org.apache.dubbo.registry.Registry; import org.apache.dubbo.registry.RegistryFactory; import org.apache.dubbo.registry.RegistryService; import org.apache.dubbo.registry.client.ServiceDiscoveryRegistryDirectory; +import org.apache.dubbo.registry.client.event.RegistryRsEvent; import org.apache.dubbo.registry.client.migration.MigrationClusterInvoker; import org.apache.dubbo.registry.client.migration.ServiceDiscoveryMigrationInvoker; import org.apache.dubbo.registry.retry.ReExportTask; @@ -220,8 +220,8 @@ private static void register(Registry registry, URL registeredProviderUrl) { UrlUtils.isServiceDiscoveryURL(u) ? u.getParameter(REGISTRY_KEY) : u.getProtocol())) .filter(StringUtils::isNotEmpty) .orElse("unknown"); - MetricsEventBus.post( - RegistryEvent.toRsEvent( + DubboEventBus.post( + new RegistryRsEvent( registeredProviderUrl.getApplicationModel(), registeredProviderUrl.getServiceKey(), 1, diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistryTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistryTest.java index f1711eb3b34..6045f5bacd7 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistryTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistryTest.java @@ -25,6 +25,7 @@ import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; +import org.apache.dubbo.rpc.model.ScopeModelUtil; import java.util.ArrayList; import java.util.Collections; @@ -105,6 +106,7 @@ public void init() { doNothing().when(instanceListener).onEvent(any()); when(serviceDiscovery.createListener(any())).thenReturn(instanceListener); when(serviceDiscovery.getInstances(any())).thenReturn(Collections.emptyList()); + url = url.setScopeModel(ScopeModelUtil.getApplicationModel(null)); when(serviceDiscovery.getUrl()).thenReturn(url); ApplicationModel applicationModel = spy(ApplicationModel.defaultModel()); when(applicationModel.getDefaultExtension(ServiceNameMapping.class)).thenReturn(mapping); @@ -225,6 +227,7 @@ void testSubscribeURLs() { // different interface mapping to the same apps NotifyListener testServiceListener2 = mock(NotifyListener.class); URL url2 = URL.valueOf("tri://127.0.0.1/TestService2?interface=TestService2&check=false&protocol=tri"); + url2 = url2.setScopeModel(ScopeModelUtil.getApplicationModel(null)); when(testServiceListener2.getConsumerUrl()).thenReturn(url2); serviceDiscoveryRegistry.subscribeURLs(url2, testServiceListener2, multiApps); // check instance listeners not changed, methods not called @@ -265,6 +268,7 @@ void testUnsubscribe() { multiApps.add(APP_NAME2); NotifyListener testServiceListener2 = mock(NotifyListener.class); URL url2 = URL.valueOf("consumer://127.0.0.1/TestService2?interface=TestService1&check=false&protocol=tri"); + url2 = url2.setScopeModel(ScopeModelUtil.getApplicationModel(null)); when(testServiceListener2.getConsumerUrl()).thenReturn(url2); serviceDiscoveryRegistry.subscribeURLs(url, testServiceListener, multiApps); serviceDiscoveryRegistry.subscribeURLs(url2, testServiceListener2, multiApps); diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Request.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Request.java index 6a0739b78ca..aaf37f2b997 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Request.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Request.java @@ -19,6 +19,7 @@ import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.common.utils.SystemPropertyConfigUtils; +import java.io.Serializable; import java.security.SecureRandom; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicLong; @@ -29,7 +30,7 @@ /** * Request. */ -public class Request { +public class Request implements Serializable { private static final AtomicLong INVOKE_ID; diff --git a/dubbo-remoting/dubbo-remoting-netty4/pom.xml b/dubbo-remoting/dubbo-remoting-netty4/pom.xml index 06d548d1bdf..eac2bc7510f 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/pom.xml +++ b/dubbo-remoting/dubbo-remoting-netty4/pom.xml @@ -41,16 +41,6 @@ dubbo-remoting-api ${project.parent.version} - - org.apache.dubbo - dubbo-metrics-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-metrics-netty - ${project.parent.version} - io.netty netty-handler-proxy diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyEvent.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyEvent.java new file mode 100644 index 00000000000..2c6e06e15df --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyEvent.java @@ -0,0 +1,58 @@ +/* + * 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.remoting.transport.netty4; + +import org.apache.dubbo.common.event.CustomAfterPost; +import org.apache.dubbo.common.event.DubboEvent; +import org.apache.dubbo.rpc.model.ApplicationModel; + +public class NettyEvent extends DubboEvent implements CustomAfterPost { + + private MetricsData postResult; + + public NettyEvent(ApplicationModel source) { + super(source); + } + + @Override + public void customAfterPost(MetricsData postResult) { + this.postResult = postResult; + } + + public MetricsData getPostResult() { + return postResult; + } + + public static class MetricsData { + + public Long usedHeapMemory; + + public Long usedDirectMemory; + + public Long numHeapArenas; + + public Long numDirectArenas; + + public Long normalCacheSize; + + public Long smallCacheSize; + + public Long numThreadLocalCaches; + + public Long chunkSize; + } +} diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServer.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServer.java index 9f5bd0a075c..46cc3f7fe61 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServer.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServer.java @@ -18,14 +18,12 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.ConfigurationUtils; +import org.apache.dubbo.common.event.DubboEventBus; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.metrics.event.MetricsEventBus; -import org.apache.dubbo.metrics.model.key.MetricsKey; -import org.apache.dubbo.metrics.registry.event.NettyEvent; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.Constants; @@ -39,7 +37,6 @@ import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Collection; -import java.util.HashMap; import java.util.Map; import io.netty.bootstrap.ServerBootstrap; @@ -123,27 +120,19 @@ protected void doOpen() throws Throwable { // metrics if (isSupportMetrics()) { ApplicationModel applicationModel = ApplicationModel.defaultModel(); - MetricsEventBus.post(NettyEvent.toNettyEvent(applicationModel), () -> { - Map dataMap = new HashMap<>(); - dataMap.put( - MetricsKey.NETTY_ALLOCATOR_HEAP_MEMORY_USED.getName(), - PooledByteBufAllocator.DEFAULT.metric().usedHeapMemory()); - dataMap.put( - MetricsKey.NETTY_ALLOCATOR_DIRECT_MEMORY_USED.getName(), - PooledByteBufAllocator.DEFAULT.metric().usedDirectMemory()); - dataMap.put(MetricsKey.NETTY_ALLOCATOR_HEAP_ARENAS_NUM.getName(), (long) - PooledByteBufAllocator.DEFAULT.numHeapArenas()); - dataMap.put(MetricsKey.NETTY_ALLOCATOR_DIRECT_ARENAS_NUM.getName(), (long) - PooledByteBufAllocator.DEFAULT.numDirectArenas()); - dataMap.put(MetricsKey.NETTY_ALLOCATOR_NORMAL_CACHE_SIZE.getName(), (long) - PooledByteBufAllocator.DEFAULT.normalCacheSize()); - dataMap.put(MetricsKey.NETTY_ALLOCATOR_SMALL_CACHE_SIZE.getName(), (long) - PooledByteBufAllocator.DEFAULT.smallCacheSize()); - dataMap.put(MetricsKey.NETTY_ALLOCATOR_THREAD_LOCAL_CACHES_NUM.getName(), (long) - PooledByteBufAllocator.DEFAULT.numThreadLocalCaches()); - dataMap.put(MetricsKey.NETTY_ALLOCATOR_CHUNK_SIZE.getName(), (long) - PooledByteBufAllocator.DEFAULT.chunkSize()); - return dataMap; + DubboEventBus.post(new NettyEvent(applicationModel), () -> { + NettyEvent.MetricsData metricsData = new NettyEvent.MetricsData(); + metricsData.usedHeapMemory = + PooledByteBufAllocator.DEFAULT.metric().usedHeapMemory(); + metricsData.usedDirectMemory = + PooledByteBufAllocator.DEFAULT.metric().usedDirectMemory(); + metricsData.numHeapArenas = (long) PooledByteBufAllocator.DEFAULT.numHeapArenas(); + metricsData.numDirectArenas = (long) PooledByteBufAllocator.DEFAULT.numDirectArenas(); + metricsData.normalCacheSize = (long) PooledByteBufAllocator.DEFAULT.normalCacheSize(); + metricsData.smallCacheSize = (long) PooledByteBufAllocator.DEFAULT.smallCacheSize(); + metricsData.numThreadLocalCaches = (long) PooledByteBufAllocator.DEFAULT.numThreadLocalCaches(); + metricsData.chunkSize = (long) PooledByteBufAllocator.DEFAULT.chunkSize(); + return metricsData; }); } } diff --git a/dubbo-remoting/dubbo-remoting-zookeeper-curator5/pom.xml b/dubbo-remoting/dubbo-remoting-zookeeper-curator5/pom.xml index 5f57672cedb..5b8510d6f88 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper-curator5/pom.xml +++ b/dubbo-remoting/dubbo-remoting-zookeeper-curator5/pom.xml @@ -46,11 +46,6 @@ test - - org.apache.dubbo - dubbo-common - ${project.parent.version} - org.apache.curator curator-framework diff --git a/dubbo-test/dubbo-dependencies-all/pom.xml b/dubbo-test/dubbo-dependencies-all/pom.xml index b86a36b8901..d437215ecaf 100644 --- a/dubbo-test/dubbo-dependencies-all/pom.xml +++ b/dubbo-test/dubbo-dependencies-all/pom.xml @@ -158,7 +158,7 @@ org.apache.dubbo - dubbo-metrics-event + dubbo-metrics-monitor ${project.version}