From bd7fe568e4e364340d2aa5a738c742d90c68f051 Mon Sep 17 00:00:00 2001 From: liu Date: Thu, 1 Aug 2024 17:19:41 +0800 Subject: [PATCH 1/8] feat(client): Add more observability in apollo config client --- .../ctrip/framework/apollo/ConfigService.java | 24 +- .../apollo/internals/AbstractConfig.java | 2 +- .../apollo/internals/AbstractConfigFile.java | 7 +- .../internals/AbstractConfigRepository.java | 4 +- .../internals/ConfigMonitorInitializer.java | 134 ++++++++ .../internals/ConfigServiceLocator.java | 40 +-- .../apollo/internals/DefaultConfig.java | 4 +- .../internals/DefaultConfigManager.java | 25 +- .../apollo/internals/DefaultInjector.java | 12 +- .../internals/LocalFileConfigRepository.java | 4 +- .../RemoteConfigLongPollService.java | 15 +- .../internals/RemoteConfigRepository.java | 36 ++- .../apollo/internals/SimpleConfig.java | 4 +- .../apollo/internals/YamlConfigFile.java | 4 +- .../api/ApolloExceptionMonitorApi.java | 38 +++ .../api/ApolloNamespaceMonitorApi.java | 53 ++++ .../api/ApolloRunningParamsMonitorApi.java | 70 +++++ .../api/ApolloThreadPoolMonitorApi.java | 89 ++++++ .../apollo/monitor/api/ConfigMonitor.java | 33 ++ .../internal/DefaultConfigMonitor.java | 78 +++++ .../monitor/internal/MonitorConstant.java | 29 ++ .../internal/NullExceptionMonitorApi.java | 34 ++ .../internal/NullNamespaceMonitorApi.java | 89 ++++++ .../internal/NullRunningParamsMonitorApi.java | 132 ++++++++ .../internal/NullThreadPoolMonitorApi.java | 172 ++++++++++ .../collector/AbstractMetricsCollector.java | 80 +++++ .../internal/collector/MetricsCollector.java | 52 +++ .../collector/MetricsCollectorManager.java | 36 +++ .../DefaultApolloExceptionCollector.java | 83 +++++ .../DefaultApolloNamespaceCollector.java | 296 ++++++++++++++++++ .../DefaultApolloRunningParamsCollector.java | 230 ++++++++++++++ .../DefaultApolloThreadPoolCollector.java | 259 +++++++++++++++ .../DefaultMetricsCollectorManager.java | 42 +++ .../exporter/AbstractMetricsExporter.java | 112 +++++++ .../internal/exporter/MetricsExporter.java | 61 ++++ .../exporter/MetricsExporterFactory.java | 28 ++ .../DefaultMetricsExporterFactory.java | 77 +++++ .../monitor/internal/model/CounterModel.java | 100 ++++++ .../monitor/internal/model/GaugeModel.java | 98 ++++++ .../monitor/internal/model/MetricsEvent.java | 102 ++++++ .../internal/model/MetricsEventPusher.java | 45 +++ .../monitor/internal/model/MetricsModel.java | 48 +++ .../tracer/ClientMessageProducerManager.java | 43 +++ .../tracer/MessageProducerComposite.java | 84 +++++ .../tracer/MonitorMessageProducer.java | 169 ++++++++++ .../apollo/monitor/internal/util/JMXUtil.java | 58 ++++ .../monitor/internal/util/MeterType.java | 25 ++ .../ApolloApplicationContextInitializer.java | 11 +- .../framework/apollo/util/ConfigUtil.java | 134 ++++++-- .../framework/apollo/util/ExceptionUtil.java | 2 +- ...itional-spring-configuration-metadata.json | 29 ++ ...k.apollo.tracer.spi.MessageProducerManager | 1 + .../AbstractApolloMetricsCollectorTest.java | 90 ++++++ .../AbstractApolloMetricsExporterTest.java | 123 ++++++++ ...faultApolloMetricsExporterFactoryTest.java | 60 ++++ .../apollo/core/ApolloClientSystemConsts.java | 20 ++ .../framework/apollo/core/ConfigConsts.java | 1 + .../DefaultMessageProducerManager.java | 22 +- .../tracer/internals/cat/CatTransaction.java | 2 +- .../apollo/tracer/spi/MessageProducer.java | 10 +- .../apollo-plugin-client-prometheus/pom.xml | 46 +++ .../prometheus/PrometheusMetricExporter.java | 106 +++++++ ....monitor.internal.exporter.MetricsExporter | 1 + apollo-plugin/pom.xml | 1 + 64 files changed, 3824 insertions(+), 95 deletions(-) create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigMonitorInitializer.java create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloExceptionMonitorApi.java create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloNamespaceMonitorApi.java create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloRunningParamsMonitorApi.java create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloThreadPoolMonitorApi.java create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ConfigMonitor.java create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/DefaultConfigMonitor.java create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/MonitorConstant.java create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/NullExceptionMonitorApi.java create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/NullNamespaceMonitorApi.java create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/NullRunningParamsMonitorApi.java create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/NullThreadPoolMonitorApi.java create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/AbstractMetricsCollector.java create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/MetricsCollector.java create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/MetricsCollectorManager.java create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/internal/DefaultApolloExceptionCollector.java create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/internal/DefaultApolloNamespaceCollector.java create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/internal/DefaultApolloRunningParamsCollector.java create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/internal/DefaultApolloThreadPoolCollector.java create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/internal/DefaultMetricsCollectorManager.java create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractMetricsExporter.java create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/MetricsExporter.java create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/MetricsExporterFactory.java create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/internals/DefaultMetricsExporterFactory.java create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/CounterModel.java create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/GaugeModel.java create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/MetricsEvent.java create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/MetricsEventPusher.java create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/MetricsModel.java create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/ClientMessageProducerManager.java create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/MessageProducerComposite.java create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/MonitorMessageProducer.java create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/util/JMXUtil.java create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/util/MeterType.java create mode 100644 apollo-client/src/main/resources/META-INF/services/com.ctrip.framework.apollo.tracer.spi.MessageProducerManager create mode 100644 apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/collector/AbstractApolloMetricsCollectorTest.java create mode 100644 apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractApolloMetricsExporterTest.java create mode 100644 apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/DefaultApolloMetricsExporterFactoryTest.java create mode 100644 apollo-plugin/apollo-plugin-client-prometheus/pom.xml create mode 100644 apollo-plugin/apollo-plugin-client-prometheus/src/main/java/com/ctrip/framework/apollo/plugin/prometheus/PrometheusMetricExporter.java create mode 100644 apollo-plugin/apollo-plugin-client-prometheus/src/main/resources/META-INF/services/com.ctrip.framework.apollo.monitor.internal.exporter.MetricsExporter diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/ConfigService.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/ConfigService.java index 184c5ee3..02ccdc36 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/ConfigService.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/ConfigService.java @@ -20,6 +20,8 @@ import com.ctrip.framework.apollo.core.ConfigConsts; import com.ctrip.framework.apollo.core.enums.ConfigFileFormat; import com.ctrip.framework.apollo.internals.ConfigManager; +import com.ctrip.framework.apollo.internals.ConfigMonitorInitializer; +import com.ctrip.framework.apollo.monitor.api.ConfigMonitor; import com.ctrip.framework.apollo.spi.ConfigFactory; import com.ctrip.framework.apollo.spi.ConfigRegistry; @@ -30,19 +32,31 @@ */ public class ConfigService { private static final ConfigService s_instance = new ConfigService(); - + private volatile ConfigMonitor m_configMonitor; private volatile ConfigManager m_configManager; private volatile ConfigRegistry m_configRegistry; - + + private ConfigMonitor getMonitor() { + getManager(); + if (m_configMonitor == null) { + synchronized (this) { + if (m_configMonitor == null) { + m_configMonitor = ApolloInjector.getInstance(ConfigMonitor.class); + } + } + } + return m_configMonitor; + } + private ConfigManager getManager() { if (m_configManager == null) { synchronized (this) { if (m_configManager == null) { m_configManager = ApolloInjector.getInstance(ConfigManager.class); + ConfigMonitorInitializer.initialize(); } } } - return m_configManager; } @@ -81,6 +95,10 @@ public static ConfigFile getConfigFile(String namespace, ConfigFileFormat config return s_instance.getManager().getConfigFile(namespace, configFileFormat); } + public static ConfigMonitor getConfigMonitor(){ + return s_instance.getMonitor(); + } + static void setConfig(Config config) { setConfig(ConfigConsts.NAMESPACE_APPLICATION, config); } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/AbstractConfig.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/AbstractConfig.java index 7ce41dca..22ba6cde 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/AbstractConfig.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/AbstractConfig.java @@ -53,7 +53,7 @@ public abstract class AbstractConfig implements Config { private static final Logger logger = LoggerFactory.getLogger(AbstractConfig.class); - private static final ExecutorService m_executorService; + protected static final ExecutorService m_executorService; private final List m_listeners = Lists.newCopyOnWriteArrayList(); private final Map> m_interestedKeys = Maps.newConcurrentMap(); diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/AbstractConfigFile.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/AbstractConfigFile.java index 3a1c0df0..8fc574cf 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/AbstractConfigFile.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/AbstractConfigFile.java @@ -16,6 +16,9 @@ */ package com.ctrip.framework.apollo.internals; + +import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_CLIENT_CONFIGCHANGES; + import com.ctrip.framework.apollo.build.ApolloInjector; import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory; import com.ctrip.framework.apollo.enums.ConfigSourceType; @@ -43,7 +46,7 @@ */ public abstract class AbstractConfigFile implements ConfigFile, RepositoryChangeListener { private static final Logger logger = DeferredLoggerFactory.getLogger(AbstractConfigFile.class); - private static ExecutorService m_executorService; + protected static ExecutorService m_executorService; protected final ConfigRepository m_configRepository; protected final String m_namespace; protected final AtomicReference m_configProperties; @@ -112,7 +115,7 @@ public synchronized void onRepositoryChange(String namespace, Properties newProp this.fireConfigChange(new ConfigFileChangeEvent(m_namespace, oldValue, newValue, changeType)); - Tracer.logEvent("Apollo.Client.ConfigChanges", m_namespace); + Tracer.logEvent(APOLLO_CLIENT_CONFIGCHANGES, m_namespace); } @Override diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/AbstractConfigRepository.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/AbstractConfigRepository.java index b4505297..62d3e9ab 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/AbstractConfigRepository.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/AbstractConfigRepository.java @@ -16,6 +16,8 @@ */ package com.ctrip.framework.apollo.internals; +import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_CONFIG_EXCEPTION; + import com.ctrip.framework.apollo.build.ApolloInjector; import com.ctrip.framework.apollo.util.factory.PropertiesFactory; import java.util.List; @@ -41,7 +43,7 @@ protected boolean trySync() { sync(); return true; } catch (Throwable ex) { - Tracer.logEvent("ApolloConfigException", ExceptionUtil.getDetailMessage(ex)); + Tracer.logEvent(APOLLO_CONFIG_EXCEPTION, ExceptionUtil.getDetailMessage(ex)); logger .warn("Sync config failed, will retry. Repository {}, reason: {}", this.getClass(), ExceptionUtil .getDetailMessage(ex)); diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigMonitorInitializer.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigMonitorInitializer.java new file mode 100644 index 00000000..8256125b --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigMonitorInitializer.java @@ -0,0 +1,134 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.internals; + +import com.ctrip.framework.apollo.build.ApolloInjector; +import com.ctrip.framework.apollo.core.utils.ClassLoaderUtil; +import com.ctrip.framework.apollo.monitor.api.ConfigMonitor; +import com.ctrip.framework.apollo.monitor.internal.DefaultConfigMonitor; +import com.ctrip.framework.apollo.monitor.internal.collector.MetricsCollector; +import com.ctrip.framework.apollo.monitor.internal.collector.MetricsCollectorManager; +import com.ctrip.framework.apollo.monitor.internal.collector.internal.DefaultApolloExceptionCollector; +import com.ctrip.framework.apollo.monitor.internal.collector.internal.DefaultApolloNamespaceCollector; +import com.ctrip.framework.apollo.monitor.internal.collector.internal.DefaultApolloRunningParamsCollector; +import com.ctrip.framework.apollo.monitor.internal.collector.internal.DefaultApolloThreadPoolCollector; +import com.ctrip.framework.apollo.monitor.internal.collector.internal.DefaultMetricsCollectorManager; +import com.ctrip.framework.apollo.monitor.internal.exporter.MetricsExporter; +import com.ctrip.framework.apollo.monitor.internal.exporter.MetricsExporterFactory; +import com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite; +import com.ctrip.framework.apollo.monitor.internal.tracer.MonitorMessageProducer; +import com.ctrip.framework.apollo.tracer.internals.NullMessageProducer; +import com.ctrip.framework.apollo.tracer.internals.cat.CatMessageProducer; +import com.ctrip.framework.apollo.tracer.internals.cat.CatNames; +import com.ctrip.framework.apollo.tracer.spi.MessageProducer; +import com.ctrip.framework.apollo.util.ConfigUtil; +import com.ctrip.framework.foundation.internals.ServiceBootstrap; +import com.google.common.collect.Lists; +import java.util.List; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * @author Rawven + */ +public class ConfigMonitorInitializer { + + private static final Logger logger = LoggerFactory.getLogger(ConfigMonitorInitializer.class); + + private static ConfigUtil m_configUtil = ApolloInjector.getInstance(ConfigUtil.class); + private static Boolean hasInitialized = false; + + public static void initialize() { + if (m_configUtil.isClientMonitorEnabled() && !hasInitialized) { + logger.info("Initializing ConfigMonitor..."); + DefaultMetricsCollectorManager manager = initializeMetricsCollectorManager(); + List collectors = initializeCollectors(manager); + MetricsExporter metricsExporter = initializeMetricsExporter(collectors); + initializeConfigMonitor(collectors, metricsExporter); + hasInitialized = true; + logger.info("ConfigMonitor initialized successfully."); + } + } + + private static DefaultMetricsCollectorManager initializeMetricsCollectorManager() { + return (DefaultMetricsCollectorManager) ApolloInjector.getInstance( + MetricsCollectorManager.class); + } + + private static List initializeCollectors( + DefaultMetricsCollectorManager manager) { + DefaultConfigManager configManager = (DefaultConfigManager) ApolloInjector.getInstance( + ConfigManager.class); + DefaultApolloExceptionCollector exceptionCollector = new DefaultApolloExceptionCollector(); + DefaultApolloThreadPoolCollector threadPoolCollector = new DefaultApolloThreadPoolCollector( + RemoteConfigRepository.m_executorService, AbstractConfig.m_executorService, + AbstractConfigFile.m_executorService); + DefaultApolloNamespaceCollector namespaceCollector = new DefaultApolloNamespaceCollector( + configManager.m_configs, configManager.m_configLocks, configManager.m_configFiles, + configManager.m_configFileLocks); + DefaultApolloRunningParamsCollector startupCollector = new DefaultApolloRunningParamsCollector( + m_configUtil); + + List collectors = Lists.newArrayList(exceptionCollector, namespaceCollector, + threadPoolCollector, startupCollector); + manager.setCollectors(collectors); + return collectors; + } + + private static MetricsExporter initializeMetricsExporter(List collectors) { + MetricsExporterFactory reporterFactory = ApolloInjector.getInstance( + MetricsExporterFactory.class); + return reporterFactory.getMetricsReporter(collectors); + } + + private static void initializeConfigMonitor(List collectors, + MetricsExporter metricsExporter) { + DefaultConfigMonitor defaultConfigMonitor = (DefaultConfigMonitor) ApolloInjector.getInstance( + ConfigMonitor.class); + DefaultApolloExceptionCollector exceptionCollector = (DefaultApolloExceptionCollector) collectors.get( + 0); + DefaultApolloNamespaceCollector namespaceCollector = (DefaultApolloNamespaceCollector) collectors.get( + 1); + DefaultApolloThreadPoolCollector threadPoolCollector = (DefaultApolloThreadPoolCollector) collectors.get( + 2); + DefaultApolloRunningParamsCollector startupCollector = (DefaultApolloRunningParamsCollector) collectors.get( + 3); + defaultConfigMonitor.init(namespaceCollector, threadPoolCollector, exceptionCollector, + startupCollector, metricsExporter); + } + + public static MessageProducerComposite initializeMessageProducerComposite() { + + // Prioritize loading user-defined producers from SPI + List producers = ServiceBootstrap.loadAllOrdered(MessageProducer.class); + + // The producer that comes with the client + if (m_configUtil.isClientMonitorEnabled()) { + producers.add(new MonitorMessageProducer()); + } + + if (ClassLoaderUtil.isClassPresent(CatNames.CAT_CLASS)) { + producers.add(new CatMessageProducer()); + } + + // default logic + if (producers.isEmpty()) { + producers.add(new NullMessageProducer()); + } + return new MessageProducerComposite(producers); + } +} \ No newline at end of file diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigServiceLocator.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigServiceLocator.java index ce9b097c..281e440e 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigServiceLocator.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigServiceLocator.java @@ -16,40 +16,42 @@ */ package com.ctrip.framework.apollo.internals; -import com.ctrip.framework.apollo.core.ApolloClientSystemConsts; -import com.ctrip.framework.apollo.core.ServiceNameConsts; -import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory; -import com.ctrip.framework.apollo.core.utils.DeprecatedPropertyNotifyUtil; -import com.ctrip.framework.foundation.Foundation; -import com.google.common.util.concurrent.RateLimiter; -import java.lang.reflect.Type; -import java.util.List; -import java.util.Map; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; - -import org.slf4j.Logger; +import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_CONFIG_EXCEPTION; +import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_CONFIG_SERVICES; +import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_META_SERVICE; import com.ctrip.framework.apollo.build.ApolloInjector; +import com.ctrip.framework.apollo.core.ApolloClientSystemConsts; +import com.ctrip.framework.apollo.core.ServiceNameConsts; import com.ctrip.framework.apollo.core.dto.ServiceDTO; import com.ctrip.framework.apollo.core.utils.ApolloThreadFactory; +import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory; +import com.ctrip.framework.apollo.core.utils.DeprecatedPropertyNotifyUtil; import com.ctrip.framework.apollo.exceptions.ApolloConfigException; import com.ctrip.framework.apollo.tracer.Tracer; import com.ctrip.framework.apollo.tracer.spi.Transaction; import com.ctrip.framework.apollo.util.ConfigUtil; import com.ctrip.framework.apollo.util.ExceptionUtil; +import com.ctrip.framework.apollo.util.http.HttpClient; import com.ctrip.framework.apollo.util.http.HttpRequest; import com.ctrip.framework.apollo.util.http.HttpResponse; -import com.ctrip.framework.apollo.util.http.HttpClient; +import com.ctrip.framework.foundation.Foundation; import com.google.common.base.Joiner; import com.google.common.base.Strings; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.escape.Escaper; import com.google.common.net.UrlEscapers; +import com.google.common.util.concurrent.RateLimiter; import com.google.gson.reflect.TypeToken; +import java.lang.reflect.Type; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import org.slf4j.Logger; public class ConfigServiceLocator { private static final Logger logger = DeferredLoggerFactory.getLogger(ConfigServiceLocator.class); @@ -218,7 +220,7 @@ private void schedulePeriodicRefresh() { @Override public void run() { logger.debug("refresh config services"); - Tracer.logEvent("Apollo.MetaService", "periodicRefresh"); + Tracer.logEvent(APOLLO_META_SERVICE, "periodicRefresh"); tryUpdateConfigServices(); } }, m_configUtil.getRefreshInterval(), m_configUtil.getRefreshInterval(), @@ -258,7 +260,7 @@ private synchronized void updateConfigServices() { setConfigServices(services); return; } catch (Throwable ex) { - Tracer.logEvent("ApolloConfigException", ExceptionUtil.getDetailMessage(ex)); + Tracer.logEvent(APOLLO_CONFIG_EXCEPTION, ExceptionUtil.getDetailMessage(ex)); transaction.setStatus(ex); exception = ex; } finally { @@ -302,6 +304,6 @@ private void logConfigServices(List serviceDtos) { } private void logConfigService(String serviceUrl) { - Tracer.logEvent("Apollo.Config.Services", serviceUrl); + Tracer.logEvent(APOLLO_CONFIG_SERVICES, serviceUrl); } } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultConfig.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultConfig.java index 750abd0e..b859e32e 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultConfig.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultConfig.java @@ -16,6 +16,8 @@ */ package com.ctrip.framework.apollo.internals; +import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_CLIENT_CONFIGCHANGES; + import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory; import com.ctrip.framework.apollo.enums.ConfigSourceType; import com.google.common.collect.Maps; @@ -236,7 +238,7 @@ public synchronized void onRepositoryChange(String namespace, Properties newProp this.fireConfigChange(m_namespace, actualChanges); - Tracer.logEvent("Apollo.Client.ConfigChanges", m_namespace); + Tracer.logEvent(APOLLO_CLIENT_CONFIGCHANGES, m_namespace); } private void updateConfig(Properties newConfigProperties, ConfigSourceType sourceType) { diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultConfigManager.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultConfigManager.java index e897b6f7..54243307 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultConfigManager.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultConfigManager.java @@ -16,35 +16,39 @@ */ package com.ctrip.framework.apollo.internals; -import java.util.Map; +import static com.ctrip.framework.apollo.monitor.internal.collector.internal.DefaultApolloNamespaceCollector.NAMESPACE_MONITOR; +import static com.ctrip.framework.apollo.monitor.internal.collector.internal.DefaultApolloNamespaceCollector.NAMESPACE_USAGE_COUNT; import com.ctrip.framework.apollo.Config; import com.ctrip.framework.apollo.ConfigFile; import com.ctrip.framework.apollo.build.ApolloInjector; import com.ctrip.framework.apollo.core.enums.ConfigFileFormat; +import com.ctrip.framework.apollo.monitor.internal.MonitorConstant; +import com.ctrip.framework.apollo.monitor.internal.model.MetricsEvent; import com.ctrip.framework.apollo.spi.ConfigFactory; import com.ctrip.framework.apollo.spi.ConfigFactoryManager; import com.google.common.collect.Maps; +import java.util.Map; /** * @author Jason Song(song_s@ctrip.com) */ public class DefaultConfigManager implements ConfigManager { - private ConfigFactoryManager m_factoryManager; - private Map m_configs = Maps.newConcurrentMap(); - private Map m_configLocks = Maps.newConcurrentMap(); - private Map m_configFiles = Maps.newConcurrentMap(); - private Map m_configFileLocks = Maps.newConcurrentMap(); + protected Map m_configs = Maps.newConcurrentMap(); + protected Map m_configLocks = Maps.newConcurrentMap(); + protected Map m_configFiles = Maps.newConcurrentMap(); + protected Map m_configFileLocks = Maps.newConcurrentMap(); + private ConfigFactoryManager m_factoryManager; public DefaultConfigManager() { m_factoryManager = ApolloInjector.getInstance(ConfigFactoryManager.class); + } @Override public Config getConfig(String namespace) { Config config = m_configs.get(namespace); - if (config == null) { Object lock = m_configLocks.computeIfAbsent(namespace, key -> new Object()); synchronized (lock) { @@ -59,11 +63,16 @@ public Config getConfig(String namespace) { } } + MetricsEvent.builder().withName(NAMESPACE_USAGE_COUNT) + .putAttachment(MonitorConstant.NAMESPACE, namespace) + .withTag(NAMESPACE_MONITOR).push(); + return config; } @Override - public ConfigFile getConfigFile(String namespace, ConfigFileFormat configFileFormat) { + public ConfigFile getConfigFile(String namespace, + ConfigFileFormat configFileFormat) { String namespaceFileName = String.format("%s.%s", namespace, configFileFormat.getValue()); ConfigFile configFile = m_configFiles.get(namespaceFileName); diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultInjector.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultInjector.java index 707ad6c5..8aae65e0 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultInjector.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultInjector.java @@ -17,6 +17,12 @@ package com.ctrip.framework.apollo.internals; import com.ctrip.framework.apollo.exceptions.ApolloConfigException; +import com.ctrip.framework.apollo.monitor.api.ConfigMonitor; +import com.ctrip.framework.apollo.monitor.internal.DefaultConfigMonitor; +import com.ctrip.framework.apollo.monitor.internal.exporter.internals.DefaultMetricsExporterFactory; +import com.ctrip.framework.apollo.monitor.internal.collector.MetricsCollectorManager; +import com.ctrip.framework.apollo.monitor.internal.collector.internal.DefaultMetricsCollectorManager; +import com.ctrip.framework.apollo.monitor.internal.exporter.MetricsExporterFactory; import com.ctrip.framework.apollo.spi.ApolloInjectorCustomizer; import com.ctrip.framework.apollo.spi.ConfigFactory; import com.ctrip.framework.apollo.spi.ConfigFactoryManager; @@ -30,7 +36,6 @@ import com.ctrip.framework.apollo.util.factory.PropertiesFactory; import com.ctrip.framework.apollo.util.http.DefaultHttpClient; import com.ctrip.framework.apollo.util.http.HttpClient; - import com.ctrip.framework.apollo.util.yaml.YamlParser; import com.ctrip.framework.foundation.internals.ServiceBootstrap; import com.google.inject.AbstractModule; @@ -38,6 +43,8 @@ import com.google.inject.Singleton; import java.util.List; +; + /** * Guice injector * @author Jason Song(song_s@ctrip.com) @@ -105,6 +112,9 @@ protected void configure() { bind(RemoteConfigLongPollService.class).in(Singleton.class); bind(YamlParser.class).in(Singleton.class); bind(PropertiesFactory.class).to(DefaultPropertiesFactory.class).in(Singleton.class); + bind(ConfigMonitor.class).to(DefaultConfigMonitor.class).in(Singleton.class); + bind(MetricsCollectorManager.class).to(DefaultMetricsCollectorManager.class).in(Singleton.class); + bind(MetricsExporterFactory.class).to(DefaultMetricsExporterFactory.class).in(Singleton.class); } } } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/LocalFileConfigRepository.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/LocalFileConfigRepository.java index 1820fd1a..13ca7929 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/LocalFileConfigRepository.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/LocalFileConfigRepository.java @@ -16,6 +16,8 @@ */ package com.ctrip.framework.apollo.internals; +import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_CONFIG_EXCEPTION; + import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory; import com.ctrip.framework.apollo.enums.ConfigSourceType; import java.io.File; @@ -154,7 +156,7 @@ protected void sync() { m_sourceType = ConfigSourceType.LOCAL; transaction.setStatus(Transaction.SUCCESS); } catch (Throwable ex) { - Tracer.logEvent("ApolloConfigException", ExceptionUtil.getDetailMessage(ex)); + Tracer.logEvent(APOLLO_CONFIG_EXCEPTION, ExceptionUtil.getDetailMessage(ex)); transaction.setStatus(ex); exception = ex; //ignore diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigLongPollService.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigLongPollService.java index 59806b2a..1ab51080 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigLongPollService.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigLongPollService.java @@ -16,6 +16,9 @@ */ package com.ctrip.framework.apollo.internals; +import static com.ctrip.framework.apollo.monitor.internal.MonitorConstant.NAMESPACE; +import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_CONFIG_EXCEPTION; + import com.ctrip.framework.apollo.build.ApolloInjector; import com.ctrip.framework.apollo.core.ConfigConsts; import com.ctrip.framework.apollo.core.dto.ApolloConfigNotification; @@ -28,14 +31,16 @@ import com.ctrip.framework.apollo.core.utils.ApolloThreadFactory; import com.ctrip.framework.apollo.core.utils.StringUtils; import com.ctrip.framework.apollo.exceptions.ApolloConfigException; +import com.ctrip.framework.apollo.monitor.internal.collector.internal.DefaultApolloNamespaceCollector; +import com.ctrip.framework.apollo.monitor.internal.model.MetricsEvent; import com.ctrip.framework.apollo.spi.ConfigServiceLoadBalancerClient; import com.ctrip.framework.apollo.tracer.Tracer; import com.ctrip.framework.apollo.tracer.spi.Transaction; import com.ctrip.framework.apollo.util.ConfigUtil; import com.ctrip.framework.apollo.util.ExceptionUtil; +import com.ctrip.framework.apollo.util.http.HttpClient; import com.ctrip.framework.apollo.util.http.HttpRequest; import com.ctrip.framework.apollo.util.http.HttpResponse; -import com.ctrip.framework.apollo.util.http.HttpClient; import com.ctrip.framework.foundation.internals.ServiceBootstrap; import com.google.common.base.Joiner; import com.google.common.base.Strings; @@ -50,6 +55,7 @@ import com.google.common.util.concurrent.RateLimiter; import com.google.gson.Gson; import java.lang.reflect.Type; +import java.net.SocketTimeoutException; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentMap; @@ -209,9 +215,14 @@ private void doLongPollingRefresh(String appId, String cluster, String dataCente transaction.setStatus(Transaction.SUCCESS); } catch (Throwable ex) { lastServiceDto = null; - Tracer.logEvent("ApolloConfigException", ExceptionUtil.getDetailMessage(ex)); + Tracer.logEvent(APOLLO_CONFIG_EXCEPTION, ExceptionUtil.getDetailMessage(ex)); transaction.setStatus(ex); long sleepTimeInSecond = m_longPollFailSchedulePolicyInSecond.fail(); + if (ex.getCause() instanceof SocketTimeoutException) { + MetricsEvent.builder().withName(DefaultApolloNamespaceCollector.NAMESPACE_TIMEOUT) + .putAttachment(NAMESPACE, assembleNamespaces()) + .withTag(DefaultApolloNamespaceCollector.NAMESPACE_MONITOR).push(); + } logger.warn( "Long polling failed, will retry in {} seconds. appId: {}, cluster: {}, namespaces: {}, long polling url: {}, reason: {}", sleepTimeInSecond, appId, cluster, assembleNamespaces(), url, ExceptionUtil.getDetailMessage(ex)); diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigRepository.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigRepository.java index c3aab684..6ca75336 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigRepository.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigRepository.java @@ -16,6 +16,15 @@ */ package com.ctrip.framework.apollo.internals; +import static com.ctrip.framework.apollo.monitor.internal.MonitorConstant.NAMESPACE; +import static com.ctrip.framework.apollo.monitor.internal.MonitorConstant.TIMESTAMP; +import static com.ctrip.framework.apollo.monitor.internal.collector.internal.DefaultApolloNamespaceCollector.NAMESPACE_MONITOR; +import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_CLIENT_CONFIGS; +import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_CLIENT_CONFIGMETA; +import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_CLIENT_VERSION; +import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_CONFIGSERVICE; +import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_CONFIG_EXCEPTION; + import com.ctrip.framework.apollo.Apollo; import com.ctrip.framework.apollo.build.ApolloInjector; import com.ctrip.framework.apollo.core.ConfigConsts; @@ -31,13 +40,15 @@ import com.ctrip.framework.apollo.enums.ConfigSourceType; import com.ctrip.framework.apollo.exceptions.ApolloConfigException; import com.ctrip.framework.apollo.exceptions.ApolloConfigStatusCodeException; +import com.ctrip.framework.apollo.monitor.internal.collector.internal.DefaultApolloNamespaceCollector; +import com.ctrip.framework.apollo.monitor.internal.model.MetricsEvent; import com.ctrip.framework.apollo.tracer.Tracer; import com.ctrip.framework.apollo.tracer.spi.Transaction; import com.ctrip.framework.apollo.util.ConfigUtil; import com.ctrip.framework.apollo.util.ExceptionUtil; +import com.ctrip.framework.apollo.util.http.HttpClient; import com.ctrip.framework.apollo.util.http.HttpRequest; import com.ctrip.framework.apollo.util.http.HttpResponse; -import com.ctrip.framework.apollo.util.http.HttpClient; import com.google.common.base.Joiner; import com.google.common.base.Strings; import com.google.common.collect.Lists; @@ -73,7 +84,7 @@ public class RemoteConfigRepository extends AbstractConfigRepository { private final RemoteConfigLongPollService remoteConfigLongPollService; private volatile AtomicReference m_configCache; private final String m_namespace; - private final static ScheduledExecutorService m_executorService; + protected final static ScheduledExecutorService m_executorService; private final AtomicReference m_longPollServiceDto; private final AtomicReference m_remoteMessages; private final RateLimiter m_loadConfigRateLimiter; @@ -111,7 +122,12 @@ public RemoteConfigRepository(String namespace) { @Override public Properties getConfig() { if (m_configCache.get() == null) { + long start = System.currentTimeMillis(); this.sync(); + MetricsEvent.builder().withName(DefaultApolloNamespaceCollector.NAMESPACE_FIRST_LOAD_SPEND).withTag( + NAMESPACE_MONITOR) + .putAttachment(NAMESPACE, m_namespace) + .putAttachment(TIMESTAMP, System.currentTimeMillis() - start).push(); } return transformApolloConfigToProperties(m_configCache.get()); } @@ -133,10 +149,10 @@ private void schedulePeriodicRefresh() { new Runnable() { @Override public void run() { - Tracer.logEvent("Apollo.ConfigService", String.format("periodicRefresh: %s", m_namespace)); + Tracer.logEvent(APOLLO_CONFIGSERVICE, String.format("periodicRefresh: %s", m_namespace)); logger.debug("refresh config for namespace: {}", m_namespace); trySync(); - Tracer.logEvent("Apollo.Client.Version", Apollo.VERSION); + Tracer.logEvent(APOLLO_CLIENT_VERSION, Apollo.VERSION); } }, m_configUtil.getRefreshInterval(), m_configUtil.getRefreshInterval(), m_configUtil.getRefreshIntervalTimeUnit()); @@ -147,6 +163,7 @@ protected synchronized void sync() { Transaction transaction = Tracer.newTransaction("Apollo.ConfigService", "syncRemoteConfig"); try { + ApolloConfig previous = m_configCache.get(); ApolloConfig current = loadApolloConfig(); @@ -155,10 +172,11 @@ protected synchronized void sync() { logger.debug("Remote Config refreshed!"); m_configCache.set(current); this.fireRepositoryChange(m_namespace, this.getConfig()); + } if (current != null) { - Tracer.logEvent(String.format("Apollo.Client.Configs.%s", current.getNamespaceName()), + Tracer.logEvent(String.format(APOLLO_CLIENT_CONFIGS+"%s", current.getNamespaceName()), current.getReleaseKey()); } @@ -189,7 +207,7 @@ private ApolloConfig loadApolloConfig() { String cluster = m_configUtil.getCluster(); String dataCenter = m_configUtil.getDataCenter(); String secret = m_configUtil.getAccessKeySecret(); - Tracer.logEvent("Apollo.Client.ConfigMeta", STRING_JOINER.join(appId, cluster, m_namespace)); + Tracer.logEvent(APOLLO_CLIENT_CONFIGMETA, STRING_JOINER.join(appId, cluster, m_namespace)); int maxRetries = m_configNeedForceRefresh.get() ? 2 : 1; long onErrorSleepTime = 0; // 0 means no sleep Throwable exception = null; @@ -260,15 +278,17 @@ private ApolloConfig loadApolloConfig() { appId, cluster, m_namespace); statusCodeException = new ApolloConfigStatusCodeException(ex.getStatusCode(), message); + MetricsEvent.builder().withName(DefaultApolloNamespaceCollector.NAMESPACE_NOT_FOUND).withTag( + NAMESPACE_MONITOR).putAttachment(NAMESPACE, m_namespace).push(); } - Tracer.logEvent("ApolloConfigException", ExceptionUtil.getDetailMessage(statusCodeException)); + Tracer.logEvent(APOLLO_CONFIG_EXCEPTION, ExceptionUtil.getDetailMessage(statusCodeException)); transaction.setStatus(statusCodeException); exception = statusCodeException; if(ex.getStatusCode() == 404) { break retryLoopLabel; } } catch (Throwable ex) { - Tracer.logEvent("ApolloConfigException", ExceptionUtil.getDetailMessage(ex)); + Tracer.logEvent(APOLLO_CONFIG_EXCEPTION, ExceptionUtil.getDetailMessage(ex)); transaction.setStatus(ex); exception = ex; } finally { diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/SimpleConfig.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/SimpleConfig.java index c8897bbd..10ba29af 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/SimpleConfig.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/SimpleConfig.java @@ -16,6 +16,8 @@ */ package com.ctrip.framework.apollo.internals; +import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_CLIENT_CONFIGCHANGES; + import com.ctrip.framework.apollo.enums.ConfigSourceType; import java.util.Collections; import java.util.List; @@ -113,7 +115,7 @@ public String apply(ConfigChange input) { this.fireConfigChange(m_namespace, changeMap); - Tracer.logEvent("Apollo.Client.ConfigChanges", m_namespace); + Tracer.logEvent(APOLLO_CLIENT_CONFIGCHANGES, m_namespace); } private void updateConfig(Properties newConfigProperties, ConfigSourceType sourceType) { diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/YamlConfigFile.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/YamlConfigFile.java index 3443d582..d7757895 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/YamlConfigFile.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/YamlConfigFile.java @@ -16,6 +16,8 @@ */ package com.ctrip.framework.apollo.internals; +import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_CONFIG_EXCEPTION; + import com.ctrip.framework.apollo.util.ExceptionUtil; import java.util.Properties; @@ -65,7 +67,7 @@ private boolean tryTransformToProperties() { transformToProperties(); return true; } catch (Throwable ex) { - Tracer.logEvent("ApolloConfigException", ExceptionUtil.getDetailMessage(ex)); + Tracer.logEvent(APOLLO_CONFIG_EXCEPTION, ExceptionUtil.getDetailMessage(ex)); logger.warn("yaml to properties failed, reason: {}", ExceptionUtil.getDetailMessage(ex)); } return false; diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloExceptionMonitorApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloExceptionMonitorApi.java new file mode 100644 index 00000000..6a826a56 --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloExceptionMonitorApi.java @@ -0,0 +1,38 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.api; + +import java.util.List; +import javax.management.MXBean; + +/** + * @author Rawven + */ +@MXBean +public interface ApolloExceptionMonitorApi { + + + /** + * get the number of exceptions + */ + Integer getExceptionNum(); + + /** + * get exception details + */ + List getExceptionDetails(); +} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloNamespaceMonitorApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloNamespaceMonitorApi.java new file mode 100644 index 00000000..d9ce8ee9 --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloNamespaceMonitorApi.java @@ -0,0 +1,53 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.api; + +import java.util.List; +import javax.management.MXBean; + +/** + * @author Rawven + */ +@MXBean +public interface ApolloNamespaceMonitorApi { + + String getNamespaceReleaseKey(String namespace); + + long getNamespaceUsageCount(String namespace); + + String getNamespaceLatestUpdateTime(String namespace); + + long getNamespaceFirstLoadSpend(String namespace); + + String getNamespace404(); + + String getNamespaceTimeout(); + + List getNamespaceItemName(String namespace); + + List getAllNamespaceReleaseKey(); + + List getAllNamespaceUsageCount(); + + List getAllNamespacesLatestUpdateTime(); + + List getAllUsedNamespaceName(); + + List getAllNamespaceFirstLoadSpend(); + + List getAllNamespaceItemName(); +} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloRunningParamsMonitorApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloRunningParamsMonitorApi.java new file mode 100644 index 00000000..ff9e2205 --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloRunningParamsMonitorApi.java @@ -0,0 +1,70 @@ +/* + * Copyright 2022 Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.api; + +import javax.management.MXBean; + +/** + * @author Rawven + */ +@MXBean +public interface ApolloRunningParamsMonitorApi { + + String getStartupParams(String key); + + String getConfigServiceUrl(); + + String getAccessKeySecret(); + + Boolean getAutoUpdateInjectedSpringProperties(); + + Boolean getBootstrapEnabled(); + + String getBootstrapNamespaces(); + + Boolean getBootstrapEagerLoadEnabled(); + + Boolean getOverrideSystemProperties(); + + String getCacheDir(); + + String getCluster(); + + String getConfigService(); + + Boolean getClientMonitorEnabled(); + + Boolean getClientMonitorJmxEnabled(); + + String getClientMonitorExternalForm(); + + long getClientMonitorExternalExportPeriod(); + + String getMeta(); + + String getMetaLatestFreshTime(); + + Boolean getPropertyNamesCacheEnable(); + + Boolean getPropertyOrderEnable(); + + String getVersion(); + + String getEnv(); + + String getAppId(); +} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloThreadPoolMonitorApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloThreadPoolMonitorApi.java new file mode 100644 index 00000000..33c09e77 --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloThreadPoolMonitorApi.java @@ -0,0 +1,89 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.api; + +import javax.management.MXBean; + +/** + * @author Rawven + */ +@MXBean +public interface ApolloThreadPoolMonitorApi { + + + int getRemoteConfigRepositoryThreadPoolActiveCount(); + + int getRemoteConfigRepositoryThreadPoolQueueSize(); + + int getRemoteConfigRepositoryThreadPoolCorePoolSize(); + + int getRemoteConfigRepositoryThreadPoolMaximumPoolSize(); + + int getRemoteConfigRepositoryThreadPoolPoolSize(); + + long getRemoteConfigRepositoryThreadPoolTaskCount(); + + long getRemoteConfigRepositoryThreadPoolCompletedTaskCount(); + + int getRemoteConfigRepositoryThreadPoolLargestPoolSize(); + + int getRemoteConfigRepositoryThreadPoolRemainingCapacity(); + + double getRemoteConfigRepositoryThreadPoolCurrentLoad(); + + int getAbstractConfigThreadPoolActiveCount(); + + int getAbstractConfigThreadPoolQueueSize(); + + int getAbstractConfigThreadPoolCorePoolSize(); + + int getAbstractConfigThreadPoolMaximumPoolSize(); + + int getAbstractConfigThreadPoolPoolSize(); + + long getAbstractConfigThreadPoolTaskCount(); + + long getAbstractConfigThreadPoolCompletedTaskCount(); + + int getAbstractConfigThreadPoolLargestPoolSize(); + + int getAbstractConfigThreadPoolRemainingCapacity(); + + double getAbstractConfigThreadPoolCurrentLoad(); + + + int getAbstractConfigFileThreadPoolActiveCount(); + + int getAbstractConfigFileThreadPoolQueueSize(); + + int getAbstractConfigFileThreadPoolCorePoolSize(); + + int getAbstractConfigFileThreadPoolMaximumPoolSize(); + + int getAbstractConfigFileThreadPoolPoolSize(); + + long getAbstractConfigFileThreadPoolTaskCount(); + + long getAbstractConfigFileThreadPoolCompletedTaskCount(); + + int getAbstractConfigFileThreadPoolLargestPoolSize(); + + int getAbstractConfigFileThreadPoolRemainingCapacity(); + + double getAbstractConfigFileThreadPoolCurrentLoad(); + +} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ConfigMonitor.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ConfigMonitor.java new file mode 100644 index 00000000..898f7739 --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ConfigMonitor.java @@ -0,0 +1,33 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.api; + +/** + * @author Rawven + */ +public interface ConfigMonitor { + + ApolloThreadPoolMonitorApi getThreadPoolMonitorApi(); + + ApolloExceptionMonitorApi getExceptionMonitorApi(); + + ApolloNamespaceMonitorApi getNamespaceMonitorApi(); + + ApolloRunningParamsMonitorApi getRunningParamsMonitorApi(); + + String getDataWithCurrentMonitoringSystemFormat(); +} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/DefaultConfigMonitor.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/DefaultConfigMonitor.java new file mode 100644 index 00000000..cbd33505 --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/DefaultConfigMonitor.java @@ -0,0 +1,78 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal; + +import com.ctrip.framework.apollo.monitor.api.ApolloExceptionMonitorApi; +import com.ctrip.framework.apollo.monitor.api.ApolloNamespaceMonitorApi; +import com.ctrip.framework.apollo.monitor.api.ApolloRunningParamsMonitorApi; +import com.ctrip.framework.apollo.monitor.api.ApolloThreadPoolMonitorApi; +import com.ctrip.framework.apollo.monitor.api.ConfigMonitor; +import com.ctrip.framework.apollo.monitor.internal.exporter.MetricsExporter; + +/** + * exposes all collected data through ConfigService + * + * @author Rawven + */ +public class DefaultConfigMonitor implements ConfigMonitor { + + private MetricsExporter reporter; + private ApolloThreadPoolMonitorApi threadPoolMonitorApi = new NullThreadPoolMonitorApi(); + private ApolloExceptionMonitorApi exceptionMonitorApi = new NullExceptionMonitorApi(); + private ApolloNamespaceMonitorApi apolloNamespaceMonitorApi = new NullNamespaceMonitorApi(); + private ApolloRunningParamsMonitorApi apolloRunningParamsMonitorApi = new NullRunningParamsMonitorApi(); + + @Override + public ApolloThreadPoolMonitorApi getThreadPoolMonitorApi() { + return threadPoolMonitorApi; + } + + @Override + public ApolloExceptionMonitorApi getExceptionMonitorApi() { + return exceptionMonitorApi; + } + + @Override + public ApolloNamespaceMonitorApi getNamespaceMonitorApi() { + return apolloNamespaceMonitorApi; + } + + @Override + public ApolloRunningParamsMonitorApi getRunningParamsMonitorApi() { + return apolloRunningParamsMonitorApi; + } + + @Override + public String getDataWithCurrentMonitoringSystemFormat() { + if (reporter == null) { + return "No MonitoringSystem Use"; + } + return reporter.response(); + } + + public void init(ApolloNamespaceMonitorApi apolloNamespaceMonitorApi, + ApolloThreadPoolMonitorApi threadPoolMonitorApi, + ApolloExceptionMonitorApi exceptionMonitorApi, + ApolloRunningParamsMonitorApi apolloRunningParamsMonitorApi, + MetricsExporter reporter) { + this.apolloNamespaceMonitorApi = apolloNamespaceMonitorApi; + this.threadPoolMonitorApi = threadPoolMonitorApi; + this.exceptionMonitorApi = exceptionMonitorApi; + this.apolloRunningParamsMonitorApi = apolloRunningParamsMonitorApi; + this.reporter = reporter; + } +} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/MonitorConstant.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/MonitorConstant.java new file mode 100644 index 00000000..ea289e1f --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/MonitorConstant.java @@ -0,0 +1,29 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal; + +/** + * metrics constant + * + * @author Rawven + */ +public class MonitorConstant { + + public static final String NAMESPACE = "namespace"; + public static final String TIMESTAMP = "timestamp"; + public static final String MBEAN_NAME = "apollo.client.monitor:type="; +} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/NullExceptionMonitorApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/NullExceptionMonitorApi.java new file mode 100644 index 00000000..d700baee --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/NullExceptionMonitorApi.java @@ -0,0 +1,34 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal; + +import com.ctrip.framework.apollo.monitor.api.ApolloExceptionMonitorApi; +import java.util.Collections; +import java.util.List; + +public class NullExceptionMonitorApi implements ApolloExceptionMonitorApi { + + @Override + public Integer getExceptionNum() { + return 0; + } + + @Override + public List getExceptionDetails() { + return Collections.emptyList(); + } +} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/NullNamespaceMonitorApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/NullNamespaceMonitorApi.java new file mode 100644 index 00000000..5377b6d9 --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/NullNamespaceMonitorApi.java @@ -0,0 +1,89 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal; + +import com.ctrip.framework.apollo.monitor.api.ApolloNamespaceMonitorApi; +import java.util.Collections; +import java.util.List; + +public class NullNamespaceMonitorApi implements ApolloNamespaceMonitorApi { + + @Override + public String getNamespaceReleaseKey(String namespace) { + return ""; + } + + @Override + public long getNamespaceUsageCount(String namespace) { + return 0; + } + + @Override + public String getNamespaceLatestUpdateTime(String namespace) { + return ""; + } + + @Override + public long getNamespaceFirstLoadSpend(String namespace) { + return 0; + } + + @Override + public String getNamespace404() { + return ""; + } + + @Override + public String getNamespaceTimeout() { + return ""; + } + + @Override + public List getNamespaceItemName(String namespace) { + return Collections.emptyList(); + } + + @Override + public List getAllNamespaceReleaseKey() { + return Collections.emptyList(); + } + + @Override + public List getAllNamespaceUsageCount() { + return Collections.emptyList(); + } + + @Override + public List getAllNamespacesLatestUpdateTime() { + return Collections.emptyList(); + } + + @Override + public List getAllUsedNamespaceName() { + return Collections.emptyList(); + } + + @Override + public List getAllNamespaceFirstLoadSpend() { + return Collections.emptyList(); + } + + @Override + public List getAllNamespaceItemName() { + return Collections.emptyList(); + } +} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/NullRunningParamsMonitorApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/NullRunningParamsMonitorApi.java new file mode 100644 index 00000000..d5a019d5 --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/NullRunningParamsMonitorApi.java @@ -0,0 +1,132 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal; + +import com.ctrip.framework.apollo.monitor.api.ApolloRunningParamsMonitorApi; + +public class NullRunningParamsMonitorApi implements ApolloRunningParamsMonitorApi { + + @Override + public String getStartupParams(String key) { + return ""; + } + + @Override + public String getConfigServiceUrl() { + return ""; + } + + @Override + public String getAccessKeySecret() { + return ""; + } + + @Override + public Boolean getAutoUpdateInjectedSpringProperties() { + return null; + } + + @Override + public Boolean getBootstrapEnabled() { + return null; + } + + @Override + public String getBootstrapNamespaces() { + return ""; + } + + @Override + public Boolean getBootstrapEagerLoadEnabled() { + return null; + } + + @Override + public Boolean getOverrideSystemProperties() { + return null; + } + + @Override + public String getCacheDir() { + return ""; + } + + @Override + public String getCluster() { + return ""; + } + + @Override + public String getConfigService() { + return ""; + } + + @Override + public Boolean getClientMonitorEnabled() { + return null; + } + + @Override + public Boolean getClientMonitorJmxEnabled() { + return null; + } + + @Override + public String getClientMonitorExternalForm() { + return ""; + } + + @Override + public long getClientMonitorExternalExportPeriod() { + return 0; + } + + @Override + public String getMeta() { + return ""; + } + + @Override + public String getMetaLatestFreshTime() { + return ""; + } + + @Override + public Boolean getPropertyNamesCacheEnable() { + return null; + } + + @Override + public Boolean getPropertyOrderEnable() { + return null; + } + + @Override + public String getVersion() { + return ""; + } + + @Override + public String getEnv() { + return ""; + } + + @Override + public String getAppId() { + return ""; + } +} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/NullThreadPoolMonitorApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/NullThreadPoolMonitorApi.java new file mode 100644 index 00000000..34384df0 --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/NullThreadPoolMonitorApi.java @@ -0,0 +1,172 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal; + +import com.ctrip.framework.apollo.monitor.api.ApolloThreadPoolMonitorApi; + +public class NullThreadPoolMonitorApi implements ApolloThreadPoolMonitorApi { + + @Override + public int getRemoteConfigRepositoryThreadPoolActiveCount() { + return 0; + } + + @Override + public int getRemoteConfigRepositoryThreadPoolQueueSize() { + return 0; + } + + @Override + public int getRemoteConfigRepositoryThreadPoolCorePoolSize() { + return 0; + } + + @Override + public int getRemoteConfigRepositoryThreadPoolMaximumPoolSize() { + return 0; + } + + @Override + public int getRemoteConfigRepositoryThreadPoolPoolSize() { + return 0; + } + + @Override + public long getRemoteConfigRepositoryThreadPoolTaskCount() { + return 0; + } + + @Override + public long getRemoteConfigRepositoryThreadPoolCompletedTaskCount() { + return 0; + } + + @Override + public int getRemoteConfigRepositoryThreadPoolLargestPoolSize() { + return 0; + } + + @Override + public int getRemoteConfigRepositoryThreadPoolRemainingCapacity() { + return 0; + } + + @Override + public double getRemoteConfigRepositoryThreadPoolCurrentLoad() { + return 0; + } + + @Override + public int getAbstractConfigThreadPoolActiveCount() { + return 0; + } + + @Override + public int getAbstractConfigThreadPoolQueueSize() { + return 0; + } + + @Override + public int getAbstractConfigThreadPoolCorePoolSize() { + return 0; + } + + @Override + public int getAbstractConfigThreadPoolMaximumPoolSize() { + return 0; + } + + @Override + public int getAbstractConfigThreadPoolPoolSize() { + return 0; + } + + @Override + public long getAbstractConfigThreadPoolTaskCount() { + return 0; + } + + @Override + public long getAbstractConfigThreadPoolCompletedTaskCount() { + return 0; + } + + @Override + public int getAbstractConfigThreadPoolLargestPoolSize() { + return 0; + } + + @Override + public int getAbstractConfigThreadPoolRemainingCapacity() { + return 0; + } + + @Override + public double getAbstractConfigThreadPoolCurrentLoad() { + return 0; + } + + @Override + public int getAbstractConfigFileThreadPoolActiveCount() { + return 0; + } + + @Override + public int getAbstractConfigFileThreadPoolQueueSize() { + return 0; + } + + @Override + public int getAbstractConfigFileThreadPoolCorePoolSize() { + return 0; + } + + @Override + public int getAbstractConfigFileThreadPoolMaximumPoolSize() { + return 0; + } + + @Override + public int getAbstractConfigFileThreadPoolPoolSize() { + return 0; + } + + @Override + public long getAbstractConfigFileThreadPoolTaskCount() { + return 0; + } + + @Override + public long getAbstractConfigFileThreadPoolCompletedTaskCount() { + return 0; + } + + @Override + public int getAbstractConfigFileThreadPoolLargestPoolSize() { + return 0; + } + + @Override + public int getAbstractConfigFileThreadPoolRemainingCapacity() { + return 0; + } + + @Override + public double getAbstractConfigFileThreadPoolCurrentLoad() { + return 0; + } +} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/AbstractMetricsCollector.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/AbstractMetricsCollector.java new file mode 100644 index 00000000..55314f78 --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/AbstractMetricsCollector.java @@ -0,0 +1,80 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.collector; + +import com.ctrip.framework.apollo.monitor.internal.model.CounterModel; +import com.ctrip.framework.apollo.monitor.internal.model.GaugeModel; +import com.ctrip.framework.apollo.monitor.internal.model.MetricsEvent; +import com.ctrip.framework.apollo.monitor.internal.model.MetricsModel; +import com.google.common.collect.Maps; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * 抽象的 Metrics 收集器 用于收集和导出指标样本 + * + * @author Rawven + */ +public abstract class AbstractMetricsCollector implements MetricsCollector { + + protected final Map counterSamples = Maps.newHashMap(); + protected final Map gaugeSamples = Maps.newHashMap(); + private final AtomicBoolean isUpdated = new AtomicBoolean(); + private final List tags; + private final String name; + + public AbstractMetricsCollector(String name, String... tags) { + this.name = name; + this.tags = Arrays.asList(tags); + } + + @Override + public String name() { + return name; + } + + @Override + public boolean isSupport(MetricsEvent event) { + return tags.contains(event.getTag()); + } + + @Override + public void collect(MetricsEvent event) { + collect0(event); + isUpdated.set(true); + } + + @Override + public boolean isSamplesUpdated() { + return isUpdated.getAndSet(false); + } + + @Override + public List export() { + export0(); + List samples = new ArrayList<>(counterSamples.values()); + samples.addAll(gaugeSamples.values()); + return samples; + } + + protected abstract void collect0(MetricsEvent event); + + protected abstract void export0(); +} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/MetricsCollector.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/MetricsCollector.java new file mode 100644 index 00000000..e1efd0d2 --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/MetricsCollector.java @@ -0,0 +1,52 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.collector; + +import com.ctrip.framework.apollo.monitor.internal.model.MetricsEvent; +import com.ctrip.framework.apollo.monitor.internal.model.MetricsModel; +import java.util.List; + +/** + * @author Rawven + */ +public interface MetricsCollector { + + + String name(); + + /** + * is support the event + */ + boolean isSupport(MetricsEvent event); + + /** + * collect metrics from event + */ + void collect(MetricsEvent event); + + /** + * is samples updated + */ + boolean isSamplesUpdated(); + + /** + * export to a format recognized by the monitoring system + */ + List export(); + + +} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/MetricsCollectorManager.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/MetricsCollectorManager.java new file mode 100644 index 00000000..75a28aa5 --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/MetricsCollectorManager.java @@ -0,0 +1,36 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.collector; + +import com.ctrip.framework.apollo.core.spi.Ordered; +import java.util.List; + +/** + * @author Rawven + */ +public interface MetricsCollectorManager extends Ordered { + + /** + * get collectors + */ + List getCollectors(); + + @Override + default int getOrder() { + return 0; + } +} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/internal/DefaultApolloExceptionCollector.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/internal/DefaultApolloExceptionCollector.java new file mode 100644 index 00000000..f4895592 --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/internal/DefaultApolloExceptionCollector.java @@ -0,0 +1,83 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.collector.internal; + +import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.ERROR_METRICS; +import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.THROWABLE; + +import com.ctrip.framework.apollo.exceptions.ApolloConfigException; +import com.ctrip.framework.apollo.monitor.api.ApolloExceptionMonitorApi; +import com.ctrip.framework.apollo.monitor.internal.collector.AbstractMetricsCollector; +import com.ctrip.framework.apollo.monitor.internal.model.CounterModel; +import com.ctrip.framework.apollo.monitor.internal.model.MetricsEvent; +import java.util.List; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Collectors; + +/** + * @author Rawven + */ +public class DefaultApolloExceptionCollector extends AbstractMetricsCollector implements + ApolloExceptionMonitorApi { + + public static final String EXCEPTION_NUM = "exception_num"; + + private static final int MAX_EXCEPTIONS_SIZE = 25; + private final BlockingQueue exceptions = new ArrayBlockingQueue<>( + MAX_EXCEPTIONS_SIZE); + + private final AtomicInteger exceptionNum = new AtomicInteger(0); + + public DefaultApolloExceptionCollector() { + super(ERROR_METRICS, ERROR_METRICS); + } + + @Override + public Integer getExceptionNum() { + return exceptionNum.get(); + } + + @Override + public List getExceptionDetails() { + return exceptions.stream().map(ApolloConfigException::getMessage) + .collect(Collectors.toList()); + } + + @Override + public void collect0(MetricsEvent event) { + ApolloConfigException exception = event.getAttachmentValue(THROWABLE); + if (exception != null) { + if (exceptions.size() >= MAX_EXCEPTIONS_SIZE) { + exceptions.poll(); + } + exceptions.add(exception); + exceptionNum.incrementAndGet(); + } + } + + @Override + public void export0() { + if (!counterSamples.containsKey(EXCEPTION_NUM)) { + counterSamples.put(EXCEPTION_NUM, CounterModel.builder().name(EXCEPTION_NUM).value(0) + .build()); + } + counterSamples.get(EXCEPTION_NUM).updateValue(exceptionNum.get()); + } + +} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/internal/DefaultApolloNamespaceCollector.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/internal/DefaultApolloNamespaceCollector.java new file mode 100644 index 00000000..8caa5a9b --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/internal/DefaultApolloNamespaceCollector.java @@ -0,0 +1,296 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.collector.internal; + + +import static com.ctrip.framework.apollo.monitor.internal.MonitorConstant.NAMESPACE; +import static com.ctrip.framework.apollo.monitor.internal.model.GaugeModel.INT_CONVERTER; +import static com.ctrip.framework.apollo.monitor.internal.model.GaugeModel.LONG_CONVERTER; + +import com.ctrip.framework.apollo.Config; +import com.ctrip.framework.apollo.ConfigFile; +import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory; +import com.ctrip.framework.apollo.monitor.api.ApolloNamespaceMonitorApi; +import com.ctrip.framework.apollo.monitor.internal.MonitorConstant; +import com.ctrip.framework.apollo.monitor.internal.collector.AbstractMetricsCollector; +import com.ctrip.framework.apollo.monitor.internal.model.CounterModel; +import com.ctrip.framework.apollo.monitor.internal.model.GaugeModel; +import com.ctrip.framework.apollo.monitor.internal.model.MetricsEvent; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import java.time.Instant; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.function.ToDoubleFunction; +import org.slf4j.Logger; + +/** + * @author Rawven + */ +public class DefaultApolloNamespaceCollector extends AbstractMetricsCollector implements + ApolloNamespaceMonitorApi { + + public static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern( + "yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault()); + public static final String NAMESPACE_MONITOR = "namespace_monitor"; + public static final String NAMESPACE_LATEST_UPDATE_TIME = "namespace_latest_update_time"; + public static final String NAMESPACE_FIRST_LOAD_SPEND = "namespace_first_load_spend_time"; + public static final String NAMESPACE_USAGE_COUNT = "namespace_usage_count"; + public static final String NAMESPACE_RELEASE_KEY = "namespace_release_key"; + public static final String NAMESPACE_ITEM_NUM = "namespace_item_num"; + public static final String CONFIG_FILE_NUM = "config_file_num"; + public static final String NAMESPACE_NOT_FOUND = "namespace_not_found"; + public static final String NAMESPACE_TIMEOUT = "namespace_timeout"; + private static final Logger logger = DeferredLoggerFactory.getLogger( + DefaultApolloNamespaceCollector.class); + private final Map m_configs; + private final Map m_configLocks; + private final Map m_configFiles; + private final Map m_configFileLocks; + private final Map namespaces = Maps.newConcurrentMap(); + private final List namespace404 = Lists.newCopyOnWriteArrayList(); + private final List namespaceTimeout = Lists.newCopyOnWriteArrayList(); + + public DefaultApolloNamespaceCollector(Map m_configs, + Map m_configLocks, + Map m_configFiles, + Map m_configFileLocks) { + super(NAMESPACE_MONITOR, NAMESPACE_MONITOR); + this.m_configs = m_configs; + this.m_configLocks = m_configLocks; + this.m_configFiles = m_configFiles; + this.m_configFileLocks = m_configFileLocks; + } + + + @Override + public void collect0(MetricsEvent event) { + String namespace = event.getAttachmentValue(NAMESPACE); + NamespaceMetrics namespaceMetrics = namespaces.computeIfAbsent(namespace, + k -> new NamespaceMetrics()); + switch (event.getName()) { + case NAMESPACE_USAGE_COUNT: + namespaceMetrics.incrementUsageCount(); + break; + case NAMESPACE_LATEST_UPDATE_TIME: + long updateTime = event.getAttachmentValue(MonitorConstant.TIMESTAMP); + namespaceMetrics.setLatestUpdateTime(updateTime); + break; + case NAMESPACE_FIRST_LOAD_SPEND: + long firstLoadSpendTime = event.getAttachmentValue(MonitorConstant.TIMESTAMP); + namespaceMetrics.setFirstLoadSpend(firstLoadSpendTime); + break; + case NAMESPACE_RELEASE_KEY: + String releaseKey = event.getAttachmentValue(NAMESPACE_RELEASE_KEY); + namespaceMetrics.setReleaseKey(releaseKey); + break; + case NAMESPACE_TIMEOUT: + namespaceTimeout.add(namespace); + break; + case NAMESPACE_NOT_FOUND: + namespace404.add(namespace); + break; + default: + logger.warn("Unknown event: {}", event); + break; + } + } + + @Override + public void export0() { + namespaces.forEach((namespace, metrics) -> { + updateCounterSample(NAMESPACE_USAGE_COUNT, namespace, metrics.getUsageCount()); + updateGaugeSample(NAMESPACE_FIRST_LOAD_SPEND, namespace, metrics.getFirstLoadSpend(), + LONG_CONVERTER); + updateGaugeSample(NAMESPACE_LATEST_UPDATE_TIME, namespace, metrics.getLatestUpdateTime(), + LONG_CONVERTER); + updateGaugeSample(NAMESPACE_ITEM_NUM, namespace, + m_configs.get(namespace).getPropertyNames().size(), INT_CONVERTER); + updateGaugeSample(CONFIG_FILE_NUM, namespace, m_configFiles.size(), INT_CONVERTER); + }); + updateGaugeSample(NAMESPACE_NOT_FOUND, "", namespace404.size(), INT_CONVERTER); + updateGaugeSample(NAMESPACE_TIMEOUT, "", namespaceTimeout.size(), INT_CONVERTER); + } + + private void updateCounterSample(String key, String namespace, double value) { + String mapKey = namespace + key; + if (!counterSamples.containsKey(mapKey)) { + CounterModel.CounterBuilder builder = CounterModel.builder().name(key).value(0); + if (!namespace.isEmpty()) { + builder.putTag(NAMESPACE, namespace); + } + counterSamples.put(mapKey, builder.build()); + } + counterSamples.get(mapKey).updateValue(value); + } + + @SuppressWarnings("unchecked") + private void updateGaugeSample(String key, String namespace, Object value, + ToDoubleFunction applyFunction) { + String mapKey = namespace + key; + if (!gaugeSamples.containsKey(mapKey)) { + GaugeModel.GaugeBuilder builder = GaugeModel.builder().name(key).value(0) + .apply(applyFunction); + if (!namespace.isEmpty()) { + builder.putTag(NAMESPACE, namespace); + } + gaugeSamples.put(mapKey, builder.build()); + } + gaugeSamples.get(mapKey).updateValue(value); + } + + + @Override + public String getNamespaceReleaseKey(String namespace) { + NamespaceMetrics namespaceMetrics = namespaces.get(namespace); + return namespaceMetrics == null ? null : namespaceMetrics.getReleaseKey(); + } + + @Override + public long getNamespaceUsageCount(String namespace) { + NamespaceMetrics namespaceMetrics = namespaces.get(namespace); + return namespaceMetrics == null ? 0 : namespaceMetrics.getUsageCount(); + } + + @Override + public String getNamespaceLatestUpdateTime(String namespace) { + NamespaceMetrics namespaceMetrics = namespaces.get(namespace); + return namespaceMetrics == null ? null + : DATE_FORMATTER.format(Instant.ofEpochMilli(namespaceMetrics.getLatestUpdateTime())); + } + + @Override + public long getNamespaceFirstLoadSpend(String namespace) { + NamespaceMetrics namespaceMetrics = namespaces.get(namespace); + return namespaceMetrics == null ? 0 : namespaceMetrics.getFirstLoadSpend(); + } + + @Override + public String getNamespace404() { + return namespace404.toString(); + } + + @Override + public String getNamespaceTimeout() { + return namespaceTimeout.toString(); + } + + @Override + public List getNamespaceItemName(String namespace) { + Config config = m_configs.get(namespace); + return config == null ? Collections.emptyList() : new ArrayList<>(config.getPropertyNames()); + } + + @Override + public List getAllNamespaceReleaseKey() { + List releaseKeys = Lists.newArrayList(); + namespaces.forEach((k, v) -> releaseKeys.add(k + ":" + v.getReleaseKey())); + return releaseKeys; + } + + @Override + public List getAllNamespaceUsageCount() { + List usedTimes = Lists.newArrayList(); + namespaces.forEach((k, v) -> usedTimes.add(k + ":" + v.getUsageCount())); + return usedTimes; + } + + @Override + public List getAllNamespacesLatestUpdateTime() { + List latestUpdateTimes = Lists.newArrayList(); + namespaces.forEach((k, v) -> latestUpdateTimes.add( + k + ":" + DATE_FORMATTER.format(Instant.ofEpochMilli(v.getLatestUpdateTime())))); + return latestUpdateTimes; + } + + @Override + public List getAllUsedNamespaceName() { + ArrayList namespaces = Lists.newArrayList(); + m_configs.forEach((k, v) -> namespaces.add(k)); + return namespaces; + } + + @Override + public List getAllNamespaceFirstLoadSpend() { + List firstLoadSpends = Lists.newArrayList(); + namespaces.forEach((k, v) -> firstLoadSpends.add( + k + ":" + v.getFirstLoadSpend())); + return firstLoadSpends; + } + + @Override + public List getAllNamespaceItemName() { + List namespaceItems = Lists.newArrayList(); + m_configs.forEach((k, v) -> namespaceItems.add(v.getPropertyNames().toString())); + return namespaceItems; + } + + public static class NamespaceMetrics { + + private int usageCount; + private long firstLoadSpend; + private long latestUpdateTime = System.currentTimeMillis(); + private String releaseKey = "default"; + + public String getReleaseKey() { + return releaseKey; + } + + public void setReleaseKey(String releaseKey) { + this.releaseKey = releaseKey; + } + + @Override + public String toString() { + return "NamespaceMetrics{" + + "usageCount=" + usageCount + + ", firstLoadSpend=" + firstLoadSpend + + ", latestUpdateTime=" + latestUpdateTime + + ", releaseKey='" + releaseKey + '\'' + + '}'; + } + + public int getUsageCount() { + return usageCount; + } + + public void incrementUsageCount() { + this.usageCount++; + } + + public long getFirstLoadSpend() { + return firstLoadSpend; + } + + public void setFirstLoadSpend(long firstLoadSpend) { + this.firstLoadSpend = firstLoadSpend; + } + + public long getLatestUpdateTime() { + return latestUpdateTime; + } + + public void setLatestUpdateTime(long latestUpdateTime) { + this.latestUpdateTime = latestUpdateTime; + } + } + +} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/internal/DefaultApolloRunningParamsCollector.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/internal/DefaultApolloRunningParamsCollector.java new file mode 100644 index 00000000..a5133af5 --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/internal/DefaultApolloRunningParamsCollector.java @@ -0,0 +1,230 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.collector.internal; + +import static com.ctrip.framework.apollo.core.ApolloClientSystemConsts.APOLLO_ACCESS_KEY_SECRET; +import static com.ctrip.framework.apollo.core.ApolloClientSystemConsts.APOLLO_CACHE_DIR; +import static com.ctrip.framework.apollo.core.ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_ENABLED; +import static com.ctrip.framework.apollo.core.ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_EXTERNAL_EXPORT_PERIOD; +import static com.ctrip.framework.apollo.core.ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_EXTERNAL_TYPE; +import static com.ctrip.framework.apollo.core.ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_JMX_ENABLED; +import static com.ctrip.framework.apollo.core.ApolloClientSystemConsts.APOLLO_CLUSTER; +import static com.ctrip.framework.apollo.core.ApolloClientSystemConsts.APOLLO_CONFIG_SERVICE; +import static com.ctrip.framework.apollo.core.ApolloClientSystemConsts.APOLLO_META; +import static com.ctrip.framework.apollo.core.ApolloClientSystemConsts.APOLLO_OVERRIDE_SYSTEM_PROPERTIES; +import static com.ctrip.framework.apollo.core.ApolloClientSystemConsts.APOLLO_PROPERTY_NAMES_CACHE_ENABLE; +import static com.ctrip.framework.apollo.core.ApolloClientSystemConsts.APOLLO_PROPERTY_ORDER_ENABLE; +import static com.ctrip.framework.apollo.core.ApolloClientSystemConsts.APP_ID; +import static com.ctrip.framework.apollo.core.ConfigConsts.APOLLO_AUTO_UPDATE_INJECTED_SPRING_PROPERTIES; +import static com.ctrip.framework.apollo.spring.config.PropertySourcesConstants.APOLLO_BOOTSTRAP_EAGER_LOAD_ENABLED; +import static com.ctrip.framework.apollo.spring.config.PropertySourcesConstants.APOLLO_BOOTSTRAP_ENABLED; +import static com.ctrip.framework.apollo.spring.config.PropertySourcesConstants.APOLLO_BOOTSTRAP_NAMESPACES; + +import com.ctrip.framework.apollo.Apollo; +import com.ctrip.framework.apollo.monitor.api.ApolloRunningParamsMonitorApi; +import com.ctrip.framework.apollo.monitor.internal.collector.AbstractMetricsCollector; +import com.ctrip.framework.apollo.monitor.internal.model.MetricsEvent; +import com.ctrip.framework.apollo.util.ConfigUtil; +import com.google.common.collect.Maps; +import java.util.Map; + +/** + * @author Rawven + */ +public class DefaultApolloRunningParamsCollector extends AbstractMetricsCollector implements + ApolloRunningParamsMonitorApi { + + public static final String ENV = "env"; + public static final String VERSION = "version"; + public static final String RUNNING_PARAMS = "RunningParams"; + public static final String META_FRESH = "metaFreshTime"; + public static final String CONFIG_SERVICE_URL = "configServiceUrl"; + private final Map map = Maps.newHashMap(); + + public DefaultApolloRunningParamsCollector(ConfigUtil configUtil) { + super(RUNNING_PARAMS, RUNNING_PARAMS); + map.put(APOLLO_ACCESS_KEY_SECRET, configUtil.getAccessKeySecret()); + map.put(APOLLO_AUTO_UPDATE_INJECTED_SPRING_PROPERTIES, + configUtil.isAutoUpdateInjectedSpringPropertiesEnabled()); + map.put(APOLLO_BOOTSTRAP_ENABLED, + Boolean.parseBoolean(System.getProperty(APOLLO_BOOTSTRAP_ENABLED))); + map.put(APOLLO_BOOTSTRAP_NAMESPACES, + System.getProperty(APOLLO_BOOTSTRAP_NAMESPACES)); + map.put(APOLLO_BOOTSTRAP_EAGER_LOAD_ENABLED, + Boolean.parseBoolean(System.getProperty(APOLLO_BOOTSTRAP_EAGER_LOAD_ENABLED))); + map.put(APOLLO_OVERRIDE_SYSTEM_PROPERTIES, configUtil.isOverrideSystemProperties()); + map.put(APOLLO_CACHE_DIR, configUtil.getDefaultLocalCacheDir()); + map.put(APOLLO_CLUSTER, configUtil.getCluster()); + map.put(APOLLO_CONFIG_SERVICE, + System.getProperty(APOLLO_CONFIG_SERVICE)); + map.put(APOLLO_CLIENT_MONITOR_EXTERNAL_TYPE, configUtil.getMonitorExternalType()); + map.put(APOLLO_CLIENT_MONITOR_ENABLED, configUtil.isClientMonitorEnabled()); + map.put(APOLLO_CLIENT_MONITOR_EXTERNAL_EXPORT_PERIOD, + configUtil.getMonitorExternalExportPeriod()); + map.put(APOLLO_META, configUtil.getMetaServerDomainName()); + map.put(APOLLO_PROPERTY_NAMES_CACHE_ENABLE, configUtil.isPropertyNamesCacheEnabled()); + map.put(APOLLO_PROPERTY_ORDER_ENABLE, configUtil.isPropertiesOrderEnabled()); + map.put(APOLLO_CLIENT_MONITOR_JMX_ENABLED, configUtil.isClientMonitorJmxEnabled()); + map.put(APP_ID, configUtil.getAppId()); + map.put(ENV, configUtil.getApolloEnv()); + map.put(VERSION, Apollo.VERSION); + } + + @Override + public String name() { + return RUNNING_PARAMS; + } + + @Override + public void collect0(MetricsEvent event) { + switch (event.getName()) { + case VERSION: + map.put(VERSION, event.getAttachmentValue(VERSION)); + break; + case META_FRESH: + map.put(META_FRESH, event.getAttachmentValue(META_FRESH)); + break; + case CONFIG_SERVICE_URL: + map.put(CONFIG_SERVICE_URL, event.getAttachmentValue(CONFIG_SERVICE_URL)); + break; + default: + break; + } + } + + @Override + public boolean isSamplesUpdated() { + return false; + } + + @Override + public void export0() { + } + + @Override + public String getStartupParams(String key) { + return map.getOrDefault(key, "").toString(); + } + + @Override + public String getConfigServiceUrl() { + return map.get(CONFIG_SERVICE_URL).toString(); + } + + + @Override + public String getAccessKeySecret() { + return map.getOrDefault(APOLLO_ACCESS_KEY_SECRET, "").toString(); + } + + @Override + public Boolean getAutoUpdateInjectedSpringProperties() { + return (Boolean) map.get(APOLLO_AUTO_UPDATE_INJECTED_SPRING_PROPERTIES); + } + + @Override + public Boolean getBootstrapEnabled() { + return (Boolean) map.get(APOLLO_BOOTSTRAP_ENABLED); + } + + @Override + public String getBootstrapNamespaces() { + return (String) map.get(APOLLO_BOOTSTRAP_NAMESPACES); + } + + @Override + public Boolean getBootstrapEagerLoadEnabled() { + return (Boolean) map.get(APOLLO_BOOTSTRAP_EAGER_LOAD_ENABLED); + } + + @Override + public Boolean getOverrideSystemProperties() { + return (Boolean) map.get(APOLLO_OVERRIDE_SYSTEM_PROPERTIES); + } + + @Override + public String getCacheDir() { + return map.get(APOLLO_CACHE_DIR).toString(); + } + + @Override + public String getCluster() { + return map.get( + APOLLO_CLUSTER).toString(); + } + + @Override + public String getConfigService() { + return map.get(APOLLO_CONFIG_SERVICE).toString(); + } + + @Override + public String getClientMonitorExternalForm() { + return map.get(APOLLO_CLIENT_MONITOR_EXTERNAL_TYPE).toString(); + } + + @Override + public Boolean getClientMonitorEnabled() { + return (Boolean) map.get(APOLLO_CLIENT_MONITOR_ENABLED); + } + + @Override + public Boolean getClientMonitorJmxEnabled() { + return (Boolean) map.get(APOLLO_CLIENT_MONITOR_JMX_ENABLED); + } + + @Override + public long getClientMonitorExternalExportPeriod() { + return (Long) map.get(APOLLO_CLIENT_MONITOR_EXTERNAL_EXPORT_PERIOD); + } + + @Override + public String getMeta() { + return map.get(APOLLO_META).toString(); + } + + @Override + public Boolean getPropertyNamesCacheEnable() { + return (Boolean) map.get(APOLLO_PROPERTY_NAMES_CACHE_ENABLE); + } + + @Override + public Boolean getPropertyOrderEnable() { + return (Boolean) map.get(APOLLO_PROPERTY_ORDER_ENABLE); + } + + @Override + public String getMetaLatestFreshTime() { + return map.get(META_FRESH).toString(); + } + + @Override + public String getVersion() { + return map.get(VERSION).toString(); + } + + @Override + public String getEnv() { + return map.get(ENV).toString(); + } + + @Override + public String getAppId() { + return map.get(APP_ID).toString(); + } + +} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/internal/DefaultApolloThreadPoolCollector.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/internal/DefaultApolloThreadPoolCollector.java new file mode 100644 index 00000000..96312168 --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/internal/DefaultApolloThreadPoolCollector.java @@ -0,0 +1,259 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.collector.internal; + +import com.ctrip.framework.apollo.internals.AbstractConfig; +import com.ctrip.framework.apollo.internals.AbstractConfigFile; +import com.ctrip.framework.apollo.internals.RemoteConfigRepository; +import com.ctrip.framework.apollo.monitor.api.ApolloThreadPoolMonitorApi; +import com.ctrip.framework.apollo.monitor.internal.collector.AbstractMetricsCollector; +import com.ctrip.framework.apollo.monitor.internal.model.GaugeModel; +import com.ctrip.framework.apollo.monitor.internal.model.MetricsEvent; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.ThreadPoolExecutor; + +/** + * @author Rawven + */ +public class DefaultApolloThreadPoolCollector extends AbstractMetricsCollector implements + ApolloThreadPoolMonitorApi { + + public static final String THREAD_POOL_METRICS = "ThreadPoolMetrics"; + public static final String[] THREAD_POOL_PARAMS = new String[]{"ThreadPoolName", + "activeTaskCount", "queueSize", + "completedTaskCount", + "poolSize", "totalTaskCount", "corePoolSize", "maximumPoolSize", "largestPoolSize", + "queueCapacity", "queueRemainingCapacity", "currentLoad"}; + + private final ScheduledThreadPoolExecutor remoteConfigRepositoryExecutorService; + private final ThreadPoolExecutor abstractConfigExecutorService; + private final ThreadPoolExecutor abstractConfigFileExecutorService; + + public DefaultApolloThreadPoolCollector( + ScheduledExecutorService remoteConfigRepositoryExecutorService, + ExecutorService abstractConfigExecutorService, + ExecutorService abstractConfigFileExecutorService) { + super(THREAD_POOL_METRICS, "Nop"); + this.remoteConfigRepositoryExecutorService = (ScheduledThreadPoolExecutor) remoteConfigRepositoryExecutorService; + this.abstractConfigExecutorService = (ThreadPoolExecutor) abstractConfigExecutorService; + this.abstractConfigFileExecutorService = (ThreadPoolExecutor) abstractConfigFileExecutorService; + } + + @Override + public void collect0(MetricsEvent event) { + // do nothing + return; + } + + @Override + public void export0() { + exportThreadPoolMetrics(abstractConfigExecutorService, + AbstractConfig.class.getSimpleName()); + exportThreadPoolMetrics(abstractConfigFileExecutorService, + AbstractConfigFile.class.getSimpleName()); + exportThreadPoolMetrics(remoteConfigRepositoryExecutorService, + RemoteConfigRepository.class.getSimpleName()); + } + + @Override + public boolean isSamplesUpdated() { + // memory status special + return true; + } + + + @SuppressWarnings("unchecked") + public void exportThreadPoolMetrics(ThreadPoolExecutor executor, + String name) { + List metrics = Arrays.asList((double) executor.getActiveCount(), + (double) executor.getQueue().size(), + (double) executor.getCompletedTaskCount(), (double) executor.getPoolSize(), + (double) executor.getTaskCount(), (double) executor.getCorePoolSize(), + (double) executor.getMaximumPoolSize(), (double) executor.getLargestPoolSize(), + (double) (executor.getQueue().remainingCapacity() + executor.getQueue().size()), + (double) executor.getQueue().remainingCapacity(), + (double) executor.getPoolSize() / executor.getMaximumPoolSize()); + for (int i = 0; i < metrics.size(); i++) { + if (!gaugeSamples.containsKey(name + THREAD_POOL_PARAMS[i + 1])) { + gaugeSamples.put(name + THREAD_POOL_PARAMS[i + 1], + GaugeModel.builder().putTag(THREAD_POOL_PARAMS[0], name) + .name(THREAD_POOL_PARAMS[i + 1]) + .value(0).apply(GaugeModel.DOUBLE_CONVERTER).build()); + } + gaugeSamples.get(name + THREAD_POOL_PARAMS[i + 1]).updateValue(metrics.get(i)); + } + } + + + @Override + public int getRemoteConfigRepositoryThreadPoolActiveCount() { + return remoteConfigRepositoryExecutorService.getActiveCount(); + } + + @Override + public int getRemoteConfigRepositoryThreadPoolQueueSize() { + return remoteConfigRepositoryExecutorService.getQueue().size(); + } + + @Override + public int getRemoteConfigRepositoryThreadPoolCorePoolSize() { + return remoteConfigRepositoryExecutorService.getCorePoolSize(); + } + + @Override + public int getRemoteConfigRepositoryThreadPoolMaximumPoolSize() { + return remoteConfigRepositoryExecutorService.getMaximumPoolSize(); + } + + @Override + public int getRemoteConfigRepositoryThreadPoolPoolSize() { + return remoteConfigRepositoryExecutorService.getPoolSize(); + } + + @Override + public long getRemoteConfigRepositoryThreadPoolTaskCount() { + return remoteConfigRepositoryExecutorService.getTaskCount(); + } + + @Override + public long getRemoteConfigRepositoryThreadPoolCompletedTaskCount() { + return remoteConfigRepositoryExecutorService.getCompletedTaskCount(); + } + + @Override + public int getRemoteConfigRepositoryThreadPoolLargestPoolSize() { + return remoteConfigRepositoryExecutorService.getLargestPoolSize(); + } + + @Override + public int getRemoteConfigRepositoryThreadPoolRemainingCapacity() { + return remoteConfigRepositoryExecutorService.getQueue().remainingCapacity(); + } + + @Override + public double getRemoteConfigRepositoryThreadPoolCurrentLoad() { + return (double) remoteConfigRepositoryExecutorService.getPoolSize() + / remoteConfigRepositoryExecutorService.getMaximumPoolSize(); + } + + @Override + public int getAbstractConfigThreadPoolActiveCount() { + return abstractConfigExecutorService.getActiveCount(); + } + + @Override + public int getAbstractConfigThreadPoolQueueSize() { + return abstractConfigExecutorService.getQueue().size(); + } + + @Override + public int getAbstractConfigThreadPoolCorePoolSize() { + return abstractConfigExecutorService.getCorePoolSize(); + } + + @Override + public int getAbstractConfigThreadPoolMaximumPoolSize() { + return abstractConfigExecutorService.getMaximumPoolSize(); + } + + @Override + public int getAbstractConfigThreadPoolPoolSize() { + return abstractConfigExecutorService.getPoolSize(); + } + + @Override + public long getAbstractConfigThreadPoolTaskCount() { + return abstractConfigExecutorService.getTaskCount(); + } + + @Override + public long getAbstractConfigThreadPoolCompletedTaskCount() { + return abstractConfigExecutorService.getCompletedTaskCount(); + } + + @Override + public int getAbstractConfigThreadPoolLargestPoolSize() { + return abstractConfigExecutorService.getLargestPoolSize(); + } + + @Override + public int getAbstractConfigThreadPoolRemainingCapacity() { + return abstractConfigExecutorService.getQueue().remainingCapacity(); + } + + @Override + public double getAbstractConfigThreadPoolCurrentLoad() { + return (double) abstractConfigExecutorService.getPoolSize() + / abstractConfigExecutorService.getMaximumPoolSize(); + } + + @Override + public int getAbstractConfigFileThreadPoolActiveCount() { + return abstractConfigFileExecutorService.getActiveCount(); + } + + @Override + public int getAbstractConfigFileThreadPoolQueueSize() { + return abstractConfigFileExecutorService.getQueue().size(); + } + + @Override + public int getAbstractConfigFileThreadPoolCorePoolSize() { + return abstractConfigFileExecutorService.getCorePoolSize(); + } + + @Override + public int getAbstractConfigFileThreadPoolMaximumPoolSize() { + return abstractConfigFileExecutorService.getMaximumPoolSize(); + } + + @Override + public int getAbstractConfigFileThreadPoolPoolSize() { + return abstractConfigFileExecutorService.getPoolSize(); + } + + @Override + public long getAbstractConfigFileThreadPoolTaskCount() { + return abstractConfigFileExecutorService.getTaskCount(); + } + + @Override + public long getAbstractConfigFileThreadPoolCompletedTaskCount() { + return abstractConfigFileExecutorService.getCompletedTaskCount(); + } + + @Override + public int getAbstractConfigFileThreadPoolLargestPoolSize() { + return abstractConfigFileExecutorService.getLargestPoolSize(); + } + + @Override + public int getAbstractConfigFileThreadPoolRemainingCapacity() { + return abstractConfigFileExecutorService.getQueue().remainingCapacity(); + } + + @Override + public double getAbstractConfigFileThreadPoolCurrentLoad() { + return (double) abstractConfigFileExecutorService.getPoolSize() + / abstractConfigFileExecutorService.getMaximumPoolSize(); + } + +} \ No newline at end of file diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/internal/DefaultMetricsCollectorManager.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/internal/DefaultMetricsCollectorManager.java new file mode 100644 index 00000000..972b4da0 --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/internal/DefaultMetricsCollectorManager.java @@ -0,0 +1,42 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.collector.internal; + +import com.ctrip.framework.apollo.monitor.internal.collector.MetricsCollector; +import com.ctrip.framework.apollo.monitor.internal.collector.MetricsCollectorManager; +import java.util.List; + +/** + * @author Rawven + */ +public class DefaultMetricsCollectorManager implements MetricsCollectorManager { + + private List collectors; + + public DefaultMetricsCollectorManager() { + } + + @Override + public List getCollectors() { + return collectors; + } + + public void setCollectors(List collectors) { + this.collectors = collectors; + } + +} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractMetricsExporter.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractMetricsExporter.java new file mode 100644 index 00000000..0f6e27ff --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractMetricsExporter.java @@ -0,0 +1,112 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.exporter; + +import com.ctrip.framework.apollo.core.utils.ApolloThreadFactory; +import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory; +import com.ctrip.framework.apollo.monitor.internal.collector.MetricsCollector; +import com.ctrip.framework.apollo.monitor.internal.model.CounterModel; +import com.ctrip.framework.apollo.monitor.internal.model.GaugeModel; +import com.ctrip.framework.apollo.monitor.internal.model.MetricsModel; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import org.slf4j.Logger; + +/** + * General framework for access monitoring systems + *

+ * 作者:Rawven + */ +public abstract class AbstractMetricsExporter implements MetricsExporter { + + protected static final Logger log = DeferredLoggerFactory.getLogger( + AbstractMetricsExporter.class); + protected static final ScheduledExecutorService m_executorService; + private static final long INITIAL_DELAY = 5L; + private static final int THREAD_POOL_SIZE = 1; + + static { + m_executorService = Executors.newScheduledThreadPool(THREAD_POOL_SIZE, + ApolloThreadFactory.create("MetricsReporter", true)); + } + + protected List collectors; + + @Override + public void init(List collectors, long collectPeriod) { + log.info("Initializing metrics exporter with {} collectors and collect period of {} seconds.", + collectors.size(), collectPeriod); + doInit(); + this.collectors = collectors; + initScheduleMetricsCollectSync(collectPeriod); + log.info("Metrics collection scheduled with a period of {} seconds.", collectPeriod); + } + + protected abstract void doInit(); + + private void initScheduleMetricsCollectSync(long collectPeriod) { + m_executorService.scheduleAtFixedRate(() -> { + try { + updateMetricsData(); + } catch (Throwable ex) { + log.error("Error updating metrics data", ex); + } + }, INITIAL_DELAY, collectPeriod, TimeUnit.SECONDS); + } + + protected void updateMetricsData() { + log.debug("Start to update metrics data job"); + collectors.forEach(collector -> { + if (collector.isSamplesUpdated()) { + log.debug("Collector {} has updated samples.", collector.name()); + collector.export().forEach(this::registerSample); + } + }); + } + + protected void registerSample(MetricsModel sample) { + try { + switch (sample.getType()) { + case GAUGE: + registerGaugeSample((GaugeModel) sample); + break; + case COUNTER: + registerCounterSample((CounterModel) sample); + break; + default: + log.warn("Unsupported sample type: {}", sample.getType()); + break; + } + } catch (Exception e) { + log.error("Register sample error", e); + } + } + + protected String[][] getTags(MetricsModel sample) { + Map tags = sample.getTags(); + if (tags == null || tags.isEmpty()) { + return new String[][]{new String[0], new String[0]}; + } + String[] labelNames = tags.keySet().toArray(new String[0]); + String[] labelValues = tags.values().toArray(new String[0]); + return new String[][]{labelNames, labelValues}; + } + +} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/MetricsExporter.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/MetricsExporter.java new file mode 100644 index 00000000..da9c64f9 --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/MetricsExporter.java @@ -0,0 +1,61 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.exporter; + +import com.ctrip.framework.apollo.core.spi.Ordered; +import com.ctrip.framework.apollo.monitor.internal.collector.MetricsCollector; +import com.ctrip.framework.apollo.monitor.internal.model.CounterModel; +import com.ctrip.framework.apollo.monitor.internal.model.GaugeModel; +import java.util.List; + +/** + * @author Rawven + */ +public interface MetricsExporter extends Ordered { + + /** + * init method + */ + void init(List collectors, long collectPeriod); + + /** + * is support + * + * @param form form + */ + boolean isSupport(String form); + + /** + * used to register Counter type metrics + */ + void registerCounterSample(CounterModel sample); + + /** + * used to register Gauge type metrics + */ + void registerGaugeSample(GaugeModel sample); + + /** + * result of the collect metrics + */ + String response(); + + @Override + default int getOrder() { + return 0; + } +} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/MetricsExporterFactory.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/MetricsExporterFactory.java new file mode 100644 index 00000000..178c5f27 --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/MetricsExporterFactory.java @@ -0,0 +1,28 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.exporter; + +import com.ctrip.framework.apollo.monitor.internal.collector.MetricsCollector; +import java.util.List; + +/** + * @author Rawven + */ +public interface MetricsExporterFactory { + + MetricsExporter getMetricsReporter(List collectors); +} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/internals/DefaultMetricsExporterFactory.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/internals/DefaultMetricsExporterFactory.java new file mode 100644 index 00000000..5a0279b1 --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/internals/DefaultMetricsExporterFactory.java @@ -0,0 +1,77 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.exporter.internals; + +import static com.ctrip.framework.apollo.monitor.internal.MonitorConstant.MBEAN_NAME; + +import com.ctrip.framework.apollo.build.ApolloInjector; +import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory; +import com.ctrip.framework.apollo.exceptions.ApolloConfigException; +import com.ctrip.framework.apollo.monitor.internal.collector.MetricsCollector; +import com.ctrip.framework.apollo.monitor.internal.collector.internal.DefaultMetricsCollectorManager; +import com.ctrip.framework.apollo.monitor.internal.exporter.MetricsExporter; +import com.ctrip.framework.apollo.monitor.internal.exporter.MetricsExporterFactory; +import com.ctrip.framework.apollo.monitor.internal.util.JMXUtil; +import com.ctrip.framework.apollo.tracer.Tracer; +import com.ctrip.framework.apollo.util.ConfigUtil; +import com.ctrip.framework.foundation.internals.ServiceBootstrap; +import java.util.List; +import org.slf4j.Logger; + +public class DefaultMetricsExporterFactory implements MetricsExporterFactory { + + private static final Logger logger = DeferredLoggerFactory.getLogger( + DefaultMetricsCollectorManager.class); + private final ConfigUtil m_configUtil; + + public DefaultMetricsExporterFactory() { + m_configUtil = ApolloInjector.getInstance(ConfigUtil.class); + } + + @Override + public MetricsExporter getMetricsReporter(List collectors) { + //initialize reporter + if (m_configUtil.isClientMonitorJmxEnabled()) { + collectors.forEach(metricsCollector -> + JMXUtil.register(MBEAN_NAME + metricsCollector.name(), + metricsCollector)); + } + String externalSystemType = m_configUtil.getMonitorExternalType(); + MetricsExporter reporter = null; + if (externalSystemType != null) { + List metricsExporters = ServiceBootstrap.loadAllOrdered( + MetricsExporter.class); + for (MetricsExporter metricsExporter : metricsExporters) { + if (metricsExporter.isSupport(externalSystemType)) { + reporter = metricsExporter; + reporter.init(collectors, m_configUtil.getMonitorExternalExportPeriod()); + break; + } + } + if (reporter == null) { + String errorMessage = + "No matching exporter found with monitor-external-type " + externalSystemType; + ApolloConfigException exception = new ApolloConfigException(errorMessage); + logger.error( + "Error initializing exporter for external-type: {}. Please check if external-type is misspelled or the correct dependency is not introduced, such as apollo-plugin-client-prometheus", + externalSystemType, exception); + Tracer.logError(exception); + } + } + return reporter; + } +} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/CounterModel.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/CounterModel.java new file mode 100644 index 00000000..67d5c1ba --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/CounterModel.java @@ -0,0 +1,100 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.model; + +import com.ctrip.framework.apollo.monitor.internal.util.MeterType; +import java.util.HashMap; +import java.util.Map; + +/** + * @author Rawven + */ +public class CounterModel extends MetricsModel { + + private double nowValue; + private double increaseValue; + + public CounterModel(String name, double num) { + if (name == null || name.isEmpty()) { + throw new IllegalArgumentException("Name cannot be null or empty"); + } + if (Double.isNaN(num) || Double.isInfinite(num)) { + throw new IllegalArgumentException("Number must be a valid double"); + } + this.name = name; + this.nowValue = num; + this.increaseValue = num; + this.type = MeterType.COUNTER; + } + + public static CounterBuilder builder() { + return new CounterBuilder(); + } + + public void updateValue(double value) { + if (Double.isNaN(value) || Double.isInfinite(value)) { + throw new IllegalArgumentException("Value must be a valid double"); + } + increaseValue = value - nowValue; + nowValue = value; + } + + public Double getIncreaseValue() { + return increaseValue; + } + + public void setValue(Double value) { + if (value == null || Double.isNaN(value) || Double.isInfinite(value)) { + throw new IllegalArgumentException("Value must be a valid double"); + } + this.nowValue = value; + } + + public static class CounterBuilder { + + private final Map tags = new HashMap<>(); + private String name; + private double value; + + public CounterBuilder name(String name) { + if (name == null || name.isEmpty()) { + throw new IllegalArgumentException("Name cannot be null or empty"); + } + this.name = name; + return this; + } + + public CounterBuilder value(double value) { + if (Double.isNaN(value) || Double.isInfinite(value)) { + throw new IllegalArgumentException("Value must be a valid double"); + } + this.value = value; + return this; + } + + public CounterBuilder putTag(String key, String value) { + this.tags.put(key, value); + return this; + } + + public CounterModel build() { + CounterModel sample = new CounterModel(name, value); + sample.tags.putAll(tags); + return sample; + } + } +} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/GaugeModel.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/GaugeModel.java new file mode 100644 index 00000000..b7026012 --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/GaugeModel.java @@ -0,0 +1,98 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.model; + +import com.ctrip.framework.apollo.monitor.internal.util.MeterType; +import java.util.HashMap; +import java.util.Map; +import java.util.function.ToDoubleFunction; + +public class GaugeModel extends MetricsModel { + + public static final ToDoubleFunction INT_CONVERTER = v -> (int) v; + public static final ToDoubleFunction LONG_CONVERTER = v -> (long) v; + public static final ToDoubleFunction DOUBLE_CONVERTER = v -> (double) v; + + private T value; + private ToDoubleFunction apply; + + public GaugeModel(String name, T value, ToDoubleFunction apply) { + this.name = name; + this.value = value; + this.apply = apply; + this.type = MeterType.GAUGE; + } + + public static GaugeBuilder builder() { + return new GaugeBuilder<>(); + } + + public T getValue() { + return value; + } + + public void updateValue(T value) { + this.value = value; + } + + public ToDoubleFunction getApply() { + return this.apply; + } + + public void setApply(ToDoubleFunction apply) { + this.apply = apply; + } + + public double getApplyValue() { + return getApply().applyAsDouble(getValue()); + } + + public static class GaugeBuilder { + + private final Map tags = new HashMap<>(1); + private String name; + private T value; + private ToDoubleFunction apply; + + public GaugeBuilder name(String name) { + this.name = name; + return this; + } + + public GaugeBuilder value(T value) { + this.value = value; + return this; + } + + public GaugeBuilder apply(ToDoubleFunction apply) { + this.apply = apply; + return this; + } + + public GaugeBuilder putTag(String key, String value) { + this.tags.put(key, value); + return this; + } + + public GaugeModel build() { + GaugeModel sample = new GaugeModel<>(name, value, apply); + sample.tags.putAll(tags); + return sample; + } + } +} + diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/MetricsEvent.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/MetricsEvent.java new file mode 100644 index 00000000..f8c5db31 --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/MetricsEvent.java @@ -0,0 +1,102 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.model; + +import java.util.HashMap; +import java.util.Map; + +/** + * metrics event model + * + * @author Rawven + */ +public class MetricsEvent { + + private final String name; + private final String tag; + private final Map attachments; + + private MetricsEvent(Builder builder) { + this.name = builder.name; + this.attachments = builder.attachment; + this.tag = builder.tag; + } + + public static Builder builder() { + return new Builder(); + } + + public String getName() { + return name; + } + + @SuppressWarnings("unchecked") + public T getAttachmentValue(String key) { + Object value = attachments.get(key); + if (value == null) { + return null; + } + try { + return (T) value; + } catch (ClassCastException e) { + throw new IllegalArgumentException("Value for key " + key + " is not of expected type", e); + } + } + + public String getTag() { + return tag; + } + + @Override + public String toString() { + return "MetricsEvent{" + + "name='" + name + '\'' + + ", attachments=" + attachments + + ", tag='" + tag + '\'' + + '}'; + } + + public static class Builder { + + private final Map attachment = new HashMap<>(3); + private String name; + private String tag; + + public Builder withName(String name) { + this.name = name; + return this; + } + + public Builder putAttachment(String k, Object v) { + this.attachment.put(k, v); + return this; + } + + public Builder withTag(String tag) { + this.tag = tag; + return this; + } + + public void push() { + MetricsEventPusher.push(this.build()); + } + + public MetricsEvent build() { + return new MetricsEvent(this); + } + } +} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/MetricsEventPusher.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/MetricsEventPusher.java new file mode 100644 index 00000000..0334a863 --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/MetricsEventPusher.java @@ -0,0 +1,45 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.model; + +import com.ctrip.framework.apollo.build.ApolloInjector; +import com.ctrip.framework.apollo.monitor.internal.collector.MetricsCollector; +import com.ctrip.framework.apollo.monitor.internal.collector.MetricsCollectorManager; +import com.ctrip.framework.apollo.util.ConfigUtil; + +/** + * @author Rawven + */ +public abstract class MetricsEventPusher { + + private static final MetricsCollectorManager COLLECTOR_MANAGER = ApolloInjector.getInstance( + MetricsCollectorManager.class); + private static final ConfigUtil m_configUtil = ApolloInjector.getInstance(ConfigUtil.class); + + public static void push(MetricsEvent event) { + if (m_configUtil.isClientMonitorEnabled()) { + for (MetricsCollector collector : COLLECTOR_MANAGER.getCollectors()) { + if (collector.isSupport(event)) { + collector.collect(event); + return; + } + } + } + } +} + + diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/MetricsModel.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/MetricsModel.java new file mode 100644 index 00000000..e293ce6f --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/MetricsModel.java @@ -0,0 +1,48 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.model; + +import com.ctrip.framework.apollo.monitor.internal.util.MeterType; +import java.util.HashMap; +import java.util.Map; + +/** + * @author Rawven + */ +public class MetricsModel { + + protected final Map tags = new HashMap<>(); + protected String name; + protected MeterType type; + + public String getName() { + return "Apollo_Client_" + name; + } + + public void setName(String name) { + this.name = name; + } + + public MeterType getType() { + return type; + } + + public Map getTags() { + return tags; + } +} + diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/ClientMessageProducerManager.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/ClientMessageProducerManager.java new file mode 100644 index 00000000..9fc9290b --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/ClientMessageProducerManager.java @@ -0,0 +1,43 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.tracer; + +import com.ctrip.framework.apollo.internals.ConfigMonitorInitializer; +import com.ctrip.framework.apollo.tracer.spi.MessageProducer; +import com.ctrip.framework.apollo.tracer.spi.MessageProducerManager; + +/** + * @author Rawven + */ +public class ClientMessageProducerManager implements MessageProducerManager { + + private static MessageProducer producer; + + public ClientMessageProducerManager() { + producer = ConfigMonitorInitializer.initializeMessageProducerComposite(); + } + + @Override + public MessageProducer getProducer() { + return producer; + } + + @Override + public int getOrder() { + return -1; + } +} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/MessageProducerComposite.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/MessageProducerComposite.java new file mode 100644 index 00000000..91a0db6b --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/MessageProducerComposite.java @@ -0,0 +1,84 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.tracer; + +import com.ctrip.framework.apollo.tracer.internals.NullTransaction; +import com.ctrip.framework.apollo.tracer.spi.MessageProducer; +import com.ctrip.framework.apollo.tracer.spi.Transaction; +import java.util.List; +import java.util.Objects; + +/** + * message producer composite + * + * @author Rawven + */ +public class MessageProducerComposite implements MessageProducer { + + public static final String ERROR_METRICS = "errorMetrics"; + public static final String THROWABLE = ERROR_METRICS + ".throwable"; + public static final String APOLLO_CLIENT_CONFIGCHANGES = "Apollo.Client.ConfigChanges"; + public static final String APOLLO_CONFIG_EXCEPTION = "ApolloConfigException"; + public static final String APOLLO_META_SERVICE = "Apollo.MetaService"; + public static final String APOLLO_CONFIG_SERVICES = "Apollo.Config.Services"; + public static final String APOLLO_CLIENT_VERSION = "Apollo.Client.Version"; + public static final String APOLLO_CONFIGSERVICE = "Apollo.ConfigService"; + public static final String APOLLO_CLIENT_CONFIGS = "Apollo.Client.Configs."; + public static final String APOLLO_CLIENT_CONFIGMETA = "Apollo.Client.ConfigMeta"; + public static final String HELP_STR = "periodicRefresh: "; + private static final NullTransaction NULL_TRANSACTION = new NullTransaction(); + private List producers; + + public MessageProducerComposite(List producers) { + this.producers = producers; + } + + + @Override + public void logError(Throwable cause) { + producers.forEach(producer -> producer.logError(cause)); + } + + @Override + public void logError(String message, Throwable cause) { + producers.forEach(producer -> producer.logError(message, cause)); + } + + @Override + public void logEvent(String type, String name) { + producers.forEach(producer -> producer.logEvent(type, name)); + } + + @Override + public void logEvent(String type, String name, String status, + String nameValuePairs) { + producers.forEach(producer -> producer.logEvent(type, name, status, nameValuePairs)); + } + + @Override + public Transaction newTransaction(String type, String name) { + return producers.stream() + .map(producer -> producer.newTransaction(type, name)) + .filter(Objects::nonNull) + .findFirst() + .orElse(NULL_TRANSACTION); + } + + public List getProducers() { + return producers; + } +} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/MonitorMessageProducer.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/MonitorMessageProducer.java new file mode 100644 index 00000000..83625f20 --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/MonitorMessageProducer.java @@ -0,0 +1,169 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.tracer; + +import static com.ctrip.framework.apollo.monitor.internal.MonitorConstant.NAMESPACE; +import static com.ctrip.framework.apollo.monitor.internal.MonitorConstant.TIMESTAMP; +import static com.ctrip.framework.apollo.monitor.internal.collector.internal.DefaultApolloNamespaceCollector.DATE_FORMATTER; +import static com.ctrip.framework.apollo.monitor.internal.collector.internal.DefaultApolloNamespaceCollector.NAMESPACE_LATEST_UPDATE_TIME; +import static com.ctrip.framework.apollo.monitor.internal.collector.internal.DefaultApolloNamespaceCollector.NAMESPACE_MONITOR; +import static com.ctrip.framework.apollo.monitor.internal.collector.internal.DefaultApolloNamespaceCollector.NAMESPACE_RELEASE_KEY; +import static com.ctrip.framework.apollo.monitor.internal.collector.internal.DefaultApolloRunningParamsCollector.CONFIG_SERVICE_URL; +import static com.ctrip.framework.apollo.monitor.internal.collector.internal.DefaultApolloRunningParamsCollector.META_FRESH; +import static com.ctrip.framework.apollo.monitor.internal.collector.internal.DefaultApolloRunningParamsCollector.RUNNING_PARAMS; +import static com.ctrip.framework.apollo.monitor.internal.collector.internal.DefaultApolloRunningParamsCollector.VERSION; +import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_CLIENT_CONFIGCHANGES; +import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_CLIENT_CONFIGMETA; +import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_CLIENT_CONFIGS; +import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_CLIENT_VERSION; +import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_CONFIGSERVICE; +import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_CONFIG_EXCEPTION; +import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_CONFIG_SERVICES; +import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_META_SERVICE; +import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.ERROR_METRICS; +import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.HELP_STR; +import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.THROWABLE; + +import com.ctrip.framework.apollo.exceptions.ApolloConfigException; +import com.ctrip.framework.apollo.monitor.internal.model.MetricsEvent; +import com.ctrip.framework.apollo.tracer.spi.MessageProducer; +import com.ctrip.framework.apollo.tracer.spi.Transaction; +import java.time.Instant; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +/** + * metrics message producer + * + * @author Rawven + */ +public class MonitorMessageProducer implements MessageProducer { + + public static final List TAGS = Collections.unmodifiableList( + Arrays.asList( + APOLLO_CLIENT_CONFIGCHANGES, + APOLLO_CONFIG_EXCEPTION, + APOLLO_META_SERVICE, + APOLLO_CONFIG_SERVICES, + APOLLO_CLIENT_VERSION, + APOLLO_CONFIGSERVICE, + APOLLO_CLIENT_CONFIGMETA + ) + ); + + @Override + public void logError(Throwable cause) { + MetricsEvent.builder().withName(ERROR_METRICS) + .withTag(ERROR_METRICS) + .putAttachment(THROWABLE, cause) + .push(); + } + + @Override + public void logError(String message, Throwable cause) { + MetricsEvent.builder().withName(ERROR_METRICS) + .withTag(ERROR_METRICS) + .putAttachment(THROWABLE, cause).push(); + } + + @Override + public void logEvent(String type, String name) { + if (TAGS.contains(type)) { + handleTaggedEvent(type, name); + } else if (type.startsWith(APOLLO_CLIENT_CONFIGS)) { + handleClientConfigEvent(type, name); + } + } + + private void handleTaggedEvent(String type, String name) { + String namespace; + switch (type) { + case APOLLO_CONFIGSERVICE: { + name = name.substring(HELP_STR.length()); + } + case APOLLO_CLIENT_CONFIGCHANGES: { + namespace = name; + MetricsEvent.builder() + .withName(NAMESPACE_LATEST_UPDATE_TIME) + .putAttachment(NAMESPACE, namespace) + .putAttachment(TIMESTAMP, System.currentTimeMillis()) + .withTag(NAMESPACE_MONITOR) + .push(); + break; + } + case APOLLO_CONFIG_EXCEPTION: { + logError(new ApolloConfigException(name)); + break; + } + case APOLLO_META_SERVICE: { + MetricsEvent.builder() + .withName(META_FRESH) + .withTag(RUNNING_PARAMS) + .putAttachment(META_FRESH, + DATE_FORMATTER.format(Instant.ofEpochMilli(System.currentTimeMillis()))) + .push(); + break; + } + case APOLLO_CONFIG_SERVICES: { + MetricsEvent.builder() + .withName(CONFIG_SERVICE_URL) + .withTag(RUNNING_PARAMS) + .putAttachment(CONFIG_SERVICE_URL, name) + .push(); + break; + } + case APOLLO_CLIENT_VERSION: { + MetricsEvent.builder() + .withName(VERSION) + .withTag(RUNNING_PARAMS) + .putAttachment(VERSION, name) + .push(); + break; + } + case APOLLO_CLIENT_CONFIGMETA: + // 不需要收集 + break; + default: + break; + } + } + + private void handleClientConfigEvent(String type, String name) { + int len = APOLLO_CLIENT_CONFIGS.length(); + String namespace = type.substring(len); + String releaseKey = name; + MetricsEvent.builder() + .withName(NAMESPACE_RELEASE_KEY) + .withTag(NAMESPACE_MONITOR) + .putAttachment(NAMESPACE_RELEASE_KEY, releaseKey) + .putAttachment(NAMESPACE, namespace) + .push(); + } + + @Override + public void logEvent(String type, String name, String status, + String nameValuePairs) { + // + } + + @Override + public Transaction newTransaction(String type, String name) { + return null; + } + +} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/util/JMXUtil.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/util/JMXUtil.java new file mode 100644 index 00000000..cc34c68a --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/util/JMXUtil.java @@ -0,0 +1,58 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.util; + +import java.lang.management.ManagementFactory; +import javax.management.JMException; +import javax.management.MBeanServer; +import javax.management.ObjectName; + +/** + * @author Rawven + */ +public final class JMXUtil { + + public static MBeanServer mbeanServer; + + public static ObjectName register(String name, Object mbean) { + try { + ObjectName objectName = new ObjectName(name); + + if (mbeanServer == null) { + mbeanServer = ManagementFactory.getPlatformMBeanServer(); + } + + if (mbeanServer.isRegistered(objectName)) { + mbeanServer.unregisterMBean(objectName); + } + mbeanServer.registerMBean(mbean, objectName); + + return objectName; + } catch (JMException e) { + throw new IllegalArgumentException(name, e); + } + } + + public static void unregister(String name) { + try { + MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); + mbeanServer.unregisterMBean(new ObjectName(name)); + } catch (JMException e) { + throw new IllegalArgumentException(name, e); + } + } +} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/util/MeterType.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/util/MeterType.java new file mode 100644 index 00000000..f200e262 --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/util/MeterType.java @@ -0,0 +1,25 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.util; + +/** + * @author Rawven + */ +public enum MeterType { + COUNTER, + GAUGE +} \ No newline at end of file diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/boot/ApolloApplicationContextInitializer.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/boot/ApolloApplicationContextInitializer.java index 17890055..af3e347e 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/boot/ApolloApplicationContextInitializer.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/boot/ApolloApplicationContextInitializer.java @@ -93,7 +93,11 @@ public class ApolloApplicationContextInitializer implements ApolloClientSystemConsts.APOLLO_CONFIG_SERVICE, ApolloClientSystemConsts.APOLLO_PROPERTY_ORDER_ENABLE, ApolloClientSystemConsts.APOLLO_PROPERTY_NAMES_CACHE_ENABLE, - ApolloClientSystemConsts.APOLLO_OVERRIDE_SYSTEM_PROPERTIES}; + ApolloClientSystemConsts.APOLLO_OVERRIDE_SYSTEM_PROPERTIES, + ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_EXTERNAL_TYPE, + ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_ENABLED, + ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_EXTERNAL_EXPORT_PERIOD, + ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_JMX_ENABLED,}; private final ConfigPropertySourceFactory configPropertySourceFactory = SpringInjector .getInstance(ConfigPropertySourceFactory.class); @@ -132,6 +136,7 @@ protected void initialize(ConfigurableEnvironment environment) { } String namespaces = environment.getProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_NAMESPACES, ConfigConsts.NAMESPACE_APPLICATION); + System.setProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_NAMESPACES, namespaces); logger.debug("Apollo bootstrap namespaces: {}", namespaces); List namespaceList = NAMESPACE_SPLITTER.splitToList(namespaces); @@ -197,14 +202,14 @@ public void postProcessEnvironment(ConfigurableEnvironment configurableEnvironme initializeSystemProperty(configurableEnvironment); Boolean eagerLoadEnabled = configurableEnvironment.getProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_EAGER_LOAD_ENABLED, Boolean.class, false); - + System.setProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_EAGER_LOAD_ENABLED, String.valueOf(eagerLoadEnabled)); //EnvironmentPostProcessor should not be triggered if you don't want Apollo Loading before Logging System Initialization if (!eagerLoadEnabled) { return; } Boolean bootstrapEnabled = configurableEnvironment.getProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_ENABLED, Boolean.class, false); - + System.setProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_ENABLED, String.valueOf(bootstrapEnabled)); if (bootstrapEnabled) { DeferredLogger.enable(); initialize(configurableEnvironment); diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/util/ConfigUtil.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/util/ConfigUtil.java index 9b99a4bf..731c7513 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/util/ConfigUtil.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/util/ConfigUtil.java @@ -38,18 +38,21 @@ public class ConfigUtil { private static final Logger logger = LoggerFactory.getLogger(ConfigUtil.class); - + private final RateLimiter warnLogRateLimiter; /** * qps limit: discovery config service from meta *

* 1 times per second */ private int discoveryQPS = 1; - /** 1 second */ + /** + * 1 second + */ private int discoveryConnectTimeout = 1000; - /** 1 second */ + /** + * 1 second + */ private int discoveryReadTimeout = 1000; - private int refreshInterval = 5; private TimeUnit refreshIntervalTimeUnit = TimeUnit.MINUTES; private int connectTimeout = 1000; //1 second @@ -66,11 +69,14 @@ public class ConfigUtil { private TimeUnit configCacheExpireTimeUnit = TimeUnit.MINUTES;//1 minute private long longPollingInitialDelayInMills = 2000;//2 seconds private boolean autoUpdateInjectedSpringProperties = true; - private final RateLimiter warnLogRateLimiter; private boolean propertiesOrdered = false; private boolean propertyNamesCacheEnabled = false; private boolean propertyFileCacheEnabled = true; private boolean overrideSystemProperties = true; + private boolean isClientMonitorEnabled = false; + private boolean isClientMonitorJmxEnabled = false; + private String monitorExternalType = null; + private long monitorExternalExportPeriod = 10; public ConfigUtil() { warnLogRateLimiter = RateLimiter.create(0.017); // 1 warning log output per minute @@ -86,6 +92,23 @@ public ConfigUtil() { initPropertyNamesCacheEnabled(); initPropertyFileCacheEnabled(); initOverrideSystemProperties(); + initMonitorExternalType(); + initMonitorExternalCollectPeriod(); + initClientMonitorEnabled(); + initClientMonitorJmxEnabled(); + } + + + static Integer getCustomizedIntegerValue(String systemKey) { + String customizedValue = System.getProperty(systemKey); + if (!Strings.isNullOrEmpty(customizedValue)) { + try { + return Integer.parseInt(customizedValue); + } catch (Throwable ex) { + logger.error("Config for {} is invalid: {}", systemKey, customizedValue); + } + } + return null; } /** @@ -222,18 +245,6 @@ public TimeUnit getRefreshIntervalTimeUnit() { return refreshIntervalTimeUnit; } - static Integer getCustomizedIntegerValue(String systemKey) { - String customizedValue = System.getProperty(systemKey); - if (!Strings.isNullOrEmpty(customizedValue)) { - try { - return Integer.parseInt(customizedValue); - } catch (Throwable ex) { - logger.error("Config for {} is invalid: {}", systemKey, customizedValue); - } - } - return null; - } - private void initQPS() { { Integer value = getCustomizedIntegerValue("apollo.discoveryConnectTimeout"); @@ -340,7 +351,8 @@ private String getDeprecatedCustomizedCacheRoot() { } if (Strings.isNullOrEmpty(cacheRoot)) { // 2. Get from OS environment variable - cacheRoot = System.getenv(ApolloClientSystemConsts.DEPRECATED_APOLLO_CACHE_DIR_ENVIRONMENT_VARIABLES); + cacheRoot = System.getenv( + ApolloClientSystemConsts.DEPRECATED_APOLLO_CACHE_DIR_ENVIRONMENT_VARIABLES); if (!Strings.isNullOrEmpty(cacheRoot)) { DeprecatedPropertyNotifyUtil .warn(ApolloClientSystemConsts.DEPRECATED_APOLLO_CACHE_DIR_ENVIRONMENT_VARIABLES, @@ -349,7 +361,8 @@ private String getDeprecatedCustomizedCacheRoot() { } if (Strings.isNullOrEmpty(cacheRoot)) { // 3. Get from server.properties - cacheRoot = Foundation.server().getProperty(ApolloClientSystemConsts.DEPRECATED_APOLLO_CACHE_DIR, null); + cacheRoot = Foundation.server() + .getProperty(ApolloClientSystemConsts.DEPRECATED_APOLLO_CACHE_DIR, null); if (!Strings.isNullOrEmpty(cacheRoot)) { DeprecatedPropertyNotifyUtil.warn(ApolloClientSystemConsts.DEPRECATED_APOLLO_CACHE_DIR, ApolloClientSystemConsts.APOLLO_CACHE_DIR); @@ -357,7 +370,8 @@ private String getDeprecatedCustomizedCacheRoot() { } if (Strings.isNullOrEmpty(cacheRoot)) { // 4. Get from app.properties - cacheRoot = Foundation.app().getProperty(ApolloClientSystemConsts.DEPRECATED_APOLLO_CACHE_DIR, null); + cacheRoot = Foundation.app() + .getProperty(ApolloClientSystemConsts.DEPRECATED_APOLLO_CACHE_DIR, null); if (!Strings.isNullOrEmpty(cacheRoot)) { DeprecatedPropertyNotifyUtil.warn(ApolloClientSystemConsts.DEPRECATED_APOLLO_CACHE_DIR, ApolloClientSystemConsts.APOLLO_CACHE_DIR); @@ -474,23 +488,85 @@ public boolean isOverrideSystemProperties() { } private void initPropertyNamesCacheEnabled() { - propertyNamesCacheEnabled = getPropertyBoolean(ApolloClientSystemConsts.APOLLO_PROPERTY_NAMES_CACHE_ENABLE, - ApolloClientSystemConsts.APOLLO_PROPERTY_NAMES_CACHE_ENABLE_ENVIRONMENT_VARIABLES, - propertyNamesCacheEnabled); + propertyNamesCacheEnabled = getPropertyBoolean( + ApolloClientSystemConsts.APOLLO_PROPERTY_NAMES_CACHE_ENABLE, + ApolloClientSystemConsts.APOLLO_PROPERTY_NAMES_CACHE_ENABLE_ENVIRONMENT_VARIABLES, + propertyNamesCacheEnabled); } private void initPropertyFileCacheEnabled() { propertyFileCacheEnabled = getPropertyBoolean(ApolloClientSystemConsts.APOLLO_CACHE_FILE_ENABLE, - ApolloClientSystemConsts.APOLLO_CACHE_FILE_ENABLE_ENVIRONMENT_VARIABLES, - propertyFileCacheEnabled); + ApolloClientSystemConsts.APOLLO_CACHE_FILE_ENABLE_ENVIRONMENT_VARIABLES, + propertyFileCacheEnabled); } private void initOverrideSystemProperties() { - overrideSystemProperties = getPropertyBoolean(ApolloClientSystemConsts.APOLLO_OVERRIDE_SYSTEM_PROPERTIES, - ApolloClientSystemConsts.APOLLO_OVERRIDE_SYSTEM_PROPERTIES, - overrideSystemProperties); + overrideSystemProperties = getPropertyBoolean( + ApolloClientSystemConsts.APOLLO_OVERRIDE_SYSTEM_PROPERTIES, + ApolloClientSystemConsts.APOLLO_OVERRIDE_SYSTEM_PROPERTIES, + overrideSystemProperties); } + private void initMonitorExternalType() { + monitorExternalType = System.getProperty(ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_EXTERNAL_TYPE); + if (Strings.isNullOrEmpty(monitorExternalType)) { + monitorExternalType = Foundation.app() + .getProperty(ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_EXTERNAL_TYPE, null); + } + } + + public String getMonitorExternalType() { + return monitorExternalType; + } + + private void initMonitorExternalCollectPeriod() { + String collectPeriod = System.getProperty( + ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_EXTERNAL_EXPORT_PERIOD); + if (Strings.isNullOrEmpty(collectPeriod)) { + collectPeriod = Foundation.app() + .getProperty(ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_EXTERNAL_EXPORT_PERIOD, null); + } + if (!Strings.isNullOrEmpty(collectPeriod)) { + try { + monitorExternalExportPeriod = Long.parseLong(collectPeriod); + } catch (Throwable ex) { + logger.error("Config for {} is invalid: {}", + ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_EXTERNAL_EXPORT_PERIOD, collectPeriod); + } + } + } + + public long getMonitorExternalExportPeriod() { + return monitorExternalExportPeriod; + } + + + private void initClientMonitorEnabled() { + String enabled = System.getProperty(ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_ENABLED); + if (enabled == null) { + enabled = Foundation.app() + .getProperty(ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_ENABLED, "false"); + } + isClientMonitorEnabled = Boolean.parseBoolean(enabled); + } + + public boolean isClientMonitorEnabled() { + return isClientMonitorEnabled; + } + + private void initClientMonitorJmxEnabled() { + String enabled = System.getProperty(ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_JMX_ENABLED); + if (enabled == null) { + enabled = Foundation.app() + .getProperty(ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_JMX_ENABLED, "false"); + } + isClientMonitorJmxEnabled = Boolean.parseBoolean(enabled); + } + public boolean isClientMonitorJmxEnabled() { + return isClientMonitorJmxEnabled; + } + + private boolean getPropertyBoolean(String propertyName, String envName, boolean defaultVal) { String enablePropertyNamesCache = System.getProperty(propertyName); if (Strings.isNullOrEmpty(enablePropertyNamesCache)) { @@ -504,7 +580,7 @@ private boolean getPropertyBoolean(String propertyName, String envName, boolean return Boolean.parseBoolean(enablePropertyNamesCache); } catch (Throwable ex) { logger.warn("Config for {} is invalid: {}, set default value: {}", - propertyName, enablePropertyNamesCache, defaultVal); + propertyName, enablePropertyNamesCache, defaultVal); } } return defaultVal; diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/util/ExceptionUtil.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/util/ExceptionUtil.java index 28df3f5f..875246a1 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/util/ExceptionUtil.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/util/ExceptionUtil.java @@ -64,4 +64,4 @@ public static String getDetailMessage(Throwable ex) { return builder.toString(); } -} +} \ No newline at end of file diff --git a/apollo-client/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/apollo-client/src/main/resources/META-INF/additional-spring-configuration-metadata.json index a14b1d03..cb9deb74 100644 --- a/apollo-client/src/main/resources/META-INF/additional-spring-configuration-metadata.json +++ b/apollo-client/src/main/resources/META-INF/additional-spring-configuration-metadata.json @@ -63,6 +63,35 @@ "description": "apollo config service address. if it's configured apollo client will not refresh config services from remote meta service.", "defaultValue": "" }, + { + "name": "apollo.client.monitor.enabled", + "type": "java.lang.Boolean", + "sourceType": "com.ctrip.framework.apollo.core.ApolloClientSystemConsts", + "description": "apollo client monitor enabled.", + "defaultValue": false + }, + { + "name": "apollo.client.monitor.jmx.enabled", + "type": "java.lang.Boolean", + "sourceType": "com.ctrip.framework.apollo.core.ApolloClientSystemConsts", + "description": "apollo client monitor jmx enabled.", + "defaultValue": false + }, + { + "name": "apollo.client.monitor.external.type", + "type": "java.lang.String", + "sourceType": "com.ctrip.framework.apollo.core.ApolloClientSystemConsts", + "description": "apollo client monitor external monitoring system type.", + "defaultValue": "" + }, + + { + "name": "apollo.client.monitor.external.export-period", + "type": "java.lang.String", + "sourceType": "com.ctrip.framework.apollo.core.ApolloClientSystemConsts", + "description": "apollo client monitor external metrics export period.", + "defaultValue": "" + }, { "name": "apollo.meta", "type": "java.net.URI", diff --git a/apollo-client/src/main/resources/META-INF/services/com.ctrip.framework.apollo.tracer.spi.MessageProducerManager b/apollo-client/src/main/resources/META-INF/services/com.ctrip.framework.apollo.tracer.spi.MessageProducerManager new file mode 100644 index 00000000..fbae9d1c --- /dev/null +++ b/apollo-client/src/main/resources/META-INF/services/com.ctrip.framework.apollo.tracer.spi.MessageProducerManager @@ -0,0 +1 @@ +com.ctrip.framework.apollo.monitor.internal.tracer.ClientMessageProducerManager \ No newline at end of file diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/collector/AbstractApolloMetricsCollectorTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/collector/AbstractApolloMetricsCollectorTest.java new file mode 100644 index 00000000..4a3da10c --- /dev/null +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/collector/AbstractApolloMetricsCollectorTest.java @@ -0,0 +1,90 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.collector; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.when; + +import com.ctrip.framework.apollo.monitor.internal.model.MetricsEvent; +import com.ctrip.framework.apollo.monitor.internal.model.MetricsModel; +import java.util.List; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +public class AbstractApolloMetricsCollectorTest { + + private AbstractMetricsCollector metricsCollector; + + @Before + public void setUp() { + metricsCollector = new AbstractMetricsCollector("mock","tag1", "tag2") { + @Override + public String name() { + return "MockMetricsCollector"; + } + + @Override + public void collect0(MetricsEvent event) { + // 模拟实现 + } + + @Override + public void export0() { + // 模拟实现 + } + }; + } + + @Test + public void testConstructorInitialization() { + assertNotNull(metricsCollector); + } + + @Test + public void testIsSupport() { + MetricsEvent event = Mockito.mock(MetricsEvent.class); + + when(event.getTag()).thenReturn("tag1"); + assertTrue(metricsCollector.isSupport(event)); + + when(event.getTag()).thenReturn("tag3"); + assertFalse(metricsCollector.isSupport(event)); + } + + @Test + public void testCollect() { + MetricsEvent event = Mockito.mock(MetricsEvent.class); + metricsCollector.collect(event); + assertTrue(metricsCollector.isSamplesUpdated()); + } + + @Test + public void testIsSamplesUpdated() { + MetricsEvent event = Mockito.mock(MetricsEvent.class); + metricsCollector.collect(event); + assertTrue(metricsCollector.isSamplesUpdated()); + assertFalse(metricsCollector.isSamplesUpdated()); + } + + @Test + public void testExport() { + List samples = metricsCollector.export(); + assertNotNull(samples); + } +} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractApolloMetricsExporterTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractApolloMetricsExporterTest.java new file mode 100644 index 00000000..e7122eb4 --- /dev/null +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractApolloMetricsExporterTest.java @@ -0,0 +1,123 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.exporter; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.ctrip.framework.apollo.monitor.internal.collector.MetricsCollector; +import com.ctrip.framework.apollo.monitor.internal.model.CounterModel; +import com.ctrip.framework.apollo.monitor.internal.model.GaugeModel; +import com.ctrip.framework.apollo.monitor.internal.model.MetricsModel; +import com.ctrip.framework.apollo.monitor.internal.util.MeterType; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +@RunWith(MockitoJUnitRunner.class) +public class AbstractApolloMetricsExporterTest { + + @Mock + private MetricsCollector mockCollector; + + @InjectMocks + private final AbstractMetricsExporter reporter = new AbstractMetricsExporter() { + @Override + protected void doInit() { + // Do nothing for test purposes + } + + @Override + public void registerGaugeSample(GaugeModel sample) { + // Mock implementation for test purposes + } + + @Override + public String response() { + return "test"; + } + + @Override + public boolean isSupport(String form) { + return "mock".equals(form); + } + + @Override + public void registerCounterSample(CounterModel sample) { + // Mock implementation for test purposes + } + }; + + + + @Test + public void testInit() { + List collectors = Collections.singletonList(mockCollector); + long collectPeriod = 10L; + + reporter.init(collectors, collectPeriod); + + assertNotNull(reporter.m_executorService); + } + @Test + public void testIsSupport(){ + assertTrue(reporter.isSupport("mock")); + assertFalse(reporter.isSupport("mock1")); + } + + @Test + public void testUpdateMetricsData() { + MetricsModel mockSample = mock(MetricsModel.class); + when(mockSample.getType()).thenReturn(MeterType.GAUGE); + when(mockCollector.isSamplesUpdated()).thenReturn(true); + when(mockCollector.export()).thenReturn(Collections.singletonList(mockSample)); + + reporter.init(Collections.singletonList(mockCollector), 10L); + reporter.updateMetricsData(); + + verify(mockCollector, times(1)).isSamplesUpdated(); + verify(mockCollector, times(1)).export(); + verify(mockSample, times(1)).getType(); + } + + @Test + public void testGetTags() { + MetricsModel sample = mock(MetricsModel.class); + Map tags = new HashMap<>(); + tags.put("key1", "value1"); + tags.put("key2", "value2"); + + when(sample.getTags()).thenReturn(tags); + + String[][] result = reporter.getTags(sample); + + assertArrayEquals(new String[]{"key1", "key2"}, result[0]); + assertArrayEquals(new String[]{"value1", "value2"}, result[1]); + } +} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/DefaultApolloMetricsExporterFactoryTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/DefaultApolloMetricsExporterFactoryTest.java new file mode 100644 index 00000000..ca4e807e --- /dev/null +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/DefaultApolloMetricsExporterFactoryTest.java @@ -0,0 +1,60 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.exporter; + +import static org.junit.Assert.assertNull; + +import com.ctrip.framework.apollo.build.MockInjector; +import com.ctrip.framework.apollo.core.ApolloClientSystemConsts; +import com.ctrip.framework.apollo.monitor.internal.collector.MetricsCollector; +import com.ctrip.framework.apollo.monitor.internal.exporter.internals.DefaultMetricsExporterFactory; +import com.ctrip.framework.apollo.util.ConfigUtil; +import java.util.ArrayList; +import java.util.List; +import org.junit.Test; + +public class DefaultApolloMetricsExporterFactoryTest { + + private DefaultMetricsExporterFactory defaultMetricsReporterFactory; + + public void init(String form, String period) { + if (form!=null){ + System.setProperty(ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_EXTERNAL_TYPE,form); + } + if (period!=null){ + System.setProperty(ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_EXTERNAL_EXPORT_PERIOD,period); + } + ConfigUtil mockConfigUtil = new ConfigUtil(); + defaultMetricsReporterFactory = new DefaultMetricsExporterFactory(); + MockInjector.setInstance(ConfigUtil.class, mockConfigUtil); + } + + @Test + public void testGetMetricsReporter_NoSupportedReporter() { + init("prometheus","300"); + List collectors = new ArrayList<>(); + assertNull(defaultMetricsReporterFactory.getMetricsReporter(collectors)); + } + + @Test + public void testGetMetricsReporter_NullForm() { + init(null,null); + List collectors = new ArrayList<>(); + MetricsExporter reporter = defaultMetricsReporterFactory.getMetricsReporter(collectors); + assertNull(reporter); + } +} diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/ApolloClientSystemConsts.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/core/ApolloClientSystemConsts.java index 0fa0550a..b28f7883 100644 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/ApolloClientSystemConsts.java +++ b/apollo-core/src/main/java/com/ctrip/framework/apollo/core/ApolloClientSystemConsts.java @@ -161,4 +161,24 @@ public class ApolloClientSystemConsts { * enable apollo overrideSystemProperties */ public static final String APOLLO_OVERRIDE_SYSTEM_PROPERTIES = "apollo.override-system-properties"; + + /** + * apollo client monitor enabled + */ + public static final String APOLLO_CLIENT_MONITOR_ENABLED = "apollo.client.monitor.enabled"; + + /** + * apollo client monitor jmx enabled + */ + public static final String APOLLO_CLIENT_MONITOR_JMX_ENABLED = "apollo.client.monitor.jmx.enabled"; + + /** + * apollo client monitor form {such as jmx,prometheus} + */ + public static final String APOLLO_CLIENT_MONITOR_EXTERNAL_TYPE = "apollo.client.monitor.external.type"; + + /** + * apollo client monitor collect period + */ + public static final String APOLLO_CLIENT_MONITOR_EXTERNAL_EXPORT_PERIOD = "apollo.client.monitor.external.export-period"; } diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/ConfigConsts.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/core/ConfigConsts.java index a6108dfb..19f33278 100644 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/ConfigConsts.java +++ b/apollo-core/src/main/java/com/ctrip/framework/apollo/core/ConfigConsts.java @@ -24,5 +24,6 @@ public interface ConfigConsts { String APOLLO_META_KEY = "apollo.meta"; String CONFIG_FILE_CONTENT_KEY = "content"; String NO_APPID_PLACEHOLDER = "ApolloNoAppIdPlaceHolder"; + String APOLLO_AUTO_UPDATE_INJECTED_SPRING_PROPERTIES = "ApolloAutoUpdateInjectedSpringProperties"; long NOTIFICATION_ID_PLACEHOLDER = -1; } diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/internals/DefaultMessageProducerManager.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/internals/DefaultMessageProducerManager.java index 2490abdb..53204d89 100644 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/internals/DefaultMessageProducerManager.java +++ b/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/internals/DefaultMessageProducerManager.java @@ -26,18 +26,18 @@ * @author Jason Song(song_s@ctrip.com) */ public class DefaultMessageProducerManager implements MessageProducerManager { - private static MessageProducer producer; + private static MessageProducer producer; - public DefaultMessageProducerManager() { - if (ClassLoaderUtil.isClassPresent(CatNames.CAT_CLASS)) { - producer = new CatMessageProducer(); - } else { - producer = new NullMessageProducerManager().getProducer(); + public DefaultMessageProducerManager() { + if (ClassLoaderUtil.isClassPresent(CatNames.CAT_CLASS)) { + producer = new CatMessageProducer(); + } else { + producer = new NullMessageProducerManager().getProducer(); + } } - } - @Override - public MessageProducer getProducer() { - return producer; - } + @Override + public MessageProducer getProducer() { + return producer; + } } diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/internals/cat/CatTransaction.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/internals/cat/CatTransaction.java index bccdb5e9..0251c6f8 100644 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/internals/cat/CatTransaction.java +++ b/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/internals/cat/CatTransaction.java @@ -50,4 +50,4 @@ public void addData(String key, Object value) { public void complete() { catTransaction.complete(); } -} +} \ No newline at end of file diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/spi/MessageProducer.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/spi/MessageProducer.java index 61eb8040..b556b8ab 100644 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/spi/MessageProducer.java +++ b/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/spi/MessageProducer.java @@ -16,10 +16,12 @@ */ package com.ctrip.framework.apollo.tracer.spi; +import com.ctrip.framework.apollo.core.spi.Ordered; + /** * @author Jason Song(song_s@ctrip.com) */ -public interface MessageProducer { +public interface MessageProducer extends Ordered { /** * Log an error. * @@ -59,4 +61,10 @@ public interface MessageProducer { * @param name transaction name */ Transaction newTransaction(String type, String name); + + + @Override + default int getOrder() { + return 0; + } } diff --git a/apollo-plugin/apollo-plugin-client-prometheus/pom.xml b/apollo-plugin/apollo-plugin-client-prometheus/pom.xml new file mode 100644 index 00000000..860c5f08 --- /dev/null +++ b/apollo-plugin/apollo-plugin-client-prometheus/pom.xml @@ -0,0 +1,46 @@ + + + + 4.0.0 + + apollo-plugin + com.ctrip.framework.apollo + ${revision} + ../pom.xml + + + apollo-plugin-client-prometheus + Apollo Plugin Prometheus + jar + + + + com.ctrip.framework.apollo + apollo-client + provided + + + io.prometheus + simpleclient_common + provided + + + + \ No newline at end of file diff --git a/apollo-plugin/apollo-plugin-client-prometheus/src/main/java/com/ctrip/framework/apollo/plugin/prometheus/PrometheusMetricExporter.java b/apollo-plugin/apollo-plugin-client-prometheus/src/main/java/com/ctrip/framework/apollo/plugin/prometheus/PrometheusMetricExporter.java new file mode 100644 index 00000000..76c921b5 --- /dev/null +++ b/apollo-plugin/apollo-plugin-client-prometheus/src/main/java/com/ctrip/framework/apollo/plugin/prometheus/PrometheusMetricExporter.java @@ -0,0 +1,106 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.plugin.prometheus; + +import com.ctrip.framework.apollo.monitor.internal.model.CounterModel; +import com.ctrip.framework.apollo.monitor.internal.model.GaugeModel; +import com.ctrip.framework.apollo.monitor.internal.exporter.AbstractMetricsExporter; +import com.ctrip.framework.apollo.monitor.internal.exporter.MetricsExporter; +import io.prometheus.client.Collector; +import io.prometheus.client.CollectorRegistry; +import io.prometheus.client.Counter; +import io.prometheus.client.Gauge; +import io.prometheus.client.exporter.common.TextFormat; +import java.io.IOException; +import java.io.StringWriter; +import java.util.HashMap; +import java.util.Map; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * @author Rawven + */ +public class PrometheusMetricExporter extends AbstractMetricsExporter implements MetricsExporter { + + private static final Logger logger = LoggerFactory.getLogger( + PrometheusMetricExporter.class); + private final CollectorRegistry registry; + private final Map map = new HashMap<>(); + private final String PROMETHEUS = "prometheus"; + + public PrometheusMetricExporter() { + this.registry = new CollectorRegistry(); + } + + @Override + public void doInit() { + + } + + @Override + public boolean isSupport(String form) { + return PROMETHEUS.equals(form); + } + + @Override + public void registerCounterSample(CounterModel sample) { + String[][] tags = getTags(sample); + Counter counter; + if (!map.containsKey(sample.getName())) { + counter = Counter.build() + .name(sample.getName()) + .help("apollo") + .labelNames(tags[0]) + .register(registry); + map.put(sample.getName(), counter); + } else { + counter = (Counter) map.get(sample.getName()); + } + counter.labels(tags[1]).inc(sample.getIncreaseValue()); + } + + @Override + public void registerGaugeSample(GaugeModel sample) { + String[][] tags = getTags(sample); + Gauge gauge; + if (!map.containsKey(sample.getName())) { + gauge = Gauge.build() + .name(sample.getName()) + .help("apollo") + .labelNames(tags[0]) + .register(registry); + map.put(sample.getName(), gauge); + } else { + gauge = (Gauge) map.get(sample.getName()); + } + gauge.labels(tags[1]).set(sample.getApplyValue()); + } + + + @Override + public String response() { + StringWriter writer = new StringWriter(); + try { + TextFormat.writeFormat(TextFormat.CONTENT_TYPE_OPENMETRICS_100, writer, + registry.metricFamilySamples()); + } catch (IOException e) { + logger.error("Write metrics to Prometheus format failed", e); + } + return writer.toString(); + } +} \ No newline at end of file diff --git a/apollo-plugin/apollo-plugin-client-prometheus/src/main/resources/META-INF/services/com.ctrip.framework.apollo.monitor.internal.exporter.MetricsExporter b/apollo-plugin/apollo-plugin-client-prometheus/src/main/resources/META-INF/services/com.ctrip.framework.apollo.monitor.internal.exporter.MetricsExporter new file mode 100644 index 00000000..51289143 --- /dev/null +++ b/apollo-plugin/apollo-plugin-client-prometheus/src/main/resources/META-INF/services/com.ctrip.framework.apollo.monitor.internal.exporter.MetricsExporter @@ -0,0 +1 @@ +com.ctrip.framework.apollo.plugin.prometheus.PrometheusMetricExporter \ No newline at end of file diff --git a/apollo-plugin/pom.xml b/apollo-plugin/pom.xml index 3a47b738..f0d1b00f 100644 --- a/apollo-plugin/pom.xml +++ b/apollo-plugin/pom.xml @@ -31,6 +31,7 @@ apollo-plugin-log4j2 + apollo-plugin-client-prometheus From ccadc303339d0fdbd1d67696c194af6a83e4fcc4 Mon Sep 17 00:00:00 2001 From: liu Date: Sat, 3 Aug 2024 13:52:05 +0800 Subject: [PATCH 2/8] feat(client): Add more observability in apollo config client --- .../apollo/internals/AbstractConfigFile.java | 3 +- .../internals/AbstractConfigRepository.java | 3 +- .../internals/ConfigMonitorInitializer.java | 122 ++++---- .../internals/ConfigServiceLocator.java | 5 +- .../apollo/internals/DefaultConfig.java | 3 +- .../internals/DefaultConfigManager.java | 14 +- .../apollo/internals/DefaultInjector.java | 13 +- .../internals/LocalFileConfigRepository.java | 3 +- .../RemoteConfigLongPollService.java | 10 +- .../internals/RemoteConfigRepository.java | 21 +- .../apollo/internals/SimpleConfig.java | 3 +- .../apollo/internals/YamlConfigFile.java | 3 +- ... ApolloClientBootstrapArgsMonitorApi.java} | 14 +- ...a => ApolloClientExceptionMonitorApi.java} | 13 +- ...a => ApolloClientNamespaceMonitorApi.java} | 25 +- .../ApolloClientThreadPoolMonitorApi.java} | 31 +- .../api/ApolloThreadPoolMonitorApi.java | 89 ------ .../apollo/monitor/api/ConfigMonitor.java | 10 +- .../internal/ApolloClientMonitorConstant.java | 88 ++++++ .../internal/DefaultConfigMonitor.java | 56 ++-- .../internal/NullThreadPoolMonitorApi.java | 172 ---------- .../collector/AbstractMetricsCollector.java | 80 ----- .../DefaultApolloExceptionCollector.java | 83 ----- .../DefaultApolloNamespaceCollector.java | 296 ------------------ .../DefaultApolloRunningParamsCollector.java | 230 -------------- .../DefaultApolloThreadPoolCollector.java | 259 --------------- .../MeterType.java => enums/MeterEnums.java} | 11 +- .../ApolloConfigMetricsEvent.java} | 73 ++--- .../ApolloConfigMetricsEventFactory.java | 46 +++ .../ApolloConfigMetricsEventPublisher.java} | 18 +- ... AbstractApolloClientMetricsExporter.java} | 48 ++- ....java => ApolloClientMetricsExporter.java} | 21 +- ...> ApolloClientMetricsExporterFactory.java} | 6 +- ...ultApolloClientMetricsExporterFactory.java | 89 ++++++ .../impl/NullApolloClientMetricsExporter.java | 55 ++++ .../DefaultMetricsExporterFactory.java | 77 ----- .../ApolloClientJmxMBeanRegister.java} | 35 ++- .../ApolloClientJmxBootstrapArgsMBean.java} | 13 +- .../mbean/ApolloClientJmxExceptionMBean.java | 34 ++ .../mbean/ApolloClientJmxNamespaceMBean.java | 28 ++ .../mbean/ApolloClientJmxThreadPoolMBean.java | 29 ++ ...tractApolloClientMetricsEventListener.java | 114 +++++++ .../ApolloClientMetricsEventListener.java} | 21 +- ...lloClientMetricsEventListenerManager.java} | 6 +- .../DefaultApolloClientBootstrapArgsApi.java | 225 +++++++++++++ .../impl/DefaultApolloClientExceptionApi.java | 89 ++++++ ...lloClientMetricsEventListenerManager.java} | 19 +- .../impl/DefaultApolloClientNamespaceApi.java | 239 ++++++++++++++ .../DefaultApolloClientThreadPoolApi.java | 173 ++++++++++ .../NullClientBootstrapArgsMonitorApi.java} | 27 +- .../impl/NullClientExceptionMonitorApi.java} | 17 +- .../impl/NullClientNamespaceMonitorApi.java} | 39 +-- .../impl/NullClientThreadPoolMonitorApi.java | 50 +++ .../monitor/internal/model/CounterModel.java | 71 +---- .../monitor/internal/model/GaugeModel.java | 88 +----- .../monitor/internal/model/SampleModel.java | 75 +++++ .../ApolloClientMessageProducerComposite.java | 72 +++++ ...> ApolloClientMessageProducerManager.java} | 4 +- .../ApolloClientMonitorMessageProducer.java | 197 ++++++++++++ .../tracer/MessageProducerComposite.java | 84 ----- .../tracer/MonitorMessageProducer.java | 169 ---------- .../ApolloApplicationContextInitializer.java | 3 +- .../framework/apollo/util/ConfigUtil.java | 52 +-- ...itional-spring-configuration-metadata.json | 15 + ...k.apollo.tracer.spi.MessageProducerManager | 2 +- .../internal/DefaultConfigMonitorTest.java | 87 +++++ .../AbstractApolloMetricsCollectorTest.java | 90 ------ ...stractApolloClientMetricsExporterTest.java | 120 +++++++ .../AbstractApolloMetricsExporterTest.java | 123 -------- ...polloClientMetricsExporterFactoryTest.java | 93 ++++++ ...faultApolloMetricsExporterFactoryTest.java | 60 ---- .../MockApolloClientMetricsExporter.java | 48 +++ .../jmx/ApolloClientJmxMBeanRegisterTest.java | 65 ++++ ...tApolloClientMetricsEventListenerTest.java | 111 +++++++ ...ClientMetricsEventListenerManagerTest.java | 68 ++++ ...lloClientMessageProducerCompositeTest.java | 134 ++++++++ ...polloClientMonitorMessageProducerTest.java | 83 +++++ ...ernal.exporter.ApolloClientMetricsExporter | 1 + .../apollo/core/ApolloClientSystemConsts.java | 6 +- .../ctrip/framework/apollo/tracer/Tracer.java | 8 + .../DefaultMessageProducerManager.java | 22 +- .../internals/cat/CatMessageProducer.java | 5 + .../apollo/tracer/spi/MessageProducer.java | 10 + .../apollo-plugin-client-prometheus/pom.xml | 9 +- ...PrometheusApolloClientMetricsExporter.java | 94 ++++++ .../prometheus/PrometheusMetricExporter.java | 106 ------- ...ernal.exporter.ApolloClientMetricsExporter | 1 + ....monitor.internal.exporter.MetricsExporter | 1 - 88 files changed, 2961 insertions(+), 2467 deletions(-) rename apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/{ApolloRunningParamsMonitorApi.java => ApolloClientBootstrapArgsMonitorApi.java} (85%) rename apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/{ApolloExceptionMonitorApi.java => ApolloClientExceptionMonitorApi.java} (75%) rename apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/{ApolloNamespaceMonitorApi.java => ApolloClientNamespaceMonitorApi.java} (71%) rename apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/{internal/model/MetricsModel.java => api/ApolloClientThreadPoolMonitorApi.java} (53%) delete mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloThreadPoolMonitorApi.java create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/ApolloClientMonitorConstant.java delete mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/NullThreadPoolMonitorApi.java delete mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/AbstractMetricsCollector.java delete mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/internal/DefaultApolloExceptionCollector.java delete mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/internal/DefaultApolloNamespaceCollector.java delete mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/internal/DefaultApolloRunningParamsCollector.java delete mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/internal/DefaultApolloThreadPoolCollector.java rename apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/{util/MeterType.java => enums/MeterEnums.java} (82%) rename apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/{model/MetricsEvent.java => event/ApolloConfigMetricsEvent.java} (51%) create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/event/ApolloConfigMetricsEventFactory.java rename apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/{model/MetricsEventPusher.java => event/ApolloConfigMetricsEventPublisher.java} (58%) rename apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/{AbstractMetricsExporter.java => AbstractApolloClientMetricsExporter.java} (68%) rename apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/{MetricsExporter.java => ApolloClientMetricsExporter.java} (65%) rename apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/{MetricsExporterFactory.java => ApolloClientMetricsExporterFactory.java} (74%) create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/impl/DefaultApolloClientMetricsExporterFactory.java create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/impl/NullApolloClientMetricsExporter.java delete mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/internals/DefaultMetricsExporterFactory.java rename apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/{util/JMXUtil.java => jmx/ApolloClientJmxMBeanRegister.java} (53%) rename apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/{MonitorConstant.java => jmx/mbean/ApolloClientJmxBootstrapArgsMBean.java} (68%) create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/jmx/mbean/ApolloClientJmxExceptionMBean.java create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/jmx/mbean/ApolloClientJmxNamespaceMBean.java create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/jmx/mbean/ApolloClientJmxThreadPoolMBean.java create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/AbstractApolloClientMetricsEventListener.java rename apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/{collector/MetricsCollector.java => listener/ApolloClientMetricsEventListener.java} (63%) rename apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/{collector/MetricsCollectorManager.java => listener/ApolloClientMetricsEventListenerManager.java} (80%) create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientBootstrapArgsApi.java create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientExceptionApi.java rename apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/{collector/internal/DefaultMetricsCollectorManager.java => listener/impl/DefaultApolloClientMetricsEventListenerManager.java} (50%) create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientNamespaceApi.java create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientThreadPoolApi.java rename apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/{NullRunningParamsMonitorApi.java => listener/impl/NullClientBootstrapArgsMonitorApi.java} (75%) rename apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/{NullExceptionMonitorApi.java => listener/impl/NullClientExceptionMonitorApi.java} (57%) rename apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/{NullNamespaceMonitorApi.java => listener/impl/NullClientNamespaceMonitorApi.java} (65%) create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientThreadPoolMonitorApi.java create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/SampleModel.java create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMessageProducerComposite.java rename apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/{ClientMessageProducerManager.java => ApolloClientMessageProducerManager.java} (89%) create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMonitorMessageProducer.java delete mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/MessageProducerComposite.java delete mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/MonitorMessageProducer.java create mode 100644 apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/DefaultConfigMonitorTest.java delete mode 100644 apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/collector/AbstractApolloMetricsCollectorTest.java create mode 100644 apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractApolloClientMetricsExporterTest.java delete mode 100644 apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractApolloMetricsExporterTest.java create mode 100644 apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/DefaultApolloClientMetricsExporterFactoryTest.java delete mode 100644 apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/DefaultApolloMetricsExporterFactoryTest.java create mode 100644 apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/MockApolloClientMetricsExporter.java create mode 100644 apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/jmx/ApolloClientJmxMBeanRegisterTest.java create mode 100644 apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/AbstractApolloClientMetricsEventListenerTest.java create mode 100644 apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/DefaultApolloClientMetricsEventListenerManagerTest.java create mode 100644 apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMessageProducerCompositeTest.java create mode 100644 apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMonitorMessageProducerTest.java create mode 100644 apollo-client/src/test/resources/META-INF/services/com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporter create mode 100644 apollo-plugin/apollo-plugin-client-prometheus/src/main/java/com/ctrip/framework/apollo/plugin/prometheus/PrometheusApolloClientMetricsExporter.java delete mode 100644 apollo-plugin/apollo-plugin-client-prometheus/src/main/java/com/ctrip/framework/apollo/plugin/prometheus/PrometheusMetricExporter.java create mode 100644 apollo-plugin/apollo-plugin-client-prometheus/src/main/resources/META-INF/services/com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporter delete mode 100644 apollo-plugin/apollo-plugin-client-prometheus/src/main/resources/META-INF/services/com.ctrip.framework.apollo.monitor.internal.exporter.MetricsExporter diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/AbstractConfigFile.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/AbstractConfigFile.java index 8fc574cf..5ef1d37f 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/AbstractConfigFile.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/AbstractConfigFile.java @@ -17,8 +17,7 @@ package com.ctrip.framework.apollo.internals; -import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_CLIENT_CONFIGCHANGES; - +import static com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorConstant.*; import com.ctrip.framework.apollo.build.ApolloInjector; import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory; import com.ctrip.framework.apollo.enums.ConfigSourceType; diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/AbstractConfigRepository.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/AbstractConfigRepository.java index 62d3e9ab..6b00c4c0 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/AbstractConfigRepository.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/AbstractConfigRepository.java @@ -16,8 +16,7 @@ */ package com.ctrip.framework.apollo.internals; -import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_CONFIG_EXCEPTION; - +import static com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorConstant.*; import com.ctrip.framework.apollo.build.ApolloInjector; import com.ctrip.framework.apollo.util.factory.PropertiesFactory; import java.util.List; diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigMonitorInitializer.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigMonitorInitializer.java index 8256125b..6f5cf85d 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigMonitorInitializer.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigMonitorInitializer.java @@ -20,17 +20,17 @@ import com.ctrip.framework.apollo.core.utils.ClassLoaderUtil; import com.ctrip.framework.apollo.monitor.api.ConfigMonitor; import com.ctrip.framework.apollo.monitor.internal.DefaultConfigMonitor; -import com.ctrip.framework.apollo.monitor.internal.collector.MetricsCollector; -import com.ctrip.framework.apollo.monitor.internal.collector.MetricsCollectorManager; -import com.ctrip.framework.apollo.monitor.internal.collector.internal.DefaultApolloExceptionCollector; -import com.ctrip.framework.apollo.monitor.internal.collector.internal.DefaultApolloNamespaceCollector; -import com.ctrip.framework.apollo.monitor.internal.collector.internal.DefaultApolloRunningParamsCollector; -import com.ctrip.framework.apollo.monitor.internal.collector.internal.DefaultApolloThreadPoolCollector; -import com.ctrip.framework.apollo.monitor.internal.collector.internal.DefaultMetricsCollectorManager; -import com.ctrip.framework.apollo.monitor.internal.exporter.MetricsExporter; -import com.ctrip.framework.apollo.monitor.internal.exporter.MetricsExporterFactory; -import com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite; -import com.ctrip.framework.apollo.monitor.internal.tracer.MonitorMessageProducer; +import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMetricsEventListener; +import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMetricsEventListenerManager; +import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientBootstrapArgsApi; +import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientExceptionApi; +import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientNamespaceApi; +import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientThreadPoolApi; +import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientMetricsEventListenerManager; +import com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporter; +import com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporterFactory; +import com.ctrip.framework.apollo.monitor.internal.tracer.ApolloClientMonitorMessageProducer; +import com.ctrip.framework.apollo.monitor.internal.tracer.ApolloClientMessageProducerComposite; import com.ctrip.framework.apollo.tracer.internals.NullMessageProducer; import com.ctrip.framework.apollo.tracer.internals.cat.CatMessageProducer; import com.ctrip.framework.apollo.tracer.internals.cat.CatNames; @@ -43,92 +43,82 @@ import org.slf4j.LoggerFactory; /** - * @author Rawven + * ConfigMonitorInitializer initializes the Apollo Config Monitor. */ public class ConfigMonitorInitializer { private static final Logger logger = LoggerFactory.getLogger(ConfigMonitorInitializer.class); - - private static ConfigUtil m_configUtil = ApolloInjector.getInstance(ConfigUtil.class); - private static Boolean hasInitialized = false; + private static final ConfigUtil CONFIG_UTIL = ApolloInjector.getInstance(ConfigUtil.class); + private static boolean hasInitialized = false; public static void initialize() { - if (m_configUtil.isClientMonitorEnabled() && !hasInitialized) { - logger.info("Initializing ConfigMonitor..."); - DefaultMetricsCollectorManager manager = initializeMetricsCollectorManager(); - List collectors = initializeCollectors(manager); - MetricsExporter metricsExporter = initializeMetricsExporter(collectors); + if (CONFIG_UTIL.getClientMonitorEnabled() && !hasInitialized) { + logger.debug("Initializing ConfigMonitor"); + DefaultApolloClientMetricsEventListenerManager manager = initializeMetricsEventListenerManager(); + List collectors = initializeCollectors(manager); + ApolloClientMetricsExporter metricsExporter = initializeMetricsExporter(collectors); initializeConfigMonitor(collectors, metricsExporter); hasInitialized = true; - logger.info("ConfigMonitor initialized successfully."); + logger.debug("ConfigMonitor initialized successfully."); } } - private static DefaultMetricsCollectorManager initializeMetricsCollectorManager() { - return (DefaultMetricsCollectorManager) ApolloInjector.getInstance( - MetricsCollectorManager.class); + private static DefaultApolloClientMetricsEventListenerManager initializeMetricsEventListenerManager() { + return (DefaultApolloClientMetricsEventListenerManager) ApolloInjector.getInstance( + ApolloClientMetricsEventListenerManager.class); } - private static List initializeCollectors( - DefaultMetricsCollectorManager manager) { - DefaultConfigManager configManager = (DefaultConfigManager) ApolloInjector.getInstance( - ConfigManager.class); - DefaultApolloExceptionCollector exceptionCollector = new DefaultApolloExceptionCollector(); - DefaultApolloThreadPoolCollector threadPoolCollector = new DefaultApolloThreadPoolCollector( - RemoteConfigRepository.m_executorService, AbstractConfig.m_executorService, - AbstractConfigFile.m_executorService); - DefaultApolloNamespaceCollector namespaceCollector = new DefaultApolloNamespaceCollector( - configManager.m_configs, configManager.m_configLocks, configManager.m_configFiles, - configManager.m_configFileLocks); - DefaultApolloRunningParamsCollector startupCollector = new DefaultApolloRunningParamsCollector( - m_configUtil); - - List collectors = Lists.newArrayList(exceptionCollector, namespaceCollector, - threadPoolCollector, startupCollector); + private static List initializeCollectors( + DefaultApolloClientMetricsEventListenerManager manager) { + + DefaultConfigManager configManager = (DefaultConfigManager) ApolloInjector.getInstance(ConfigManager.class); + + List collectors = Lists.newArrayList( + new DefaultApolloClientExceptionApi(), + new DefaultApolloClientNamespaceApi(configManager.m_configs, configManager.m_configFiles), + new DefaultApolloClientThreadPoolApi(RemoteConfigRepository.m_executorService, + AbstractConfig.m_executorService, AbstractConfigFile.m_executorService), + new DefaultApolloClientBootstrapArgsApi(CONFIG_UTIL) + ); + manager.setCollectors(collectors); return collectors; } - private static MetricsExporter initializeMetricsExporter(List collectors) { - MetricsExporterFactory reporterFactory = ApolloInjector.getInstance( - MetricsExporterFactory.class); - return reporterFactory.getMetricsReporter(collectors); + private static ApolloClientMetricsExporter initializeMetricsExporter(List collectors) { + ApolloClientMetricsExporterFactory exporterFactory = ApolloInjector.getInstance( + ApolloClientMetricsExporterFactory.class); + return exporterFactory.getMetricsReporter(collectors); } - private static void initializeConfigMonitor(List collectors, - MetricsExporter metricsExporter) { - DefaultConfigMonitor defaultConfigMonitor = (DefaultConfigMonitor) ApolloInjector.getInstance( - ConfigMonitor.class); - DefaultApolloExceptionCollector exceptionCollector = (DefaultApolloExceptionCollector) collectors.get( - 0); - DefaultApolloNamespaceCollector namespaceCollector = (DefaultApolloNamespaceCollector) collectors.get( - 1); - DefaultApolloThreadPoolCollector threadPoolCollector = (DefaultApolloThreadPoolCollector) collectors.get( - 2); - DefaultApolloRunningParamsCollector startupCollector = (DefaultApolloRunningParamsCollector) collectors.get( - 3); - defaultConfigMonitor.init(namespaceCollector, threadPoolCollector, exceptionCollector, - startupCollector, metricsExporter); - } + private static void initializeConfigMonitor(List collectors, + ApolloClientMetricsExporter metricsExporter) { - public static MessageProducerComposite initializeMessageProducerComposite() { + DefaultConfigMonitor configMonitor = (DefaultConfigMonitor) ApolloInjector.getInstance(ConfigMonitor.class); + configMonitor.init( + (DefaultApolloClientNamespaceApi) collectors.get(1), + (DefaultApolloClientThreadPoolApi) collectors.get(2), + (DefaultApolloClientExceptionApi) collectors.get(0), + (DefaultApolloClientBootstrapArgsApi) collectors.get(3), + metricsExporter + ); + } - // Prioritize loading user-defined producers from SPI + public static ApolloClientMessageProducerComposite initializeMessageProducerComposite() { List producers = ServiceBootstrap.loadAllOrdered(MessageProducer.class); - // The producer that comes with the client - if (m_configUtil.isClientMonitorEnabled()) { - producers.add(new MonitorMessageProducer()); + if (CONFIG_UTIL.getClientMonitorEnabled()) { + producers.add(new ApolloClientMonitorMessageProducer()); } if (ClassLoaderUtil.isClassPresent(CatNames.CAT_CLASS)) { producers.add(new CatMessageProducer()); } - // default logic if (producers.isEmpty()) { producers.add(new NullMessageProducer()); } - return new MessageProducerComposite(producers); + + return new ApolloClientMessageProducerComposite(producers); } } \ No newline at end of file diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigServiceLocator.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigServiceLocator.java index 281e440e..ebccd7e5 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigServiceLocator.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigServiceLocator.java @@ -16,10 +16,7 @@ */ package com.ctrip.framework.apollo.internals; -import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_CONFIG_EXCEPTION; -import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_CONFIG_SERVICES; -import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_META_SERVICE; - +import static com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorConstant.*; import com.ctrip.framework.apollo.build.ApolloInjector; import com.ctrip.framework.apollo.core.ApolloClientSystemConsts; import com.ctrip.framework.apollo.core.ServiceNameConsts; diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultConfig.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultConfig.java index b859e32e..586391f0 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultConfig.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultConfig.java @@ -16,8 +16,7 @@ */ package com.ctrip.framework.apollo.internals; -import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_CLIENT_CONFIGCHANGES; - +import static com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorConstant.*; import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory; import com.ctrip.framework.apollo.enums.ConfigSourceType; import com.google.common.collect.Maps; diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultConfigManager.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultConfigManager.java index 54243307..c2b8c20c 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultConfigManager.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultConfigManager.java @@ -16,17 +16,16 @@ */ package com.ctrip.framework.apollo.internals; -import static com.ctrip.framework.apollo.monitor.internal.collector.internal.DefaultApolloNamespaceCollector.NAMESPACE_MONITOR; -import static com.ctrip.framework.apollo.monitor.internal.collector.internal.DefaultApolloNamespaceCollector.NAMESPACE_USAGE_COUNT; +import static com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorConstant.APOLLO_CLIENT_NAMESPACE_USAGE; import com.ctrip.framework.apollo.Config; import com.ctrip.framework.apollo.ConfigFile; import com.ctrip.framework.apollo.build.ApolloInjector; import com.ctrip.framework.apollo.core.enums.ConfigFileFormat; -import com.ctrip.framework.apollo.monitor.internal.MonitorConstant; -import com.ctrip.framework.apollo.monitor.internal.model.MetricsEvent; +import com.ctrip.framework.apollo.enums.ConfigSourceType; import com.ctrip.framework.apollo.spi.ConfigFactory; import com.ctrip.framework.apollo.spi.ConfigFactoryManager; +import com.ctrip.framework.apollo.tracer.Tracer; import com.google.common.collect.Maps; import java.util.Map; @@ -62,10 +61,9 @@ public Config getConfig(String namespace) { } } } - - MetricsEvent.builder().withName(NAMESPACE_USAGE_COUNT) - .putAttachment(MonitorConstant.NAMESPACE, namespace) - .withTag(NAMESPACE_MONITOR).push(); + if(!ConfigSourceType.NONE.equals(config.getSourceType())) { + Tracer.logMetricsForCount(APOLLO_CLIENT_NAMESPACE_USAGE+":"+namespace); + } return config; } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultInjector.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultInjector.java index 8aae65e0..60b75b73 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultInjector.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultInjector.java @@ -19,10 +19,10 @@ import com.ctrip.framework.apollo.exceptions.ApolloConfigException; import com.ctrip.framework.apollo.monitor.api.ConfigMonitor; import com.ctrip.framework.apollo.monitor.internal.DefaultConfigMonitor; -import com.ctrip.framework.apollo.monitor.internal.exporter.internals.DefaultMetricsExporterFactory; -import com.ctrip.framework.apollo.monitor.internal.collector.MetricsCollectorManager; -import com.ctrip.framework.apollo.monitor.internal.collector.internal.DefaultMetricsCollectorManager; -import com.ctrip.framework.apollo.monitor.internal.exporter.MetricsExporterFactory; +import com.ctrip.framework.apollo.monitor.internal.exporter.impl.DefaultApolloClientMetricsExporterFactory; +import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMetricsEventListenerManager; +import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientMetricsEventListenerManager; +import com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporterFactory; import com.ctrip.framework.apollo.spi.ApolloInjectorCustomizer; import com.ctrip.framework.apollo.spi.ConfigFactory; import com.ctrip.framework.apollo.spi.ConfigFactoryManager; @@ -113,8 +113,9 @@ protected void configure() { bind(YamlParser.class).in(Singleton.class); bind(PropertiesFactory.class).to(DefaultPropertiesFactory.class).in(Singleton.class); bind(ConfigMonitor.class).to(DefaultConfigMonitor.class).in(Singleton.class); - bind(MetricsCollectorManager.class).to(DefaultMetricsCollectorManager.class).in(Singleton.class); - bind(MetricsExporterFactory.class).to(DefaultMetricsExporterFactory.class).in(Singleton.class); + bind(ApolloClientMetricsEventListenerManager.class).to( + DefaultApolloClientMetricsEventListenerManager.class).in(Singleton.class); + bind(ApolloClientMetricsExporterFactory.class).to(DefaultApolloClientMetricsExporterFactory.class).in(Singleton.class); } } } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/LocalFileConfigRepository.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/LocalFileConfigRepository.java index 13ca7929..52786384 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/LocalFileConfigRepository.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/LocalFileConfigRepository.java @@ -16,8 +16,7 @@ */ package com.ctrip.framework.apollo.internals; -import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_CONFIG_EXCEPTION; - +import static com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorConstant.*; import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory; import com.ctrip.framework.apollo.enums.ConfigSourceType; import java.io.File; diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigLongPollService.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigLongPollService.java index 1ab51080..fde34ca1 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigLongPollService.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigLongPollService.java @@ -16,9 +16,7 @@ */ package com.ctrip.framework.apollo.internals; -import static com.ctrip.framework.apollo.monitor.internal.MonitorConstant.NAMESPACE; -import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_CONFIG_EXCEPTION; - +import static com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorConstant.*; import com.ctrip.framework.apollo.build.ApolloInjector; import com.ctrip.framework.apollo.core.ConfigConsts; import com.ctrip.framework.apollo.core.dto.ApolloConfigNotification; @@ -31,8 +29,6 @@ import com.ctrip.framework.apollo.core.utils.ApolloThreadFactory; import com.ctrip.framework.apollo.core.utils.StringUtils; import com.ctrip.framework.apollo.exceptions.ApolloConfigException; -import com.ctrip.framework.apollo.monitor.internal.collector.internal.DefaultApolloNamespaceCollector; -import com.ctrip.framework.apollo.monitor.internal.model.MetricsEvent; import com.ctrip.framework.apollo.spi.ConfigServiceLoadBalancerClient; import com.ctrip.framework.apollo.tracer.Tracer; import com.ctrip.framework.apollo.tracer.spi.Transaction; @@ -219,9 +215,7 @@ private void doLongPollingRefresh(String appId, String cluster, String dataCente transaction.setStatus(ex); long sleepTimeInSecond = m_longPollFailSchedulePolicyInSecond.fail(); if (ex.getCause() instanceof SocketTimeoutException) { - MetricsEvent.builder().withName(DefaultApolloNamespaceCollector.NAMESPACE_TIMEOUT) - .putAttachment(NAMESPACE, assembleNamespaces()) - .withTag(DefaultApolloNamespaceCollector.NAMESPACE_MONITOR).push(); + Tracer.logEvent(APOLLO_CLIENT_NAMESPACE_TIMEOUT,assembleNamespaces()); } logger.warn( "Long polling failed, will retry in {} seconds. appId: {}, cluster: {}, namespaces: {}, long polling url: {}, reason: {}", diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigRepository.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigRepository.java index 6ca75336..be19f42e 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigRepository.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigRepository.java @@ -16,14 +16,7 @@ */ package com.ctrip.framework.apollo.internals; -import static com.ctrip.framework.apollo.monitor.internal.MonitorConstant.NAMESPACE; -import static com.ctrip.framework.apollo.monitor.internal.MonitorConstant.TIMESTAMP; -import static com.ctrip.framework.apollo.monitor.internal.collector.internal.DefaultApolloNamespaceCollector.NAMESPACE_MONITOR; -import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_CLIENT_CONFIGS; -import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_CLIENT_CONFIGMETA; -import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_CLIENT_VERSION; -import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_CONFIGSERVICE; -import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_CONFIG_EXCEPTION; +import static com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorConstant.*; import com.ctrip.framework.apollo.Apollo; import com.ctrip.framework.apollo.build.ApolloInjector; @@ -40,8 +33,6 @@ import com.ctrip.framework.apollo.enums.ConfigSourceType; import com.ctrip.framework.apollo.exceptions.ApolloConfigException; import com.ctrip.framework.apollo.exceptions.ApolloConfigStatusCodeException; -import com.ctrip.framework.apollo.monitor.internal.collector.internal.DefaultApolloNamespaceCollector; -import com.ctrip.framework.apollo.monitor.internal.model.MetricsEvent; import com.ctrip.framework.apollo.tracer.Tracer; import com.ctrip.framework.apollo.tracer.spi.Transaction; import com.ctrip.framework.apollo.util.ConfigUtil; @@ -124,10 +115,8 @@ public Properties getConfig() { if (m_configCache.get() == null) { long start = System.currentTimeMillis(); this.sync(); - MetricsEvent.builder().withName(DefaultApolloNamespaceCollector.NAMESPACE_FIRST_LOAD_SPEND).withTag( - NAMESPACE_MONITOR) - .putAttachment(NAMESPACE, m_namespace) - .putAttachment(TIMESTAMP, System.currentTimeMillis() - start).push(); + Tracer.logEvent(APOLLO_CLIENT_NAMESPACE_FIRST_LOAD_SPEND+m_namespace, + String.valueOf(System.currentTimeMillis() - start)); } return transformApolloConfigToProperties(m_configCache.get()); } @@ -278,8 +267,8 @@ private ApolloConfig loadApolloConfig() { appId, cluster, m_namespace); statusCodeException = new ApolloConfigStatusCodeException(ex.getStatusCode(), message); - MetricsEvent.builder().withName(DefaultApolloNamespaceCollector.NAMESPACE_NOT_FOUND).withTag( - NAMESPACE_MONITOR).putAttachment(NAMESPACE, m_namespace).push(); + Tracer.logEvent(APOLLO_CLIENT_NAMESPACE_NOT_FOUND,m_namespace); + } Tracer.logEvent(APOLLO_CONFIG_EXCEPTION, ExceptionUtil.getDetailMessage(statusCodeException)); transaction.setStatus(statusCodeException); diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/SimpleConfig.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/SimpleConfig.java index 10ba29af..2d333988 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/SimpleConfig.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/SimpleConfig.java @@ -16,8 +16,7 @@ */ package com.ctrip.framework.apollo.internals; -import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_CLIENT_CONFIGCHANGES; - +import static com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorConstant.*; import com.ctrip.framework.apollo.enums.ConfigSourceType; import java.util.Collections; import java.util.List; diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/YamlConfigFile.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/YamlConfigFile.java index d7757895..05f87569 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/YamlConfigFile.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/YamlConfigFile.java @@ -16,8 +16,7 @@ */ package com.ctrip.framework.apollo.internals; -import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_CONFIG_EXCEPTION; - +import static com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorConstant.*; import com.ctrip.framework.apollo.util.ExceptionUtil; import java.util.Properties; diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloRunningParamsMonitorApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientBootstrapArgsMonitorApi.java similarity index 85% rename from apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloRunningParamsMonitorApi.java rename to apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientBootstrapArgsMonitorApi.java index ff9e2205..b9c46d78 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloRunningParamsMonitorApi.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientBootstrapArgsMonitorApi.java @@ -16,13 +16,17 @@ */ package com.ctrip.framework.apollo.monitor.api; -import javax.management.MXBean; +import java.util.Map; /** * @author Rawven */ -@MXBean -public interface ApolloRunningParamsMonitorApi { +public interface ApolloClientBootstrapArgsMonitorApi { + + /** + * get bootstrap args map + */ + Map getBootstrapArgs(); String getStartupParams(String key); @@ -54,7 +58,9 @@ public interface ApolloRunningParamsMonitorApi { long getClientMonitorExternalExportPeriod(); - String getMeta(); + int getClientMonitorExceptionSaveSize(); + + String getApolloMeta(); String getMetaLatestFreshTime(); diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloExceptionMonitorApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientExceptionMonitorApi.java similarity index 75% rename from apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloExceptionMonitorApi.java rename to apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientExceptionMonitorApi.java index 6a826a56..14b45d49 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloExceptionMonitorApi.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientExceptionMonitorApi.java @@ -17,22 +17,15 @@ package com.ctrip.framework.apollo.monitor.api; import java.util.List; -import javax.management.MXBean; /** * @author Rawven */ -@MXBean -public interface ApolloExceptionMonitorApi { - +public interface ApolloClientExceptionMonitorApi { /** - * get the number of exceptions + * get ApolloConfigException details */ - Integer getExceptionNum(); + List getApolloConfigExceptionList(); - /** - * get exception details - */ - List getExceptionDetails(); } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloNamespaceMonitorApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientNamespaceMonitorApi.java similarity index 71% rename from apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloNamespaceMonitorApi.java rename to apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientNamespaceMonitorApi.java index d9ce8ee9..6fc740ab 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloNamespaceMonitorApi.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientNamespaceMonitorApi.java @@ -16,28 +16,25 @@ */ package com.ctrip.framework.apollo.monitor.api; +import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientNamespaceApi.NamespaceMetrics; import java.util.List; -import javax.management.MXBean; +import java.util.Map; /** * @author Rawven */ -@MXBean -public interface ApolloNamespaceMonitorApi { +public interface ApolloClientNamespaceMonitorApi { - String getNamespaceReleaseKey(String namespace); + /** + * NamespaceMetrics: 1.usageCount 2.firstLoadSpend 3.latestUpdateTime 4.releaseKey + */ + Map getNamespaceMetrics(); - long getNamespaceUsageCount(String namespace); - - String getNamespaceLatestUpdateTime(String namespace); - - long getNamespaceFirstLoadSpend(String namespace); + List getNamespaceItemName(String namespace); - String getNamespace404(); + List getNamespace404(); - String getNamespaceTimeout(); - - List getNamespaceItemName(String namespace); + List getNamespaceTimeout(); List getAllNamespaceReleaseKey(); @@ -50,4 +47,6 @@ public interface ApolloNamespaceMonitorApi { List getAllNamespaceFirstLoadSpend(); List getAllNamespaceItemName(); + + } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/MetricsModel.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientThreadPoolMonitorApi.java similarity index 53% rename from apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/MetricsModel.java rename to apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientThreadPoolMonitorApi.java index e293ce6f..c78f9c18 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/MetricsModel.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientThreadPoolMonitorApi.java @@ -14,35 +14,24 @@ * limitations under the License. * */ -package com.ctrip.framework.apollo.monitor.internal.model; +package com.ctrip.framework.apollo.monitor.api; -import com.ctrip.framework.apollo.monitor.internal.util.MeterType; -import java.util.HashMap; +import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientThreadPoolApi.ApolloThreadPoolInfo; import java.util.Map; /** * @author Rawven */ -public class MetricsModel { +public interface ApolloClientThreadPoolMonitorApi { - protected final Map tags = new HashMap<>(); - protected String name; - protected MeterType type; + /** + * get thread pool info key "RemoteConfigRepository" ,"AbstractConfig","AbstractConfigFile"; + */ + Map getThreadPoolInfo(); - public String getName() { - return "Apollo_Client_" + name; - } + ApolloThreadPoolInfo getRemoteConfigRepositoryThreadPoolInfo(); - public void setName(String name) { - this.name = name; - } + ApolloThreadPoolInfo getAbstractConfigThreadPoolInfo(); - public MeterType getType() { - return type; - } - - public Map getTags() { - return tags; - } + ApolloThreadPoolInfo getAbstractConfigFileThreadPoolInfo(); } - diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloThreadPoolMonitorApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloThreadPoolMonitorApi.java deleted file mode 100644 index 33c09e77..00000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloThreadPoolMonitorApi.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright 2022 Apollo Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.ctrip.framework.apollo.monitor.api; - -import javax.management.MXBean; - -/** - * @author Rawven - */ -@MXBean -public interface ApolloThreadPoolMonitorApi { - - - int getRemoteConfigRepositoryThreadPoolActiveCount(); - - int getRemoteConfigRepositoryThreadPoolQueueSize(); - - int getRemoteConfigRepositoryThreadPoolCorePoolSize(); - - int getRemoteConfigRepositoryThreadPoolMaximumPoolSize(); - - int getRemoteConfigRepositoryThreadPoolPoolSize(); - - long getRemoteConfigRepositoryThreadPoolTaskCount(); - - long getRemoteConfigRepositoryThreadPoolCompletedTaskCount(); - - int getRemoteConfigRepositoryThreadPoolLargestPoolSize(); - - int getRemoteConfigRepositoryThreadPoolRemainingCapacity(); - - double getRemoteConfigRepositoryThreadPoolCurrentLoad(); - - int getAbstractConfigThreadPoolActiveCount(); - - int getAbstractConfigThreadPoolQueueSize(); - - int getAbstractConfigThreadPoolCorePoolSize(); - - int getAbstractConfigThreadPoolMaximumPoolSize(); - - int getAbstractConfigThreadPoolPoolSize(); - - long getAbstractConfigThreadPoolTaskCount(); - - long getAbstractConfigThreadPoolCompletedTaskCount(); - - int getAbstractConfigThreadPoolLargestPoolSize(); - - int getAbstractConfigThreadPoolRemainingCapacity(); - - double getAbstractConfigThreadPoolCurrentLoad(); - - - int getAbstractConfigFileThreadPoolActiveCount(); - - int getAbstractConfigFileThreadPoolQueueSize(); - - int getAbstractConfigFileThreadPoolCorePoolSize(); - - int getAbstractConfigFileThreadPoolMaximumPoolSize(); - - int getAbstractConfigFileThreadPoolPoolSize(); - - long getAbstractConfigFileThreadPoolTaskCount(); - - long getAbstractConfigFileThreadPoolCompletedTaskCount(); - - int getAbstractConfigFileThreadPoolLargestPoolSize(); - - int getAbstractConfigFileThreadPoolRemainingCapacity(); - - double getAbstractConfigFileThreadPoolCurrentLoad(); - -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ConfigMonitor.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ConfigMonitor.java index 898f7739..a808cfb0 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ConfigMonitor.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ConfigMonitor.java @@ -21,13 +21,13 @@ */ public interface ConfigMonitor { - ApolloThreadPoolMonitorApi getThreadPoolMonitorApi(); + ApolloClientThreadPoolMonitorApi getThreadPoolMonitorApi(); - ApolloExceptionMonitorApi getExceptionMonitorApi(); + ApolloClientExceptionMonitorApi getExceptionMonitorApi(); - ApolloNamespaceMonitorApi getNamespaceMonitorApi(); + ApolloClientNamespaceMonitorApi getNamespaceMonitorApi(); - ApolloRunningParamsMonitorApi getRunningParamsMonitorApi(); + ApolloClientBootstrapArgsMonitorApi getRunningParamsMonitorApi(); - String getDataWithCurrentMonitoringSystemFormat(); + String getExporterData(); } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/ApolloClientMonitorConstant.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/ApolloClientMonitorConstant.java new file mode 100644 index 00000000..ccac2fe3 --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/ApolloClientMonitorConstant.java @@ -0,0 +1,88 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal; + +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; + +/** + * @author Rawven + */ +public class ApolloClientMonitorConstant { + + /** + * util + */ + public static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern( + "yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault()); + + /** + * common + */ + public static final String MBEAN_NAME = "apollo.client.monitor:type="; + public static final String NAMESPACE = "namespace"; + public static final String TIMESTAMP = "timestamp"; + public static final String THROWABLE = "throwable"; + public static final String NAMESPACE_RELEASE_KEY = "releaseKey"; + public static final String APOLLO_CLIENT = "Apollo_Client_"; + public static final String ENV = "env"; + public static final String VERSION = "version"; + public static final String META_FRESH = "metaFreshTime"; + public static final String CONFIG_SERVICE_URL = "configServiceUrl"; + + /** + * tracer + */ + public static final String APOLLO_CLIENT_CONFIGCHANGES = "Apollo.Client.ConfigChanges"; + public static final String APOLLO_CONFIG_EXCEPTION = "ApolloConfigException"; + public static final String APOLLO_META_SERVICE = "Apollo.MetaService"; + public static final String APOLLO_CONFIG_SERVICES = "Apollo.Config.Services"; + public static final String APOLLO_CLIENT_VERSION = "Apollo.Client.Version"; + public static final String APOLLO_CONFIGSERVICE = "Apollo.ConfigService"; + public static final String APOLLO_CLIENT_CONFIGS = "Apollo.Client.Configs."; + public static final String APOLLO_CLIENT_CONFIGMETA = "Apollo.Client.ConfigMeta"; + public static final String APOLLO_CLIENT_NAMESPACE_NOT_FOUND = "Apollo.Client.NamespaceNotFound"; + public static final String APOLLO_CLIENT_NAMESPACE_TIMEOUT = "Apollo.Client.NamespaceTimeout"; + public static final String APOLLO_CLIENT_NAMESPACE_USAGE = "Apollo.Client.NamespaceUsage"; + public static final String APOLLO_CLIENT_NAMESPACE_FIRST_LOAD_SPEND = "Apollo.Client.NamespaceFirstLoadSpendTime"; + public static final String HELP_STR = "periodicRefresh: "; + + /** + * collector tag + */ + public static final String TAG_ERROR = "ErrorMonitor"; + public static final String TAG_NAMESPACE = "NamespaceMonitor"; + public static final String TAG_BOOTSTRAP = "BootstrapMonitor"; + public static final String TAG_THREAD_POOL = "ThreadPoolMonitor"; + + /** + * metrics + */ + public static final String METRICS_NAMESPACE_LATEST_UPDATE_TIME = "namespace_latest_update_time"; + public static final String METRICS_NAMESPACE_ITEM_NUM = "namespace_item_num"; + public static final String METRICS_CONFIG_FILE_NUM = "config_file_num"; + public static final String METRICS_EXCEPTION_NUM = "exception_num"; + public static final String METRICS_NAMESPACE_FIRST_LOAD_SPEND = "namespace_first_load_spend"; + public static final String METRICS_NAMESPACE_USAGE = "namespace_usage"; + public static final String METRICS_NAMESPACE_NOT_FOUND = "namespace_not_found"; + public static final String METRICS_NAMESPACE_TIMEOUT = "namespace_timeout"; + public static final String[] METRICS_THREAD_POOL_PARAMS = new String[]{"ThreadPoolName", + "activeTaskCount", "queueSize", + "completedTaskCount", + "poolSize", "totalTaskCount", "corePoolSize", "maximumPoolSize", "largestPoolSize", + "queueCapacity", "queueRemainingCapacity", "currentLoad"}; +} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/DefaultConfigMonitor.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/DefaultConfigMonitor.java index cbd33505..c296496d 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/DefaultConfigMonitor.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/DefaultConfigMonitor.java @@ -16,12 +16,17 @@ */ package com.ctrip.framework.apollo.monitor.internal; -import com.ctrip.framework.apollo.monitor.api.ApolloExceptionMonitorApi; -import com.ctrip.framework.apollo.monitor.api.ApolloNamespaceMonitorApi; -import com.ctrip.framework.apollo.monitor.api.ApolloRunningParamsMonitorApi; -import com.ctrip.framework.apollo.monitor.api.ApolloThreadPoolMonitorApi; +import com.ctrip.framework.apollo.monitor.api.ApolloClientBootstrapArgsMonitorApi; +import com.ctrip.framework.apollo.monitor.api.ApolloClientExceptionMonitorApi; +import com.ctrip.framework.apollo.monitor.api.ApolloClientNamespaceMonitorApi; +import com.ctrip.framework.apollo.monitor.api.ApolloClientThreadPoolMonitorApi; import com.ctrip.framework.apollo.monitor.api.ConfigMonitor; -import com.ctrip.framework.apollo.monitor.internal.exporter.MetricsExporter; +import com.ctrip.framework.apollo.monitor.internal.listener.impl.NullClientBootstrapArgsMonitorApi; +import com.ctrip.framework.apollo.monitor.internal.listener.impl.NullClientExceptionMonitorApi; +import com.ctrip.framework.apollo.monitor.internal.listener.impl.NullClientNamespaceMonitorApi; +import com.ctrip.framework.apollo.monitor.internal.listener.impl.NullClientThreadPoolMonitorApi; +import com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporter; +import com.ctrip.framework.apollo.monitor.internal.exporter.impl.NullApolloClientMetricsExporter; /** * exposes all collected data through ConfigService @@ -30,49 +35,46 @@ */ public class DefaultConfigMonitor implements ConfigMonitor { - private MetricsExporter reporter; - private ApolloThreadPoolMonitorApi threadPoolMonitorApi = new NullThreadPoolMonitorApi(); - private ApolloExceptionMonitorApi exceptionMonitorApi = new NullExceptionMonitorApi(); - private ApolloNamespaceMonitorApi apolloNamespaceMonitorApi = new NullNamespaceMonitorApi(); - private ApolloRunningParamsMonitorApi apolloRunningParamsMonitorApi = new NullRunningParamsMonitorApi(); + private ApolloClientMetricsExporter reporter = new NullApolloClientMetricsExporter(); + private ApolloClientThreadPoolMonitorApi threadPoolMonitorApi = new NullClientThreadPoolMonitorApi(); + private ApolloClientExceptionMonitorApi exceptionMonitorApi = new NullClientExceptionMonitorApi(); + private ApolloClientNamespaceMonitorApi apolloClientNamespaceMonitorApi = new NullClientNamespaceMonitorApi(); + private ApolloClientBootstrapArgsMonitorApi apolloClientBootstrapArgsMonitorApi = new NullClientBootstrapArgsMonitorApi(); @Override - public ApolloThreadPoolMonitorApi getThreadPoolMonitorApi() { + public ApolloClientThreadPoolMonitorApi getThreadPoolMonitorApi() { return threadPoolMonitorApi; } @Override - public ApolloExceptionMonitorApi getExceptionMonitorApi() { + public ApolloClientExceptionMonitorApi getExceptionMonitorApi() { return exceptionMonitorApi; } @Override - public ApolloNamespaceMonitorApi getNamespaceMonitorApi() { - return apolloNamespaceMonitorApi; + public ApolloClientNamespaceMonitorApi getNamespaceMonitorApi() { + return apolloClientNamespaceMonitorApi; } @Override - public ApolloRunningParamsMonitorApi getRunningParamsMonitorApi() { - return apolloRunningParamsMonitorApi; + public ApolloClientBootstrapArgsMonitorApi getRunningParamsMonitorApi() { + return apolloClientBootstrapArgsMonitorApi; } @Override - public String getDataWithCurrentMonitoringSystemFormat() { - if (reporter == null) { - return "No MonitoringSystem Use"; - } + public String getExporterData() { return reporter.response(); } - public void init(ApolloNamespaceMonitorApi apolloNamespaceMonitorApi, - ApolloThreadPoolMonitorApi threadPoolMonitorApi, - ApolloExceptionMonitorApi exceptionMonitorApi, - ApolloRunningParamsMonitorApi apolloRunningParamsMonitorApi, - MetricsExporter reporter) { - this.apolloNamespaceMonitorApi = apolloNamespaceMonitorApi; + public void init(ApolloClientNamespaceMonitorApi apolloClientNamespaceMonitorApi, + ApolloClientThreadPoolMonitorApi threadPoolMonitorApi, + ApolloClientExceptionMonitorApi exceptionMonitorApi, + ApolloClientBootstrapArgsMonitorApi apolloClientBootstrapArgsMonitorApi, + ApolloClientMetricsExporter reporter) { + this.apolloClientNamespaceMonitorApi = apolloClientNamespaceMonitorApi; this.threadPoolMonitorApi = threadPoolMonitorApi; this.exceptionMonitorApi = exceptionMonitorApi; - this.apolloRunningParamsMonitorApi = apolloRunningParamsMonitorApi; + this.apolloClientBootstrapArgsMonitorApi = apolloClientBootstrapArgsMonitorApi; this.reporter = reporter; } } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/NullThreadPoolMonitorApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/NullThreadPoolMonitorApi.java deleted file mode 100644 index 34384df0..00000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/NullThreadPoolMonitorApi.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * Copyright 2022 Apollo Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.ctrip.framework.apollo.monitor.internal; - -import com.ctrip.framework.apollo.monitor.api.ApolloThreadPoolMonitorApi; - -public class NullThreadPoolMonitorApi implements ApolloThreadPoolMonitorApi { - - @Override - public int getRemoteConfigRepositoryThreadPoolActiveCount() { - return 0; - } - - @Override - public int getRemoteConfigRepositoryThreadPoolQueueSize() { - return 0; - } - - @Override - public int getRemoteConfigRepositoryThreadPoolCorePoolSize() { - return 0; - } - - @Override - public int getRemoteConfigRepositoryThreadPoolMaximumPoolSize() { - return 0; - } - - @Override - public int getRemoteConfigRepositoryThreadPoolPoolSize() { - return 0; - } - - @Override - public long getRemoteConfigRepositoryThreadPoolTaskCount() { - return 0; - } - - @Override - public long getRemoteConfigRepositoryThreadPoolCompletedTaskCount() { - return 0; - } - - @Override - public int getRemoteConfigRepositoryThreadPoolLargestPoolSize() { - return 0; - } - - @Override - public int getRemoteConfigRepositoryThreadPoolRemainingCapacity() { - return 0; - } - - @Override - public double getRemoteConfigRepositoryThreadPoolCurrentLoad() { - return 0; - } - - @Override - public int getAbstractConfigThreadPoolActiveCount() { - return 0; - } - - @Override - public int getAbstractConfigThreadPoolQueueSize() { - return 0; - } - - @Override - public int getAbstractConfigThreadPoolCorePoolSize() { - return 0; - } - - @Override - public int getAbstractConfigThreadPoolMaximumPoolSize() { - return 0; - } - - @Override - public int getAbstractConfigThreadPoolPoolSize() { - return 0; - } - - @Override - public long getAbstractConfigThreadPoolTaskCount() { - return 0; - } - - @Override - public long getAbstractConfigThreadPoolCompletedTaskCount() { - return 0; - } - - @Override - public int getAbstractConfigThreadPoolLargestPoolSize() { - return 0; - } - - @Override - public int getAbstractConfigThreadPoolRemainingCapacity() { - return 0; - } - - @Override - public double getAbstractConfigThreadPoolCurrentLoad() { - return 0; - } - - @Override - public int getAbstractConfigFileThreadPoolActiveCount() { - return 0; - } - - @Override - public int getAbstractConfigFileThreadPoolQueueSize() { - return 0; - } - - @Override - public int getAbstractConfigFileThreadPoolCorePoolSize() { - return 0; - } - - @Override - public int getAbstractConfigFileThreadPoolMaximumPoolSize() { - return 0; - } - - @Override - public int getAbstractConfigFileThreadPoolPoolSize() { - return 0; - } - - @Override - public long getAbstractConfigFileThreadPoolTaskCount() { - return 0; - } - - @Override - public long getAbstractConfigFileThreadPoolCompletedTaskCount() { - return 0; - } - - @Override - public int getAbstractConfigFileThreadPoolLargestPoolSize() { - return 0; - } - - @Override - public int getAbstractConfigFileThreadPoolRemainingCapacity() { - return 0; - } - - @Override - public double getAbstractConfigFileThreadPoolCurrentLoad() { - return 0; - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/AbstractMetricsCollector.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/AbstractMetricsCollector.java deleted file mode 100644 index 55314f78..00000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/AbstractMetricsCollector.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright 2022 Apollo Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.ctrip.framework.apollo.monitor.internal.collector; - -import com.ctrip.framework.apollo.monitor.internal.model.CounterModel; -import com.ctrip.framework.apollo.monitor.internal.model.GaugeModel; -import com.ctrip.framework.apollo.monitor.internal.model.MetricsEvent; -import com.ctrip.framework.apollo.monitor.internal.model.MetricsModel; -import com.google.common.collect.Maps; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * 抽象的 Metrics 收集器 用于收集和导出指标样本 - * - * @author Rawven - */ -public abstract class AbstractMetricsCollector implements MetricsCollector { - - protected final Map counterSamples = Maps.newHashMap(); - protected final Map gaugeSamples = Maps.newHashMap(); - private final AtomicBoolean isUpdated = new AtomicBoolean(); - private final List tags; - private final String name; - - public AbstractMetricsCollector(String name, String... tags) { - this.name = name; - this.tags = Arrays.asList(tags); - } - - @Override - public String name() { - return name; - } - - @Override - public boolean isSupport(MetricsEvent event) { - return tags.contains(event.getTag()); - } - - @Override - public void collect(MetricsEvent event) { - collect0(event); - isUpdated.set(true); - } - - @Override - public boolean isSamplesUpdated() { - return isUpdated.getAndSet(false); - } - - @Override - public List export() { - export0(); - List samples = new ArrayList<>(counterSamples.values()); - samples.addAll(gaugeSamples.values()); - return samples; - } - - protected abstract void collect0(MetricsEvent event); - - protected abstract void export0(); -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/internal/DefaultApolloExceptionCollector.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/internal/DefaultApolloExceptionCollector.java deleted file mode 100644 index f4895592..00000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/internal/DefaultApolloExceptionCollector.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 2022 Apollo Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.ctrip.framework.apollo.monitor.internal.collector.internal; - -import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.ERROR_METRICS; -import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.THROWABLE; - -import com.ctrip.framework.apollo.exceptions.ApolloConfigException; -import com.ctrip.framework.apollo.monitor.api.ApolloExceptionMonitorApi; -import com.ctrip.framework.apollo.monitor.internal.collector.AbstractMetricsCollector; -import com.ctrip.framework.apollo.monitor.internal.model.CounterModel; -import com.ctrip.framework.apollo.monitor.internal.model.MetricsEvent; -import java.util.List; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.stream.Collectors; - -/** - * @author Rawven - */ -public class DefaultApolloExceptionCollector extends AbstractMetricsCollector implements - ApolloExceptionMonitorApi { - - public static final String EXCEPTION_NUM = "exception_num"; - - private static final int MAX_EXCEPTIONS_SIZE = 25; - private final BlockingQueue exceptions = new ArrayBlockingQueue<>( - MAX_EXCEPTIONS_SIZE); - - private final AtomicInteger exceptionNum = new AtomicInteger(0); - - public DefaultApolloExceptionCollector() { - super(ERROR_METRICS, ERROR_METRICS); - } - - @Override - public Integer getExceptionNum() { - return exceptionNum.get(); - } - - @Override - public List getExceptionDetails() { - return exceptions.stream().map(ApolloConfigException::getMessage) - .collect(Collectors.toList()); - } - - @Override - public void collect0(MetricsEvent event) { - ApolloConfigException exception = event.getAttachmentValue(THROWABLE); - if (exception != null) { - if (exceptions.size() >= MAX_EXCEPTIONS_SIZE) { - exceptions.poll(); - } - exceptions.add(exception); - exceptionNum.incrementAndGet(); - } - } - - @Override - public void export0() { - if (!counterSamples.containsKey(EXCEPTION_NUM)) { - counterSamples.put(EXCEPTION_NUM, CounterModel.builder().name(EXCEPTION_NUM).value(0) - .build()); - } - counterSamples.get(EXCEPTION_NUM).updateValue(exceptionNum.get()); - } - -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/internal/DefaultApolloNamespaceCollector.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/internal/DefaultApolloNamespaceCollector.java deleted file mode 100644 index 8caa5a9b..00000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/internal/DefaultApolloNamespaceCollector.java +++ /dev/null @@ -1,296 +0,0 @@ -/* - * Copyright 2022 Apollo Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.ctrip.framework.apollo.monitor.internal.collector.internal; - - -import static com.ctrip.framework.apollo.monitor.internal.MonitorConstant.NAMESPACE; -import static com.ctrip.framework.apollo.monitor.internal.model.GaugeModel.INT_CONVERTER; -import static com.ctrip.framework.apollo.monitor.internal.model.GaugeModel.LONG_CONVERTER; - -import com.ctrip.framework.apollo.Config; -import com.ctrip.framework.apollo.ConfigFile; -import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory; -import com.ctrip.framework.apollo.monitor.api.ApolloNamespaceMonitorApi; -import com.ctrip.framework.apollo.monitor.internal.MonitorConstant; -import com.ctrip.framework.apollo.monitor.internal.collector.AbstractMetricsCollector; -import com.ctrip.framework.apollo.monitor.internal.model.CounterModel; -import com.ctrip.framework.apollo.monitor.internal.model.GaugeModel; -import com.ctrip.framework.apollo.monitor.internal.model.MetricsEvent; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import java.time.Instant; -import java.time.ZoneId; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.function.ToDoubleFunction; -import org.slf4j.Logger; - -/** - * @author Rawven - */ -public class DefaultApolloNamespaceCollector extends AbstractMetricsCollector implements - ApolloNamespaceMonitorApi { - - public static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern( - "yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault()); - public static final String NAMESPACE_MONITOR = "namespace_monitor"; - public static final String NAMESPACE_LATEST_UPDATE_TIME = "namespace_latest_update_time"; - public static final String NAMESPACE_FIRST_LOAD_SPEND = "namespace_first_load_spend_time"; - public static final String NAMESPACE_USAGE_COUNT = "namespace_usage_count"; - public static final String NAMESPACE_RELEASE_KEY = "namespace_release_key"; - public static final String NAMESPACE_ITEM_NUM = "namespace_item_num"; - public static final String CONFIG_FILE_NUM = "config_file_num"; - public static final String NAMESPACE_NOT_FOUND = "namespace_not_found"; - public static final String NAMESPACE_TIMEOUT = "namespace_timeout"; - private static final Logger logger = DeferredLoggerFactory.getLogger( - DefaultApolloNamespaceCollector.class); - private final Map m_configs; - private final Map m_configLocks; - private final Map m_configFiles; - private final Map m_configFileLocks; - private final Map namespaces = Maps.newConcurrentMap(); - private final List namespace404 = Lists.newCopyOnWriteArrayList(); - private final List namespaceTimeout = Lists.newCopyOnWriteArrayList(); - - public DefaultApolloNamespaceCollector(Map m_configs, - Map m_configLocks, - Map m_configFiles, - Map m_configFileLocks) { - super(NAMESPACE_MONITOR, NAMESPACE_MONITOR); - this.m_configs = m_configs; - this.m_configLocks = m_configLocks; - this.m_configFiles = m_configFiles; - this.m_configFileLocks = m_configFileLocks; - } - - - @Override - public void collect0(MetricsEvent event) { - String namespace = event.getAttachmentValue(NAMESPACE); - NamespaceMetrics namespaceMetrics = namespaces.computeIfAbsent(namespace, - k -> new NamespaceMetrics()); - switch (event.getName()) { - case NAMESPACE_USAGE_COUNT: - namespaceMetrics.incrementUsageCount(); - break; - case NAMESPACE_LATEST_UPDATE_TIME: - long updateTime = event.getAttachmentValue(MonitorConstant.TIMESTAMP); - namespaceMetrics.setLatestUpdateTime(updateTime); - break; - case NAMESPACE_FIRST_LOAD_SPEND: - long firstLoadSpendTime = event.getAttachmentValue(MonitorConstant.TIMESTAMP); - namespaceMetrics.setFirstLoadSpend(firstLoadSpendTime); - break; - case NAMESPACE_RELEASE_KEY: - String releaseKey = event.getAttachmentValue(NAMESPACE_RELEASE_KEY); - namespaceMetrics.setReleaseKey(releaseKey); - break; - case NAMESPACE_TIMEOUT: - namespaceTimeout.add(namespace); - break; - case NAMESPACE_NOT_FOUND: - namespace404.add(namespace); - break; - default: - logger.warn("Unknown event: {}", event); - break; - } - } - - @Override - public void export0() { - namespaces.forEach((namespace, metrics) -> { - updateCounterSample(NAMESPACE_USAGE_COUNT, namespace, metrics.getUsageCount()); - updateGaugeSample(NAMESPACE_FIRST_LOAD_SPEND, namespace, metrics.getFirstLoadSpend(), - LONG_CONVERTER); - updateGaugeSample(NAMESPACE_LATEST_UPDATE_TIME, namespace, metrics.getLatestUpdateTime(), - LONG_CONVERTER); - updateGaugeSample(NAMESPACE_ITEM_NUM, namespace, - m_configs.get(namespace).getPropertyNames().size(), INT_CONVERTER); - updateGaugeSample(CONFIG_FILE_NUM, namespace, m_configFiles.size(), INT_CONVERTER); - }); - updateGaugeSample(NAMESPACE_NOT_FOUND, "", namespace404.size(), INT_CONVERTER); - updateGaugeSample(NAMESPACE_TIMEOUT, "", namespaceTimeout.size(), INT_CONVERTER); - } - - private void updateCounterSample(String key, String namespace, double value) { - String mapKey = namespace + key; - if (!counterSamples.containsKey(mapKey)) { - CounterModel.CounterBuilder builder = CounterModel.builder().name(key).value(0); - if (!namespace.isEmpty()) { - builder.putTag(NAMESPACE, namespace); - } - counterSamples.put(mapKey, builder.build()); - } - counterSamples.get(mapKey).updateValue(value); - } - - @SuppressWarnings("unchecked") - private void updateGaugeSample(String key, String namespace, Object value, - ToDoubleFunction applyFunction) { - String mapKey = namespace + key; - if (!gaugeSamples.containsKey(mapKey)) { - GaugeModel.GaugeBuilder builder = GaugeModel.builder().name(key).value(0) - .apply(applyFunction); - if (!namespace.isEmpty()) { - builder.putTag(NAMESPACE, namespace); - } - gaugeSamples.put(mapKey, builder.build()); - } - gaugeSamples.get(mapKey).updateValue(value); - } - - - @Override - public String getNamespaceReleaseKey(String namespace) { - NamespaceMetrics namespaceMetrics = namespaces.get(namespace); - return namespaceMetrics == null ? null : namespaceMetrics.getReleaseKey(); - } - - @Override - public long getNamespaceUsageCount(String namespace) { - NamespaceMetrics namespaceMetrics = namespaces.get(namespace); - return namespaceMetrics == null ? 0 : namespaceMetrics.getUsageCount(); - } - - @Override - public String getNamespaceLatestUpdateTime(String namespace) { - NamespaceMetrics namespaceMetrics = namespaces.get(namespace); - return namespaceMetrics == null ? null - : DATE_FORMATTER.format(Instant.ofEpochMilli(namespaceMetrics.getLatestUpdateTime())); - } - - @Override - public long getNamespaceFirstLoadSpend(String namespace) { - NamespaceMetrics namespaceMetrics = namespaces.get(namespace); - return namespaceMetrics == null ? 0 : namespaceMetrics.getFirstLoadSpend(); - } - - @Override - public String getNamespace404() { - return namespace404.toString(); - } - - @Override - public String getNamespaceTimeout() { - return namespaceTimeout.toString(); - } - - @Override - public List getNamespaceItemName(String namespace) { - Config config = m_configs.get(namespace); - return config == null ? Collections.emptyList() : new ArrayList<>(config.getPropertyNames()); - } - - @Override - public List getAllNamespaceReleaseKey() { - List releaseKeys = Lists.newArrayList(); - namespaces.forEach((k, v) -> releaseKeys.add(k + ":" + v.getReleaseKey())); - return releaseKeys; - } - - @Override - public List getAllNamespaceUsageCount() { - List usedTimes = Lists.newArrayList(); - namespaces.forEach((k, v) -> usedTimes.add(k + ":" + v.getUsageCount())); - return usedTimes; - } - - @Override - public List getAllNamespacesLatestUpdateTime() { - List latestUpdateTimes = Lists.newArrayList(); - namespaces.forEach((k, v) -> latestUpdateTimes.add( - k + ":" + DATE_FORMATTER.format(Instant.ofEpochMilli(v.getLatestUpdateTime())))); - return latestUpdateTimes; - } - - @Override - public List getAllUsedNamespaceName() { - ArrayList namespaces = Lists.newArrayList(); - m_configs.forEach((k, v) -> namespaces.add(k)); - return namespaces; - } - - @Override - public List getAllNamespaceFirstLoadSpend() { - List firstLoadSpends = Lists.newArrayList(); - namespaces.forEach((k, v) -> firstLoadSpends.add( - k + ":" + v.getFirstLoadSpend())); - return firstLoadSpends; - } - - @Override - public List getAllNamespaceItemName() { - List namespaceItems = Lists.newArrayList(); - m_configs.forEach((k, v) -> namespaceItems.add(v.getPropertyNames().toString())); - return namespaceItems; - } - - public static class NamespaceMetrics { - - private int usageCount; - private long firstLoadSpend; - private long latestUpdateTime = System.currentTimeMillis(); - private String releaseKey = "default"; - - public String getReleaseKey() { - return releaseKey; - } - - public void setReleaseKey(String releaseKey) { - this.releaseKey = releaseKey; - } - - @Override - public String toString() { - return "NamespaceMetrics{" + - "usageCount=" + usageCount + - ", firstLoadSpend=" + firstLoadSpend + - ", latestUpdateTime=" + latestUpdateTime + - ", releaseKey='" + releaseKey + '\'' + - '}'; - } - - public int getUsageCount() { - return usageCount; - } - - public void incrementUsageCount() { - this.usageCount++; - } - - public long getFirstLoadSpend() { - return firstLoadSpend; - } - - public void setFirstLoadSpend(long firstLoadSpend) { - this.firstLoadSpend = firstLoadSpend; - } - - public long getLatestUpdateTime() { - return latestUpdateTime; - } - - public void setLatestUpdateTime(long latestUpdateTime) { - this.latestUpdateTime = latestUpdateTime; - } - } - -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/internal/DefaultApolloRunningParamsCollector.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/internal/DefaultApolloRunningParamsCollector.java deleted file mode 100644 index a5133af5..00000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/internal/DefaultApolloRunningParamsCollector.java +++ /dev/null @@ -1,230 +0,0 @@ -/* - * Copyright 2022 Apollo Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.ctrip.framework.apollo.monitor.internal.collector.internal; - -import static com.ctrip.framework.apollo.core.ApolloClientSystemConsts.APOLLO_ACCESS_KEY_SECRET; -import static com.ctrip.framework.apollo.core.ApolloClientSystemConsts.APOLLO_CACHE_DIR; -import static com.ctrip.framework.apollo.core.ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_ENABLED; -import static com.ctrip.framework.apollo.core.ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_EXTERNAL_EXPORT_PERIOD; -import static com.ctrip.framework.apollo.core.ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_EXTERNAL_TYPE; -import static com.ctrip.framework.apollo.core.ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_JMX_ENABLED; -import static com.ctrip.framework.apollo.core.ApolloClientSystemConsts.APOLLO_CLUSTER; -import static com.ctrip.framework.apollo.core.ApolloClientSystemConsts.APOLLO_CONFIG_SERVICE; -import static com.ctrip.framework.apollo.core.ApolloClientSystemConsts.APOLLO_META; -import static com.ctrip.framework.apollo.core.ApolloClientSystemConsts.APOLLO_OVERRIDE_SYSTEM_PROPERTIES; -import static com.ctrip.framework.apollo.core.ApolloClientSystemConsts.APOLLO_PROPERTY_NAMES_CACHE_ENABLE; -import static com.ctrip.framework.apollo.core.ApolloClientSystemConsts.APOLLO_PROPERTY_ORDER_ENABLE; -import static com.ctrip.framework.apollo.core.ApolloClientSystemConsts.APP_ID; -import static com.ctrip.framework.apollo.core.ConfigConsts.APOLLO_AUTO_UPDATE_INJECTED_SPRING_PROPERTIES; -import static com.ctrip.framework.apollo.spring.config.PropertySourcesConstants.APOLLO_BOOTSTRAP_EAGER_LOAD_ENABLED; -import static com.ctrip.framework.apollo.spring.config.PropertySourcesConstants.APOLLO_BOOTSTRAP_ENABLED; -import static com.ctrip.framework.apollo.spring.config.PropertySourcesConstants.APOLLO_BOOTSTRAP_NAMESPACES; - -import com.ctrip.framework.apollo.Apollo; -import com.ctrip.framework.apollo.monitor.api.ApolloRunningParamsMonitorApi; -import com.ctrip.framework.apollo.monitor.internal.collector.AbstractMetricsCollector; -import com.ctrip.framework.apollo.monitor.internal.model.MetricsEvent; -import com.ctrip.framework.apollo.util.ConfigUtil; -import com.google.common.collect.Maps; -import java.util.Map; - -/** - * @author Rawven - */ -public class DefaultApolloRunningParamsCollector extends AbstractMetricsCollector implements - ApolloRunningParamsMonitorApi { - - public static final String ENV = "env"; - public static final String VERSION = "version"; - public static final String RUNNING_PARAMS = "RunningParams"; - public static final String META_FRESH = "metaFreshTime"; - public static final String CONFIG_SERVICE_URL = "configServiceUrl"; - private final Map map = Maps.newHashMap(); - - public DefaultApolloRunningParamsCollector(ConfigUtil configUtil) { - super(RUNNING_PARAMS, RUNNING_PARAMS); - map.put(APOLLO_ACCESS_KEY_SECRET, configUtil.getAccessKeySecret()); - map.put(APOLLO_AUTO_UPDATE_INJECTED_SPRING_PROPERTIES, - configUtil.isAutoUpdateInjectedSpringPropertiesEnabled()); - map.put(APOLLO_BOOTSTRAP_ENABLED, - Boolean.parseBoolean(System.getProperty(APOLLO_BOOTSTRAP_ENABLED))); - map.put(APOLLO_BOOTSTRAP_NAMESPACES, - System.getProperty(APOLLO_BOOTSTRAP_NAMESPACES)); - map.put(APOLLO_BOOTSTRAP_EAGER_LOAD_ENABLED, - Boolean.parseBoolean(System.getProperty(APOLLO_BOOTSTRAP_EAGER_LOAD_ENABLED))); - map.put(APOLLO_OVERRIDE_SYSTEM_PROPERTIES, configUtil.isOverrideSystemProperties()); - map.put(APOLLO_CACHE_DIR, configUtil.getDefaultLocalCacheDir()); - map.put(APOLLO_CLUSTER, configUtil.getCluster()); - map.put(APOLLO_CONFIG_SERVICE, - System.getProperty(APOLLO_CONFIG_SERVICE)); - map.put(APOLLO_CLIENT_MONITOR_EXTERNAL_TYPE, configUtil.getMonitorExternalType()); - map.put(APOLLO_CLIENT_MONITOR_ENABLED, configUtil.isClientMonitorEnabled()); - map.put(APOLLO_CLIENT_MONITOR_EXTERNAL_EXPORT_PERIOD, - configUtil.getMonitorExternalExportPeriod()); - map.put(APOLLO_META, configUtil.getMetaServerDomainName()); - map.put(APOLLO_PROPERTY_NAMES_CACHE_ENABLE, configUtil.isPropertyNamesCacheEnabled()); - map.put(APOLLO_PROPERTY_ORDER_ENABLE, configUtil.isPropertiesOrderEnabled()); - map.put(APOLLO_CLIENT_MONITOR_JMX_ENABLED, configUtil.isClientMonitorJmxEnabled()); - map.put(APP_ID, configUtil.getAppId()); - map.put(ENV, configUtil.getApolloEnv()); - map.put(VERSION, Apollo.VERSION); - } - - @Override - public String name() { - return RUNNING_PARAMS; - } - - @Override - public void collect0(MetricsEvent event) { - switch (event.getName()) { - case VERSION: - map.put(VERSION, event.getAttachmentValue(VERSION)); - break; - case META_FRESH: - map.put(META_FRESH, event.getAttachmentValue(META_FRESH)); - break; - case CONFIG_SERVICE_URL: - map.put(CONFIG_SERVICE_URL, event.getAttachmentValue(CONFIG_SERVICE_URL)); - break; - default: - break; - } - } - - @Override - public boolean isSamplesUpdated() { - return false; - } - - @Override - public void export0() { - } - - @Override - public String getStartupParams(String key) { - return map.getOrDefault(key, "").toString(); - } - - @Override - public String getConfigServiceUrl() { - return map.get(CONFIG_SERVICE_URL).toString(); - } - - - @Override - public String getAccessKeySecret() { - return map.getOrDefault(APOLLO_ACCESS_KEY_SECRET, "").toString(); - } - - @Override - public Boolean getAutoUpdateInjectedSpringProperties() { - return (Boolean) map.get(APOLLO_AUTO_UPDATE_INJECTED_SPRING_PROPERTIES); - } - - @Override - public Boolean getBootstrapEnabled() { - return (Boolean) map.get(APOLLO_BOOTSTRAP_ENABLED); - } - - @Override - public String getBootstrapNamespaces() { - return (String) map.get(APOLLO_BOOTSTRAP_NAMESPACES); - } - - @Override - public Boolean getBootstrapEagerLoadEnabled() { - return (Boolean) map.get(APOLLO_BOOTSTRAP_EAGER_LOAD_ENABLED); - } - - @Override - public Boolean getOverrideSystemProperties() { - return (Boolean) map.get(APOLLO_OVERRIDE_SYSTEM_PROPERTIES); - } - - @Override - public String getCacheDir() { - return map.get(APOLLO_CACHE_DIR).toString(); - } - - @Override - public String getCluster() { - return map.get( - APOLLO_CLUSTER).toString(); - } - - @Override - public String getConfigService() { - return map.get(APOLLO_CONFIG_SERVICE).toString(); - } - - @Override - public String getClientMonitorExternalForm() { - return map.get(APOLLO_CLIENT_MONITOR_EXTERNAL_TYPE).toString(); - } - - @Override - public Boolean getClientMonitorEnabled() { - return (Boolean) map.get(APOLLO_CLIENT_MONITOR_ENABLED); - } - - @Override - public Boolean getClientMonitorJmxEnabled() { - return (Boolean) map.get(APOLLO_CLIENT_MONITOR_JMX_ENABLED); - } - - @Override - public long getClientMonitorExternalExportPeriod() { - return (Long) map.get(APOLLO_CLIENT_MONITOR_EXTERNAL_EXPORT_PERIOD); - } - - @Override - public String getMeta() { - return map.get(APOLLO_META).toString(); - } - - @Override - public Boolean getPropertyNamesCacheEnable() { - return (Boolean) map.get(APOLLO_PROPERTY_NAMES_CACHE_ENABLE); - } - - @Override - public Boolean getPropertyOrderEnable() { - return (Boolean) map.get(APOLLO_PROPERTY_ORDER_ENABLE); - } - - @Override - public String getMetaLatestFreshTime() { - return map.get(META_FRESH).toString(); - } - - @Override - public String getVersion() { - return map.get(VERSION).toString(); - } - - @Override - public String getEnv() { - return map.get(ENV).toString(); - } - - @Override - public String getAppId() { - return map.get(APP_ID).toString(); - } - -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/internal/DefaultApolloThreadPoolCollector.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/internal/DefaultApolloThreadPoolCollector.java deleted file mode 100644 index 96312168..00000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/internal/DefaultApolloThreadPoolCollector.java +++ /dev/null @@ -1,259 +0,0 @@ -/* - * Copyright 2022 Apollo Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.ctrip.framework.apollo.monitor.internal.collector.internal; - -import com.ctrip.framework.apollo.internals.AbstractConfig; -import com.ctrip.framework.apollo.internals.AbstractConfigFile; -import com.ctrip.framework.apollo.internals.RemoteConfigRepository; -import com.ctrip.framework.apollo.monitor.api.ApolloThreadPoolMonitorApi; -import com.ctrip.framework.apollo.monitor.internal.collector.AbstractMetricsCollector; -import com.ctrip.framework.apollo.monitor.internal.model.GaugeModel; -import com.ctrip.framework.apollo.monitor.internal.model.MetricsEvent; -import java.util.Arrays; -import java.util.List; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.ThreadPoolExecutor; - -/** - * @author Rawven - */ -public class DefaultApolloThreadPoolCollector extends AbstractMetricsCollector implements - ApolloThreadPoolMonitorApi { - - public static final String THREAD_POOL_METRICS = "ThreadPoolMetrics"; - public static final String[] THREAD_POOL_PARAMS = new String[]{"ThreadPoolName", - "activeTaskCount", "queueSize", - "completedTaskCount", - "poolSize", "totalTaskCount", "corePoolSize", "maximumPoolSize", "largestPoolSize", - "queueCapacity", "queueRemainingCapacity", "currentLoad"}; - - private final ScheduledThreadPoolExecutor remoteConfigRepositoryExecutorService; - private final ThreadPoolExecutor abstractConfigExecutorService; - private final ThreadPoolExecutor abstractConfigFileExecutorService; - - public DefaultApolloThreadPoolCollector( - ScheduledExecutorService remoteConfigRepositoryExecutorService, - ExecutorService abstractConfigExecutorService, - ExecutorService abstractConfigFileExecutorService) { - super(THREAD_POOL_METRICS, "Nop"); - this.remoteConfigRepositoryExecutorService = (ScheduledThreadPoolExecutor) remoteConfigRepositoryExecutorService; - this.abstractConfigExecutorService = (ThreadPoolExecutor) abstractConfigExecutorService; - this.abstractConfigFileExecutorService = (ThreadPoolExecutor) abstractConfigFileExecutorService; - } - - @Override - public void collect0(MetricsEvent event) { - // do nothing - return; - } - - @Override - public void export0() { - exportThreadPoolMetrics(abstractConfigExecutorService, - AbstractConfig.class.getSimpleName()); - exportThreadPoolMetrics(abstractConfigFileExecutorService, - AbstractConfigFile.class.getSimpleName()); - exportThreadPoolMetrics(remoteConfigRepositoryExecutorService, - RemoteConfigRepository.class.getSimpleName()); - } - - @Override - public boolean isSamplesUpdated() { - // memory status special - return true; - } - - - @SuppressWarnings("unchecked") - public void exportThreadPoolMetrics(ThreadPoolExecutor executor, - String name) { - List metrics = Arrays.asList((double) executor.getActiveCount(), - (double) executor.getQueue().size(), - (double) executor.getCompletedTaskCount(), (double) executor.getPoolSize(), - (double) executor.getTaskCount(), (double) executor.getCorePoolSize(), - (double) executor.getMaximumPoolSize(), (double) executor.getLargestPoolSize(), - (double) (executor.getQueue().remainingCapacity() + executor.getQueue().size()), - (double) executor.getQueue().remainingCapacity(), - (double) executor.getPoolSize() / executor.getMaximumPoolSize()); - for (int i = 0; i < metrics.size(); i++) { - if (!gaugeSamples.containsKey(name + THREAD_POOL_PARAMS[i + 1])) { - gaugeSamples.put(name + THREAD_POOL_PARAMS[i + 1], - GaugeModel.builder().putTag(THREAD_POOL_PARAMS[0], name) - .name(THREAD_POOL_PARAMS[i + 1]) - .value(0).apply(GaugeModel.DOUBLE_CONVERTER).build()); - } - gaugeSamples.get(name + THREAD_POOL_PARAMS[i + 1]).updateValue(metrics.get(i)); - } - } - - - @Override - public int getRemoteConfigRepositoryThreadPoolActiveCount() { - return remoteConfigRepositoryExecutorService.getActiveCount(); - } - - @Override - public int getRemoteConfigRepositoryThreadPoolQueueSize() { - return remoteConfigRepositoryExecutorService.getQueue().size(); - } - - @Override - public int getRemoteConfigRepositoryThreadPoolCorePoolSize() { - return remoteConfigRepositoryExecutorService.getCorePoolSize(); - } - - @Override - public int getRemoteConfigRepositoryThreadPoolMaximumPoolSize() { - return remoteConfigRepositoryExecutorService.getMaximumPoolSize(); - } - - @Override - public int getRemoteConfigRepositoryThreadPoolPoolSize() { - return remoteConfigRepositoryExecutorService.getPoolSize(); - } - - @Override - public long getRemoteConfigRepositoryThreadPoolTaskCount() { - return remoteConfigRepositoryExecutorService.getTaskCount(); - } - - @Override - public long getRemoteConfigRepositoryThreadPoolCompletedTaskCount() { - return remoteConfigRepositoryExecutorService.getCompletedTaskCount(); - } - - @Override - public int getRemoteConfigRepositoryThreadPoolLargestPoolSize() { - return remoteConfigRepositoryExecutorService.getLargestPoolSize(); - } - - @Override - public int getRemoteConfigRepositoryThreadPoolRemainingCapacity() { - return remoteConfigRepositoryExecutorService.getQueue().remainingCapacity(); - } - - @Override - public double getRemoteConfigRepositoryThreadPoolCurrentLoad() { - return (double) remoteConfigRepositoryExecutorService.getPoolSize() - / remoteConfigRepositoryExecutorService.getMaximumPoolSize(); - } - - @Override - public int getAbstractConfigThreadPoolActiveCount() { - return abstractConfigExecutorService.getActiveCount(); - } - - @Override - public int getAbstractConfigThreadPoolQueueSize() { - return abstractConfigExecutorService.getQueue().size(); - } - - @Override - public int getAbstractConfigThreadPoolCorePoolSize() { - return abstractConfigExecutorService.getCorePoolSize(); - } - - @Override - public int getAbstractConfigThreadPoolMaximumPoolSize() { - return abstractConfigExecutorService.getMaximumPoolSize(); - } - - @Override - public int getAbstractConfigThreadPoolPoolSize() { - return abstractConfigExecutorService.getPoolSize(); - } - - @Override - public long getAbstractConfigThreadPoolTaskCount() { - return abstractConfigExecutorService.getTaskCount(); - } - - @Override - public long getAbstractConfigThreadPoolCompletedTaskCount() { - return abstractConfigExecutorService.getCompletedTaskCount(); - } - - @Override - public int getAbstractConfigThreadPoolLargestPoolSize() { - return abstractConfigExecutorService.getLargestPoolSize(); - } - - @Override - public int getAbstractConfigThreadPoolRemainingCapacity() { - return abstractConfigExecutorService.getQueue().remainingCapacity(); - } - - @Override - public double getAbstractConfigThreadPoolCurrentLoad() { - return (double) abstractConfigExecutorService.getPoolSize() - / abstractConfigExecutorService.getMaximumPoolSize(); - } - - @Override - public int getAbstractConfigFileThreadPoolActiveCount() { - return abstractConfigFileExecutorService.getActiveCount(); - } - - @Override - public int getAbstractConfigFileThreadPoolQueueSize() { - return abstractConfigFileExecutorService.getQueue().size(); - } - - @Override - public int getAbstractConfigFileThreadPoolCorePoolSize() { - return abstractConfigFileExecutorService.getCorePoolSize(); - } - - @Override - public int getAbstractConfigFileThreadPoolMaximumPoolSize() { - return abstractConfigFileExecutorService.getMaximumPoolSize(); - } - - @Override - public int getAbstractConfigFileThreadPoolPoolSize() { - return abstractConfigFileExecutorService.getPoolSize(); - } - - @Override - public long getAbstractConfigFileThreadPoolTaskCount() { - return abstractConfigFileExecutorService.getTaskCount(); - } - - @Override - public long getAbstractConfigFileThreadPoolCompletedTaskCount() { - return abstractConfigFileExecutorService.getCompletedTaskCount(); - } - - @Override - public int getAbstractConfigFileThreadPoolLargestPoolSize() { - return abstractConfigFileExecutorService.getLargestPoolSize(); - } - - @Override - public int getAbstractConfigFileThreadPoolRemainingCapacity() { - return abstractConfigFileExecutorService.getQueue().remainingCapacity(); - } - - @Override - public double getAbstractConfigFileThreadPoolCurrentLoad() { - return (double) abstractConfigFileExecutorService.getPoolSize() - / abstractConfigFileExecutorService.getMaximumPoolSize(); - } - -} \ No newline at end of file diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/util/MeterType.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/enums/MeterEnums.java similarity index 82% rename from apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/util/MeterType.java rename to apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/enums/MeterEnums.java index f200e262..1009d3ed 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/util/MeterType.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/enums/MeterEnums.java @@ -14,12 +14,19 @@ * limitations under the License. * */ -package com.ctrip.framework.apollo.monitor.internal.util; +package com.ctrip.framework.apollo.monitor.internal.enums; /** * @author Rawven */ -public enum MeterType { +public enum MeterEnums { + /** + * counter + */ COUNTER, + + /** + * gauge + */ GAUGE } \ No newline at end of file diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/MetricsEvent.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/event/ApolloConfigMetricsEvent.java similarity index 51% rename from apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/MetricsEvent.java rename to apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/event/ApolloConfigMetricsEvent.java index f8c5db31..78b44bb7 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/MetricsEvent.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/event/ApolloConfigMetricsEvent.java @@ -14,35 +14,43 @@ * limitations under the License. * */ -package com.ctrip.framework.apollo.monitor.internal.model; +package com.ctrip.framework.apollo.monitor.internal.event; import java.util.HashMap; import java.util.Map; /** - * metrics event model - * * @author Rawven */ -public class MetricsEvent { +public class ApolloConfigMetricsEvent { private final String name; - private final String tag; + private String tag; private final Map attachments; - private MetricsEvent(Builder builder) { - this.name = builder.name; - this.attachments = builder.attachment; - this.tag = builder.tag; + public ApolloConfigMetricsEvent(String name, String tag, Map attachments) { + this.name = name; + this.tag = tag; + this.attachments = attachments != null ? new HashMap<>(attachments) : new HashMap<>(); } - public static Builder builder() { - return new Builder(); + public ApolloConfigMetricsEvent withTag(String tag) { + this.tag = tag; + return this; } + public String getTag() { + return tag; + } public String getName() { return name; } + + public ApolloConfigMetricsEvent putAttachment(String key, Object value) { + this.attachments.put(key, value); + return this; + } + @SuppressWarnings("unchecked") public T getAttachmentValue(String key) { @@ -57,46 +65,9 @@ public T getAttachmentValue(String key) { } } - public String getTag() { - return tag; - } - @Override - public String toString() { - return "MetricsEvent{" + - "name='" + name + '\'' + - ", attachments=" + attachments + - ", tag='" + tag + '\'' + - '}'; + public void publish() { + ApolloConfigMetricsEventPublisher.publish(this); } - public static class Builder { - - private final Map attachment = new HashMap<>(3); - private String name; - private String tag; - - public Builder withName(String name) { - this.name = name; - return this; - } - - public Builder putAttachment(String k, Object v) { - this.attachment.put(k, v); - return this; - } - - public Builder withTag(String tag) { - this.tag = tag; - return this; - } - - public void push() { - MetricsEventPusher.push(this.build()); - } - - public MetricsEvent build() { - return new MetricsEvent(this); - } - } -} +} \ No newline at end of file diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/event/ApolloConfigMetricsEventFactory.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/event/ApolloConfigMetricsEventFactory.java new file mode 100644 index 00000000..b551dcc6 --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/event/ApolloConfigMetricsEventFactory.java @@ -0,0 +1,46 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.event; + +import java.util.HashMap; + +/** + * @author Rawven + * @date 2024/08/08 + */ +public class ApolloConfigMetricsEventFactory { + + public static volatile ApolloConfigMetricsEventFactory INSTANCE; + + private ApolloConfigMetricsEventFactory() { + } + + public static ApolloConfigMetricsEventFactory getInstance() { + if (INSTANCE == null) { + synchronized (ApolloConfigMetricsEventFactory.class) { + if (INSTANCE == null) { + INSTANCE = new ApolloConfigMetricsEventFactory(); + } + } + } + return INSTANCE; + } + + public ApolloConfigMetricsEvent createEvent(String name) { + return new ApolloConfigMetricsEvent(name, null, new HashMap<>(2)); + } +} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/MetricsEventPusher.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/event/ApolloConfigMetricsEventPublisher.java similarity index 58% rename from apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/MetricsEventPusher.java rename to apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/event/ApolloConfigMetricsEventPublisher.java index 0334a863..00906295 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/MetricsEventPusher.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/event/ApolloConfigMetricsEventPublisher.java @@ -14,25 +14,25 @@ * limitations under the License. * */ -package com.ctrip.framework.apollo.monitor.internal.model; +package com.ctrip.framework.apollo.monitor.internal.event; import com.ctrip.framework.apollo.build.ApolloInjector; -import com.ctrip.framework.apollo.monitor.internal.collector.MetricsCollector; -import com.ctrip.framework.apollo.monitor.internal.collector.MetricsCollectorManager; +import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMetricsEventListener; +import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMetricsEventListenerManager; import com.ctrip.framework.apollo.util.ConfigUtil; /** * @author Rawven */ -public abstract class MetricsEventPusher { +public class ApolloConfigMetricsEventPublisher { - private static final MetricsCollectorManager COLLECTOR_MANAGER = ApolloInjector.getInstance( - MetricsCollectorManager.class); + private static final ApolloClientMetricsEventListenerManager COLLECTOR_MANAGER = ApolloInjector.getInstance( + ApolloClientMetricsEventListenerManager.class); private static final ConfigUtil m_configUtil = ApolloInjector.getInstance(ConfigUtil.class); - public static void push(MetricsEvent event) { - if (m_configUtil.isClientMonitorEnabled()) { - for (MetricsCollector collector : COLLECTOR_MANAGER.getCollectors()) { + public static void publish(ApolloConfigMetricsEvent event) { + if (m_configUtil.getClientMonitorEnabled()) { + for (ApolloClientMetricsEventListener collector : COLLECTOR_MANAGER.getCollectors()) { if (collector.isSupport(event)) { collector.collect(event); return; diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractMetricsExporter.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractApolloClientMetricsExporter.java similarity index 68% rename from apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractMetricsExporter.java rename to apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractApolloClientMetricsExporter.java index 0f6e27ff..751b7449 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractMetricsExporter.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractApolloClientMetricsExporter.java @@ -18,27 +18,24 @@ import com.ctrip.framework.apollo.core.utils.ApolloThreadFactory; import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory; -import com.ctrip.framework.apollo.monitor.internal.collector.MetricsCollector; +import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMetricsEventListener; import com.ctrip.framework.apollo.monitor.internal.model.CounterModel; import com.ctrip.framework.apollo.monitor.internal.model.GaugeModel; -import com.ctrip.framework.apollo.monitor.internal.model.MetricsModel; +import com.ctrip.framework.apollo.monitor.internal.model.SampleModel; import java.util.List; -import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; /** - * General framework for access monitoring systems - *

- * 作者:Rawven + * @author Rawven */ -public abstract class AbstractMetricsExporter implements MetricsExporter { +public abstract class AbstractApolloClientMetricsExporter implements ApolloClientMetricsExporter { - protected static final Logger log = DeferredLoggerFactory.getLogger( - AbstractMetricsExporter.class); - protected static final ScheduledExecutorService m_executorService; + private static final Logger log = DeferredLoggerFactory.getLogger( + AbstractApolloClientMetricsExporter.class); + private static final ScheduledExecutorService m_executorService; private static final long INITIAL_DELAY = 5L; private static final int THREAD_POOL_SIZE = 1; @@ -47,10 +44,10 @@ public abstract class AbstractMetricsExporter implements MetricsExporter { ApolloThreadFactory.create("MetricsReporter", true)); } - protected List collectors; + protected List collectors; @Override - public void init(List collectors, long collectPeriod) { + public void init(List collectors, long collectPeriod) { log.info("Initializing metrics exporter with {} collectors and collect period of {} seconds.", collectors.size(), collectPeriod); doInit(); @@ -59,6 +56,9 @@ public void init(List collectors, long collectPeriod) { log.info("Metrics collection scheduled with a period of {} seconds.", collectPeriod); } + /** + * Provide initialization extension points + */ protected abstract void doInit(); private void initScheduleMetricsCollectSync(long collectPeriod) { @@ -74,21 +74,25 @@ private void initScheduleMetricsCollectSync(long collectPeriod) { protected void updateMetricsData() { log.debug("Start to update metrics data job"); collectors.forEach(collector -> { - if (collector.isSamplesUpdated()) { - log.debug("Collector {} has updated samples.", collector.name()); + if (collector.isMetricsSampleUpdated()) { + log.debug("Collector {} has updated samples.", collector.mBeanName()); collector.export().forEach(this::registerSample); } }); } - protected void registerSample(MetricsModel sample) { + protected void registerSample(SampleModel sample) { try { switch (sample.getType()) { case GAUGE: - registerGaugeSample((GaugeModel) sample); + GaugeModel gaugeModel = (GaugeModel) sample; + registerOrUpdateGaugeSample(gaugeModel.getName(), gaugeModel.getTags(), + gaugeModel.getValue()); break; case COUNTER: - registerCounterSample((CounterModel) sample); + CounterModel counterModel = (CounterModel) sample; + registerOrUpdateCounterSample(counterModel.getName(), counterModel.getTags(), + counterModel.getIncreaseValueAndResetZero()); break; default: log.warn("Unsupported sample type: {}", sample.getType()); @@ -99,14 +103,4 @@ protected void registerSample(MetricsModel sample) { } } - protected String[][] getTags(MetricsModel sample) { - Map tags = sample.getTags(); - if (tags == null || tags.isEmpty()) { - return new String[][]{new String[0], new String[0]}; - } - String[] labelNames = tags.keySet().toArray(new String[0]); - String[] labelValues = tags.values().toArray(new String[0]); - return new String[][]{labelNames, labelValues}; - } - } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/MetricsExporter.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/ApolloClientMetricsExporter.java similarity index 65% rename from apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/MetricsExporter.java rename to apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/ApolloClientMetricsExporter.java index da9c64f9..079ab88e 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/MetricsExporter.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/ApolloClientMetricsExporter.java @@ -17,37 +17,38 @@ package com.ctrip.framework.apollo.monitor.internal.exporter; import com.ctrip.framework.apollo.core.spi.Ordered; -import com.ctrip.framework.apollo.monitor.internal.collector.MetricsCollector; +import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMetricsEventListener; import com.ctrip.framework.apollo.monitor.internal.model.CounterModel; import com.ctrip.framework.apollo.monitor.internal.model.GaugeModel; +import java.util.Date; import java.util.List; +import java.util.Map; /** * @author Rawven */ -public interface MetricsExporter extends Ordered { +public interface ApolloClientMetricsExporter extends Ordered { /** * init method */ - void init(List collectors, long collectPeriod); + void init(List collectors, long collectPeriod); /** - * is support - * - * @param form form + * Used to access custom monitoring systems */ boolean isSupport(String form); /** - * used to register Counter type metrics + * register or update counter sample */ - void registerCounterSample(CounterModel sample); + void registerOrUpdateCounterSample(String name, Map tag, double incrValue); + /** - * used to register Gauge type metrics + * register or update gauge sample */ - void registerGaugeSample(GaugeModel sample); + void registerOrUpdateGaugeSample(String name, Map tag, double value); /** * result of the collect metrics diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/MetricsExporterFactory.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/ApolloClientMetricsExporterFactory.java similarity index 74% rename from apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/MetricsExporterFactory.java rename to apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/ApolloClientMetricsExporterFactory.java index 178c5f27..5433674a 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/MetricsExporterFactory.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/ApolloClientMetricsExporterFactory.java @@ -16,13 +16,13 @@ */ package com.ctrip.framework.apollo.monitor.internal.exporter; -import com.ctrip.framework.apollo.monitor.internal.collector.MetricsCollector; +import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMetricsEventListener; import java.util.List; /** * @author Rawven */ -public interface MetricsExporterFactory { +public interface ApolloClientMetricsExporterFactory { - MetricsExporter getMetricsReporter(List collectors); + ApolloClientMetricsExporter getMetricsReporter(List collectors); } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/impl/DefaultApolloClientMetricsExporterFactory.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/impl/DefaultApolloClientMetricsExporterFactory.java new file mode 100644 index 00000000..5f8793e5 --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/impl/DefaultApolloClientMetricsExporterFactory.java @@ -0,0 +1,89 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.exporter.impl; + +import static com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorConstant.MBEAN_NAME; + +import com.ctrip.framework.apollo.build.ApolloInjector; +import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory; +import com.ctrip.framework.apollo.exceptions.ApolloConfigException; +import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMetricsEventListener; +import com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporter; +import com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporterFactory; +import com.ctrip.framework.apollo.monitor.internal.jmx.ApolloClientJmxMBeanRegister; +import com.ctrip.framework.apollo.tracer.Tracer; +import com.ctrip.framework.apollo.util.ConfigUtil; +import com.ctrip.framework.foundation.internals.ServiceBootstrap; +import java.util.List; +import org.slf4j.Logger; + +/** + * @author Rawven + */ +public class DefaultApolloClientMetricsExporterFactory implements + ApolloClientMetricsExporterFactory { + + private static final Logger logger = DeferredLoggerFactory.getLogger( + DefaultApolloClientMetricsExporterFactory.class); + private final ConfigUtil configUtil = ApolloInjector.getInstance(ConfigUtil.class); + + @Override + public ApolloClientMetricsExporter getMetricsReporter( + List collectors) { + initializeJmxMonitoring(collectors); + + String externalSystemType = configUtil.getMonitorExternalType(); + if (externalSystemType == null) { + return null; + } + + return findAndInitializeExporter(collectors, externalSystemType); + } + + public void initializeJmxMonitoring(List collectors) { + if (configUtil.getClientMonitorJmxEnabled()) { + collectors.forEach(metricsCollector -> + ApolloClientJmxMBeanRegister.register( + MBEAN_NAME + metricsCollector.mBeanName(), metricsCollector) + ); + } + } + + private ApolloClientMetricsExporter findAndInitializeExporter( + List collectors, String externalSystemType) { + List exporters = ServiceBootstrap.loadAllOrdered( + ApolloClientMetricsExporter.class); + ApolloClientMetricsExporter reporter = exporters.stream() + .filter(metricsExporter -> metricsExporter.isSupport(externalSystemType)) + .findFirst() + .orElse(null); + + if (reporter != null) { + reporter.init(collectors, configUtil.getMonitorExternalExportPeriod()); + } else { + String errorMessage = + "No matching exporter found with monitor-external-type " + externalSystemType; + ApolloConfigException exception = new ApolloConfigException(errorMessage); + logger.error( + "Error initializing exporter for external-type: {}. Please check if external-type is misspelled or the correct dependency is not introduced, such as apollo-plugin-client-prometheus", + externalSystemType, exception); + Tracer.logError(exception); + } + return reporter; + } + +} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/impl/NullApolloClientMetricsExporter.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/impl/NullApolloClientMetricsExporter.java new file mode 100644 index 00000000..44d51d57 --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/impl/NullApolloClientMetricsExporter.java @@ -0,0 +1,55 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.exporter.impl; + +import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMetricsEventListener; +import com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporter; +import com.ctrip.framework.apollo.monitor.internal.model.CounterModel; +import com.ctrip.framework.apollo.monitor.internal.model.GaugeModel; +import java.util.List; +import java.util.Map; + +/** + * @author Rawven + */ +public class NullApolloClientMetricsExporter implements ApolloClientMetricsExporter { + + @Override + public void init(List collectors, long collectPeriod) { + } + + @Override + public boolean isSupport(String form) { + return false; + } + + @Override + public void registerOrUpdateCounterSample(String name, Map tag, + double incrValue) { + + } + + @Override + public void registerOrUpdateGaugeSample(String name, Map tag, double value) { + + } + + @Override + public String response() { + return "No Reporter Use"; + } +} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/internals/DefaultMetricsExporterFactory.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/internals/DefaultMetricsExporterFactory.java deleted file mode 100644 index 5a0279b1..00000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/internals/DefaultMetricsExporterFactory.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright 2022 Apollo Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.ctrip.framework.apollo.monitor.internal.exporter.internals; - -import static com.ctrip.framework.apollo.monitor.internal.MonitorConstant.MBEAN_NAME; - -import com.ctrip.framework.apollo.build.ApolloInjector; -import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory; -import com.ctrip.framework.apollo.exceptions.ApolloConfigException; -import com.ctrip.framework.apollo.monitor.internal.collector.MetricsCollector; -import com.ctrip.framework.apollo.monitor.internal.collector.internal.DefaultMetricsCollectorManager; -import com.ctrip.framework.apollo.monitor.internal.exporter.MetricsExporter; -import com.ctrip.framework.apollo.monitor.internal.exporter.MetricsExporterFactory; -import com.ctrip.framework.apollo.monitor.internal.util.JMXUtil; -import com.ctrip.framework.apollo.tracer.Tracer; -import com.ctrip.framework.apollo.util.ConfigUtil; -import com.ctrip.framework.foundation.internals.ServiceBootstrap; -import java.util.List; -import org.slf4j.Logger; - -public class DefaultMetricsExporterFactory implements MetricsExporterFactory { - - private static final Logger logger = DeferredLoggerFactory.getLogger( - DefaultMetricsCollectorManager.class); - private final ConfigUtil m_configUtil; - - public DefaultMetricsExporterFactory() { - m_configUtil = ApolloInjector.getInstance(ConfigUtil.class); - } - - @Override - public MetricsExporter getMetricsReporter(List collectors) { - //initialize reporter - if (m_configUtil.isClientMonitorJmxEnabled()) { - collectors.forEach(metricsCollector -> - JMXUtil.register(MBEAN_NAME + metricsCollector.name(), - metricsCollector)); - } - String externalSystemType = m_configUtil.getMonitorExternalType(); - MetricsExporter reporter = null; - if (externalSystemType != null) { - List metricsExporters = ServiceBootstrap.loadAllOrdered( - MetricsExporter.class); - for (MetricsExporter metricsExporter : metricsExporters) { - if (metricsExporter.isSupport(externalSystemType)) { - reporter = metricsExporter; - reporter.init(collectors, m_configUtil.getMonitorExternalExportPeriod()); - break; - } - } - if (reporter == null) { - String errorMessage = - "No matching exporter found with monitor-external-type " + externalSystemType; - ApolloConfigException exception = new ApolloConfigException(errorMessage); - logger.error( - "Error initializing exporter for external-type: {}. Please check if external-type is misspelled or the correct dependency is not introduced, such as apollo-plugin-client-prometheus", - externalSystemType, exception); - Tracer.logError(exception); - } - } - return reporter; - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/util/JMXUtil.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/jmx/ApolloClientJmxMBeanRegister.java similarity index 53% rename from apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/util/JMXUtil.java rename to apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/jmx/ApolloClientJmxMBeanRegister.java index cc34c68a..33d9108d 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/util/JMXUtil.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/jmx/ApolloClientJmxMBeanRegister.java @@ -14,21 +14,41 @@ * limitations under the License. * */ -package com.ctrip.framework.apollo.monitor.internal.util; +package com.ctrip.framework.apollo.monitor.internal.jmx; +import static com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorConstant.MBEAN_NAME; + +import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory; import java.lang.management.ManagementFactory; import javax.management.JMException; import javax.management.MBeanServer; +import javax.management.MalformedObjectNameException; import javax.management.ObjectName; +import org.slf4j.Logger; /** * @author Rawven */ -public final class JMXUtil { +public final class ApolloClientJmxMBeanRegister { + + private static final Logger logger = DeferredLoggerFactory.getLogger( + ApolloClientJmxMBeanRegister.class); + private static MBeanServer mbeanServer; + private static ObjectName ERROR_OBJECT_NAME; - public static MBeanServer mbeanServer; + static { + try { + ERROR_OBJECT_NAME = new ObjectName(MBEAN_NAME + "error"); + } catch (MalformedObjectNameException e) { + logger.warn("MalformedObjectNameException during static initialization.", e); + } + } + + public static synchronized void setMBeanServer(MBeanServer mbeanServer) { + ApolloClientJmxMBeanRegister.mbeanServer = mbeanServer; + } - public static ObjectName register(String name, Object mbean) { + public static synchronized ObjectName register(String name, Object mbean) { try { ObjectName objectName = new ObjectName(name); @@ -43,16 +63,17 @@ public static ObjectName register(String name, Object mbean) { return objectName; } catch (JMException e) { - throw new IllegalArgumentException(name, e); + logger.error("Register JMX MBean failed.", e); + return ERROR_OBJECT_NAME; } } - public static void unregister(String name) { + public static synchronized void unregister(String name) { try { MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); mbeanServer.unregisterMBean(new ObjectName(name)); } catch (JMException e) { - throw new IllegalArgumentException(name, e); + logger.error("Unregister JMX MBean failed.", e); } } } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/MonitorConstant.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/jmx/mbean/ApolloClientJmxBootstrapArgsMBean.java similarity index 68% rename from apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/MonitorConstant.java rename to apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/jmx/mbean/ApolloClientJmxBootstrapArgsMBean.java index ea289e1f..024cbd8c 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/MonitorConstant.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/jmx/mbean/ApolloClientJmxBootstrapArgsMBean.java @@ -14,16 +14,15 @@ * limitations under the License. * */ -package com.ctrip.framework.apollo.monitor.internal; +package com.ctrip.framework.apollo.monitor.internal.jmx.mbean; + +import com.ctrip.framework.apollo.monitor.api.ApolloClientBootstrapArgsMonitorApi; +import javax.management.MXBean; /** - * metrics constant - * * @author Rawven */ -public class MonitorConstant { +@MXBean +public interface ApolloClientJmxBootstrapArgsMBean extends ApolloClientBootstrapArgsMonitorApi { - public static final String NAMESPACE = "namespace"; - public static final String TIMESTAMP = "timestamp"; - public static final String MBEAN_NAME = "apollo.client.monitor:type="; } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/jmx/mbean/ApolloClientJmxExceptionMBean.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/jmx/mbean/ApolloClientJmxExceptionMBean.java new file mode 100644 index 00000000..016c5451 --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/jmx/mbean/ApolloClientJmxExceptionMBean.java @@ -0,0 +1,34 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.jmx.mbean; + +import java.util.List; +import javax.management.MXBean; + +/** + * @author Rawven + */ +@MXBean +public interface ApolloClientJmxExceptionMBean { + // Because JMX does not support Exception type return values + // declare the interface separately. + + /** + * get exception details + */ + List getApolloConfigExceptionDetails(); +} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/jmx/mbean/ApolloClientJmxNamespaceMBean.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/jmx/mbean/ApolloClientJmxNamespaceMBean.java new file mode 100644 index 00000000..569a6a2a --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/jmx/mbean/ApolloClientJmxNamespaceMBean.java @@ -0,0 +1,28 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.jmx.mbean; + +import com.ctrip.framework.apollo.monitor.api.ApolloClientNamespaceMonitorApi; +import javax.management.MXBean; + +/** + * @author Rawven + */ +@MXBean +public interface ApolloClientJmxNamespaceMBean extends ApolloClientNamespaceMonitorApi { + +} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/jmx/mbean/ApolloClientJmxThreadPoolMBean.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/jmx/mbean/ApolloClientJmxThreadPoolMBean.java new file mode 100644 index 00000000..78d090fa --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/jmx/mbean/ApolloClientJmxThreadPoolMBean.java @@ -0,0 +1,29 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.jmx.mbean; + +import com.ctrip.framework.apollo.monitor.api.ApolloClientThreadPoolMonitorApi; +import javax.management.MXBean; + +/** + * @author Rawven + */ +@MXBean +public interface ApolloClientJmxThreadPoolMBean extends ApolloClientThreadPoolMonitorApi { + + +} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/AbstractApolloClientMetricsEventListener.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/AbstractApolloClientMetricsEventListener.java new file mode 100644 index 00000000..db670c0d --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/AbstractApolloClientMetricsEventListener.java @@ -0,0 +1,114 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.listener; + +import com.ctrip.framework.apollo.monitor.internal.event.ApolloConfigMetricsEvent; +import com.ctrip.framework.apollo.monitor.internal.model.CounterModel; +import com.ctrip.framework.apollo.monitor.internal.model.GaugeModel; +import com.ctrip.framework.apollo.monitor.internal.model.SampleModel; +import com.google.common.collect.Maps; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * 抽象的 Metrics 收集器 用于收集数据和导出指标样本 + * + * @author Rawven + */ +public abstract class AbstractApolloClientMetricsEventListener implements + ApolloClientMetricsEventListener { + + private final Map counterSamples = Maps.newConcurrentMap(); + private final Map gaugeSamples = Maps.newConcurrentMap(); + private final AtomicBoolean isUpdated = new AtomicBoolean(); + private final String tag; + + public AbstractApolloClientMetricsEventListener(String tag) { + this.tag = tag; + } + + /** + * Specific collection logic + */ + protected abstract void collect0(ApolloConfigMetricsEvent event); + + /** + * Convenient for indicators that can only be obtained from the status object + */ + protected abstract void export0(); + + @Override + public String mBeanName() { + return tag; + } + + @Override + public boolean isSupport(ApolloConfigMetricsEvent event) { + return tag.equals(event.getTag()); + } + + @Override + public void collect(ApolloConfigMetricsEvent event) { + collect0(event); + isUpdated.set(true); + } + + /** + * Whether the sample data has been updated + */ + @Override + public boolean isMetricsSampleUpdated() { + return isUpdated.getAndSet(false); + } + + @Override + public List export() { + export0(); + List samples = new ArrayList<>(counterSamples.values()); + samples.addAll(gaugeSamples.values()); + return samples; + } + + + /** + * tool method for updating indicator model + */ + public void createOrUpdateGaugeSample(String mapKey, String metricsName, Map tags, + double value) { + if (!gaugeSamples.containsKey(mapKey)) { + GaugeModel builder = (GaugeModel) GaugeModel.create(metricsName, 0).putTags(tags); + gaugeSamples.put(mapKey, builder); + } + gaugeSamples.get(mapKey).setValue(value); + } + + /** + * tool method for updating indicator model + */ + public void createOrUpdateCounterSample(String mapKey, String metricsName, + Map tags, + double increaseValue) { + if (!counterSamples.containsKey(mapKey)) { + CounterModel builder = (CounterModel) CounterModel.create(metricsName, 0).putTags(tags); + counterSamples.put(mapKey, builder); + } + counterSamples.get(mapKey).increase(increaseValue); + } + +} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/MetricsCollector.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/ApolloClientMetricsEventListener.java similarity index 63% rename from apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/MetricsCollector.java rename to apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/ApolloClientMetricsEventListener.java index e1efd0d2..3dc3eda4 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/MetricsCollector.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/ApolloClientMetricsEventListener.java @@ -14,39 +14,42 @@ * limitations under the License. * */ -package com.ctrip.framework.apollo.monitor.internal.collector; +package com.ctrip.framework.apollo.monitor.internal.listener; -import com.ctrip.framework.apollo.monitor.internal.model.MetricsEvent; -import com.ctrip.framework.apollo.monitor.internal.model.MetricsModel; +import com.ctrip.framework.apollo.monitor.internal.event.ApolloConfigMetricsEvent; +import com.ctrip.framework.apollo.monitor.internal.model.SampleModel; import java.util.List; /** * @author Rawven */ -public interface MetricsCollector { +public interface ApolloClientMetricsEventListener { - String name(); + /** + * mbean name + */ + String mBeanName(); /** * is support the event */ - boolean isSupport(MetricsEvent event); + boolean isSupport(ApolloConfigMetricsEvent event); /** * collect metrics from event */ - void collect(MetricsEvent event); + void collect(ApolloConfigMetricsEvent event); /** * is samples updated */ - boolean isSamplesUpdated(); + boolean isMetricsSampleUpdated(); /** * export to a format recognized by the monitoring system */ - List export(); + List export(); } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/MetricsCollectorManager.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/ApolloClientMetricsEventListenerManager.java similarity index 80% rename from apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/MetricsCollectorManager.java rename to apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/ApolloClientMetricsEventListenerManager.java index 75a28aa5..283631a9 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/MetricsCollectorManager.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/ApolloClientMetricsEventListenerManager.java @@ -14,7 +14,7 @@ * limitations under the License. * */ -package com.ctrip.framework.apollo.monitor.internal.collector; +package com.ctrip.framework.apollo.monitor.internal.listener; import com.ctrip.framework.apollo.core.spi.Ordered; import java.util.List; @@ -22,12 +22,12 @@ /** * @author Rawven */ -public interface MetricsCollectorManager extends Ordered { +public interface ApolloClientMetricsEventListenerManager extends Ordered { /** * get collectors */ - List getCollectors(); + List getCollectors(); @Override default int getOrder() { diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientBootstrapArgsApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientBootstrapArgsApi.java new file mode 100644 index 00000000..5ffd5357 --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientBootstrapArgsApi.java @@ -0,0 +1,225 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.listener.impl; + +import static com.ctrip.framework.apollo.core.ApolloClientSystemConsts.*; +import static com.ctrip.framework.apollo.core.ConfigConsts.APOLLO_AUTO_UPDATE_INJECTED_SPRING_PROPERTIES; +import static com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorConstant.*; +import static com.ctrip.framework.apollo.spring.config.PropertySourcesConstants.*; + +import com.ctrip.framework.apollo.Apollo; +import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory; +import com.ctrip.framework.apollo.monitor.api.ApolloClientBootstrapArgsMonitorApi; +import com.ctrip.framework.apollo.monitor.internal.jmx.mbean.ApolloClientJmxBootstrapArgsMBean; +import com.ctrip.framework.apollo.monitor.internal.listener.AbstractApolloClientMetricsEventListener; +import com.ctrip.framework.apollo.monitor.internal.event.ApolloConfigMetricsEvent; +import com.ctrip.framework.apollo.util.ConfigUtil; +import com.google.common.collect.Maps; +import java.util.Map; +import java.util.Optional; +import org.slf4j.Logger; + +/** + * @author Rawven + */ +public class DefaultApolloClientBootstrapArgsApi extends + AbstractApolloClientMetricsEventListener implements + ApolloClientBootstrapArgsMonitorApi, ApolloClientJmxBootstrapArgsMBean { + + private static final Logger logger = DeferredLoggerFactory.getLogger( + DefaultApolloClientBootstrapArgsApi.class); + private final Map bootstrapArgs = Maps.newHashMap(); + private final Map bootstrapArgsString = Maps.newHashMap(); + + public DefaultApolloClientBootstrapArgsApi(ConfigUtil configUtil) { + super(TAG_BOOTSTRAP); + bootstrapArgs.put(APOLLO_ACCESS_KEY_SECRET, configUtil.getAccessKeySecret()); + bootstrapArgs.put(APOLLO_AUTO_UPDATE_INJECTED_SPRING_PROPERTIES, + configUtil.isAutoUpdateInjectedSpringPropertiesEnabled()); + bootstrapArgs.put(APOLLO_BOOTSTRAP_ENABLED, + Boolean.parseBoolean(System.getProperty(APOLLO_BOOTSTRAP_ENABLED))); + bootstrapArgs.put(APOLLO_BOOTSTRAP_NAMESPACES, + System.getProperty(APOLLO_BOOTSTRAP_NAMESPACES)); + bootstrapArgs.put(APOLLO_BOOTSTRAP_EAGER_LOAD_ENABLED, + Boolean.parseBoolean(System.getProperty(APOLLO_BOOTSTRAP_EAGER_LOAD_ENABLED))); + bootstrapArgs.put(APOLLO_OVERRIDE_SYSTEM_PROPERTIES, configUtil.isOverrideSystemProperties()); + bootstrapArgs.put(APOLLO_CACHE_DIR, configUtil.getDefaultLocalCacheDir()); + bootstrapArgs.put(APOLLO_CLUSTER, configUtil.getCluster()); + bootstrapArgs.put(APOLLO_CONFIG_SERVICE, + System.getProperty(APOLLO_CONFIG_SERVICE)); + bootstrapArgs.put(APOLLO_CLIENT_MONITOR_EXTERNAL_TYPE, configUtil.getMonitorExternalType()); + bootstrapArgs.put(APOLLO_CLIENT_MONITOR_ENABLED, configUtil.getClientMonitorEnabled()); + bootstrapArgs.put(APOLLO_CLIENT_MONITOR_EXTERNAL_EXPORT_PERIOD, + configUtil.getMonitorExternalExportPeriod()); + bootstrapArgs.put(APOLLO_META, configUtil.getMetaServerDomainName()); + bootstrapArgs.put(APOLLO_PROPERTY_NAMES_CACHE_ENABLE, configUtil.isPropertyNamesCacheEnabled()); + bootstrapArgs.put(APOLLO_PROPERTY_ORDER_ENABLE, configUtil.isPropertiesOrderEnabled()); + bootstrapArgs.put(APOLLO_CLIENT_MONITOR_JMX_ENABLED, configUtil.getClientMonitorJmxEnabled()); + bootstrapArgs.put(APOLLO_CLIENT_MONITOR_EXCEPTION_QUEUE_SIZE, + configUtil.getMonitorExceptionQueueSize()); + bootstrapArgs.put(APP_ID, configUtil.getAppId()); + bootstrapArgs.put(ENV, configUtil.getApolloEnv()); + bootstrapArgs.put(VERSION, Apollo.VERSION); + bootstrapArgs.forEach((key, value) -> { + if (value != null) { + bootstrapArgsString.put(key, value.toString()); + } + }); + + } + + @Override + public void collect0(ApolloConfigMetricsEvent event) { + String argName = event.getName(); + if (bootstrapArgs.containsKey(argName)) { + bootstrapArgs.put(argName, event.getAttachmentValue(argName)); + } else { + logger.warn("Unhandled event name: {}", argName); + } + } + + @Override + public boolean isMetricsSampleUpdated() { + return false; + } + + @Override + public void export0() { + // do nothing + } + + @Override + public String getStartupParams(String key) { + return Optional.ofNullable(bootstrapArgs.get(key)).orElse("").toString(); + } + + @Override + public String getConfigServiceUrl() { + return bootstrapArgs.get(CONFIG_SERVICE_URL).toString(); + } + + + @Override + public String getAccessKeySecret() { + return bootstrapArgs.getOrDefault(APOLLO_ACCESS_KEY_SECRET, "").toString(); + } + + @Override + public Boolean getAutoUpdateInjectedSpringProperties() { + return (Boolean) bootstrapArgs.get(APOLLO_AUTO_UPDATE_INJECTED_SPRING_PROPERTIES); + } + + @Override + public Boolean getBootstrapEnabled() { + return (Boolean) bootstrapArgs.get(APOLLO_BOOTSTRAP_ENABLED); + } + + @Override + public String getBootstrapNamespaces() { + return (String) bootstrapArgs.get(APOLLO_BOOTSTRAP_NAMESPACES); + } + + @Override + public Boolean getBootstrapEagerLoadEnabled() { + return (Boolean) bootstrapArgs.get(APOLLO_BOOTSTRAP_EAGER_LOAD_ENABLED); + } + + @Override + public Boolean getOverrideSystemProperties() { + return (Boolean) bootstrapArgs.get(APOLLO_OVERRIDE_SYSTEM_PROPERTIES); + } + + @Override + public String getCacheDir() { + return bootstrapArgs.get(APOLLO_CACHE_DIR).toString(); + } + + @Override + public String getCluster() { + return bootstrapArgs.get(APOLLO_CLUSTER).toString(); + } + + @Override + public String getConfigService() { + return bootstrapArgs.get(APOLLO_CONFIG_SERVICE).toString(); + } + + @Override + public String getClientMonitorExternalForm() { + return bootstrapArgs.get(APOLLO_CLIENT_MONITOR_EXTERNAL_TYPE).toString(); + } + + @Override + public Boolean getClientMonitorEnabled() { + return (Boolean) bootstrapArgs.get(APOLLO_CLIENT_MONITOR_ENABLED); + } + + @Override + public Boolean getClientMonitorJmxEnabled() { + return (Boolean) bootstrapArgs.get(APOLLO_CLIENT_MONITOR_JMX_ENABLED); + } + + @Override + public long getClientMonitorExternalExportPeriod() { + return (Long) bootstrapArgs.get(APOLLO_CLIENT_MONITOR_EXTERNAL_EXPORT_PERIOD); + } + + @Override + public int getClientMonitorExceptionSaveSize() { + return (int) bootstrapArgs.get(APOLLO_CLIENT_MONITOR_EXCEPTION_QUEUE_SIZE); + } + + @Override + public String getApolloMeta() { + return bootstrapArgs.get(APOLLO_META).toString(); + } + + @Override + public Boolean getPropertyNamesCacheEnable() { + return (Boolean) bootstrapArgs.get(APOLLO_PROPERTY_NAMES_CACHE_ENABLE); + } + + @Override + public Boolean getPropertyOrderEnable() { + return (Boolean) bootstrapArgs.get(APOLLO_PROPERTY_ORDER_ENABLE); + } + + @Override + public String getMetaLatestFreshTime() { + return bootstrapArgs.get(META_FRESH).toString(); + } + + @Override + public String getVersion() { + return bootstrapArgs.get(VERSION).toString(); + } + + @Override + public String getEnv() { + return bootstrapArgs.get(ENV).toString(); + } + + @Override + public String getAppId() { + return bootstrapArgs.get(APP_ID).toString(); + } + + @Override + public Map getBootstrapArgs() { + return bootstrapArgsString; + } +} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientExceptionApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientExceptionApi.java new file mode 100644 index 00000000..c7cd41aa --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientExceptionApi.java @@ -0,0 +1,89 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.listener.impl; + +import static com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorConstant.METRICS_EXCEPTION_NUM; +import static com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorConstant.TAG_ERROR; +import static com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorConstant.THROWABLE; + +import com.ctrip.framework.apollo.build.ApolloInjector; +import com.ctrip.framework.apollo.exceptions.ApolloConfigException; +import com.ctrip.framework.apollo.monitor.api.ApolloClientExceptionMonitorApi; +import com.ctrip.framework.apollo.monitor.internal.jmx.mbean.ApolloClientJmxExceptionMBean; +import com.ctrip.framework.apollo.monitor.internal.listener.AbstractApolloClientMetricsEventListener; +import com.ctrip.framework.apollo.monitor.internal.event.ApolloConfigMetricsEvent; +import com.ctrip.framework.apollo.monitor.internal.model.CounterModel; +import com.ctrip.framework.apollo.util.ConfigUtil; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Collectors; + +/** + * @author Rawven + */ +public class DefaultApolloClientExceptionApi extends + AbstractApolloClientMetricsEventListener implements + ApolloClientExceptionMonitorApi, ApolloClientJmxExceptionMBean { + + private static final int MAX_EXCEPTIONS_SIZE = ApolloInjector.getInstance(ConfigUtil.class) + .getMonitorExceptionQueueSize(); + private final BlockingQueue exceptions = new ArrayBlockingQueue<>( + MAX_EXCEPTIONS_SIZE); + private final AtomicInteger exceptionNum = new AtomicInteger(0); + + public DefaultApolloClientExceptionApi() { + super(TAG_ERROR); + } + + @Override + public List getApolloConfigExceptionList() { + return new ArrayList<>(exceptions); + } + + @Override + public void collect0(ApolloConfigMetricsEvent event) { + ApolloConfigException exception = event.getAttachmentValue(THROWABLE); + if (exception != null) { + addExceptionToQueue(exception); + exceptionNum.incrementAndGet(); + createOrUpdateCounterSample(METRICS_EXCEPTION_NUM, METRICS_EXCEPTION_NUM, + Collections.emptyMap(), + 1); + } + } + + private void addExceptionToQueue(ApolloConfigException exception) { + if (exceptions.size() >= MAX_EXCEPTIONS_SIZE) { + exceptions.poll(); + } + exceptions.add(exception); + } + + @Override + public void export0() {} + + @Override + public List getApolloConfigExceptionDetails() { + return exceptions.stream() + .map(ApolloConfigException::getMessage) + .collect(Collectors.toList()); + } +} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/internal/DefaultMetricsCollectorManager.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientMetricsEventListenerManager.java similarity index 50% rename from apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/internal/DefaultMetricsCollectorManager.java rename to apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientMetricsEventListenerManager.java index 972b4da0..f0a54fc5 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/collector/internal/DefaultMetricsCollectorManager.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientMetricsEventListenerManager.java @@ -14,28 +14,31 @@ * limitations under the License. * */ -package com.ctrip.framework.apollo.monitor.internal.collector.internal; +package com.ctrip.framework.apollo.monitor.internal.listener.impl; -import com.ctrip.framework.apollo.monitor.internal.collector.MetricsCollector; -import com.ctrip.framework.apollo.monitor.internal.collector.MetricsCollectorManager; +import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMetricsEventListener; +import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMetricsEventListenerManager; +import java.util.Collections; import java.util.List; /** * @author Rawven */ -public class DefaultMetricsCollectorManager implements MetricsCollectorManager { +public class DefaultApolloClientMetricsEventListenerManager implements + ApolloClientMetricsEventListenerManager { - private List collectors; + private List collectors; - public DefaultMetricsCollectorManager() { + public DefaultApolloClientMetricsEventListenerManager() { + collectors = Collections.emptyList(); } @Override - public List getCollectors() { + public List getCollectors() { return collectors; } - public void setCollectors(List collectors) { + public void setCollectors(List collectors) { this.collectors = collectors; } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientNamespaceApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientNamespaceApi.java new file mode 100644 index 00000000..231bcaa2 --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientNamespaceApi.java @@ -0,0 +1,239 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.listener.impl; + + +import static com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorConstant.*; + +import com.ctrip.framework.apollo.Config; +import com.ctrip.framework.apollo.ConfigFile; +import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory; +import com.ctrip.framework.apollo.monitor.api.ApolloClientNamespaceMonitorApi; +import com.ctrip.framework.apollo.monitor.internal.jmx.mbean.ApolloClientJmxNamespaceMBean; +import com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorConstant; +import com.ctrip.framework.apollo.monitor.internal.listener.AbstractApolloClientMetricsEventListener; +import com.ctrip.framework.apollo.monitor.internal.event.ApolloConfigMetricsEvent; +import com.ctrip.framework.apollo.monitor.internal.model.CounterModel; +import com.ctrip.framework.apollo.monitor.internal.model.GaugeModel; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; +import org.slf4j.Logger; + +/** + * @author Rawven + */ +public class DefaultApolloClientNamespaceApi extends + AbstractApolloClientMetricsEventListener implements + ApolloClientNamespaceMonitorApi, ApolloClientJmxNamespaceMBean { + + private static final Logger logger = DeferredLoggerFactory.getLogger( + DefaultApolloClientNamespaceApi.class); + private final Map m_configs; + private final Map m_configFiles; + private final Map namespaces = Maps.newConcurrentMap(); + private final List namespace404 = Lists.newCopyOnWriteArrayList(); + private final List namespaceTimeout = Lists.newCopyOnWriteArrayList(); + + public DefaultApolloClientNamespaceApi(Map m_configs, + Map m_configFiles + ) { + super(TAG_NAMESPACE); + this.m_configs = m_configs; + this.m_configFiles = m_configFiles; + } + + @Override + public void collect0(ApolloConfigMetricsEvent event) { + String namespace = event.getAttachmentValue(NAMESPACE); + String eventName = event.getName(); + + switch (eventName) { + case APOLLO_CLIENT_NAMESPACE_NOT_FOUND: + namespace404.add(namespace); + break; + case APOLLO_CLIENT_NAMESPACE_TIMEOUT: + namespaceTimeout.add(namespace); + break; + default: + NamespaceMetrics namespaceMetrics = namespaces.computeIfAbsent(namespace, + k -> new NamespaceMetrics()); + handleNamespaceMetricsEvent(event, namespaceMetrics, namespace); + break; + } + } + + private void handleNamespaceMetricsEvent(ApolloConfigMetricsEvent event, + NamespaceMetrics namespaceMetrics, String namespace) { + String eventName = event.getName(); + switch (eventName) { + case APOLLO_CLIENT_NAMESPACE_USAGE: + namespaceMetrics.incrementUsageCount(); + String mapKey = namespace + ApolloClientMonitorConstant.METRICS_NAMESPACE_USAGE; + createOrUpdateCounterSample(mapKey, ApolloClientMonitorConstant.METRICS_NAMESPACE_USAGE, + Collections.singletonMap(NAMESPACE, namespace), 1); + break; + case METRICS_NAMESPACE_LATEST_UPDATE_TIME: + long updateTime = event.getAttachmentValue(ApolloClientMonitorConstant.TIMESTAMP); + namespaceMetrics.setLatestUpdateTime(updateTime); + break; + case APOLLO_CLIENT_NAMESPACE_FIRST_LOAD_SPEND: + long firstLoadSpendTime = event.getAttachmentValue(ApolloClientMonitorConstant.TIMESTAMP); + namespaceMetrics.setFirstLoadSpend(firstLoadSpendTime); + break; + case NAMESPACE_RELEASE_KEY: + String releaseKey = event.getAttachmentValue(NAMESPACE_RELEASE_KEY); + namespaceMetrics.setReleaseKey(releaseKey); + break; + default: + logger.warn("Unhandled event name: {}", eventName); + break; + } + } + + @Override + public void export0() { + namespaces.forEach((namespace, metrics) -> { + updateNamespaceGaugeSample(METRICS_NAMESPACE_FIRST_LOAD_SPEND, namespace, + metrics.getFirstLoadSpend()); + updateNamespaceGaugeSample(METRICS_NAMESPACE_ITEM_NUM, namespace, + m_configs.get(namespace).getPropertyNames().size()); + updateNamespaceGaugeSample(METRICS_CONFIG_FILE_NUM, namespace, m_configFiles.size()); + }); + createOrUpdateGaugeSample(METRICS_NAMESPACE_NOT_FOUND, METRICS_NAMESPACE_NOT_FOUND, + Collections.emptyMap(), + namespace404.size()); + createOrUpdateGaugeSample(METRICS_NAMESPACE_TIMEOUT, METRICS_NAMESPACE_TIMEOUT, + Collections.emptyMap(), namespaceTimeout.size()); + } + + private void updateNamespaceGaugeSample(String key, String namespace, double value) { + createOrUpdateGaugeSample(namespace + key, key, Collections.singletonMap(NAMESPACE, namespace), + value); + } + + + @Override + public Map getNamespaceMetrics() { + return namespaces; + } + + + @Override + public List getNamespace404() { + return namespace404; + } + + @Override + public List getNamespaceTimeout() { + return namespaceTimeout; + } + + @Override + public List getNamespaceItemName(String namespace) { + Config config = m_configs.get(namespace); + return config == null ? Collections.emptyList() : new ArrayList<>(config.getPropertyNames()); + } + + @Override + public List getAllNamespaceReleaseKey() { + return namespaces.entrySet().stream() + .map(entry -> String.format("%s:%s", entry.getKey(), entry.getValue().getReleaseKey())) + .collect(Collectors.toList()); + } + + @Override + public List getAllNamespaceUsageCount() { + return namespaces.entrySet().stream() + .map(entry -> String.format("%s:%d", entry.getKey(), entry.getValue().getUsageCount())) + .collect(Collectors.toList()); + } + + @Override + public List getAllNamespacesLatestUpdateTime() { + return namespaces.entrySet().stream() + .map(entry -> String.format("%s:%s", entry.getKey(), + DATE_FORMATTER.format(Instant.ofEpochMilli(entry.getValue().getLatestUpdateTime())))) + .collect(Collectors.toList()); + } + + @Override + public List getAllUsedNamespaceName() { + return new ArrayList<>(namespaces.keySet()); + } + + @Override + public List getAllNamespaceFirstLoadSpend() { + return namespaces.entrySet().stream() + .map(entry -> entry.getKey() + ":" + entry.getValue().getFirstLoadSpend()) + .collect(Collectors.toList()); + } + + @Override + public List getAllNamespaceItemName() { + return m_configs.values().stream() + .map(config -> config.getPropertyNames().toString()) + .collect(Collectors.toList()); + } + + public static class NamespaceMetrics { + + private int usageCount; + private long firstLoadSpend; + private long latestUpdateTime = System.currentTimeMillis(); + private String releaseKey = "default"; + + public String getReleaseKey() { + return releaseKey; + } + + public void setReleaseKey(String releaseKey) { + this.releaseKey = releaseKey; + } + + public int getUsageCount() { + return usageCount; + } + + public void incrementUsageCount() { + this.usageCount++; + } + + public long getFirstLoadSpend() { + return firstLoadSpend; + } + + public void setFirstLoadSpend(long firstLoadSpend) { + this.firstLoadSpend = firstLoadSpend; + } + + public long getLatestUpdateTime() { + return latestUpdateTime; + } + + public void setLatestUpdateTime(long latestUpdateTime) { + this.latestUpdateTime = latestUpdateTime; + } + } + +} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientThreadPoolApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientThreadPoolApi.java new file mode 100644 index 00000000..4bc7d80b --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientThreadPoolApi.java @@ -0,0 +1,173 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.listener.impl; + +import static com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorConstant.*; + +import com.ctrip.framework.apollo.internals.AbstractConfig; +import com.ctrip.framework.apollo.internals.AbstractConfigFile; +import com.ctrip.framework.apollo.internals.RemoteConfigRepository; +import com.ctrip.framework.apollo.monitor.api.ApolloClientThreadPoolMonitorApi; +import com.ctrip.framework.apollo.monitor.internal.jmx.mbean.ApolloClientJmxThreadPoolMBean; +import com.ctrip.framework.apollo.monitor.internal.listener.AbstractApolloClientMetricsEventListener; +import com.ctrip.framework.apollo.monitor.internal.event.ApolloConfigMetricsEvent; +import com.ctrip.framework.apollo.monitor.internal.model.GaugeModel; +import com.google.common.collect.Maps; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.ThreadPoolExecutor; + +/** + * @author Rawven + */ +public class DefaultApolloClientThreadPoolApi extends + AbstractApolloClientMetricsEventListener implements + ApolloClientThreadPoolMonitorApi, ApolloClientJmxThreadPoolMBean { + + public static final String REMOTE_CONFIG_REPOSITORY = RemoteConfigRepository.class.getSimpleName(); + public static final String ABSTRACT_CONFIG = AbstractConfig.class.getSimpleName(); + public static final String ABSTRACT_CONFIG_FILE = AbstractConfigFile.class.getSimpleName(); + private final Map executorMap = Maps.newHashMap(); + + public DefaultApolloClientThreadPoolApi( + ExecutorService remoteConfigRepositoryExecutorService, + ExecutorService abstractConfigExecutorService, + ExecutorService abstractConfigFileExecutorService) { + super(TAG_THREAD_POOL); + executorMap.put(REMOTE_CONFIG_REPOSITORY, + new ApolloThreadPoolInfo((ThreadPoolExecutor) remoteConfigRepositoryExecutorService)); + executorMap.put(ABSTRACT_CONFIG, + new ApolloThreadPoolInfo((ThreadPoolExecutor) abstractConfigExecutorService)); + executorMap.put(ABSTRACT_CONFIG_FILE, + new ApolloThreadPoolInfo((ThreadPoolExecutor) abstractConfigFileExecutorService)); + } + + @Override + public void collect0(ApolloConfigMetricsEvent event) { + // do nothing + } + + @Override + public void export0() { + executorMap.forEach((key, value) -> exportThreadPoolMetrics(value, key)); + } + + private void exportThreadPoolMetrics(ApolloThreadPoolInfo info, String name) { + List metrics = Arrays.asList( + (double) info.getActiveTaskCount(), + (double) info.getQueueSize(), + (double) info.getCompletedTaskCount(), + (double) info.getPoolSize(), + (double) info.getTotalTaskCount(), + (double) info.getCorePoolSize(), + (double) info.getMaximumPoolSize(), + (double) info.getLargestPoolSize(), + (double) info.getQueueCapacity(), + (double) info.getQueueRemainingCapacity(), + info.getCurrentLoad() + ); + + for (int i = 0; i < metrics.size(); i++) { + String key = name + METRICS_THREAD_POOL_PARAMS[i + 1]; + createOrUpdateGaugeSample(key, METRICS_THREAD_POOL_PARAMS[i + 1], + Collections.singletonMap(METRICS_THREAD_POOL_PARAMS[0], name), metrics.get(i)); + } + } + + + @Override + public boolean isMetricsSampleUpdated() { + // memory status special + return true; + } + + @Override + public Map getThreadPoolInfo() { + return executorMap; + } + + @Override + public ApolloThreadPoolInfo getRemoteConfigRepositoryThreadPoolInfo() { + return executorMap.get(REMOTE_CONFIG_REPOSITORY); + } + + @Override + public ApolloThreadPoolInfo getAbstractConfigThreadPoolInfo() { + return executorMap.get(ABSTRACT_CONFIG); + } + + @Override + public ApolloThreadPoolInfo getAbstractConfigFileThreadPoolInfo() { + return executorMap.get(ABSTRACT_CONFIG_FILE); + } + + public static class ApolloThreadPoolInfo { + + private final ThreadPoolExecutor executor; + + public ApolloThreadPoolInfo(ThreadPoolExecutor executor) { + this.executor = executor; + } + + public int getActiveTaskCount() { + return executor.getActiveCount(); + } + + public int getQueueSize() { + return executor.getQueue().size(); + } + + public int getCorePoolSize() { + return executor.getCorePoolSize(); + } + + public int getMaximumPoolSize() { + return executor.getMaximumPoolSize(); + } + + public int getPoolSize() { + return executor.getPoolSize(); + } + + public long getTotalTaskCount() { + return executor.getTaskCount(); + } + + public long getCompletedTaskCount() { + return executor.getCompletedTaskCount(); + } + + public int getLargestPoolSize() { + return executor.getLargestPoolSize(); + } + + public int getQueueCapacity() { + return executor.getQueue().remainingCapacity() + executor.getQueue().size(); + } + + public int getQueueRemainingCapacity() { + return executor.getQueue().remainingCapacity(); + } + + public double getCurrentLoad() { + return (double) executor.getPoolSize() / executor.getMaximumPoolSize(); + } + } +} \ No newline at end of file diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/NullRunningParamsMonitorApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientBootstrapArgsMonitorApi.java similarity index 75% rename from apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/NullRunningParamsMonitorApi.java rename to apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientBootstrapArgsMonitorApi.java index d5a019d5..f7b442f1 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/NullRunningParamsMonitorApi.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientBootstrapArgsMonitorApi.java @@ -14,11 +14,18 @@ * limitations under the License. * */ -package com.ctrip.framework.apollo.monitor.internal; +package com.ctrip.framework.apollo.monitor.internal.listener.impl; -import com.ctrip.framework.apollo.monitor.api.ApolloRunningParamsMonitorApi; +import com.ctrip.framework.apollo.monitor.api.ApolloClientBootstrapArgsMonitorApi; +import com.ctrip.framework.apollo.monitor.internal.jmx.mbean.ApolloClientJmxBootstrapArgsMBean; +import java.util.Collections; +import java.util.Map; -public class NullRunningParamsMonitorApi implements ApolloRunningParamsMonitorApi { +/** + * @author Rawven + */ +public class NullClientBootstrapArgsMonitorApi implements ApolloClientBootstrapArgsMonitorApi, + ApolloClientJmxBootstrapArgsMBean { @Override public String getStartupParams(String key) { @@ -37,7 +44,7 @@ public String getAccessKeySecret() { @Override public Boolean getAutoUpdateInjectedSpringProperties() { - return null; + return false; } @Override @@ -96,7 +103,12 @@ public long getClientMonitorExternalExportPeriod() { } @Override - public String getMeta() { + public int getClientMonitorExceptionSaveSize() { + return 0; + } + + @Override + public String getApolloMeta() { return ""; } @@ -129,4 +141,9 @@ public String getEnv() { public String getAppId() { return ""; } + + @Override + public Map getBootstrapArgs() { + return Collections.emptyMap(); + } } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/NullExceptionMonitorApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientExceptionMonitorApi.java similarity index 57% rename from apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/NullExceptionMonitorApi.java rename to apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientExceptionMonitorApi.java index d700baee..3f0a4bdd 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/NullExceptionMonitorApi.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientExceptionMonitorApi.java @@ -14,21 +14,26 @@ * limitations under the License. * */ -package com.ctrip.framework.apollo.monitor.internal; +package com.ctrip.framework.apollo.monitor.internal.listener.impl; -import com.ctrip.framework.apollo.monitor.api.ApolloExceptionMonitorApi; +import com.ctrip.framework.apollo.monitor.api.ApolloClientExceptionMonitorApi; +import com.ctrip.framework.apollo.monitor.internal.jmx.mbean.ApolloClientJmxExceptionMBean; import java.util.Collections; import java.util.List; -public class NullExceptionMonitorApi implements ApolloExceptionMonitorApi { +/** + * @author Rawven + */ +public class NullClientExceptionMonitorApi implements ApolloClientExceptionMonitorApi, + ApolloClientJmxExceptionMBean { @Override - public Integer getExceptionNum() { - return 0; + public List getApolloConfigExceptionList() { + return Collections.emptyList(); } @Override - public List getExceptionDetails() { + public List getApolloConfigExceptionDetails() { return Collections.emptyList(); } } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/NullNamespaceMonitorApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientNamespaceMonitorApi.java similarity index 65% rename from apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/NullNamespaceMonitorApi.java rename to apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientNamespaceMonitorApi.java index 5377b6d9..c5da2fdc 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/NullNamespaceMonitorApi.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientNamespaceMonitorApi.java @@ -14,42 +14,35 @@ * limitations under the License. * */ -package com.ctrip.framework.apollo.monitor.internal; +package com.ctrip.framework.apollo.monitor.internal.listener.impl; -import com.ctrip.framework.apollo.monitor.api.ApolloNamespaceMonitorApi; +import com.ctrip.framework.apollo.monitor.api.ApolloClientNamespaceMonitorApi; +import com.ctrip.framework.apollo.monitor.internal.jmx.mbean.ApolloClientJmxNamespaceMBean; +import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientNamespaceApi.NamespaceMetrics; import java.util.Collections; import java.util.List; +import java.util.Map; -public class NullNamespaceMonitorApi implements ApolloNamespaceMonitorApi { - - @Override - public String getNamespaceReleaseKey(String namespace) { - return ""; - } - - @Override - public long getNamespaceUsageCount(String namespace) { - return 0; - } +/** + * @author Rawven + */ +public class NullClientNamespaceMonitorApi implements ApolloClientNamespaceMonitorApi, + ApolloClientJmxNamespaceMBean { @Override - public String getNamespaceLatestUpdateTime(String namespace) { - return ""; + public Map getNamespaceMetrics() { + return Collections.emptyMap(); } - @Override - public long getNamespaceFirstLoadSpend(String namespace) { - return 0; - } @Override - public String getNamespace404() { - return ""; + public List getNamespace404() { + return Collections.emptyList(); } @Override - public String getNamespaceTimeout() { - return ""; + public List getNamespaceTimeout() { + return Collections.emptyList(); } @Override diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientThreadPoolMonitorApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientThreadPoolMonitorApi.java new file mode 100644 index 00000000..b45f1568 --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientThreadPoolMonitorApi.java @@ -0,0 +1,50 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.listener.impl; + +import com.ctrip.framework.apollo.monitor.api.ApolloClientThreadPoolMonitorApi; +import com.ctrip.framework.apollo.monitor.internal.jmx.mbean.ApolloClientJmxThreadPoolMBean; +import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientThreadPoolApi.ApolloThreadPoolInfo; +import java.util.Collections; +import java.util.Map; + +/** + * @author Rawven + */ +public class NullClientThreadPoolMonitorApi implements ApolloClientThreadPoolMonitorApi, + ApolloClientJmxThreadPoolMBean { + + @Override + public Map getThreadPoolInfo() { + return Collections.emptyMap(); + } + + @Override + public ApolloThreadPoolInfo getRemoteConfigRepositoryThreadPoolInfo() { + return null; + } + + @Override + public ApolloThreadPoolInfo getAbstractConfigThreadPoolInfo() { + return null; + } + + @Override + public ApolloThreadPoolInfo getAbstractConfigFileThreadPoolInfo() { + return null; + } +} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/CounterModel.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/CounterModel.java index 67d5c1ba..610d61cd 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/CounterModel.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/CounterModel.java @@ -16,85 +16,38 @@ */ package com.ctrip.framework.apollo.monitor.internal.model; -import com.ctrip.framework.apollo.monitor.internal.util.MeterType; -import java.util.HashMap; -import java.util.Map; +import com.ctrip.framework.apollo.monitor.internal.enums.MeterEnums; /** * @author Rawven */ -public class CounterModel extends MetricsModel { +public class CounterModel extends SampleModel { - private double nowValue; - private double increaseValue; - - public CounterModel(String name, double num) { + private CounterModel(String name, double num) { if (name == null || name.isEmpty()) { throw new IllegalArgumentException("Name cannot be null or empty"); } if (Double.isNaN(num) || Double.isInfinite(num)) { throw new IllegalArgumentException("Number must be a valid double"); } - this.name = name; - this.nowValue = num; - this.increaseValue = num; - this.type = MeterType.COUNTER; + setName(name); + setType(MeterEnums.COUNTER); + this.value.set(num); } - public static CounterBuilder builder() { - return new CounterBuilder(); + public static CounterModel create(String name, double value) { + return new CounterModel(name, value); } - public void updateValue(double value) { + public void increase(double value) { if (Double.isNaN(value) || Double.isInfinite(value)) { throw new IllegalArgumentException("Value must be a valid double"); } - increaseValue = value - nowValue; - nowValue = value; - } - - public Double getIncreaseValue() { - return increaseValue; + this.value.addAndGet(value); } - public void setValue(Double value) { - if (value == null || Double.isNaN(value) || Double.isInfinite(value)) { - throw new IllegalArgumentException("Value must be a valid double"); - } - this.nowValue = value; + public double getIncreaseValueAndResetZero() { + return value.getAndSet(0.0); } - public static class CounterBuilder { - - private final Map tags = new HashMap<>(); - private String name; - private double value; - - public CounterBuilder name(String name) { - if (name == null || name.isEmpty()) { - throw new IllegalArgumentException("Name cannot be null or empty"); - } - this.name = name; - return this; - } - - public CounterBuilder value(double value) { - if (Double.isNaN(value) || Double.isInfinite(value)) { - throw new IllegalArgumentException("Value must be a valid double"); - } - this.value = value; - return this; - } - - public CounterBuilder putTag(String key, String value) { - this.tags.put(key, value); - return this; - } - - public CounterModel build() { - CounterModel sample = new CounterModel(name, value); - sample.tags.putAll(tags); - return sample; - } - } } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/GaugeModel.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/GaugeModel.java index b7026012..91150100 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/GaugeModel.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/GaugeModel.java @@ -16,83 +16,25 @@ */ package com.ctrip.framework.apollo.monitor.internal.model; -import com.ctrip.framework.apollo.monitor.internal.util.MeterType; -import java.util.HashMap; -import java.util.Map; -import java.util.function.ToDoubleFunction; +import com.ctrip.framework.apollo.monitor.internal.enums.MeterEnums; +import com.google.common.util.concurrent.AtomicDouble; -public class GaugeModel extends MetricsModel { - - public static final ToDoubleFunction INT_CONVERTER = v -> (int) v; - public static final ToDoubleFunction LONG_CONVERTER = v -> (long) v; - public static final ToDoubleFunction DOUBLE_CONVERTER = v -> (double) v; - - private T value; - private ToDoubleFunction apply; - - public GaugeModel(String name, T value, ToDoubleFunction apply) { - this.name = name; - this.value = value; - this.apply = apply; - this.type = MeterType.GAUGE; - } - - public static GaugeBuilder builder() { - return new GaugeBuilder<>(); - } - - public T getValue() { - return value; - } - - public void updateValue(T value) { - this.value = value; - } - - public ToDoubleFunction getApply() { - return this.apply; - } +/** + * @author Rawven + */ +public class GaugeModel extends SampleModel { - public void setApply(ToDoubleFunction apply) { - this.apply = apply; + private GaugeModel(String name, double value) { + if (name == null || name.isEmpty()) { + throw new IllegalArgumentException("Name cannot be null or empty"); + } + setName(name); + setType(MeterEnums.GAUGE); + this.value.set(value); } - public double getApplyValue() { - return getApply().applyAsDouble(getValue()); + public static GaugeModel create(String name, double value) { + return new GaugeModel(name, value); } - public static class GaugeBuilder { - - private final Map tags = new HashMap<>(1); - private String name; - private T value; - private ToDoubleFunction apply; - - public GaugeBuilder name(String name) { - this.name = name; - return this; - } - - public GaugeBuilder value(T value) { - this.value = value; - return this; - } - - public GaugeBuilder apply(ToDoubleFunction apply) { - this.apply = apply; - return this; - } - - public GaugeBuilder putTag(String key, String value) { - this.tags.put(key, value); - return this; - } - - public GaugeModel build() { - GaugeModel sample = new GaugeModel<>(name, value, apply); - sample.tags.putAll(tags); - return sample; - } - } } - diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/SampleModel.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/SampleModel.java new file mode 100644 index 00000000..b8c785e5 --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/SampleModel.java @@ -0,0 +1,75 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.model; + +import static com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorConstant.APOLLO_CLIENT; + +import com.ctrip.framework.apollo.monitor.internal.enums.MeterEnums; +import com.google.common.util.concurrent.AtomicDouble; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +/** + * @author Rawven + */ +public class SampleModel { + + protected final AtomicDouble value = new AtomicDouble(); + private final Map tags = new HashMap<>(1); + private String name; + private MeterEnums type; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = APOLLO_CLIENT + name; + } + + public SampleModel putTag(String key, String value) { + tags.put(key, value); + return this; + } + + public SampleModel putTags(Map tags) { + this.tags.putAll(tags); + return this; + } + + public MeterEnums getType() { + return type; + } + + public void setType(MeterEnums type) { + this.type = type; + } + + public Map getTags() { + return Collections.unmodifiableMap(tags); + } + + public double getValue() { + return value.get(); + } + + public void setValue(double value) { + this.value.set(value); + } +} + diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMessageProducerComposite.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMessageProducerComposite.java new file mode 100644 index 00000000..7e5e6fc7 --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMessageProducerComposite.java @@ -0,0 +1,72 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.tracer; + +import com.ctrip.framework.apollo.tracer.internals.NullTransaction; +import com.ctrip.framework.apollo.tracer.spi.MessageProducer; +import com.ctrip.framework.apollo.tracer.spi.Transaction; +import java.util.List; +import java.util.Objects; + +/** + * message producer composite + * + * @author Rawven + */ +public class ApolloClientMessageProducerComposite implements MessageProducer { + + public static final NullTransaction NULL_TRANSACTION = new NullTransaction(); + private final List producers; + + public ApolloClientMessageProducerComposite(List producers) { + this.producers = producers; + } + + @Override + public void logError(Throwable cause) { + producers.forEach(producer -> producer.logError(cause)); + } + + @Override + public void logError(String message, Throwable cause) { + producers.forEach(producer -> producer.logError(message, cause)); + } + + @Override + public void logEvent(String type, String name) { + producers.forEach(producer -> producer.logEvent(type, name)); + } + + @Override + public void logEvent(String type, String name, String status, String nameValuePairs) { + producers.forEach(producer -> producer.logEvent(type, name, status, nameValuePairs)); + } + + @Override + public void logMetricsForCount(String name) { + producers.forEach(producer -> producer.logMetricsForCount(name)); + } + + @Override + public Transaction newTransaction(String type, String name) { + return producers.stream() + .map(producer -> producer.newTransaction(type, name)) + .filter(Objects::nonNull) + .findFirst() + .orElse(NULL_TRANSACTION); + } +} \ No newline at end of file diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/ClientMessageProducerManager.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMessageProducerManager.java similarity index 89% rename from apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/ClientMessageProducerManager.java rename to apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMessageProducerManager.java index 9fc9290b..748f2c79 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/ClientMessageProducerManager.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMessageProducerManager.java @@ -23,11 +23,11 @@ /** * @author Rawven */ -public class ClientMessageProducerManager implements MessageProducerManager { +public class ApolloClientMessageProducerManager implements MessageProducerManager { private static MessageProducer producer; - public ClientMessageProducerManager() { + public ApolloClientMessageProducerManager() { producer = ConfigMonitorInitializer.initializeMessageProducerComposite(); } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMonitorMessageProducer.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMonitorMessageProducer.java new file mode 100644 index 00000000..857b9bc9 --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMonitorMessageProducer.java @@ -0,0 +1,197 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.tracer; + +import static com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorConstant.*; +import static com.ctrip.framework.apollo.monitor.internal.tracer.ApolloClientMessageProducerComposite.NULL_TRANSACTION; + + +import com.ctrip.framework.apollo.exceptions.ApolloConfigException; +import com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorConstant; +import com.ctrip.framework.apollo.monitor.internal.event.ApolloConfigMetricsEventFactory; +import com.ctrip.framework.apollo.tracer.spi.MessageProducer; +import com.ctrip.framework.apollo.tracer.spi.Transaction; +import java.time.Instant; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +/** + * @author Rawven + */ +public class ApolloClientMonitorMessageProducer implements MessageProducer { + + public static final List TAGS = Collections.unmodifiableList(Arrays.asList( + APOLLO_CLIENT_CONFIGCHANGES, + APOLLO_CONFIG_EXCEPTION, + APOLLO_META_SERVICE, + APOLLO_CONFIG_SERVICES, + APOLLO_CLIENT_VERSION, + APOLLO_CONFIGSERVICE, + APOLLO_CLIENT_CONFIGMETA, + APOLLO_CLIENT_NAMESPACE_TIMEOUT, + APOLLO_CLIENT_NAMESPACE_USAGE, + APOLLO_CLIENT_NAMESPACE_NOT_FOUND + )); + + @Override + public void logError(Throwable cause) { + publishErrorEvent(TAG_ERROR, cause); + } + + @Override + public void logError(String message, Throwable cause) { + publishErrorEvent(TAG_ERROR, cause); + } + + @Override + public void logEvent(String type, String name) { + if (TAGS.contains(type)) { + handleTaggedEvent(type, name); + } else if (type.startsWith(APOLLO_CLIENT_CONFIGS)) { + handleClientConfigEvent(type, name); + } else if (type.startsWith(APOLLO_CLIENT_NAMESPACE_FIRST_LOAD_SPEND)) { + handleFirstLoadTimeEvent(type, name); + } + } + + private void publishErrorEvent(String tag, Throwable cause) { + ApolloConfigMetricsEventFactory.getInstance().createEvent(tag) + .withTag(tag) + .putAttachment(THROWABLE, cause) + .publish(); + } + + private void handleTaggedEvent(String type, String name) { + switch (type) { + case APOLLO_CONFIGSERVICE: + name = name.substring(HELP_STR.length()); + // fall through + case APOLLO_CLIENT_CONFIGCHANGES: + publishConfigChangeEvent(name); + break; + case APOLLO_CONFIG_EXCEPTION: + logError(new ApolloConfigException(name)); + break; + case APOLLO_META_SERVICE: + publishMetaServiceEvent(); + break; + case APOLLO_CONFIG_SERVICES: + publishConfigServiceEvent(name); + break; + case APOLLO_CLIENT_VERSION: + publishClientVersionEvent(name); + break; + case APOLLO_CLIENT_NAMESPACE_TIMEOUT: + publishNamespaceTimeoutEvent(name); + break; + case APOLLO_CLIENT_NAMESPACE_NOT_FOUND: + publishNamespaceNotFoundEvent(name); + break; + case APOLLO_CLIENT_CONFIGMETA: + // 不需要收集 + break; + default: + break; + } + } + + private void publishConfigChangeEvent(String name) { + ApolloConfigMetricsEventFactory.getInstance() + .createEvent(METRICS_NAMESPACE_LATEST_UPDATE_TIME) + .putAttachment(NAMESPACE, name) + .putAttachment(TIMESTAMP, System.currentTimeMillis()) + .withTag(TAG_NAMESPACE) + .publish(); + } + + private void publishMetaServiceEvent() { + ApolloConfigMetricsEventFactory.getInstance().createEvent(META_FRESH) + .withTag(TAG_BOOTSTRAP) + .putAttachment(META_FRESH, DATE_FORMATTER.format(Instant.now())) + .publish(); + } + + private void publishConfigServiceEvent(String name) { + ApolloConfigMetricsEventFactory.getInstance().createEvent(CONFIG_SERVICE_URL) + .withTag(TAG_BOOTSTRAP) + .putAttachment(CONFIG_SERVICE_URL, name) + .publish(); + } + + private void publishClientVersionEvent(String name) { + ApolloConfigMetricsEventFactory.getInstance().createEvent(VERSION) + .withTag(TAG_BOOTSTRAP) + .putAttachment(VERSION, name) + .publish(); + } + + private void publishNamespaceTimeoutEvent(String name) { + ApolloConfigMetricsEventFactory.getInstance().createEvent(APOLLO_CLIENT_NAMESPACE_TIMEOUT) + .putAttachment(NAMESPACE, name) + .withTag(TAG_NAMESPACE) + .publish(); + } + + private void publishNamespaceNotFoundEvent(String name) { + ApolloConfigMetricsEventFactory.getInstance().createEvent(APOLLO_CLIENT_NAMESPACE_NOT_FOUND) + .withTag(TAG_NAMESPACE) + .putAttachment(NAMESPACE, name) + .publish(); + } + + private void handleClientConfigEvent(String type, String name) { + String namespace = type.substring(APOLLO_CLIENT_CONFIGS.length()); + ApolloConfigMetricsEventFactory.getInstance().createEvent(NAMESPACE_RELEASE_KEY) + .withTag(TAG_NAMESPACE) + .putAttachment(NAMESPACE_RELEASE_KEY, name) + .putAttachment(NAMESPACE, namespace) + .publish(); + } + + private void handleFirstLoadTimeEvent(String type, String name) { + String namespace = type.substring(APOLLO_CLIENT_NAMESPACE_FIRST_LOAD_SPEND.length()); + long firstLoadTime = Long.parseLong(name); + ApolloConfigMetricsEventFactory.getInstance() + .createEvent(APOLLO_CLIENT_NAMESPACE_FIRST_LOAD_SPEND) + .putAttachment(NAMESPACE, namespace) + .putAttachment(TIMESTAMP, firstLoadTime) + .withTag(TAG_NAMESPACE) + .publish(); + } + + @Override + public void logEvent(String type, String name, String status, String nameValuePairs) { + // ignore + } + + @Override + public void logMetricsForCount(String name) { + String[] split = name.split(":"); + if (split.length == 2 && APOLLO_CLIENT_NAMESPACE_USAGE.equals(split[0])) { + ApolloConfigMetricsEventFactory.getInstance().createEvent(APOLLO_CLIENT_NAMESPACE_USAGE) + .putAttachment(ApolloClientMonitorConstant.NAMESPACE, split[1]) + .withTag(TAG_NAMESPACE) + .publish(); + } + } + + @Override + public Transaction newTransaction(String type, String name) { + return NULL_TRANSACTION; + } +} \ No newline at end of file diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/MessageProducerComposite.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/MessageProducerComposite.java deleted file mode 100644 index 91a0db6b..00000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/MessageProducerComposite.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright 2022 Apollo Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.ctrip.framework.apollo.monitor.internal.tracer; - -import com.ctrip.framework.apollo.tracer.internals.NullTransaction; -import com.ctrip.framework.apollo.tracer.spi.MessageProducer; -import com.ctrip.framework.apollo.tracer.spi.Transaction; -import java.util.List; -import java.util.Objects; - -/** - * message producer composite - * - * @author Rawven - */ -public class MessageProducerComposite implements MessageProducer { - - public static final String ERROR_METRICS = "errorMetrics"; - public static final String THROWABLE = ERROR_METRICS + ".throwable"; - public static final String APOLLO_CLIENT_CONFIGCHANGES = "Apollo.Client.ConfigChanges"; - public static final String APOLLO_CONFIG_EXCEPTION = "ApolloConfigException"; - public static final String APOLLO_META_SERVICE = "Apollo.MetaService"; - public static final String APOLLO_CONFIG_SERVICES = "Apollo.Config.Services"; - public static final String APOLLO_CLIENT_VERSION = "Apollo.Client.Version"; - public static final String APOLLO_CONFIGSERVICE = "Apollo.ConfigService"; - public static final String APOLLO_CLIENT_CONFIGS = "Apollo.Client.Configs."; - public static final String APOLLO_CLIENT_CONFIGMETA = "Apollo.Client.ConfigMeta"; - public static final String HELP_STR = "periodicRefresh: "; - private static final NullTransaction NULL_TRANSACTION = new NullTransaction(); - private List producers; - - public MessageProducerComposite(List producers) { - this.producers = producers; - } - - - @Override - public void logError(Throwable cause) { - producers.forEach(producer -> producer.logError(cause)); - } - - @Override - public void logError(String message, Throwable cause) { - producers.forEach(producer -> producer.logError(message, cause)); - } - - @Override - public void logEvent(String type, String name) { - producers.forEach(producer -> producer.logEvent(type, name)); - } - - @Override - public void logEvent(String type, String name, String status, - String nameValuePairs) { - producers.forEach(producer -> producer.logEvent(type, name, status, nameValuePairs)); - } - - @Override - public Transaction newTransaction(String type, String name) { - return producers.stream() - .map(producer -> producer.newTransaction(type, name)) - .filter(Objects::nonNull) - .findFirst() - .orElse(NULL_TRANSACTION); - } - - public List getProducers() { - return producers; - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/MonitorMessageProducer.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/MonitorMessageProducer.java deleted file mode 100644 index 83625f20..00000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/MonitorMessageProducer.java +++ /dev/null @@ -1,169 +0,0 @@ -/* - * Copyright 2022 Apollo Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.ctrip.framework.apollo.monitor.internal.tracer; - -import static com.ctrip.framework.apollo.monitor.internal.MonitorConstant.NAMESPACE; -import static com.ctrip.framework.apollo.monitor.internal.MonitorConstant.TIMESTAMP; -import static com.ctrip.framework.apollo.monitor.internal.collector.internal.DefaultApolloNamespaceCollector.DATE_FORMATTER; -import static com.ctrip.framework.apollo.monitor.internal.collector.internal.DefaultApolloNamespaceCollector.NAMESPACE_LATEST_UPDATE_TIME; -import static com.ctrip.framework.apollo.monitor.internal.collector.internal.DefaultApolloNamespaceCollector.NAMESPACE_MONITOR; -import static com.ctrip.framework.apollo.monitor.internal.collector.internal.DefaultApolloNamespaceCollector.NAMESPACE_RELEASE_KEY; -import static com.ctrip.framework.apollo.monitor.internal.collector.internal.DefaultApolloRunningParamsCollector.CONFIG_SERVICE_URL; -import static com.ctrip.framework.apollo.monitor.internal.collector.internal.DefaultApolloRunningParamsCollector.META_FRESH; -import static com.ctrip.framework.apollo.monitor.internal.collector.internal.DefaultApolloRunningParamsCollector.RUNNING_PARAMS; -import static com.ctrip.framework.apollo.monitor.internal.collector.internal.DefaultApolloRunningParamsCollector.VERSION; -import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_CLIENT_CONFIGCHANGES; -import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_CLIENT_CONFIGMETA; -import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_CLIENT_CONFIGS; -import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_CLIENT_VERSION; -import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_CONFIGSERVICE; -import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_CONFIG_EXCEPTION; -import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_CONFIG_SERVICES; -import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.APOLLO_META_SERVICE; -import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.ERROR_METRICS; -import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.HELP_STR; -import static com.ctrip.framework.apollo.monitor.internal.tracer.MessageProducerComposite.THROWABLE; - -import com.ctrip.framework.apollo.exceptions.ApolloConfigException; -import com.ctrip.framework.apollo.monitor.internal.model.MetricsEvent; -import com.ctrip.framework.apollo.tracer.spi.MessageProducer; -import com.ctrip.framework.apollo.tracer.spi.Transaction; -import java.time.Instant; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -/** - * metrics message producer - * - * @author Rawven - */ -public class MonitorMessageProducer implements MessageProducer { - - public static final List TAGS = Collections.unmodifiableList( - Arrays.asList( - APOLLO_CLIENT_CONFIGCHANGES, - APOLLO_CONFIG_EXCEPTION, - APOLLO_META_SERVICE, - APOLLO_CONFIG_SERVICES, - APOLLO_CLIENT_VERSION, - APOLLO_CONFIGSERVICE, - APOLLO_CLIENT_CONFIGMETA - ) - ); - - @Override - public void logError(Throwable cause) { - MetricsEvent.builder().withName(ERROR_METRICS) - .withTag(ERROR_METRICS) - .putAttachment(THROWABLE, cause) - .push(); - } - - @Override - public void logError(String message, Throwable cause) { - MetricsEvent.builder().withName(ERROR_METRICS) - .withTag(ERROR_METRICS) - .putAttachment(THROWABLE, cause).push(); - } - - @Override - public void logEvent(String type, String name) { - if (TAGS.contains(type)) { - handleTaggedEvent(type, name); - } else if (type.startsWith(APOLLO_CLIENT_CONFIGS)) { - handleClientConfigEvent(type, name); - } - } - - private void handleTaggedEvent(String type, String name) { - String namespace; - switch (type) { - case APOLLO_CONFIGSERVICE: { - name = name.substring(HELP_STR.length()); - } - case APOLLO_CLIENT_CONFIGCHANGES: { - namespace = name; - MetricsEvent.builder() - .withName(NAMESPACE_LATEST_UPDATE_TIME) - .putAttachment(NAMESPACE, namespace) - .putAttachment(TIMESTAMP, System.currentTimeMillis()) - .withTag(NAMESPACE_MONITOR) - .push(); - break; - } - case APOLLO_CONFIG_EXCEPTION: { - logError(new ApolloConfigException(name)); - break; - } - case APOLLO_META_SERVICE: { - MetricsEvent.builder() - .withName(META_FRESH) - .withTag(RUNNING_PARAMS) - .putAttachment(META_FRESH, - DATE_FORMATTER.format(Instant.ofEpochMilli(System.currentTimeMillis()))) - .push(); - break; - } - case APOLLO_CONFIG_SERVICES: { - MetricsEvent.builder() - .withName(CONFIG_SERVICE_URL) - .withTag(RUNNING_PARAMS) - .putAttachment(CONFIG_SERVICE_URL, name) - .push(); - break; - } - case APOLLO_CLIENT_VERSION: { - MetricsEvent.builder() - .withName(VERSION) - .withTag(RUNNING_PARAMS) - .putAttachment(VERSION, name) - .push(); - break; - } - case APOLLO_CLIENT_CONFIGMETA: - // 不需要收集 - break; - default: - break; - } - } - - private void handleClientConfigEvent(String type, String name) { - int len = APOLLO_CLIENT_CONFIGS.length(); - String namespace = type.substring(len); - String releaseKey = name; - MetricsEvent.builder() - .withName(NAMESPACE_RELEASE_KEY) - .withTag(NAMESPACE_MONITOR) - .putAttachment(NAMESPACE_RELEASE_KEY, releaseKey) - .putAttachment(NAMESPACE, namespace) - .push(); - } - - @Override - public void logEvent(String type, String name, String status, - String nameValuePairs) { - // - } - - @Override - public Transaction newTransaction(String type, String name) { - return null; - } - -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/boot/ApolloApplicationContextInitializer.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/boot/ApolloApplicationContextInitializer.java index af3e347e..05decef5 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/boot/ApolloApplicationContextInitializer.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/boot/ApolloApplicationContextInitializer.java @@ -97,7 +97,8 @@ public class ApolloApplicationContextInitializer implements ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_EXTERNAL_TYPE, ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_ENABLED, ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_EXTERNAL_EXPORT_PERIOD, - ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_JMX_ENABLED,}; + ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_JMX_ENABLED, + ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_EXCEPTION_QUEUE_SIZE,}; private final ConfigPropertySourceFactory configPropertySourceFactory = SpringInjector .getInstance(ConfigPropertySourceFactory.class); diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/util/ConfigUtil.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/util/ConfigUtil.java index 731c7513..dce0a7a9 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/util/ConfigUtil.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/util/ConfigUtil.java @@ -73,10 +73,11 @@ public class ConfigUtil { private boolean propertyNamesCacheEnabled = false; private boolean propertyFileCacheEnabled = true; private boolean overrideSystemProperties = true; - private boolean isClientMonitorEnabled = false; - private boolean isClientMonitorJmxEnabled = false; + private boolean clientMonitorEnabled = false; + private boolean clientMonitorJmxEnabled = false; private String monitorExternalType = null; private long monitorExternalExportPeriod = 10; + private int monitorExceptionSaveSize = 25; public ConfigUtil() { warnLogRateLimiter = RateLimiter.create(0.017); // 1 warning log output per minute @@ -92,10 +93,11 @@ public ConfigUtil() { initPropertyNamesCacheEnabled(); initPropertyFileCacheEnabled(); initOverrideSystemProperties(); - initMonitorExternalType(); - initMonitorExternalCollectPeriod(); initClientMonitorEnabled(); initClientMonitorJmxEnabled(); + initClientMonitorExternalType(); + initClientMonitorExternalCollectPeriod(); + initClientMonitorExceptionSaveSize(); } @@ -507,7 +509,7 @@ private void initOverrideSystemProperties() { overrideSystemProperties); } - private void initMonitorExternalType() { + private void initClientMonitorExternalType() { monitorExternalType = System.getProperty(ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_EXTERNAL_TYPE); if (Strings.isNullOrEmpty(monitorExternalType)) { monitorExternalType = Foundation.app() @@ -519,20 +521,11 @@ public String getMonitorExternalType() { return monitorExternalType; } - private void initMonitorExternalCollectPeriod() { - String collectPeriod = System.getProperty( + private void initClientMonitorExternalCollectPeriod() { + Integer value = getCustomizedIntegerValue( ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_EXTERNAL_EXPORT_PERIOD); - if (Strings.isNullOrEmpty(collectPeriod)) { - collectPeriod = Foundation.app() - .getProperty(ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_EXTERNAL_EXPORT_PERIOD, null); - } - if (!Strings.isNullOrEmpty(collectPeriod)) { - try { - monitorExternalExportPeriod = Long.parseLong(collectPeriod); - } catch (Throwable ex) { - logger.error("Config for {} is invalid: {}", - ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_EXTERNAL_EXPORT_PERIOD, collectPeriod); - } + if (null != value){ + monitorExternalExportPeriod = value; } } @@ -547,11 +540,11 @@ private void initClientMonitorEnabled() { enabled = Foundation.app() .getProperty(ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_ENABLED, "false"); } - isClientMonitorEnabled = Boolean.parseBoolean(enabled); + clientMonitorEnabled = Boolean.parseBoolean(enabled); } - public boolean isClientMonitorEnabled() { - return isClientMonitorEnabled; + public boolean getClientMonitorEnabled() { + return clientMonitorEnabled; } private void initClientMonitorJmxEnabled() { @@ -560,12 +553,21 @@ private void initClientMonitorJmxEnabled() { enabled = Foundation.app() .getProperty(ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_JMX_ENABLED, "false"); } - isClientMonitorJmxEnabled = Boolean.parseBoolean(enabled); + clientMonitorJmxEnabled = Boolean.parseBoolean(enabled); } - public boolean isClientMonitorJmxEnabled() { - return isClientMonitorJmxEnabled; + public boolean getClientMonitorJmxEnabled() { + return clientMonitorJmxEnabled; + } + private void initClientMonitorExceptionSaveSize() { + Integer value = getCustomizedIntegerValue( + ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_EXCEPTION_QUEUE_SIZE); + if (null != value){ + monitorExceptionSaveSize = value; + } + } + public int getMonitorExceptionQueueSize() { + return monitorExceptionSaveSize; } - private boolean getPropertyBoolean(String propertyName, String envName, boolean defaultVal) { String enablePropertyNamesCache = System.getProperty(propertyName); diff --git a/apollo-client/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/apollo-client/src/main/resources/META-INF/additional-spring-configuration-metadata.json index cb9deb74..8dfe0553 100644 --- a/apollo-client/src/main/resources/META-INF/additional-spring-configuration-metadata.json +++ b/apollo-client/src/main/resources/META-INF/additional-spring-configuration-metadata.json @@ -92,6 +92,21 @@ "description": "apollo client monitor external metrics export period.", "defaultValue": "" }, + { + "name": "apollo.client.monitor.exception-save-size", + "type": "java.lang.String", + "sourceType": "com.ctrip.framework.apollo.core.ApolloClientSystemConsts", + "description": "apollo client monitor exception-save-size.", + "defaultValue": "" + }, + { + "name": "apollo.client.monitor.metrics-event-pool-size", + "type": "java.lang.String", + "sourceType": "com.ctrip.framework.apollo.core.ApolloClientSystemConsts", + "description": "apollo client monitor MetricsEvent object pool size.", + "defaultValue": "" + }, + { "name": "apollo.meta", "type": "java.net.URI", diff --git a/apollo-client/src/main/resources/META-INF/services/com.ctrip.framework.apollo.tracer.spi.MessageProducerManager b/apollo-client/src/main/resources/META-INF/services/com.ctrip.framework.apollo.tracer.spi.MessageProducerManager index fbae9d1c..7b56522b 100644 --- a/apollo-client/src/main/resources/META-INF/services/com.ctrip.framework.apollo.tracer.spi.MessageProducerManager +++ b/apollo-client/src/main/resources/META-INF/services/com.ctrip.framework.apollo.tracer.spi.MessageProducerManager @@ -1 +1 @@ -com.ctrip.framework.apollo.monitor.internal.tracer.ClientMessageProducerManager \ No newline at end of file +com.ctrip.framework.apollo.monitor.internal.tracer.ApolloClientMessageProducerManager \ No newline at end of file diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/DefaultConfigMonitorTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/DefaultConfigMonitorTest.java new file mode 100644 index 00000000..1583032d --- /dev/null +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/DefaultConfigMonitorTest.java @@ -0,0 +1,87 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; + +import com.ctrip.framework.apollo.monitor.api.ApolloClientBootstrapArgsMonitorApi; +import com.ctrip.framework.apollo.monitor.api.ApolloClientExceptionMonitorApi; +import com.ctrip.framework.apollo.monitor.api.ApolloClientNamespaceMonitorApi; +import com.ctrip.framework.apollo.monitor.api.ApolloClientThreadPoolMonitorApi; +import com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporter; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +public class DefaultConfigMonitorTest { + + private DefaultConfigMonitor configMonitor; + + @Mock + private ApolloClientMetricsExporter reporter; + + @Mock + private ApolloClientThreadPoolMonitorApi threadPoolMonitorApi; + + @Mock + private ApolloClientExceptionMonitorApi exceptionMonitorApi; + + @Mock + private ApolloClientNamespaceMonitorApi namespaceMonitorApi; + + @Mock + private ApolloClientBootstrapArgsMonitorApi bootstrapArgsMonitorApi; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + configMonitor = new DefaultConfigMonitor(); + } + + @Test + public void testInit() { + configMonitor.init(namespaceMonitorApi, threadPoolMonitorApi, exceptionMonitorApi, bootstrapArgsMonitorApi, reporter); + + assertEquals(namespaceMonitorApi, configMonitor.getNamespaceMonitorApi()); + assertEquals(threadPoolMonitorApi, configMonitor.getThreadPoolMonitorApi()); + assertEquals(exceptionMonitorApi, configMonitor.getExceptionMonitorApi()); + assertEquals(bootstrapArgsMonitorApi, configMonitor.getRunningParamsMonitorApi()); + } + + @Test + public void testGetExporterData() { + when(reporter.response()).thenReturn("exporter data"); + + configMonitor.init(namespaceMonitorApi, threadPoolMonitorApi, exceptionMonitorApi, bootstrapArgsMonitorApi, reporter); + + String result = configMonitor.getExporterData(); + + assertEquals("exporter data", result); + verify(reporter).response(); + } + + @Test + public void testDefaultInstances() { + assertNotNull(configMonitor.getThreadPoolMonitorApi()); + assertNotNull(configMonitor.getExceptionMonitorApi()); + assertNotNull(configMonitor.getNamespaceMonitorApi()); + assertNotNull(configMonitor.getRunningParamsMonitorApi()); + assertEquals("No Reporter Use", configMonitor.getExporterData()); // Assuming NullApolloClientMetricsExporter returns "null" + } +} \ No newline at end of file diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/collector/AbstractApolloMetricsCollectorTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/collector/AbstractApolloMetricsCollectorTest.java deleted file mode 100644 index 4a3da10c..00000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/collector/AbstractApolloMetricsCollectorTest.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright 2022 Apollo Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.ctrip.framework.apollo.monitor.internal.collector; - -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Mockito.when; - -import com.ctrip.framework.apollo.monitor.internal.model.MetricsEvent; -import com.ctrip.framework.apollo.monitor.internal.model.MetricsModel; -import java.util.List; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; -public class AbstractApolloMetricsCollectorTest { - - private AbstractMetricsCollector metricsCollector; - - @Before - public void setUp() { - metricsCollector = new AbstractMetricsCollector("mock","tag1", "tag2") { - @Override - public String name() { - return "MockMetricsCollector"; - } - - @Override - public void collect0(MetricsEvent event) { - // 模拟实现 - } - - @Override - public void export0() { - // 模拟实现 - } - }; - } - - @Test - public void testConstructorInitialization() { - assertNotNull(metricsCollector); - } - - @Test - public void testIsSupport() { - MetricsEvent event = Mockito.mock(MetricsEvent.class); - - when(event.getTag()).thenReturn("tag1"); - assertTrue(metricsCollector.isSupport(event)); - - when(event.getTag()).thenReturn("tag3"); - assertFalse(metricsCollector.isSupport(event)); - } - - @Test - public void testCollect() { - MetricsEvent event = Mockito.mock(MetricsEvent.class); - metricsCollector.collect(event); - assertTrue(metricsCollector.isSamplesUpdated()); - } - - @Test - public void testIsSamplesUpdated() { - MetricsEvent event = Mockito.mock(MetricsEvent.class); - metricsCollector.collect(event); - assertTrue(metricsCollector.isSamplesUpdated()); - assertFalse(metricsCollector.isSamplesUpdated()); - } - - @Test - public void testExport() { - List samples = metricsCollector.export(); - assertNotNull(samples); - } -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractApolloClientMetricsExporterTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractApolloClientMetricsExporterTest.java new file mode 100644 index 00000000..3f74b126 --- /dev/null +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractApolloClientMetricsExporterTest.java @@ -0,0 +1,120 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.exporter; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; + +import com.ctrip.framework.apollo.monitor.internal.enums.MeterEnums; +import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMetricsEventListener; +import com.ctrip.framework.apollo.monitor.internal.model.CounterModel; +import com.ctrip.framework.apollo.monitor.internal.model.GaugeModel; +import com.ctrip.framework.apollo.monitor.internal.model.SampleModel; +import java.util.Collections; +import java.util.Map; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +public class AbstractApolloClientMetricsExporterTest { + + private class TestMetricsExporter extends AbstractApolloClientMetricsExporter { + @Override + protected void doInit() { + } + + public List getCollectors() { + return collectors; + } + + @Override + public boolean isSupport(String form) { + return false; + } + + @Override + public void registerOrUpdateCounterSample(String name, Map tag, + double incrValue) { + + } + + @Override + public void registerOrUpdateGaugeSample(String name, Map tag, double value) { + + } + + @Override + public String response() { + return ""; + } + } + + private TestMetricsExporter exporter; + private ApolloClientMetricsEventListener mockListener; + + @Before + public void setUp() { + exporter = new TestMetricsExporter(); + mockListener = mock(ApolloClientMetricsEventListener.class); + } + + @Test + public void testInit() { + List collectors = new ArrayList<>(); + collectors.add(mockListener); + long collectPeriod = 10L; + + exporter.init(collectors, collectPeriod); + + assertEquals(collectors, exporter.getCollectors()); + } + + @Test + public void testUpdateMetricsData() { + List samples = new ArrayList<>(); + GaugeModel gauge = mock(GaugeModel.class); + when(gauge.getType()).thenReturn(MeterEnums.GAUGE); + when(gauge.getName()).thenReturn("testGauge"); + when(gauge.getValue()).thenReturn(10.0); + samples.add(gauge); + + when(mockListener.isMetricsSampleUpdated()).thenReturn(true); + when(mockListener.export()).thenReturn(samples); + + exporter.init(Collections.singletonList(mockListener), 10L); + exporter.updateMetricsData(); + + verify(mockListener).export(); + verify(gauge).getValue(); + } + + @Test + public void testRegisterSampleGauge() { + GaugeModel gaugeModel = (GaugeModel) GaugeModel.create("testGauge", 5.0).putTag("key", "value"); + + exporter.registerSample(gaugeModel); + } + + @Test + public void testRegisterSampleCounter() { + CounterModel counterModel = (CounterModel) CounterModel.create("testCounter", 5.0).putTag("key", "value"); + exporter.registerSample(counterModel); + } + +} \ No newline at end of file diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractApolloMetricsExporterTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractApolloMetricsExporterTest.java deleted file mode 100644 index e7122eb4..00000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractApolloMetricsExporterTest.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright 2022 Apollo Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.ctrip.framework.apollo.monitor.internal.exporter; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import com.ctrip.framework.apollo.monitor.internal.collector.MetricsCollector; -import com.ctrip.framework.apollo.monitor.internal.model.CounterModel; -import com.ctrip.framework.apollo.monitor.internal.model.GaugeModel; -import com.ctrip.framework.apollo.monitor.internal.model.MetricsModel; -import com.ctrip.framework.apollo.monitor.internal.util.MeterType; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - -@RunWith(MockitoJUnitRunner.class) -public class AbstractApolloMetricsExporterTest { - - @Mock - private MetricsCollector mockCollector; - - @InjectMocks - private final AbstractMetricsExporter reporter = new AbstractMetricsExporter() { - @Override - protected void doInit() { - // Do nothing for test purposes - } - - @Override - public void registerGaugeSample(GaugeModel sample) { - // Mock implementation for test purposes - } - - @Override - public String response() { - return "test"; - } - - @Override - public boolean isSupport(String form) { - return "mock".equals(form); - } - - @Override - public void registerCounterSample(CounterModel sample) { - // Mock implementation for test purposes - } - }; - - - - @Test - public void testInit() { - List collectors = Collections.singletonList(mockCollector); - long collectPeriod = 10L; - - reporter.init(collectors, collectPeriod); - - assertNotNull(reporter.m_executorService); - } - @Test - public void testIsSupport(){ - assertTrue(reporter.isSupport("mock")); - assertFalse(reporter.isSupport("mock1")); - } - - @Test - public void testUpdateMetricsData() { - MetricsModel mockSample = mock(MetricsModel.class); - when(mockSample.getType()).thenReturn(MeterType.GAUGE); - when(mockCollector.isSamplesUpdated()).thenReturn(true); - when(mockCollector.export()).thenReturn(Collections.singletonList(mockSample)); - - reporter.init(Collections.singletonList(mockCollector), 10L); - reporter.updateMetricsData(); - - verify(mockCollector, times(1)).isSamplesUpdated(); - verify(mockCollector, times(1)).export(); - verify(mockSample, times(1)).getType(); - } - - @Test - public void testGetTags() { - MetricsModel sample = mock(MetricsModel.class); - Map tags = new HashMap<>(); - tags.put("key1", "value1"); - tags.put("key2", "value2"); - - when(sample.getTags()).thenReturn(tags); - - String[][] result = reporter.getTags(sample); - - assertArrayEquals(new String[]{"key1", "key2"}, result[0]); - assertArrayEquals(new String[]{"value1", "value2"}, result[1]); - } -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/DefaultApolloClientMetricsExporterFactoryTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/DefaultApolloClientMetricsExporterFactoryTest.java new file mode 100644 index 00000000..c4b7f510 --- /dev/null +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/DefaultApolloClientMetricsExporterFactoryTest.java @@ -0,0 +1,93 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.exporter; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; + +import com.ctrip.framework.apollo.build.MockInjector; +import com.ctrip.framework.apollo.monitor.internal.exporter.impl.DefaultApolloClientMetricsExporterFactory; +import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMetricsEventListener; +import com.ctrip.framework.apollo.util.ConfigUtil; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import java.util.Collections; +import java.util.List; + +public class DefaultApolloClientMetricsExporterFactoryTest { + + private DefaultApolloClientMetricsExporterFactory factory; + + @Mock + private ConfigUtil configUtil; + + @Mock + private ApolloClientMetricsEventListener metricsCollector; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + MockInjector.setInstance(ConfigUtil.class, configUtil); + factory = new DefaultApolloClientMetricsExporterFactory(); + } + + @Test + public void testGetMetricsReporter_NoExternalSystemType() { + when(configUtil.getMonitorExternalType()).thenReturn(null); + + ApolloClientMetricsExporter result = factory.getMetricsReporter(Collections.emptyList()); + + assertNull(result); + verify(configUtil).getMonitorExternalType(); + } + + @Test + public void testGetMetricsReporter_ExporterFound() { + when(configUtil.getMonitorExternalType()).thenReturn("mocktheus"); + when(configUtil.getClientMonitorJmxEnabled()).thenReturn(true); + when(configUtil.getMonitorExternalExportPeriod()).thenReturn(1000L); + when(metricsCollector.mBeanName()).thenReturn("testMBean"); + List collectors = Collections.singletonList(metricsCollector); + + ApolloClientMetricsExporter result = factory.getMetricsReporter(collectors); + + assertNotNull(result); + assertTrue(result instanceof MockApolloClientMetricsExporter); + } + + @Test + public void testGetMetricsReporter_ExporterNotFound() { + when(configUtil.getMonitorExternalType()).thenReturn("unknownType"); + + ApolloClientMetricsExporter result = factory.getMetricsReporter(Collections.emptyList()); + + assertNull(result); + verify(configUtil).getMonitorExternalType(); + } + + @Test + public void testInitializeJmxMonitoring() { + when(configUtil.getClientMonitorJmxEnabled()).thenReturn(true); + List collectors = Collections.singletonList(metricsCollector); + + factory.initializeJmxMonitoring(collectors); + verify(metricsCollector).mBeanName(); + } +} \ No newline at end of file diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/DefaultApolloMetricsExporterFactoryTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/DefaultApolloMetricsExporterFactoryTest.java deleted file mode 100644 index ca4e807e..00000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/DefaultApolloMetricsExporterFactoryTest.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2022 Apollo Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.ctrip.framework.apollo.monitor.internal.exporter; - -import static org.junit.Assert.assertNull; - -import com.ctrip.framework.apollo.build.MockInjector; -import com.ctrip.framework.apollo.core.ApolloClientSystemConsts; -import com.ctrip.framework.apollo.monitor.internal.collector.MetricsCollector; -import com.ctrip.framework.apollo.monitor.internal.exporter.internals.DefaultMetricsExporterFactory; -import com.ctrip.framework.apollo.util.ConfigUtil; -import java.util.ArrayList; -import java.util.List; -import org.junit.Test; - -public class DefaultApolloMetricsExporterFactoryTest { - - private DefaultMetricsExporterFactory defaultMetricsReporterFactory; - - public void init(String form, String period) { - if (form!=null){ - System.setProperty(ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_EXTERNAL_TYPE,form); - } - if (period!=null){ - System.setProperty(ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_EXTERNAL_EXPORT_PERIOD,period); - } - ConfigUtil mockConfigUtil = new ConfigUtil(); - defaultMetricsReporterFactory = new DefaultMetricsExporterFactory(); - MockInjector.setInstance(ConfigUtil.class, mockConfigUtil); - } - - @Test - public void testGetMetricsReporter_NoSupportedReporter() { - init("prometheus","300"); - List collectors = new ArrayList<>(); - assertNull(defaultMetricsReporterFactory.getMetricsReporter(collectors)); - } - - @Test - public void testGetMetricsReporter_NullForm() { - init(null,null); - List collectors = new ArrayList<>(); - MetricsExporter reporter = defaultMetricsReporterFactory.getMetricsReporter(collectors); - assertNull(reporter); - } -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/MockApolloClientMetricsExporter.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/MockApolloClientMetricsExporter.java new file mode 100644 index 00000000..31f33a2f --- /dev/null +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/MockApolloClientMetricsExporter.java @@ -0,0 +1,48 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.exporter; + +import java.util.Map; + +public class MockApolloClientMetricsExporter extends AbstractApolloClientMetricsExporter{ + + @Override + protected void doInit() { + + } + + @Override + public boolean isSupport(String form) { + return "mocktheus".equals(form); + } + + @Override + public void registerOrUpdateCounterSample(String name, Map tag, + double incrValue) { + + } + + @Override + public void registerOrUpdateGaugeSample(String name, Map tag, double value) { + + } + + @Override + public String response() { + return ""; + } +} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/jmx/ApolloClientJmxMBeanRegisterTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/jmx/ApolloClientJmxMBeanRegisterTest.java new file mode 100644 index 00000000..e192a183 --- /dev/null +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/jmx/ApolloClientJmxMBeanRegisterTest.java @@ -0,0 +1,65 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.jmx; + +import static org.mockito.Mockito.*; +import static org.junit.Assert.*; +import org.junit.Before; +import org.junit.Test; +import org.mockito.MockitoAnnotations; + +import javax.management.MBeanServer; +import javax.management.ObjectName; + +public class ApolloClientJmxMBeanRegisterTest { + + private MBeanServer mockMBeanServer; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + mockMBeanServer = mock(MBeanServer.class); + ApolloClientJmxMBeanRegister.setMBeanServer(mockMBeanServer); + } + + @Test + public void testRegister_MBeanNotRegistered() throws Exception { + String name = "com.example:type=TestMBean"; + Object mbean = new Object(); + + when(mockMBeanServer.isRegistered(any(ObjectName.class))).thenReturn(false); + ObjectName objectName = ApolloClientJmxMBeanRegister.register(name, mbean); + + assertNotNull(objectName); + verify(mockMBeanServer).registerMBean(mbean, objectName); + } + + @Test + public void testRegister_MBeanAlreadyRegistered() throws Exception { + String name = "com.example:type=TestMBean"; + Object mbean = new Object(); + + ObjectName objectName = new ObjectName(name); + when(mockMBeanServer.isRegistered(objectName)).thenReturn(true); + + ApolloClientJmxMBeanRegister.register(name, mbean); + + verify(mockMBeanServer).unregisterMBean(objectName); + verify(mockMBeanServer).registerMBean(mbean, objectName); + } + +} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/AbstractApolloClientMetricsEventListenerTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/AbstractApolloClientMetricsEventListenerTest.java new file mode 100644 index 00000000..697dfffd --- /dev/null +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/AbstractApolloClientMetricsEventListenerTest.java @@ -0,0 +1,111 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.listener; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; + +import com.ctrip.framework.apollo.monitor.internal.event.ApolloConfigMetricsEvent; +import com.ctrip.framework.apollo.monitor.internal.model.CounterModel; +import com.ctrip.framework.apollo.monitor.internal.model.GaugeModel; +import com.ctrip.framework.apollo.monitor.internal.model.SampleModel; +import org.junit.Before; +import org.junit.Test; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class AbstractApolloClientMetricsEventListenerTest { + + private class TestMetricsEventListener extends AbstractApolloClientMetricsEventListener { + public TestMetricsEventListener(String tag) { + super(tag); + } + + @Override + protected void collect0(ApolloConfigMetricsEvent event) { + // 简单的收集逻辑 + } + + @Override + protected void export0() { + // 模拟导出逻辑 + } + } + + private TestMetricsEventListener listener; + private ApolloConfigMetricsEvent event; + + @Before + public void setUp() { + listener = new TestMetricsEventListener("testTag"); + event = mock(ApolloConfigMetricsEvent.class); + when(event.getTag()).thenReturn("testTag"); + } + + @Test + public void testCollect() { + listener.collect(event); + assertTrue(listener.isMetricsSampleUpdated()); + } + + @Test + public void testIsSupport() { + assertTrue(listener.isSupport(event)); + when(event.getTag()).thenReturn("otherTag"); + assertFalse(listener.isSupport(event)); + } + + @Test + public void testExport() { + listener.collect(event); + List samples = listener.export(); + assertNotNull(samples); + assertTrue(samples.isEmpty()); // 应为空,因为尚未添加样本 + } + + @Test + public void testCreateOrUpdateGaugeSample() { + String mapKey = "gauge1"; + String metricsName = "testGauge"; + Map tags = new HashMap<>(); + tags.put("key", "value"); + + listener.createOrUpdateGaugeSample(mapKey, metricsName, tags, 42.0); + + List samples = listener.export(); + assertEquals(1, samples.size()); + assertTrue(samples.get(0) instanceof GaugeModel); + assertEquals(42.0, ((GaugeModel) samples.get(0)).getValue(), 0.01); + } + + @Test + public void testCreateOrUpdateCounterSample() { + String mapKey = "counter1"; + String metricsName = "testCounter"; + Map tags = new HashMap<>(); + tags.put("key", "value"); + + listener.createOrUpdateCounterSample(mapKey, metricsName, tags, 5.0); + + List samples = listener.export(); + assertEquals(1, samples.size()); + assertTrue(samples.get(0) instanceof CounterModel); + assertEquals(5.0, ((CounterModel) samples.get(0)).getValue(), 0.01); + } +} \ No newline at end of file diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/DefaultApolloClientMetricsEventListenerManagerTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/DefaultApolloClientMetricsEventListenerManagerTest.java new file mode 100644 index 00000000..9593b257 --- /dev/null +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/DefaultApolloClientMetricsEventListenerManagerTest.java @@ -0,0 +1,68 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.listener; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; + +import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientMetricsEventListenerManager; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class DefaultApolloClientMetricsEventListenerManagerTest { + + private DefaultApolloClientMetricsEventListenerManager manager; + + @Before + public void setUp() { + manager = new DefaultApolloClientMetricsEventListenerManager(); + } + + @Test + public void testInitialCollectors() { + List collectors = manager.getCollectors(); + assertNotNull(collectors); + assertTrue(collectors.isEmpty()); // 初始状态应该为空列表 + } + + @Test + public void testSetCollectors() { + ApolloClientMetricsEventListener mockListener = mock(ApolloClientMetricsEventListener.class); + List newCollectors = new ArrayList<>(); + newCollectors.add(mockListener); + + manager.setCollectors(newCollectors); + List collectors = manager.getCollectors(); + + assertNotNull(collectors); + assertEquals(1, collectors.size()); + assertEquals(mockListener, collectors.get(0)); // 验证设置的监听器 + } + + @Test + public void testSetEmptyCollectors() { + manager.setCollectors(Collections.emptyList()); + List collectors = manager.getCollectors(); + + assertNotNull(collectors); + assertTrue(collectors.isEmpty()); // 设置为空列表后应该为空 + } +} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMessageProducerCompositeTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMessageProducerCompositeTest.java new file mode 100644 index 00000000..f13a9892 --- /dev/null +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMessageProducerCompositeTest.java @@ -0,0 +1,134 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.tracer; + +import static org.mockito.Mockito.*; +import static org.junit.Assert.*; + +import com.ctrip.framework.apollo.tracer.spi.MessageProducer; +import com.ctrip.framework.apollo.tracer.spi.Transaction; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import java.util.Arrays; +import java.util.List; + +public class ApolloClientMessageProducerCompositeTest { + + private ApolloClientMessageProducerComposite composite; + + @Mock + private MessageProducer producer1; + + @Mock + private MessageProducer producer2; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + List producers = Arrays.asList(producer1, producer2); + composite = new ApolloClientMessageProducerComposite(producers); + } + + @Test + public void testLogError_Throwable() { + Throwable cause = new Exception("Test exception"); + + composite.logError(cause); + + verify(producer1).logError(cause); + verify(producer2).logError(cause); + } + + @Test + public void testLogError_String_Throwable() { + String message = "Test error message"; + Throwable cause = new Exception("Test exception"); + + composite.logError(message, cause); + + verify(producer1).logError(message, cause); + verify(producer2).logError(message, cause); + } + + @Test + public void testLogEvent_Type_Name() { + String type = "EVENT_TYPE"; + String name = "EVENT_NAME"; + + composite.logEvent(type, name); + + verify(producer1).logEvent(type, name); + verify(producer2).logEvent(type, name); + } + + @Test + public void testLogEvent_Type_Name_Status_NameValuePairs() { + String type = "EVENT_TYPE"; + String name = "EVENT_NAME"; + String status = "SUCCESS"; + String nameValuePairs = "key=value"; + + composite.logEvent(type, name, status, nameValuePairs); + + verify(producer1).logEvent(type, name, status, nameValuePairs); + verify(producer2).logEvent(type, name, status, nameValuePairs); + } + + @Test + public void testLogMetricsForCount() { + String name = "METRIC_NAME"; + + composite.logMetricsForCount(name); + + verify(producer1).logMetricsForCount(name); + verify(producer2).logMetricsForCount(name); + } + + @Test + public void testNewTransaction() { + String type = "TRANSACTION_TYPE"; + String name = "TRANSACTION_NAME"; + + Transaction transaction1 = mock(Transaction.class); + when(producer1.newTransaction(type, name)).thenReturn(null); + when(producer2.newTransaction(type, name)).thenReturn(transaction1); + + Transaction result = composite.newTransaction(type, name); + + assertEquals(transaction1, result); + verify(producer1).newTransaction(type, name); + verify(producer2).newTransaction(type, name); + } + + @Test + public void testNewTransaction_NoValidTransaction() { + String type = "TRANSACTION_TYPE"; + String name = "TRANSACTION_NAME"; + + when(producer1.newTransaction(type, name)).thenReturn(null); + when(producer2.newTransaction(type, name)).thenReturn(null); + + Transaction result = composite.newTransaction(type, name); + + assertEquals(ApolloClientMessageProducerComposite.NULL_TRANSACTION, result); + verify(producer1).newTransaction(type, name); + verify(producer2).newTransaction(type, name); + } +} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMonitorMessageProducerTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMonitorMessageProducerTest.java new file mode 100644 index 00000000..5efc2971 --- /dev/null +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMonitorMessageProducerTest.java @@ -0,0 +1,83 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.tracer; + +import static com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorConstant.*; +import static org.junit.Assert.*; + +import com.ctrip.framework.apollo.tracer.spi.Transaction; +import org.junit.Before; +import org.junit.Test; +import org.mockito.MockitoAnnotations; + + +public class ApolloClientMonitorMessageProducerTest { + + private ApolloClientMonitorMessageProducer producer; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + + producer = new ApolloClientMonitorMessageProducer(); + } + + @Test + public void testLogError_Throwable() { + Throwable cause = new Exception("Test exception"); + + producer.logError(cause); + } + + @Test + public void testLogError_String_Throwable() { + String message = "Test error message"; + Throwable cause = new Exception("Test exception"); + + producer.logError(message, cause); + } + + @Test + public void testLogEvent_TaggedEvent() { + String type = ApolloClientMonitorMessageProducer.TAGS.get(0); // APOLLO_CLIENT_CONFIGCHANGES + String name = "Test event"; + + producer.logEvent(type, name); + } + + @Test + public void testLogEvent_ClientConfigEvent() { + String type = APOLLO_CLIENT_CONFIGS + "namespace"; + String name = "Test config"; + + producer.logEvent(type, name); + } + + @Test + public void testLogMetricsForCount() { + String name = APOLLO_CLIENT_NAMESPACE_USAGE + ":testNamespace"; + + producer.logMetricsForCount(name); + } + + @Test + public void testNewTransaction() { + Transaction result = producer.newTransaction("type", "name"); + + assertEquals(ApolloClientMessageProducerComposite.NULL_TRANSACTION, result); + } +} \ No newline at end of file diff --git a/apollo-client/src/test/resources/META-INF/services/com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporter b/apollo-client/src/test/resources/META-INF/services/com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporter new file mode 100644 index 00000000..2deb4099 --- /dev/null +++ b/apollo-client/src/test/resources/META-INF/services/com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporter @@ -0,0 +1 @@ +com.ctrip.framework.apollo.monitor.internal.exporter.MockApolloClientMetricsExporter \ No newline at end of file diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/ApolloClientSystemConsts.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/core/ApolloClientSystemConsts.java index b28f7883..2bf8f850 100644 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/ApolloClientSystemConsts.java +++ b/apollo-core/src/main/java/com/ctrip/framework/apollo/core/ApolloClientSystemConsts.java @@ -166,7 +166,11 @@ public class ApolloClientSystemConsts { * apollo client monitor enabled */ public static final String APOLLO_CLIENT_MONITOR_ENABLED = "apollo.client.monitor.enabled"; - + + /** + * apollo client monitor exception save size + */ + public static final String APOLLO_CLIENT_MONITOR_EXCEPTION_QUEUE_SIZE = "apollo.client.monitor.exception-queue-size"; /** * apollo client monitor jmx enabled */ diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/Tracer.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/Tracer.java index e97e8a6d..d8971db0 100644 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/Tracer.java +++ b/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/Tracer.java @@ -88,6 +88,14 @@ public static void logEvent(String type, String name, String status, String name type, name, status, nameValuePairs, ex); } } + + public static void logMetricsForCount(String name) { + try { + getProducer().logMetricsForCount(name); + } catch (Throwable ex) { + logger.warn("Failed to log metrics for count: {}", name, ex); + } + } public static Transaction newTransaction(String type, String name) { try { diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/internals/DefaultMessageProducerManager.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/internals/DefaultMessageProducerManager.java index 53204d89..2490abdb 100644 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/internals/DefaultMessageProducerManager.java +++ b/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/internals/DefaultMessageProducerManager.java @@ -26,18 +26,18 @@ * @author Jason Song(song_s@ctrip.com) */ public class DefaultMessageProducerManager implements MessageProducerManager { - private static MessageProducer producer; + private static MessageProducer producer; - public DefaultMessageProducerManager() { - if (ClassLoaderUtil.isClassPresent(CatNames.CAT_CLASS)) { - producer = new CatMessageProducer(); - } else { - producer = new NullMessageProducerManager().getProducer(); - } + public DefaultMessageProducerManager() { + if (ClassLoaderUtil.isClassPresent(CatNames.CAT_CLASS)) { + producer = new CatMessageProducer(); + } else { + producer = new NullMessageProducerManager().getProducer(); } + } - @Override - public MessageProducer getProducer() { - return producer; - } + @Override + public MessageProducer getProducer() { + return producer; + } } diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/internals/cat/CatMessageProducer.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/internals/cat/CatMessageProducer.java index cb525f90..e1796073 100644 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/internals/cat/CatMessageProducer.java +++ b/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/internals/cat/CatMessageProducer.java @@ -45,6 +45,11 @@ public void logEvent(String type, String name, String status, String nameValuePa status, nameValuePairs); } + @Override + public void logMetricsForCount(String name) { + Cat.logMetricForCount(name); + } + @Override public Transaction newTransaction(String type, String name) { return new CatTransaction(Cat.newTransaction(type, name)); diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/spi/MessageProducer.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/spi/MessageProducer.java index b556b8ab..7654c56c 100644 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/spi/MessageProducer.java +++ b/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/spi/MessageProducer.java @@ -54,6 +54,16 @@ public interface MessageProducer extends Ordered { */ void logEvent(String type, String name, String status, String nameValuePairs); + + /** + * log metrics for count + * + * @param name metrics name + */ + default void logMetricsForCount(String name) { + //do nothing + } + /** * Create a new transaction with given type and name. * diff --git a/apollo-plugin/apollo-plugin-client-prometheus/pom.xml b/apollo-plugin/apollo-plugin-client-prometheus/pom.xml index 860c5f08..07cb99c6 100644 --- a/apollo-plugin/apollo-plugin-client-prometheus/pom.xml +++ b/apollo-plugin/apollo-plugin-client-prometheus/pom.xml @@ -36,11 +36,10 @@ apollo-client provided - - io.prometheus - simpleclient_common - provided - + + io.prometheus + simpleclient_common + \ No newline at end of file diff --git a/apollo-plugin/apollo-plugin-client-prometheus/src/main/java/com/ctrip/framework/apollo/plugin/prometheus/PrometheusApolloClientMetricsExporter.java b/apollo-plugin/apollo-plugin-client-prometheus/src/main/java/com/ctrip/framework/apollo/plugin/prometheus/PrometheusApolloClientMetricsExporter.java new file mode 100644 index 00000000..df518054 --- /dev/null +++ b/apollo-plugin/apollo-plugin-client-prometheus/src/main/java/com/ctrip/framework/apollo/plugin/prometheus/PrometheusApolloClientMetricsExporter.java @@ -0,0 +1,94 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.plugin.prometheus; + +import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory; +import com.ctrip.framework.apollo.monitor.internal.exporter.AbstractApolloClientMetricsExporter; +import com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporter; +import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientNamespaceApi; +import io.prometheus.client.Collector; +import io.prometheus.client.CollectorRegistry; +import io.prometheus.client.Counter; +import io.prometheus.client.Gauge; +import io.prometheus.client.exporter.common.TextFormat; +import java.io.IOException; +import java.io.StringWriter; +import java.util.HashMap; +import java.util.Map; +import org.slf4j.Logger; + +/** + * @author Rawven + */ +public class PrometheusApolloClientMetricsExporter extends + AbstractApolloClientMetricsExporter implements ApolloClientMetricsExporter { + private final Logger logger = DeferredLoggerFactory.getLogger( + DefaultApolloClientNamespaceApi.class); + private static final String PROMETHEUS = "prometheus"; + private final CollectorRegistry registry; + private final Map map = new HashMap<>(); + + + public PrometheusApolloClientMetricsExporter() { + this.registry = new CollectorRegistry(); + } + + @Override + public void doInit() { + + } + + @Override + public boolean isSupport(String form) { + return PROMETHEUS.equals(form); + } + + + @Override + public void registerOrUpdateCounterSample(String name, Map tags, double incrValue) { + Counter counter = (Counter) map.computeIfAbsent(name, k -> Counter.build() + .name(name) + .help("apollo") + .labelNames(tags.keySet().toArray(new String[0])) + .register(registry)); + counter.labels(tags.values().toArray(new String[0])).inc(incrValue); +} + + + @Override + public void registerOrUpdateGaugeSample(String name, Map tags, double value) { + Gauge gauge = (Gauge) map.computeIfAbsent(name, k -> Gauge.build() + .name(name) + .help("apollo") + .labelNames(tags.keySet().toArray(new String[0])) + .register(registry)); + gauge.labels(tags.values().toArray(new String[0])).set(value); + } + + + @Override + public String response() { + try (StringWriter writer = new StringWriter()){ + TextFormat.writeFormat(TextFormat.CONTENT_TYPE_OPENMETRICS_100, writer, registry.metricFamilySamples()); + return writer.toString(); + } catch (IOException e) { + logger.error("Write metrics to Prometheus format failed", e); + return ""; + } + } +} + \ No newline at end of file diff --git a/apollo-plugin/apollo-plugin-client-prometheus/src/main/java/com/ctrip/framework/apollo/plugin/prometheus/PrometheusMetricExporter.java b/apollo-plugin/apollo-plugin-client-prometheus/src/main/java/com/ctrip/framework/apollo/plugin/prometheus/PrometheusMetricExporter.java deleted file mode 100644 index 76c921b5..00000000 --- a/apollo-plugin/apollo-plugin-client-prometheus/src/main/java/com/ctrip/framework/apollo/plugin/prometheus/PrometheusMetricExporter.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright 2022 Apollo Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.ctrip.framework.apollo.plugin.prometheus; - -import com.ctrip.framework.apollo.monitor.internal.model.CounterModel; -import com.ctrip.framework.apollo.monitor.internal.model.GaugeModel; -import com.ctrip.framework.apollo.monitor.internal.exporter.AbstractMetricsExporter; -import com.ctrip.framework.apollo.monitor.internal.exporter.MetricsExporter; -import io.prometheus.client.Collector; -import io.prometheus.client.CollectorRegistry; -import io.prometheus.client.Counter; -import io.prometheus.client.Gauge; -import io.prometheus.client.exporter.common.TextFormat; -import java.io.IOException; -import java.io.StringWriter; -import java.util.HashMap; -import java.util.Map; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @author Rawven - */ -public class PrometheusMetricExporter extends AbstractMetricsExporter implements MetricsExporter { - - private static final Logger logger = LoggerFactory.getLogger( - PrometheusMetricExporter.class); - private final CollectorRegistry registry; - private final Map map = new HashMap<>(); - private final String PROMETHEUS = "prometheus"; - - public PrometheusMetricExporter() { - this.registry = new CollectorRegistry(); - } - - @Override - public void doInit() { - - } - - @Override - public boolean isSupport(String form) { - return PROMETHEUS.equals(form); - } - - @Override - public void registerCounterSample(CounterModel sample) { - String[][] tags = getTags(sample); - Counter counter; - if (!map.containsKey(sample.getName())) { - counter = Counter.build() - .name(sample.getName()) - .help("apollo") - .labelNames(tags[0]) - .register(registry); - map.put(sample.getName(), counter); - } else { - counter = (Counter) map.get(sample.getName()); - } - counter.labels(tags[1]).inc(sample.getIncreaseValue()); - } - - @Override - public void registerGaugeSample(GaugeModel sample) { - String[][] tags = getTags(sample); - Gauge gauge; - if (!map.containsKey(sample.getName())) { - gauge = Gauge.build() - .name(sample.getName()) - .help("apollo") - .labelNames(tags[0]) - .register(registry); - map.put(sample.getName(), gauge); - } else { - gauge = (Gauge) map.get(sample.getName()); - } - gauge.labels(tags[1]).set(sample.getApplyValue()); - } - - - @Override - public String response() { - StringWriter writer = new StringWriter(); - try { - TextFormat.writeFormat(TextFormat.CONTENT_TYPE_OPENMETRICS_100, writer, - registry.metricFamilySamples()); - } catch (IOException e) { - logger.error("Write metrics to Prometheus format failed", e); - } - return writer.toString(); - } -} \ No newline at end of file diff --git a/apollo-plugin/apollo-plugin-client-prometheus/src/main/resources/META-INF/services/com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporter b/apollo-plugin/apollo-plugin-client-prometheus/src/main/resources/META-INF/services/com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporter new file mode 100644 index 00000000..8f46cbb7 --- /dev/null +++ b/apollo-plugin/apollo-plugin-client-prometheus/src/main/resources/META-INF/services/com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporter @@ -0,0 +1 @@ +com.ctrip.framework.apollo.plugin.prometheus.PrometheusApolloClientMetricsExporter \ No newline at end of file diff --git a/apollo-plugin/apollo-plugin-client-prometheus/src/main/resources/META-INF/services/com.ctrip.framework.apollo.monitor.internal.exporter.MetricsExporter b/apollo-plugin/apollo-plugin-client-prometheus/src/main/resources/META-INF/services/com.ctrip.framework.apollo.monitor.internal.exporter.MetricsExporter deleted file mode 100644 index 51289143..00000000 --- a/apollo-plugin/apollo-plugin-client-prometheus/src/main/resources/META-INF/services/com.ctrip.framework.apollo.monitor.internal.exporter.MetricsExporter +++ /dev/null @@ -1 +0,0 @@ -com.ctrip.framework.apollo.plugin.prometheus.PrometheusMetricExporter \ No newline at end of file From 77eed66dcd97b0992e551ef4126c6d553ded07b7 Mon Sep 17 00:00:00 2001 From: liu Date: Sun, 18 Aug 2024 16:51:10 +0800 Subject: [PATCH 3/8] feat(client): add unit test --- .../apollo/monitor/api/ConfigMonitor.java | 15 +++++++++++++++ .../additional-spring-configuration-metadata.json | 12 ++---------- 2 files changed, 17 insertions(+), 10 deletions(-) diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ConfigMonitor.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ConfigMonitor.java index a808cfb0..a1731644 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ConfigMonitor.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ConfigMonitor.java @@ -21,13 +21,28 @@ */ public interface ConfigMonitor { + /** + * get thread pool monitor api + */ ApolloClientThreadPoolMonitorApi getThreadPoolMonitorApi(); + /** + * get exception monitor api + */ ApolloClientExceptionMonitorApi getExceptionMonitorApi(); + /** + * get namespace monitor api + */ ApolloClientNamespaceMonitorApi getNamespaceMonitorApi(); + /** + * get running params monitor api + */ ApolloClientBootstrapArgsMonitorApi getRunningParamsMonitorApi(); + /** + * get monitor external system data + */ String getExporterData(); } diff --git a/apollo-client/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/apollo-client/src/main/resources/META-INF/additional-spring-configuration-metadata.json index 8dfe0553..0bb9b644 100644 --- a/apollo-client/src/main/resources/META-INF/additional-spring-configuration-metadata.json +++ b/apollo-client/src/main/resources/META-INF/additional-spring-configuration-metadata.json @@ -93,20 +93,12 @@ "defaultValue": "" }, { - "name": "apollo.client.monitor.exception-save-size", + "name": "apollo.client.monitor.exception-queue-size", "type": "java.lang.String", "sourceType": "com.ctrip.framework.apollo.core.ApolloClientSystemConsts", - "description": "apollo client monitor exception-save-size.", + "description": "apollo client monitor exception-queue-size.", "defaultValue": "" }, - { - "name": "apollo.client.monitor.metrics-event-pool-size", - "type": "java.lang.String", - "sourceType": "com.ctrip.framework.apollo.core.ApolloClientSystemConsts", - "description": "apollo client monitor MetricsEvent object pool size.", - "defaultValue": "" - }, - { "name": "apollo.meta", "type": "java.net.URI", From 2ec4630387be3107686e54c86f80c4f3f3da9b16 Mon Sep 17 00:00:00 2001 From: liu Date: Thu, 1 Aug 2024 17:19:41 +0800 Subject: [PATCH 4/8] feat(client): add unit test --- .../internals/ConfigMonitorInitializer.java | 6 +- .../apollo/internals/DefaultInjector.java | 2 +- .../ApolloClientBootstrapArgsMonitorApi.java | 12 ++ .../api/ApolloClientNamespaceMonitorApi.java | 30 ++-- .../api/ApolloClientThreadPoolMonitorApi.java | 14 ++ .../internal/ApolloClientMonitorConstant.java | 17 +- .../AbstractApolloClientMetricsExporter.java | 2 +- ...tractApolloClientMonitorEventListener.java | 24 ++- ...olloClientMonitorEventListenerManager.java | 4 +- .../DefaultApolloClientBootstrapArgsApi.java | 5 - .../impl/DefaultApolloClientExceptionApi.java | 8 +- .../impl/DefaultApolloClientNamespaceApi.java | 169 +++++++++--------- .../DefaultApolloClientThreadPoolApi.java | 17 +- .../impl/NullClientNamespaceMonitorApi.java | 36 +--- .../impl/NullClientThreadPoolMonitorApi.java | 5 + .../ConfigMonitorInitializerTest.java | 2 +- .../internal/DefaultConfigMonitorTest.java | 109 +++++------ .../ApolloClientMonitorEventFactoryTest.java | 53 ++++++ ...ApolloClientMonitorEventPublisherTest.java | 96 +++++----- ...stractApolloClientMetricsExporterTest.java | 142 +++++++-------- ...polloClientMetricsExporterFactoryTest.java | 96 +++++----- .../MockApolloClientMetricsExporter.java | 4 +- .../jmx/ApolloClientJmxMBeanRegisterTest.java | 53 +++--- ...tApolloClientMonitorEventListenerTest.java | 143 +++++++-------- ...ClientMonitorEventListenerManagerTest.java | 67 +++++++ ...faultApolloClientBootstrapArgsApiTest.java | 99 +++++----- .../DefaultApolloClientExceptionApiTest.java | 132 +++++++------- ...ClientMonitorEventListenerManagerTest.java | 68 ------- .../DefaultApolloClientNamespaceApiTest.java | 117 ++++++------ .../DefaultApolloClientThreadPoolApiTest.java | 103 ++++++----- ...NullClientBootstrapArgsMonitorApiTest.java | 157 ++++++++++++++++ .../NullClientExceptionMonitorApiTest.java | 50 ++++++ .../NullClientNamespaceMonitorApiTest.java | 73 ++++++++ .../NullClientThreadPoolMonitorApiTest.java | 65 +++++++ ...lloClientMessageProducerCompositeTest.java | 148 +++++++-------- ...polloClientMonitorMessageProducerTest.java | 80 ++++----- .../stress/ApolloClientMonitorStressTest.java | 15 +- ...PrometheusApolloClientMetricsExporter.java | 94 ++++++++++ 38 files changed, 1425 insertions(+), 892 deletions(-) rename apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/{impl => }/DefaultApolloClientMonitorEventListenerManager.java (82%) create mode 100644 apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/event/ApolloClientMonitorEventFactoryTest.java create mode 100644 apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/DefaultApolloClientMonitorEventListenerManagerTest.java delete mode 100644 apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientMonitorEventListenerManagerTest.java create mode 100644 apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientBootstrapArgsMonitorApiTest.java create mode 100644 apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientExceptionMonitorApiTest.java create mode 100644 apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientNamespaceMonitorApiTest.java create mode 100644 apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientThreadPoolMonitorApiTest.java create mode 100644 apollo-plugin/apollo-plugin-client-prometheus/src/main/java/com/ctrip/framework/apollo/plugin/prometheus/PrometheusApolloClientMetricsExporter.java diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigMonitorInitializer.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigMonitorInitializer.java index 47f387f9..a6d50f5f 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigMonitorInitializer.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigMonitorInitializer.java @@ -22,6 +22,7 @@ import com.ctrip.framework.apollo.core.utils.ClassLoaderUtil; import com.ctrip.framework.apollo.monitor.api.ConfigMonitor; import com.ctrip.framework.apollo.monitor.internal.DefaultConfigMonitor; +import com.ctrip.framework.apollo.monitor.internal.exporter.AbstractApolloClientMetricsExporter; import com.ctrip.framework.apollo.monitor.internal.jmx.ApolloClientJmxMBeanRegister; import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMonitorEventListener; import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMonitorEventListenerManager; @@ -29,7 +30,7 @@ import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientExceptionApi; import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientNamespaceApi; import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientThreadPoolApi; -import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientMonitorEventListenerManager; +import com.ctrip.framework.apollo.monitor.internal.listener.DefaultApolloClientMonitorEventListenerManager; import com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporter; import com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporterFactory; import com.ctrip.framework.apollo.monitor.internal.tracer.ApolloClientMonitorMessageProducer; @@ -91,7 +92,8 @@ protected static List initializeCollectors( new DefaultApolloClientExceptionApi(), new DefaultApolloClientNamespaceApi(configManager.m_configs, configManager.m_configFiles), new DefaultApolloClientThreadPoolApi(RemoteConfigRepository.m_executorService, - AbstractConfig.m_executorService, AbstractConfigFile.m_executorService), + AbstractConfig.m_executorService, AbstractConfigFile.m_executorService, + AbstractApolloClientMetricsExporter.m_executorService), new DefaultApolloClientBootstrapArgsApi(CONFIG_UTIL) ); diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultInjector.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultInjector.java index c2171371..a4d0fca8 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultInjector.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultInjector.java @@ -21,7 +21,7 @@ import com.ctrip.framework.apollo.monitor.internal.DefaultConfigMonitor; import com.ctrip.framework.apollo.monitor.internal.exporter.impl.DefaultApolloClientMetricsExporterFactory; import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMonitorEventListenerManager; -import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientMonitorEventListenerManager; +import com.ctrip.framework.apollo.monitor.internal.listener.DefaultApolloClientMonitorEventListenerManager; import com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporterFactory; import com.ctrip.framework.apollo.spi.ApolloInjectorCustomizer; import com.ctrip.framework.apollo.spi.ConfigFactory; diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientBootstrapArgsMonitorApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientBootstrapArgsMonitorApi.java index b9c46d78..5b0e0adb 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientBootstrapArgsMonitorApi.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientBootstrapArgsMonitorApi.java @@ -28,12 +28,24 @@ public interface ApolloClientBootstrapArgsMonitorApi { */ Map getBootstrapArgs(); + /** + * get startup params by key + */ String getStartupParams(String key); + /** + * config service url + */ String getConfigServiceUrl(); + /** + * access key secret + */ String getAccessKeySecret(); + /** + * auto update injected spring properties + */ Boolean getAutoUpdateInjectedSpringProperties(); Boolean getBootstrapEnabled(); diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientNamespaceMonitorApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientNamespaceMonitorApi.java index 6fc740ab..57d5efe6 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientNamespaceMonitorApi.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientNamespaceMonitorApi.java @@ -30,23 +30,25 @@ public interface ApolloClientNamespaceMonitorApi { */ Map getNamespaceMetrics(); - List getNamespaceItemName(String namespace); - - List getNamespace404(); - - List getNamespaceTimeout(); - - List getAllNamespaceReleaseKey(); - - List getAllNamespaceUsageCount(); - - List getAllNamespacesLatestUpdateTime(); + /** + * get Namespace Config.ItemsNum + */ + Integer getNamespaceItemsNum(String namespace); - List getAllUsedNamespaceName(); + /** + * get ConfigFile num + */ + Integer getConfigFileNum(); - List getAllNamespaceFirstLoadSpend(); + /** + * get not found namespaces + */ + List getNotFoundNamespaces(); - List getAllNamespaceItemName(); + /** + * get timeout namespaces + */ + List getTimeoutNamespaces(); } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientThreadPoolMonitorApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientThreadPoolMonitorApi.java index c78f9c18..db3315d7 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientThreadPoolMonitorApi.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientThreadPoolMonitorApi.java @@ -29,9 +29,23 @@ public interface ApolloClientThreadPoolMonitorApi { */ Map getThreadPoolInfo(); + /** + * RemoteConfigRepository.m_executorService + */ ApolloThreadPoolInfo getRemoteConfigRepositoryThreadPoolInfo(); + /** + * AbstractConfig.m_executorService + */ ApolloThreadPoolInfo getAbstractConfigThreadPoolInfo(); + /** + * AbstractConfigFile.m_executorService + */ ApolloThreadPoolInfo getAbstractConfigFileThreadPoolInfo(); + + /** + * AbstractApolloClientMetricsExporter.m_executorService + */ + ApolloThreadPoolInfo getMetricsExporterThreadPoolInfo(); } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/ApolloClientMonitorConstant.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/ApolloClientMonitorConstant.java index ccac2fe3..4f615c7d 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/ApolloClientMonitorConstant.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/ApolloClientMonitorConstant.java @@ -38,7 +38,7 @@ public class ApolloClientMonitorConstant { public static final String TIMESTAMP = "timestamp"; public static final String THROWABLE = "throwable"; public static final String NAMESPACE_RELEASE_KEY = "releaseKey"; - public static final String APOLLO_CLIENT = "Apollo_Client_"; + public static final String APOLLO_CLIENT = "apollo_client_"; public static final String ENV = "env"; public static final String VERSION = "version"; public static final String META_FRESH = "metaFreshTime"; @@ -80,9 +80,14 @@ public class ApolloClientMonitorConstant { public static final String METRICS_NAMESPACE_USAGE = "namespace_usage"; public static final String METRICS_NAMESPACE_NOT_FOUND = "namespace_not_found"; public static final String METRICS_NAMESPACE_TIMEOUT = "namespace_timeout"; - public static final String[] METRICS_THREAD_POOL_PARAMS = new String[]{"ThreadPoolName", - "activeTaskCount", "queueSize", - "completedTaskCount", - "poolSize", "totalTaskCount", "corePoolSize", "maximumPoolSize", "largestPoolSize", - "queueCapacity", "queueRemainingCapacity", "currentLoad"}; + public static final String METRICS_THREAD_POOL = "thread_pool_"; + public static final String[] METRICS_THREAD_POOL_PARAMS = new String[]{ + METRICS_THREAD_POOL + "name", + METRICS_THREAD_POOL + "active_task_count", METRICS_THREAD_POOL + "queue_size", + METRICS_THREAD_POOL + "completed_task_count", + METRICS_THREAD_POOL + "pool_size", METRICS_THREAD_POOL + "total_task_count", + METRICS_THREAD_POOL + "core_pool_size", METRICS_THREAD_POOL + "maximum_pool_size", + METRICS_THREAD_POOL + "largest_pool_size", + METRICS_THREAD_POOL + "queue_capacity", METRICS_THREAD_POOL + "queue_remaining_capacity", + METRICS_THREAD_POOL + "current_load"}; } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractApolloClientMetricsExporter.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractApolloClientMetricsExporter.java index ffe15049..c85625ce 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractApolloClientMetricsExporter.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractApolloClientMetricsExporter.java @@ -35,7 +35,7 @@ public abstract class AbstractApolloClientMetricsExporter implements ApolloClien private static final Logger log = DeferredLoggerFactory.getLogger( AbstractApolloClientMetricsExporter.class); - private static final ScheduledExecutorService m_executorService; + public static final ScheduledExecutorService m_executorService; private static final long INITIAL_DELAY = 5L; private static final int THREAD_POOL_SIZE = 1; diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/AbstractApolloClientMonitorEventListener.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/AbstractApolloClientMonitorEventListener.java index ebfacddb..bffb55ed 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/AbstractApolloClientMonitorEventListener.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/AbstractApolloClientMonitorEventListener.java @@ -43,16 +43,6 @@ public AbstractApolloClientMonitorEventListener(String tag) { this.tag = tag; } - /** - * Specific collection logic - */ - protected abstract void collect0(ApolloClientMonitorEvent event); - - /** - * Convenient for indicators that can only be obtained from the status object - */ - protected abstract void export0(); - @Override public String mBeanName() { return tag; @@ -69,9 +59,6 @@ public void collect(ApolloClientMonitorEvent event) { isUpdated.set(true); } - /** - * Whether the sample data has been updated - */ @Override public boolean isMetricsSampleUpdated() { return isUpdated.getAndSet(false); @@ -84,6 +71,17 @@ public List export() { samples.addAll(gaugeSamples.values()); return samples; } + + /** + * Specific collection logic + */ + protected void collect0(ApolloClientMonitorEvent event){} + + /** + * Convenient for indicators that can only be obtained from the status object + */ + protected void export0(){} + /** diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientMonitorEventListenerManager.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/DefaultApolloClientMonitorEventListenerManager.java similarity index 82% rename from apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientMonitorEventListenerManager.java rename to apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/DefaultApolloClientMonitorEventListenerManager.java index 003195e1..8cc0444f 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientMonitorEventListenerManager.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/DefaultApolloClientMonitorEventListenerManager.java @@ -14,10 +14,8 @@ * limitations under the License. * */ -package com.ctrip.framework.apollo.monitor.internal.listener.impl; +package com.ctrip.framework.apollo.monitor.internal.listener; -import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMonitorEventListener; -import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMonitorEventListenerManager; import java.util.ArrayList; import java.util.List; diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientBootstrapArgsApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientBootstrapArgsApi.java index 7a4dcd7e..b1fd2256 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientBootstrapArgsApi.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientBootstrapArgsApi.java @@ -97,11 +97,6 @@ public boolean isMetricsSampleUpdated() { return false; } - @Override - public void export0() { - // do nothing - } - @Override public String getStartupParams(String key) { return Optional.ofNullable(bootstrapArgs.get(key)).orElse("").toString(); diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientExceptionApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientExceptionApi.java index 5cb962e2..f39f6ba0 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientExceptionApi.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientExceptionApi.java @@ -44,13 +44,13 @@ public class DefaultApolloClientExceptionApi extends private final AtomicInteger exceptionNum = new AtomicInteger(0); private int monitorExceptionQueueSize; - private BlockingQueue exceptions; + private final BlockingQueue exceptions; public DefaultApolloClientExceptionApi() { super(TAG_ERROR); monitorExceptionQueueSize = ApolloInjector.getInstance(ConfigUtil.class) .getMonitorExceptionQueueSize(); - if(monitorExceptionQueueSize <= 0){ + if (monitorExceptionQueueSize <= 0) { monitorExceptionQueueSize = 25; } exceptions = new ArrayBlockingQueue<>( @@ -81,10 +81,6 @@ private void addExceptionToQueue(ApolloConfigException exception) { exceptions.add(exception); } - @Override - public void export0() { - } - @Override public List getApolloConfigExceptionDetails() { return exceptions.stream() diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientNamespaceApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientNamespaceApi.java index 90be2059..3fc072ed 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientNamespaceApi.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientNamespaceApi.java @@ -27,14 +27,13 @@ import com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorConstant; import com.ctrip.framework.apollo.monitor.internal.listener.AbstractApolloClientMonitorEventListener; import com.ctrip.framework.apollo.monitor.internal.event.ApolloClientMonitorEvent; -import com.google.common.collect.Lists; import com.google.common.collect.Maps; -import java.time.Instant; +import com.google.common.collect.Sets; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; -import java.util.stream.Collectors; +import java.util.Set; import org.slf4j.Logger; /** @@ -49,8 +48,8 @@ public class DefaultApolloClientNamespaceApi extends private final Map m_configs; private final Map m_configFiles; private final Map namespaces = Maps.newConcurrentMap(); - private final List namespace404 = Lists.newCopyOnWriteArrayList(); - private final List namespaceTimeout = Lists.newCopyOnWriteArrayList(); + private final Set namespace404 = Sets.newCopyOnWriteArraySet(); + private final Set namespaceTimeout = Sets.newCopyOnWriteArraySet(); public DefaultApolloClientNamespaceApi(Map m_configs, Map m_configFiles @@ -67,40 +66,48 @@ public void collect0(ApolloClientMonitorEvent event) { switch (eventName) { case APOLLO_CLIENT_NAMESPACE_NOT_FOUND: - namespace404.add(namespace); + handleNamespaceNotFound(namespace); break; case APOLLO_CLIENT_NAMESPACE_TIMEOUT: - namespaceTimeout.add(namespace); + handleNamespaceTimeout(namespace); break; default: - NamespaceMetrics namespaceMetrics = namespaces.computeIfAbsent(namespace, - k -> new NamespaceMetrics()); - handleNamespaceMetricsEvent(event, namespaceMetrics, namespace); + handleNormalNamespace(namespace, event); break; } } - private void handleNamespaceMetricsEvent(ApolloClientMonitorEvent event, - NamespaceMetrics namespaceMetrics, String namespace) { + private void handleNamespaceNotFound(String namespace) { + namespace404.add(namespace); + } + + private void handleNamespaceTimeout(String namespace) { + namespaceTimeout.add(namespace); + } + + private void handleNormalNamespace(String namespace, ApolloClientMonitorEvent event) { + namespace404.remove(namespace); + namespaceTimeout.remove(namespace); + NamespaceMetrics namespaceMetrics = namespaces.computeIfAbsent(namespace, + k -> new NamespaceMetrics()); + collectMetrics(event, namespaceMetrics, namespace); + } + + private void collectMetrics(ApolloClientMonitorEvent event, NamespaceMetrics namespaceMetrics, + String namespace) { String eventName = event.getName(); switch (eventName) { case APOLLO_CLIENT_NAMESPACE_USAGE: - namespaceMetrics.incrementUsageCount(); - String mapKey = namespace + ApolloClientMonitorConstant.METRICS_NAMESPACE_USAGE; - createOrUpdateCounterSample(mapKey, ApolloClientMonitorConstant.METRICS_NAMESPACE_USAGE, - Collections.singletonMap(NAMESPACE, namespace), 1); + handleUsageEvent(namespaceMetrics, namespace); break; case METRICS_NAMESPACE_LATEST_UPDATE_TIME: - long updateTime = event.getAttachmentValue(ApolloClientMonitorConstant.TIMESTAMP); - namespaceMetrics.setLatestUpdateTime(updateTime); + handleUpdateTimeEvent(event, namespaceMetrics); break; case APOLLO_CLIENT_NAMESPACE_FIRST_LOAD_SPEND: - long firstLoadSpendTime = event.getAttachmentValue(ApolloClientMonitorConstant.TIMESTAMP); - namespaceMetrics.setFirstLoadSpend(firstLoadSpendTime); + handleFirstLoadSpendEvent(event, namespaceMetrics); break; case NAMESPACE_RELEASE_KEY: - String releaseKey = event.getAttachmentValue(NAMESPACE_RELEASE_KEY); - namespaceMetrics.setReleaseKey(releaseKey); + handleReleaseKeyEvent(event, namespaceMetrics); break; default: logger.warn("Unhandled event name: {}", eventName); @@ -108,89 +115,88 @@ private void handleNamespaceMetricsEvent(ApolloClientMonitorEvent event, } } - @Override - public void export0() { - namespaces.forEach((namespace, metrics) -> { - updateNamespaceGaugeSample(METRICS_NAMESPACE_FIRST_LOAD_SPEND, namespace, - metrics.getFirstLoadSpend()); - updateNamespaceGaugeSample(METRICS_NAMESPACE_ITEM_NUM, namespace, - m_configs.get(namespace).getPropertyNames().size()); - updateNamespaceGaugeSample(METRICS_CONFIG_FILE_NUM, namespace, m_configFiles.size()); - }); - createOrUpdateGaugeSample(METRICS_NAMESPACE_NOT_FOUND, METRICS_NAMESPACE_NOT_FOUND, - Collections.emptyMap(), - namespace404.size()); - createOrUpdateGaugeSample(METRICS_NAMESPACE_TIMEOUT, METRICS_NAMESPACE_TIMEOUT, - Collections.emptyMap(), namespaceTimeout.size()); + private void handleUsageEvent(NamespaceMetrics namespaceMetrics, String namespace) { + namespaceMetrics.incrementUsageCount(); + String mapKey = namespace + ApolloClientMonitorConstant.METRICS_NAMESPACE_USAGE; + createOrUpdateCounterSample(mapKey, ApolloClientMonitorConstant.METRICS_NAMESPACE_USAGE, + Collections.singletonMap(NAMESPACE, namespace), 1); } - private void updateNamespaceGaugeSample(String key, String namespace, double value) { - createOrUpdateGaugeSample(namespace + key, key, Collections.singletonMap(NAMESPACE, namespace), - value); + private void handleUpdateTimeEvent(ApolloClientMonitorEvent event, + NamespaceMetrics namespaceMetrics) { + long updateTime = event.getAttachmentValue(ApolloClientMonitorConstant.TIMESTAMP); + namespaceMetrics.setLatestUpdateTime(updateTime); } - - @Override - public Map getNamespaceMetrics() { - return namespaces; + private void handleFirstLoadSpendEvent(ApolloClientMonitorEvent event, + NamespaceMetrics namespaceMetrics) { + long firstLoadSpendTime = event.getAttachmentValue(ApolloClientMonitorConstant.TIMESTAMP); + namespaceMetrics.setFirstLoadSpend(firstLoadSpendTime); } - - @Override - public List getNamespace404() { - return namespace404; + private void handleReleaseKeyEvent(ApolloClientMonitorEvent event, + NamespaceMetrics namespaceMetrics) { + String releaseKey = event.getAttachmentValue(NAMESPACE_RELEASE_KEY); + namespaceMetrics.setReleaseKey(releaseKey); } @Override - public List getNamespaceTimeout() { - return namespaceTimeout; - } + public void export0() { + namespaces.forEach((namespace, metrics) -> { + // update NamespaceMetrics + createOrUpdateGaugeSample(namespace + METRICS_NAMESPACE_FIRST_LOAD_SPEND, + METRICS_NAMESPACE_FIRST_LOAD_SPEND, + Collections.singletonMap(NAMESPACE, namespace), + metrics.getFirstLoadSpend()); - @Override - public List getNamespaceItemName(String namespace) { - Config config = m_configs.get(namespace); - return config == null ? Collections.emptyList() : new ArrayList<>(config.getPropertyNames()); - } + createOrUpdateGaugeSample(namespace + METRICS_NAMESPACE_ITEM_NUM, + METRICS_NAMESPACE_ITEM_NUM, + Collections.singletonMap(NAMESPACE, namespace), + m_configs.get(namespace).getPropertyNames().size()); + }); - @Override - public List getAllNamespaceReleaseKey() { - return namespaces.entrySet().stream() - .map(entry -> String.format("%s:%s", entry.getKey(), entry.getValue().getReleaseKey())) - .collect(Collectors.toList()); + // update ConfigFile num + createOrUpdateGaugeSample(METRICS_CONFIG_FILE_NUM, + METRICS_CONFIG_FILE_NUM, + Collections.emptyMap(), + m_configFiles.size()); + + // update NamespaceStatus metrics + createOrUpdateGaugeSample(METRICS_NAMESPACE_NOT_FOUND, + METRICS_NAMESPACE_NOT_FOUND, + Collections.emptyMap(), + namespace404.size()); + + createOrUpdateGaugeSample(METRICS_NAMESPACE_TIMEOUT, + METRICS_NAMESPACE_TIMEOUT, + Collections.emptyMap(), + namespaceTimeout.size()); } @Override - public List getAllNamespaceUsageCount() { - return namespaces.entrySet().stream() - .map(entry -> String.format("%s:%d", entry.getKey(), entry.getValue().getUsageCount())) - .collect(Collectors.toList()); + public Map getNamespaceMetrics() { + return Collections.unmodifiableMap(namespaces); } @Override - public List getAllNamespacesLatestUpdateTime() { - return namespaces.entrySet().stream() - .map(entry -> String.format("%s:%s", entry.getKey(), - DATE_FORMATTER.format(Instant.ofEpochMilli(entry.getValue().getLatestUpdateTime())))) - .collect(Collectors.toList()); + public List getNotFoundNamespaces() { + return new ArrayList<>(namespace404); } @Override - public List getAllUsedNamespaceName() { - return new ArrayList<>(namespaces.keySet()); + public List getTimeoutNamespaces() { + return new ArrayList<>(namespaceTimeout); } @Override - public List getAllNamespaceFirstLoadSpend() { - return namespaces.entrySet().stream() - .map(entry -> entry.getKey() + ":" + entry.getValue().getFirstLoadSpend()) - .collect(Collectors.toList()); + public Integer getNamespaceItemsNum(String namespace) { + Config config = m_configs.get(namespace); + return (config != null) ? config.getPropertyNames().size() : 0; } @Override - public List getAllNamespaceItemName() { - return m_configs.values().stream() - .map(config -> config.getPropertyNames().toString()) - .collect(Collectors.toList()); + public Integer getConfigFileNum() { + return m_configFiles.size(); } public static class NamespaceMetrics { @@ -198,7 +204,7 @@ public static class NamespaceMetrics { private int usageCount; private long firstLoadSpend; private long latestUpdateTime = System.currentTimeMillis(); - private String releaseKey = "default"; + private String releaseKey = ""; public String getReleaseKey() { return releaseKey; @@ -213,7 +219,7 @@ public int getUsageCount() { } public void incrementUsageCount() { - this.usageCount++; + usageCount++; } public long getFirstLoadSpend() { @@ -232,5 +238,4 @@ public void setLatestUpdateTime(long latestUpdateTime) { this.latestUpdateTime = latestUpdateTime; } } - } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientThreadPoolApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientThreadPoolApi.java index 795e323f..91113eca 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientThreadPoolApi.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientThreadPoolApi.java @@ -22,6 +22,7 @@ import com.ctrip.framework.apollo.internals.AbstractConfigFile; import com.ctrip.framework.apollo.internals.RemoteConfigRepository; import com.ctrip.framework.apollo.monitor.api.ApolloClientThreadPoolMonitorApi; +import com.ctrip.framework.apollo.monitor.internal.exporter.AbstractApolloClientMetricsExporter; import com.ctrip.framework.apollo.monitor.internal.jmx.mbean.ApolloClientJmxThreadPoolMBean; import com.ctrip.framework.apollo.monitor.internal.listener.AbstractApolloClientMonitorEventListener; import com.ctrip.framework.apollo.monitor.internal.event.ApolloClientMonitorEvent; @@ -43,12 +44,14 @@ public class DefaultApolloClientThreadPoolApi extends public static final String REMOTE_CONFIG_REPOSITORY = RemoteConfigRepository.class.getSimpleName(); public static final String ABSTRACT_CONFIG = AbstractConfig.class.getSimpleName(); public static final String ABSTRACT_CONFIG_FILE = AbstractConfigFile.class.getSimpleName(); + public static final String METRICS_EXPORTER = AbstractApolloClientMetricsExporter.class.getSimpleName(); private final Map executorMap = Maps.newHashMap(); public DefaultApolloClientThreadPoolApi( ExecutorService remoteConfigRepositoryExecutorService, ExecutorService abstractConfigExecutorService, - ExecutorService abstractConfigFileExecutorService) { + ExecutorService abstractConfigFileExecutorService, + ExecutorService metricsExporterExecutorService) { super(TAG_THREAD_POOL); executorMap.put(REMOTE_CONFIG_REPOSITORY, new ApolloThreadPoolInfo((ThreadPoolExecutor) remoteConfigRepositoryExecutorService)); @@ -56,11 +59,8 @@ public DefaultApolloClientThreadPoolApi( new ApolloThreadPoolInfo((ThreadPoolExecutor) abstractConfigExecutorService)); executorMap.put(ABSTRACT_CONFIG_FILE, new ApolloThreadPoolInfo((ThreadPoolExecutor) abstractConfigFileExecutorService)); - } - - @Override - public void collect0(ApolloClientMonitorEvent event) { - // do nothing + executorMap.put(METRICS_EXPORTER, + new ApolloThreadPoolInfo((ThreadPoolExecutor) metricsExporterExecutorService)); } @Override @@ -117,6 +117,11 @@ public ApolloThreadPoolInfo getAbstractConfigFileThreadPoolInfo() { return executorMap.get(ABSTRACT_CONFIG_FILE); } + @Override + public ApolloThreadPoolInfo getMetricsExporterThreadPoolInfo() { + return executorMap.get(METRICS_EXPORTER); + } + public static class ApolloThreadPoolInfo { private final ThreadPoolExecutor executor; diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientNamespaceMonitorApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientNamespaceMonitorApi.java index c5da2fdc..051d00d3 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientNamespaceMonitorApi.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientNamespaceMonitorApi.java @@ -36,47 +36,23 @@ public Map getNamespaceMetrics() { @Override - public List getNamespace404() { + public List getNotFoundNamespaces() { return Collections.emptyList(); } @Override - public List getNamespaceTimeout() { + public List getTimeoutNamespaces() { return Collections.emptyList(); } @Override - public List getNamespaceItemName(String namespace) { - return Collections.emptyList(); - } - - @Override - public List getAllNamespaceReleaseKey() { - return Collections.emptyList(); + public Integer getNamespaceItemsNum(String namespace) { + return 0; } @Override - public List getAllNamespaceUsageCount() { - return Collections.emptyList(); + public Integer getConfigFileNum() { + return 0; } - @Override - public List getAllNamespacesLatestUpdateTime() { - return Collections.emptyList(); - } - - @Override - public List getAllUsedNamespaceName() { - return Collections.emptyList(); - } - - @Override - public List getAllNamespaceFirstLoadSpend() { - return Collections.emptyList(); - } - - @Override - public List getAllNamespaceItemName() { - return Collections.emptyList(); - } } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientThreadPoolMonitorApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientThreadPoolMonitorApi.java index b45f1568..0a779adf 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientThreadPoolMonitorApi.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientThreadPoolMonitorApi.java @@ -47,4 +47,9 @@ public ApolloThreadPoolInfo getAbstractConfigThreadPoolInfo() { public ApolloThreadPoolInfo getAbstractConfigFileThreadPoolInfo() { return null; } + + @Override + public ApolloThreadPoolInfo getMetricsExporterThreadPoolInfo() { + return null; + } } diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/ConfigMonitorInitializerTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/ConfigMonitorInitializerTest.java index 3047283a..6db638c7 100644 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/ConfigMonitorInitializerTest.java +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/ConfigMonitorInitializerTest.java @@ -25,7 +25,7 @@ import com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporter; import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMonitorEventListener; import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMonitorEventListenerManager; -import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientMonitorEventListenerManager; +import com.ctrip.framework.apollo.monitor.internal.listener.DefaultApolloClientMonitorEventListenerManager; import com.ctrip.framework.apollo.monitor.internal.tracer.ApolloClientMessageProducerComposite; import com.ctrip.framework.apollo.util.ConfigUtil; import java.util.Collections; diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/DefaultConfigMonitorTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/DefaultConfigMonitorTest.java index 1583032d..beeaf45c 100644 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/DefaultConfigMonitorTest.java +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/DefaultConfigMonitorTest.java @@ -31,57 +31,60 @@ public class DefaultConfigMonitorTest { - private DefaultConfigMonitor configMonitor; - - @Mock - private ApolloClientMetricsExporter reporter; - - @Mock - private ApolloClientThreadPoolMonitorApi threadPoolMonitorApi; - - @Mock - private ApolloClientExceptionMonitorApi exceptionMonitorApi; - - @Mock - private ApolloClientNamespaceMonitorApi namespaceMonitorApi; - - @Mock - private ApolloClientBootstrapArgsMonitorApi bootstrapArgsMonitorApi; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - configMonitor = new DefaultConfigMonitor(); - } - - @Test - public void testInit() { - configMonitor.init(namespaceMonitorApi, threadPoolMonitorApi, exceptionMonitorApi, bootstrapArgsMonitorApi, reporter); - - assertEquals(namespaceMonitorApi, configMonitor.getNamespaceMonitorApi()); - assertEquals(threadPoolMonitorApi, configMonitor.getThreadPoolMonitorApi()); - assertEquals(exceptionMonitorApi, configMonitor.getExceptionMonitorApi()); - assertEquals(bootstrapArgsMonitorApi, configMonitor.getRunningParamsMonitorApi()); - } - - @Test - public void testGetExporterData() { - when(reporter.response()).thenReturn("exporter data"); - - configMonitor.init(namespaceMonitorApi, threadPoolMonitorApi, exceptionMonitorApi, bootstrapArgsMonitorApi, reporter); - - String result = configMonitor.getExporterData(); - - assertEquals("exporter data", result); - verify(reporter).response(); - } - - @Test - public void testDefaultInstances() { - assertNotNull(configMonitor.getThreadPoolMonitorApi()); - assertNotNull(configMonitor.getExceptionMonitorApi()); - assertNotNull(configMonitor.getNamespaceMonitorApi()); - assertNotNull(configMonitor.getRunningParamsMonitorApi()); - assertEquals("No Reporter Use", configMonitor.getExporterData()); // Assuming NullApolloClientMetricsExporter returns "null" - } + private DefaultConfigMonitor configMonitor; + + @Mock + private ApolloClientMetricsExporter reporter; + + @Mock + private ApolloClientThreadPoolMonitorApi threadPoolMonitorApi; + + @Mock + private ApolloClientExceptionMonitorApi exceptionMonitorApi; + + @Mock + private ApolloClientNamespaceMonitorApi namespaceMonitorApi; + + @Mock + private ApolloClientBootstrapArgsMonitorApi bootstrapArgsMonitorApi; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + configMonitor = new DefaultConfigMonitor(); + } + + @Test + public void testInit() { + configMonitor.init(namespaceMonitorApi, threadPoolMonitorApi, exceptionMonitorApi, + bootstrapArgsMonitorApi, reporter); + + assertEquals(namespaceMonitorApi, configMonitor.getNamespaceMonitorApi()); + assertEquals(threadPoolMonitorApi, configMonitor.getThreadPoolMonitorApi()); + assertEquals(exceptionMonitorApi, configMonitor.getExceptionMonitorApi()); + assertEquals(bootstrapArgsMonitorApi, configMonitor.getRunningParamsMonitorApi()); + } + + @Test + public void testGetExporterData() { + when(reporter.response()).thenReturn("exporter data"); + + configMonitor.init(namespaceMonitorApi, threadPoolMonitorApi, exceptionMonitorApi, + bootstrapArgsMonitorApi, reporter); + + String result = configMonitor.getExporterData(); + + assertEquals("exporter data", result); + verify(reporter).response(); + } + + @Test + public void testDefaultInstances() { + assertNotNull(configMonitor.getThreadPoolMonitorApi()); + assertNotNull(configMonitor.getExceptionMonitorApi()); + assertNotNull(configMonitor.getNamespaceMonitorApi()); + assertNotNull(configMonitor.getRunningParamsMonitorApi()); + assertEquals("No Reporter Use", + configMonitor.getExporterData()); // Assuming NullApolloClientMetricsExporter returns "null" + } } \ No newline at end of file diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/event/ApolloClientMonitorEventFactoryTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/event/ApolloClientMonitorEventFactoryTest.java new file mode 100644 index 00000000..876ad176 --- /dev/null +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/event/ApolloClientMonitorEventFactoryTest.java @@ -0,0 +1,53 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.event; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; + +import org.junit.Before; +import org.junit.Test; + +public class ApolloClientMonitorEventFactoryTest { + + private ApolloClientMonitorEventFactory factory; + + @Before + public void setUp() { + factory = ApolloClientMonitorEventFactory.getInstance(); + } + + @Test + public void testGetInstance() { + ApolloClientMonitorEventFactory instance1 = ApolloClientMonitorEventFactory.getInstance(); + ApolloClientMonitorEventFactory instance2 = ApolloClientMonitorEventFactory.getInstance(); + + assertNotNull(instance1); + assertNotNull(instance2); + // 验证两个实例是同一个 + assertSame(instance1, instance2); + } + + @Test + public void testCreateEvent() { + String eventName = "TestEvent"; + ApolloClientMonitorEvent event = factory.createEvent(eventName); + + assertNotNull(event); + assertEquals(eventName, event.getName()); + } +} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/event/ApolloClientMonitorEventPublisherTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/event/ApolloClientMonitorEventPublisherTest.java index 4dbbf708..2119b25a 100644 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/event/ApolloClientMonitorEventPublisherTest.java +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/event/ApolloClientMonitorEventPublisherTest.java @@ -29,52 +29,52 @@ public class ApolloClientMonitorEventPublisherTest { - private ApolloClientMonitorEventListenerManager mockCollectorManager; - private ConfigUtil mockConfigUtil; - private ApolloClientMonitorEventListener mockCollector; - private ApolloClientMonitorEvent mockEvent; - - @Before - public void setUp() { - mockCollectorManager = mock(ApolloClientMonitorEventListenerManager.class); - mockConfigUtil = mock(ConfigUtil.class); - mockCollector = mock(ApolloClientMonitorEventListener.class); - mockEvent = mock(ApolloClientMonitorEvent.class); - - // 使用 Mockito 来模拟静态方法 - MockInjector.setInstance(ApolloClientMonitorEventListenerManager.class, mockCollectorManager); - MockInjector.setInstance(ConfigUtil.class, mockConfigUtil); - ApolloClientMonitorEventPublisher.reset(); - } - - @Test - public void testPublish_WhenClientMonitorEnabled_CollectorSupportsEvent() { - when(mockConfigUtil.getClientMonitorEnabled()).thenReturn(true); - when(mockCollectorManager.getCollectors()).thenReturn(Collections.singletonList(mockCollector)); - when(mockCollector.isSupport(mockEvent)).thenReturn(true); - - ApolloClientMonitorEventPublisher.publish(mockEvent); - - verify(mockCollector).collect(mockEvent); - } - - @Test - public void testPublish_WhenClientMonitorEnabled_CollectorDoesNotSupportEvent() { - when(mockConfigUtil.getClientMonitorEnabled()).thenReturn(true); - when(mockCollectorManager.getCollectors()).thenReturn(Collections.singletonList(mockCollector)); - when(mockCollector.isSupport(mockEvent)).thenReturn(false); - - ApolloClientMonitorEventPublisher.publish(mockEvent); - - verify(mockCollector, never()).collect(mockEvent); - } - - @Test - public void testPublish_WhenClientMonitorDisabled() { - when(mockConfigUtil.getClientMonitorEnabled()).thenReturn(false); - - ApolloClientMonitorEventPublisher.publish(mockEvent); - - verify(mockCollectorManager, never()).getCollectors(); - } + private ApolloClientMonitorEventListenerManager mockCollectorManager; + private ConfigUtil mockConfigUtil; + private ApolloClientMonitorEventListener mockCollector; + private ApolloClientMonitorEvent mockEvent; + + @Before + public void setUp() { + mockCollectorManager = mock(ApolloClientMonitorEventListenerManager.class); + mockConfigUtil = mock(ConfigUtil.class); + mockCollector = mock(ApolloClientMonitorEventListener.class); + mockEvent = mock(ApolloClientMonitorEvent.class); + + // 使用 Mockito 来模拟静态方法 + MockInjector.setInstance(ApolloClientMonitorEventListenerManager.class, mockCollectorManager); + MockInjector.setInstance(ConfigUtil.class, mockConfigUtil); + ApolloClientMonitorEventPublisher.reset(); + } + + @Test + public void testPublish_WhenClientMonitorEnabled_CollectorSupportsEvent() { + when(mockConfigUtil.getClientMonitorEnabled()).thenReturn(true); + when(mockCollectorManager.getCollectors()).thenReturn(Collections.singletonList(mockCollector)); + when(mockCollector.isSupport(mockEvent)).thenReturn(true); + + ApolloClientMonitorEventPublisher.publish(mockEvent); + + verify(mockCollector).collect(mockEvent); + } + + @Test + public void testPublish_WhenClientMonitorEnabled_CollectorDoesNotSupportEvent() { + when(mockConfigUtil.getClientMonitorEnabled()).thenReturn(true); + when(mockCollectorManager.getCollectors()).thenReturn(Collections.singletonList(mockCollector)); + when(mockCollector.isSupport(mockEvent)).thenReturn(false); + + ApolloClientMonitorEventPublisher.publish(mockEvent); + + verify(mockCollector, never()).collect(mockEvent); + } + + @Test + public void testPublish_WhenClientMonitorDisabled() { + when(mockConfigUtil.getClientMonitorEnabled()).thenReturn(false); + + ApolloClientMonitorEventPublisher.publish(mockEvent); + + verify(mockCollectorManager, never()).getCollectors(); + } } diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractApolloClientMetricsExporterTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractApolloClientMetricsExporterTest.java index d73ad67c..8728c0c2 100644 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractApolloClientMetricsExporterTest.java +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractApolloClientMetricsExporterTest.java @@ -34,87 +34,89 @@ public class AbstractApolloClientMetricsExporterTest { - private class TestMetricsExporter extends AbstractApolloClientMetricsExporter { - @Override - protected void doInit() { - } - - public List getCollectors() { - return collectors; - } - - @Override - public boolean isSupport(String form) { - return false; - } - - @Override - public void registerOrUpdateCounterSample(String name, Map tag, - double incrValue) { - - } - - @Override - public void registerOrUpdateGaugeSample(String name, Map tag, double value) { - - } - - @Override - public String response() { - return ""; - } + private TestMetricsExporter exporter; + private ApolloClientMonitorEventListener mockListener; + + @Before + public void setUp() { + exporter = new TestMetricsExporter(); + mockListener = mock(ApolloClientMonitorEventListener.class); + } + + @Test + public void testInit() { + List collectors = new ArrayList<>(); + collectors.add(mockListener); + long collectPeriod = 10L; + + exporter.init(collectors, collectPeriod); + + assertEquals(collectors, exporter.getCollectors()); + } + + @Test + public void testUpdateMetricsData() { + List samples = new ArrayList<>(); + GaugeModel gauge = mock(GaugeModel.class); + when(gauge.getType()).thenReturn(MeterEnums.GAUGE); + when(gauge.getName()).thenReturn("testGauge"); + when(gauge.getValue()).thenReturn(10.0); + samples.add(gauge); + + when(mockListener.isMetricsSampleUpdated()).thenReturn(true); + when(mockListener.export()).thenReturn(samples); + + exporter.init(Collections.singletonList(mockListener), 10L); + exporter.updateMetricsData(); + + verify(mockListener).export(); + verify(gauge).getValue(); + } + + @Test + public void testRegisterSampleGauge() { + GaugeModel gaugeModel = (GaugeModel) GaugeModel.create("testGauge", 5.0).putTag("key", "value"); + + exporter.registerSample(gaugeModel); + } + + @Test + public void testRegisterSampleCounter() { + CounterModel counterModel = (CounterModel) CounterModel.create("testCounter", 5.0) + .putTag("key", "value"); + exporter.registerSample(counterModel); + } + + private class TestMetricsExporter extends AbstractApolloClientMetricsExporter { + + @Override + protected void doInit() { } - private TestMetricsExporter exporter; - private ApolloClientMonitorEventListener mockListener; - - @Before - public void setUp() { - exporter = new TestMetricsExporter(); - mockListener = mock(ApolloClientMonitorEventListener.class); + public List getCollectors() { + return collectors; } - @Test - public void testInit() { - List collectors = new ArrayList<>(); - collectors.add(mockListener); - long collectPeriod = 10L; - - exporter.init(collectors, collectPeriod); - - assertEquals(collectors, exporter.getCollectors()); + @Override + public boolean isSupport(String form) { + return false; } - @Test - public void testUpdateMetricsData() { - List samples = new ArrayList<>(); - GaugeModel gauge = mock(GaugeModel.class); - when(gauge.getType()).thenReturn(MeterEnums.GAUGE); - when(gauge.getName()).thenReturn("testGauge"); - when(gauge.getValue()).thenReturn(10.0); - samples.add(gauge); + @Override + public void registerOrUpdateCounterSample(String name, Map tag, + double incrValue) { - when(mockListener.isMetricsSampleUpdated()).thenReturn(true); - when(mockListener.export()).thenReturn(samples); - - exporter.init(Collections.singletonList(mockListener), 10L); - exporter.updateMetricsData(); - - verify(mockListener).export(); - verify(gauge).getValue(); } - @Test - public void testRegisterSampleGauge() { - GaugeModel gaugeModel = (GaugeModel) GaugeModel.create("testGauge", 5.0).putTag("key", "value"); + @Override + public void registerOrUpdateGaugeSample(String name, Map tag, double value) { - exporter.registerSample(gaugeModel); } - @Test - public void testRegisterSampleCounter() { - CounterModel counterModel = (CounterModel) CounterModel.create("testCounter", 5.0).putTag("key", "value"); - exporter.registerSample(counterModel); + @Override + public String response() { + return ""; } - + } + } \ No newline at end of file diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/DefaultApolloClientMetricsExporterFactoryTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/DefaultApolloClientMetricsExporterFactoryTest.java index 2188ee0d..f8c32b0d 100644 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/DefaultApolloClientMetricsExporterFactoryTest.java +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/DefaultApolloClientMetricsExporterFactoryTest.java @@ -33,52 +33,52 @@ public class DefaultApolloClientMetricsExporterFactoryTest { - private DefaultApolloClientMetricsExporterFactory factory; - - @Mock - private ConfigUtil configUtil; - - @Mock - private ApolloClientMonitorEventListener metricsCollector; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - MockInjector.setInstance(ConfigUtil.class, configUtil); - factory = new DefaultApolloClientMetricsExporterFactory(); - } - - @Test - public void testGetMetricsReporter_NoExternalSystemType() { - when(configUtil.getMonitorExternalType()).thenReturn(null); - - ApolloClientMetricsExporter result = factory.getMetricsReporter(Collections.emptyList()); - - assertNull(result); - verify(configUtil).getMonitorExternalType(); - } - - @Test - public void testGetMetricsReporter_ExporterFound() { - when(configUtil.getMonitorExternalType()).thenReturn("mocktheus"); - when(configUtil.getClientMonitorJmxEnabled()).thenReturn(true); - when(configUtil.getMonitorExternalExportPeriod()).thenReturn(1000L); - when(metricsCollector.mBeanName()).thenReturn("testMBean"); - List collectors = Collections.singletonList(metricsCollector); - - ApolloClientMetricsExporter result = factory.getMetricsReporter(collectors); - - assertNotNull(result); - assertTrue(result instanceof MockApolloClientMetricsExporter); - } - - @Test - public void testGetMetricsReporter_ExporterNotFound() { - when(configUtil.getMonitorExternalType()).thenReturn("unknownType"); - - ApolloClientMetricsExporter result = factory.getMetricsReporter(Collections.emptyList()); - - assertNull(result); - verify(configUtil).getMonitorExternalType(); - } + private DefaultApolloClientMetricsExporterFactory factory; + + @Mock + private ConfigUtil configUtil; + + @Mock + private ApolloClientMonitorEventListener metricsCollector; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + MockInjector.setInstance(ConfigUtil.class, configUtil); + factory = new DefaultApolloClientMetricsExporterFactory(); + } + + @Test + public void testGetMetricsReporter_NoExternalSystemType() { + when(configUtil.getMonitorExternalType()).thenReturn(null); + + ApolloClientMetricsExporter result = factory.getMetricsReporter(Collections.emptyList()); + + assertNull(result); + verify(configUtil).getMonitorExternalType(); + } + + @Test + public void testGetMetricsReporter_ExporterFound() { + when(configUtil.getMonitorExternalType()).thenReturn("mocktheus"); + when(configUtil.getClientMonitorJmxEnabled()).thenReturn(true); + when(configUtil.getMonitorExternalExportPeriod()).thenReturn(1000L); + when(metricsCollector.mBeanName()).thenReturn("testMBean"); + List collectors = Collections.singletonList(metricsCollector); + + ApolloClientMetricsExporter result = factory.getMetricsReporter(collectors); + + assertNotNull(result); + assertTrue(result instanceof MockApolloClientMetricsExporter); + } + + @Test + public void testGetMetricsReporter_ExporterNotFound() { + when(configUtil.getMonitorExternalType()).thenReturn("unknownType"); + + ApolloClientMetricsExporter result = factory.getMetricsReporter(Collections.emptyList()); + + assertNull(result); + verify(configUtil).getMonitorExternalType(); + } } \ No newline at end of file diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/MockApolloClientMetricsExporter.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/MockApolloClientMetricsExporter.java index 31f33a2f..894af2dc 100644 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/MockApolloClientMetricsExporter.java +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/MockApolloClientMetricsExporter.java @@ -18,11 +18,11 @@ import java.util.Map; -public class MockApolloClientMetricsExporter extends AbstractApolloClientMetricsExporter{ +public class MockApolloClientMetricsExporter extends AbstractApolloClientMetricsExporter { @Override protected void doInit() { - + } @Override diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/jmx/ApolloClientJmxMBeanRegisterTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/jmx/ApolloClientJmxMBeanRegisterTest.java index e192a183..a3fec5de 100644 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/jmx/ApolloClientJmxMBeanRegisterTest.java +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/jmx/ApolloClientJmxMBeanRegisterTest.java @@ -18,6 +18,7 @@ import static org.mockito.Mockito.*; import static org.junit.Assert.*; + import org.junit.Before; import org.junit.Test; import org.mockito.MockitoAnnotations; @@ -27,39 +28,39 @@ public class ApolloClientJmxMBeanRegisterTest { - private MBeanServer mockMBeanServer; + private MBeanServer mockMBeanServer; - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - mockMBeanServer = mock(MBeanServer.class); - ApolloClientJmxMBeanRegister.setMBeanServer(mockMBeanServer); - } + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + mockMBeanServer = mock(MBeanServer.class); + ApolloClientJmxMBeanRegister.setMBeanServer(mockMBeanServer); + } - @Test - public void testRegister_MBeanNotRegistered() throws Exception { - String name = "com.example:type=TestMBean"; - Object mbean = new Object(); + @Test + public void testRegister_MBeanNotRegistered() throws Exception { + String name = "com.example:type=TestMBean"; + Object mbean = new Object(); - when(mockMBeanServer.isRegistered(any(ObjectName.class))).thenReturn(false); - ObjectName objectName = ApolloClientJmxMBeanRegister.register(name, mbean); + when(mockMBeanServer.isRegistered(any(ObjectName.class))).thenReturn(false); + ObjectName objectName = ApolloClientJmxMBeanRegister.register(name, mbean); - assertNotNull(objectName); - verify(mockMBeanServer).registerMBean(mbean, objectName); - } + assertNotNull(objectName); + verify(mockMBeanServer).registerMBean(mbean, objectName); + } - @Test - public void testRegister_MBeanAlreadyRegistered() throws Exception { - String name = "com.example:type=TestMBean"; - Object mbean = new Object(); + @Test + public void testRegister_MBeanAlreadyRegistered() throws Exception { + String name = "com.example:type=TestMBean"; + Object mbean = new Object(); - ObjectName objectName = new ObjectName(name); - when(mockMBeanServer.isRegistered(objectName)).thenReturn(true); + ObjectName objectName = new ObjectName(name); + when(mockMBeanServer.isRegistered(objectName)).thenReturn(true); - ApolloClientJmxMBeanRegister.register(name, mbean); + ApolloClientJmxMBeanRegister.register(name, mbean); - verify(mockMBeanServer).unregisterMBean(objectName); - verify(mockMBeanServer).registerMBean(mbean, objectName); - } + verify(mockMBeanServer).unregisterMBean(objectName); + verify(mockMBeanServer).registerMBean(mbean, objectName); + } } diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/AbstractApolloClientMonitorEventListenerTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/AbstractApolloClientMonitorEventListenerTest.java index 43a7a91e..1a60c02f 100644 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/AbstractApolloClientMonitorEventListenerTest.java +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/AbstractApolloClientMonitorEventListenerTest.java @@ -32,80 +32,81 @@ public class AbstractApolloClientMonitorEventListenerTest { - private class TestMonitorEventListener extends AbstractApolloClientMonitorEventListener { - public TestMonitorEventListener(String tag) { - super(tag); - } - - @Override - protected void collect0(ApolloClientMonitorEvent event) { - // 简单的收集逻辑 - } - - @Override - protected void export0() { - // 模拟导出逻辑 - } + private TestMonitorEventListener listener; + private ApolloClientMonitorEvent event; + + @Before + public void setUp() { + listener = new TestMonitorEventListener("testTag"); + event = mock(ApolloClientMonitorEvent.class); + when(event.getTag()).thenReturn("testTag"); + } + + @Test + public void testCollect() { + listener.collect(event); + assertTrue(listener.isMetricsSampleUpdated()); + } + + @Test + public void testIsSupport() { + assertTrue(listener.isSupport(event)); + when(event.getTag()).thenReturn("otherTag"); + assertFalse(listener.isSupport(event)); + } + + @Test + public void testExport() { + listener.collect(event); + List samples = listener.export(); + assertNotNull(samples); + assertTrue(samples.isEmpty()); // 应为空,因为尚未添加样本 + } + + @Test + public void testCreateOrUpdateGaugeSample() { + String mapKey = "gauge1"; + String metricsName = "testGauge"; + Map tags = new HashMap<>(); + tags.put("key", "value"); + + listener.createOrUpdateGaugeSample(mapKey, metricsName, tags, 42.0); + + List samples = listener.export(); + assertEquals(1, samples.size()); + assertTrue(samples.get(0) instanceof GaugeModel); + assertEquals(42.0, ((GaugeModel) samples.get(0)).getValue(), 0.01); + } + + @Test + public void testCreateOrUpdateCounterSample() { + String mapKey = "counter1"; + String metricsName = "testCounter"; + Map tags = new HashMap<>(); + tags.put("key", "value"); + + listener.createOrUpdateCounterSample(mapKey, metricsName, tags, 5.0); + + List samples = listener.export(); + assertEquals(1, samples.size()); + assertTrue(samples.get(0) instanceof CounterModel); + assertEquals(5.0, ((CounterModel) samples.get(0)).getValue(), 0.01); + } + + private class TestMonitorEventListener extends AbstractApolloClientMonitorEventListener { + + public TestMonitorEventListener(String tag) { + super(tag); } - private TestMonitorEventListener listener; - private ApolloClientMonitorEvent event; - - @Before - public void setUp() { - listener = new TestMonitorEventListener("testTag"); - event = mock(ApolloClientMonitorEvent.class); - when(event.getTag()).thenReturn("testTag"); - } - - @Test - public void testCollect() { - listener.collect(event); - assertTrue(listener.isMetricsSampleUpdated()); - } - - @Test - public void testIsSupport() { - assertTrue(listener.isSupport(event)); - when(event.getTag()).thenReturn("otherTag"); - assertFalse(listener.isSupport(event)); - } - - @Test - public void testExport() { - listener.collect(event); - List samples = listener.export(); - assertNotNull(samples); - assertTrue(samples.isEmpty()); // 应为空,因为尚未添加样本 + @Override + protected void collect0(ApolloClientMonitorEvent event) { + // 简单的收集逻辑 } - @Test - public void testCreateOrUpdateGaugeSample() { - String mapKey = "gauge1"; - String metricsName = "testGauge"; - Map tags = new HashMap<>(); - tags.put("key", "value"); - - listener.createOrUpdateGaugeSample(mapKey, metricsName, tags, 42.0); - - List samples = listener.export(); - assertEquals(1, samples.size()); - assertTrue(samples.get(0) instanceof GaugeModel); - assertEquals(42.0, ((GaugeModel) samples.get(0)).getValue(), 0.01); - } - - @Test - public void testCreateOrUpdateCounterSample() { - String mapKey = "counter1"; - String metricsName = "testCounter"; - Map tags = new HashMap<>(); - tags.put("key", "value"); - - listener.createOrUpdateCounterSample(mapKey, metricsName, tags, 5.0); - - List samples = listener.export(); - assertEquals(1, samples.size()); - assertTrue(samples.get(0) instanceof CounterModel); - assertEquals(5.0, ((CounterModel) samples.get(0)).getValue(), 0.01); + @Override + protected void export0() { + // 模拟导出逻辑 } + } } \ No newline at end of file diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/DefaultApolloClientMonitorEventListenerManagerTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/DefaultApolloClientMonitorEventListenerManagerTest.java new file mode 100644 index 00000000..46e3cf8e --- /dev/null +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/DefaultApolloClientMonitorEventListenerManagerTest.java @@ -0,0 +1,67 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.listener; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; + +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class DefaultApolloClientMonitorEventListenerManagerTest { + + private DefaultApolloClientMonitorEventListenerManager manager; + + @Before + public void setUp() { + manager = new DefaultApolloClientMonitorEventListenerManager(); + } + + @Test + public void testInitialCollectors() { + List collectors = manager.getCollectors(); + assertNotNull(collectors); + assertTrue(collectors.isEmpty()); // 初始状态应该为空列表 + } + + @Test + public void testSetCollectors() { + ApolloClientMonitorEventListener mockListener = mock(ApolloClientMonitorEventListener.class); + List newCollectors = new ArrayList<>(); + newCollectors.add(mockListener); + + manager.setCollectors(newCollectors); + List collectors = manager.getCollectors(); + + assertNotNull(collectors); + assertEquals(1, collectors.size()); + assertEquals(mockListener, collectors.get(0)); // 验证设置的监听器 + } + + @Test + public void testSetEmptyCollectors() { + manager.setCollectors(Collections.emptyList()); + List collectors = manager.getCollectors(); + + assertNotNull(collectors); + assertTrue(collectors.isEmpty()); // 设置为空列表后应该为空 + } +} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientBootstrapArgsApiTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientBootstrapArgsApiTest.java index 029044f0..12a1b63b 100644 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientBootstrapArgsApiTest.java +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientBootstrapArgsApiTest.java @@ -15,6 +15,7 @@ * */ package com.ctrip.framework.apollo.monitor.internal.listener.impl; + import static com.ctrip.framework.apollo.core.ApolloClientSystemConsts.*; import static org.mockito.Mockito.*; import static org.junit.Assert.*; @@ -29,61 +30,61 @@ public class DefaultApolloClientBootstrapArgsApiTest { - private ConfigUtil configUtil; - private DefaultApolloClientBootstrapArgsApi api; + private ConfigUtil configUtil; + private DefaultApolloClientBootstrapArgsApi api; + + @Before + public void setUp() { + configUtil = mock(ConfigUtil.class); + when(configUtil.getAccessKeySecret()).thenReturn("secret"); + when(configUtil.isAutoUpdateInjectedSpringPropertiesEnabled()).thenReturn(true); + when(configUtil.isOverrideSystemProperties()).thenReturn(false); + when(configUtil.getDefaultLocalCacheDir()).thenReturn("/cache"); + when(configUtil.getCluster()).thenReturn("default"); + when(configUtil.getAppId()).thenReturn("myApp"); + when(configUtil.getApolloEnv()).thenReturn(Env.DEV); + when(configUtil.getMetaServerDomainName()).thenReturn("http://meta.server"); + + api = new DefaultApolloClientBootstrapArgsApi(configUtil); + } - @Before - public void setUp() { - configUtil = mock(ConfigUtil.class); - when(configUtil.getAccessKeySecret()).thenReturn("secret"); - when(configUtil.isAutoUpdateInjectedSpringPropertiesEnabled()).thenReturn(true); - when(configUtil.isOverrideSystemProperties()).thenReturn(false); - when(configUtil.getDefaultLocalCacheDir()).thenReturn("/cache"); - when(configUtil.getCluster()).thenReturn("default"); - when(configUtil.getAppId()).thenReturn("myApp"); - when(configUtil.getApolloEnv()).thenReturn(Env.DEV); - when(configUtil.getMetaServerDomainName()).thenReturn("http://meta.server"); - - api = new DefaultApolloClientBootstrapArgsApi(configUtil); - } + @Test + public void testGetAccessKeySecret() { + assertEquals("secret", api.getAccessKeySecret()); + } - @Test - public void testGetAccessKeySecret() { - assertEquals("secret", api.getAccessKeySecret()); - } + @Test + public void testGetAutoUpdateInjectedSpringProperties() { + assertTrue(api.getAutoUpdateInjectedSpringProperties()); + } - @Test - public void testGetAutoUpdateInjectedSpringProperties() { - assertTrue(api.getAutoUpdateInjectedSpringProperties()); - } + @Test + public void testGetCacheDir() { + assertEquals("/cache", api.getCacheDir()); + } - @Test - public void testGetCacheDir() { - assertEquals("/cache", api.getCacheDir()); - } + @Test + public void testCollect0() { + ApolloClientMonitorEvent event = mock(ApolloClientMonitorEvent.class); + when(event.getName()).thenReturn(APOLLO_ACCESS_KEY_SECRET); + when(event.getAttachmentValue(APOLLO_ACCESS_KEY_SECRET)).thenReturn("newSecret"); - @Test - public void testCollect0() { - ApolloClientMonitorEvent event = mock(ApolloClientMonitorEvent.class); - when(event.getName()).thenReturn(APOLLO_ACCESS_KEY_SECRET); - when(event.getAttachmentValue(APOLLO_ACCESS_KEY_SECRET)).thenReturn("newSecret"); + api.collect0(event); - api.collect0(event); - - assertEquals("newSecret", api.getAccessKeySecret()); - } + assertEquals("newSecret", api.getAccessKeySecret()); + } - @Test - public void testUnhandledEvent() { - ApolloClientMonitorEvent event = mock(ApolloClientMonitorEvent.class); - when(event.getName()).thenReturn("unknownEvent"); - api.collect0(event); - } + @Test + public void testUnhandledEvent() { + ApolloClientMonitorEvent event = mock(ApolloClientMonitorEvent.class); + when(event.getName()).thenReturn("unknownEvent"); + api.collect0(event); + } - @Test - public void testGetBootstrapArgs() { - Map bootstrapArgs = api.getBootstrapArgs(); - assertNotNull(bootstrapArgs); - assertTrue(bootstrapArgs.containsKey(APOLLO_ACCESS_KEY_SECRET)); - } + @Test + public void testGetBootstrapArgs() { + Map bootstrapArgs = api.getBootstrapArgs(); + assertNotNull(bootstrapArgs); + assertTrue(bootstrapArgs.containsKey(APOLLO_ACCESS_KEY_SECRET)); + } } \ No newline at end of file diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientExceptionApiTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientExceptionApiTest.java index b90fe873..2391e2bd 100644 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientExceptionApiTest.java +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientExceptionApiTest.java @@ -29,73 +29,75 @@ public class DefaultApolloClientExceptionApiTest { - private DefaultApolloClientExceptionApi exceptionApi; - - @Before - public void setUp() { - exceptionApi = new DefaultApolloClientExceptionApi(); - } - - @Test - public void testCollect0_AddsException() { - ApolloConfigException exception = new ApolloConfigException("Test Exception"); - ApolloClientMonitorEvent event = mock(ApolloClientMonitorEvent.class); - when(event.getAttachmentValue(THROWABLE)).thenReturn(exception); - - exceptionApi.collect0(event); - - List exceptions = exceptionApi.getApolloConfigExceptionList(); - assertEquals(1, exceptions.size()); - assertEquals(exception, exceptions.get(0)); + private DefaultApolloClientExceptionApi exceptionApi; + + @Before + public void setUp() { + exceptionApi = new DefaultApolloClientExceptionApi(); + } + + @Test + public void testCollect0_AddsException() { + ApolloConfigException exception = new ApolloConfigException("Test Exception"); + ApolloClientMonitorEvent event = mock(ApolloClientMonitorEvent.class); + when(event.getAttachmentValue(THROWABLE)).thenReturn(exception); + + exceptionApi.collect0(event); + + List exceptions = exceptionApi.getApolloConfigExceptionList(); + assertEquals(1, exceptions.size()); + assertEquals(exception, exceptions.get(0)); + } + + @Test + public void testCollect0_IncrementsExceptionCount() { + ApolloConfigException exception = new ApolloConfigException("Test Exception"); + ApolloClientMonitorEvent event = mock(ApolloClientMonitorEvent.class); + when(event.getAttachmentValue(THROWABLE)).thenReturn(exception); + + exceptionApi.collect0(event); + exceptionApi.collect0(event); + + assertEquals(2, exceptionApi.getApolloConfigExceptionList().size()); + } + + @Test + public void testGetApolloConfigExceptionDetails() { + ApolloConfigException exception1 = new ApolloConfigException("First Exception"); + ApolloConfigException exception2 = new ApolloConfigException("Second Exception"); + + ApolloClientMonitorEvent event1 = mock(ApolloClientMonitorEvent.class); + ApolloClientMonitorEvent event2 = mock(ApolloClientMonitorEvent.class); + + when(event1.getAttachmentValue(THROWABLE)).thenReturn(exception1); + when(event2.getAttachmentValue(THROWABLE)).thenReturn(exception2); + + exceptionApi.collect0(event1); + exceptionApi.collect0(event2); + + List details = exceptionApi.getApolloConfigExceptionDetails(); + assertEquals(2, details.size()); + assertTrue(details.contains("First Exception")); + assertTrue(details.contains("Second Exception")); + } + + @Test + public void testCollect0_HandlesMaxQueueSize() { + for (int i = 0; i < 25; i++) { + ApolloClientMonitorEvent event = mock(ApolloClientMonitorEvent.class); + when(event.getAttachmentValue(THROWABLE)).thenReturn( + new ApolloConfigException("Exception " + i)); + exceptionApi.collect0(event); } - @Test - public void testCollect0_IncrementsExceptionCount() { - ApolloConfigException exception = new ApolloConfigException("Test Exception"); - ApolloClientMonitorEvent event = mock(ApolloClientMonitorEvent.class); - when(event.getAttachmentValue(THROWABLE)).thenReturn(exception); + assertEquals(25, exceptionApi.getApolloConfigExceptionList().size()); - exceptionApi.collect0(event); - exceptionApi.collect0(event); + // Add one more to exceed the size. + ApolloClientMonitorEvent overflowEvent = mock(ApolloClientMonitorEvent.class); + when(overflowEvent.getAttachmentValue(THROWABLE)).thenReturn( + new ApolloConfigException("Overflow Exception")); + exceptionApi.collect0(overflowEvent); - assertEquals(2, exceptionApi.getApolloConfigExceptionList().size()); - } - - @Test - public void testGetApolloConfigExceptionDetails() { - ApolloConfigException exception1 = new ApolloConfigException("First Exception"); - ApolloConfigException exception2 = new ApolloConfigException("Second Exception"); - - ApolloClientMonitorEvent event1 = mock(ApolloClientMonitorEvent.class); - ApolloClientMonitorEvent event2 = mock(ApolloClientMonitorEvent.class); - - when(event1.getAttachmentValue(THROWABLE)).thenReturn(exception1); - when(event2.getAttachmentValue(THROWABLE)).thenReturn(exception2); - - exceptionApi.collect0(event1); - exceptionApi.collect0(event2); - - List details = exceptionApi.getApolloConfigExceptionDetails(); - assertEquals(2, details.size()); - assertTrue(details.contains("First Exception")); - assertTrue(details.contains("Second Exception")); - } - - @Test - public void testCollect0_HandlesMaxQueueSize() { - for (int i = 0; i < 25; i++) { - ApolloClientMonitorEvent event = mock(ApolloClientMonitorEvent.class); - when(event.getAttachmentValue(THROWABLE)).thenReturn(new ApolloConfigException("Exception " + i)); - exceptionApi.collect0(event); - } - - assertEquals(25, exceptionApi.getApolloConfigExceptionList().size()); - - // Add one more to exceed the size. - ApolloClientMonitorEvent overflowEvent = mock(ApolloClientMonitorEvent.class); - when(overflowEvent.getAttachmentValue(THROWABLE)).thenReturn(new ApolloConfigException("Overflow Exception")); - exceptionApi.collect0(overflowEvent); - - assertEquals(25, exceptionApi.getApolloConfigExceptionList().size()); - } + assertEquals(25, exceptionApi.getApolloConfigExceptionList().size()); + } } \ No newline at end of file diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientMonitorEventListenerManagerTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientMonitorEventListenerManagerTest.java deleted file mode 100644 index 820fc5bf..00000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientMonitorEventListenerManagerTest.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright 2022 Apollo Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.ctrip.framework.apollo.monitor.internal.listener.impl; - -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; - -import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMonitorEventListener; -import org.junit.Before; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -public class DefaultApolloClientMonitorEventListenerManagerTest { - - private DefaultApolloClientMonitorEventListenerManager manager; - - @Before - public void setUp() { - manager = new DefaultApolloClientMonitorEventListenerManager(); - } - - @Test - public void testInitialCollectors() { - List collectors = manager.getCollectors(); - assertNotNull(collectors); - assertTrue(collectors.isEmpty()); // 初始状态应该为空列表 - } - - @Test - public void testSetCollectors() { - ApolloClientMonitorEventListener mockListener = mock(ApolloClientMonitorEventListener.class); - List newCollectors = new ArrayList<>(); - newCollectors.add(mockListener); - - manager.setCollectors(newCollectors); - List collectors = manager.getCollectors(); - - assertNotNull(collectors); - assertEquals(1, collectors.size()); - assertEquals(mockListener, collectors.get(0)); // 验证设置的监听器 - } - - @Test - public void testSetEmptyCollectors() { - manager.setCollectors(Collections.emptyList()); - List collectors = manager.getCollectors(); - - assertNotNull(collectors); - assertTrue(collectors.isEmpty()); // 设置为空列表后应该为空 - } -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientNamespaceApiTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientNamespaceApiTest.java index 02d76aaa..11fd102b 100644 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientNamespaceApiTest.java +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientNamespaceApiTest.java @@ -15,6 +15,7 @@ * */ package com.ctrip.framework.apollo.monitor.internal.listener.impl; + import static com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorConstant.APOLLO_CLIENT_NAMESPACE_NOT_FOUND; import static com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorConstant.APOLLO_CLIENT_NAMESPACE_TIMEOUT; import static com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorConstant.APOLLO_CLIENT_NAMESPACE_USAGE; @@ -34,58 +35,66 @@ public class DefaultApolloClientNamespaceApiTest { - private DefaultApolloClientNamespaceApi api; - private Map configs; - private Map configFiles; - - @Before - public void setUp() { - configs = new HashMap<>(); - configFiles = new HashMap<>(); - api = new DefaultApolloClientNamespaceApi(configs, configFiles); - } - - @Test - public void testCollectNamespaceNotFound() { - ApolloClientMonitorEvent event = mock(ApolloClientMonitorEvent.class); - when(event.getAttachmentValue(NAMESPACE)).thenReturn("testNamespace"); - when(event.getName()).thenReturn(APOLLO_CLIENT_NAMESPACE_NOT_FOUND); - - api.collect0(event); - - assertEquals(1, api.getNamespace404().size()); - assertTrue(api.getNamespace404().contains("testNamespace")); - } - - @Test - public void testCollectNamespaceTimeout() { - ApolloClientMonitorEvent event = mock(ApolloClientMonitorEvent.class); - when(event.getAttachmentValue(NAMESPACE)).thenReturn("testNamespace"); - when(event.getName()).thenReturn(APOLLO_CLIENT_NAMESPACE_TIMEOUT); - - api.collect0(event); - - assertEquals(1, api.getNamespaceTimeout().size()); - assertTrue(api.getNamespaceTimeout().contains("testNamespace")); - } - - @Test - public void testCollectNamespaceUsage() { - ApolloClientMonitorEvent event = mock(ApolloClientMonitorEvent.class); - when(event.getAttachmentValue(NAMESPACE)).thenReturn("testNamespace"); - when(event.getName()).thenReturn(APOLLO_CLIENT_NAMESPACE_USAGE); - - api.collect0(event); - - assertEquals(1, api.getNamespaceMetrics().get("testNamespace").getUsageCount()); - } - - @Test - public void testGetNamespaceItemName() { - Config mockConfig = mock(Config.class); - when(mockConfig.getPropertyNames()).thenReturn(Sets.newSet("key1", "key2")); - configs.put("testNamespace", mockConfig); - - assertEquals(2, api.getNamespaceItemName("testNamespace").size()); - } + private DefaultApolloClientNamespaceApi api; + private Map configs; + private Map configFiles; + + @Before + public void setUp() { + configs = new HashMap<>(); + configFiles = new HashMap<>(); + api = new DefaultApolloClientNamespaceApi(configs, configFiles); + } + + @Test + public void testCollectNamespaceNotFound() { + ApolloClientMonitorEvent event = mock(ApolloClientMonitorEvent.class); + when(event.getAttachmentValue(NAMESPACE)).thenReturn("testNamespace"); + when(event.getName()).thenReturn(APOLLO_CLIENT_NAMESPACE_NOT_FOUND); + + api.collect0(event); + + assertEquals(1, api.getNotFoundNamespaces().size()); + assertTrue(api.getNotFoundNamespaces().contains("testNamespace")); + } + + @Test + public void testCollectNamespaceTimeout() { + ApolloClientMonitorEvent event = mock(ApolloClientMonitorEvent.class); + when(event.getAttachmentValue(NAMESPACE)).thenReturn("testNamespace"); + when(event.getName()).thenReturn(APOLLO_CLIENT_NAMESPACE_TIMEOUT); + + api.collect0(event); + + assertEquals(1, api.getTimeoutNamespaces().size()); + assertTrue(api.getTimeoutNamespaces().contains("testNamespace")); + } + + @Test + public void testCollectNamespaceUsage() { + ApolloClientMonitorEvent event = mock(ApolloClientMonitorEvent.class); + when(event.getAttachmentValue(NAMESPACE)).thenReturn("testNamespace"); + when(event.getName()).thenReturn(APOLLO_CLIENT_NAMESPACE_USAGE); + + api.collect0(event); + + assertEquals(1, api.getNamespaceMetrics().get("testNamespace").getUsageCount()); + } + + @Test + public void testGetNamespaceItemsNum() { + Config mockConfig = mock(Config.class); + when(mockConfig.getPropertyNames()).thenReturn(Sets.newSet("key1", "key2")); + configs.put("testNamespace", mockConfig); + Integer testNamespace = api.getNamespaceItemsNum("testNamespace"); + assertEquals(2, testNamespace.intValue()); + } + + @Test + public void testGetConfigFileNum() { + ConfigFile mockConfigFile = mock(ConfigFile.class); + configFiles.put("testNamespace", mockConfigFile); + Integer testNamespace = api.getConfigFileNum(); + assertEquals(1, testNamespace.intValue()); + } } \ No newline at end of file diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientThreadPoolApiTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientThreadPoolApiTest.java index e12084b5..9c12fdfe 100644 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientThreadPoolApiTest.java +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientThreadPoolApiTest.java @@ -15,6 +15,7 @@ * */ package com.ctrip.framework.apollo.monitor.internal.listener.impl; + import static org.mockito.Mockito.*; import static org.junit.Assert.*; @@ -29,59 +30,65 @@ public class DefaultApolloClientThreadPoolApiTest { - private DefaultApolloClientThreadPoolApi threadPoolApi; - private ThreadPoolExecutor remoteConfigExecutor; - private ThreadPoolExecutor abstractConfigExecutor; - private ThreadPoolExecutor abstractConfigFileExecutor; - - @Before - public void setUp() { - remoteConfigExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2); - abstractConfigExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2); - abstractConfigFileExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2); + private DefaultApolloClientThreadPoolApi threadPoolApi; + private ThreadPoolExecutor remoteConfigExecutor; + private ThreadPoolExecutor abstractConfigExecutor; + private ThreadPoolExecutor abstractConfigFileExecutor; + private ThreadPoolExecutor metricsExporterExecutor; - threadPoolApi = new DefaultApolloClientThreadPoolApi( - remoteConfigExecutor, - abstractConfigExecutor, - abstractConfigFileExecutor - ); - } + @Before + public void setUp() { + remoteConfigExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2); + abstractConfigExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2); + abstractConfigFileExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2); + metricsExporterExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2); + threadPoolApi = new DefaultApolloClientThreadPoolApi( + remoteConfigExecutor, + abstractConfigExecutor, + abstractConfigFileExecutor, + metricsExporterExecutor + ); + } - @SneakyThrows - @Test - public void testExportThreadPoolMetrics() { - remoteConfigExecutor.execute(() -> {}); - remoteConfigExecutor.execute(() -> {}); - // 等待任务执行完成 - Thread.sleep(200); - threadPoolApi.export0(); + @SneakyThrows + @Test + public void testExportThreadPoolMetrics() { + remoteConfigExecutor.execute(() -> { + }); + remoteConfigExecutor.execute(() -> { + }); + // 等待任务执行完成 + Thread.sleep(200); + threadPoolApi.export0(); - ApolloThreadPoolInfo info = threadPoolApi.getRemoteConfigRepositoryThreadPoolInfo(); - assertEquals(0, info.getQueueSize()); - assertEquals(2, info.getCompletedTaskCount()); - assertEquals(2, info.getPoolSize()); - } + ApolloThreadPoolInfo info = threadPoolApi.getRemoteConfigRepositoryThreadPoolInfo(); + assertEquals(0, info.getQueueSize()); + assertEquals(2, info.getCompletedTaskCount()); + assertEquals(2, info.getPoolSize()); + } - @Test - public void testGetThreadPoolInfo() { - assertNotNull(threadPoolApi.getThreadPoolInfo()); - assertEquals(3, threadPoolApi.getThreadPoolInfo().size()); - } + @Test + public void testGetThreadPoolInfo() { + assertNotNull(threadPoolApi.getThreadPoolInfo()); + assertEquals(4, threadPoolApi.getThreadPoolInfo().size()); + } - @Test - public void testMetricsSampleUpdated() { - assertTrue(threadPoolApi.isMetricsSampleUpdated()); - } + @Test + public void testMetricsSampleUpdated() { + assertTrue(threadPoolApi.isMetricsSampleUpdated()); + } - @Test - public void testGetAbstractConfigThreadPoolInfo() { - ApolloThreadPoolInfo info = threadPoolApi.getAbstractConfigThreadPoolInfo(); - assertNotNull(info); - } + @Test + public void testGetAbstractConfigThreadPoolInfo() { + ApolloThreadPoolInfo info = threadPoolApi.getAbstractConfigThreadPoolInfo(); + assertNotNull(info); + } - @Test - public void testGetAbstractConfigFileThreadPoolInfo() { - ApolloThreadPoolInfo info = threadPoolApi.getAbstractConfigFileThreadPoolInfo(); - assertNotNull(info); - } + @Test + public void testGetAbstractConfigFileThreadPoolInfo() { + ApolloThreadPoolInfo info = threadPoolApi.getAbstractConfigFileThreadPoolInfo(); + assertNotNull(info); + } + + } diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientBootstrapArgsMonitorApiTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientBootstrapArgsMonitorApiTest.java new file mode 100644 index 00000000..04304a55 --- /dev/null +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientBootstrapArgsMonitorApiTest.java @@ -0,0 +1,157 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.listener.impl; + +import static org.junit.Assert.*; + +import org.junit.Before; +import org.junit.Test; + +import java.util.Map; + +public class NullClientBootstrapArgsMonitorApiTest { + + private NullClientBootstrapArgsMonitorApi bootstrapArgsMonitorApi; + + @Before + public void setUp() { + bootstrapArgsMonitorApi = new NullClientBootstrapArgsMonitorApi(); + } + + @Test + public void testGetStartupParams() { + assertEquals("", bootstrapArgsMonitorApi.getStartupParams("testKey")); + } + + @Test + public void testGetConfigServiceUrl() { + assertEquals("", bootstrapArgsMonitorApi.getConfigServiceUrl()); + } + + @Test + public void testGetAccessKeySecret() { + assertEquals("", bootstrapArgsMonitorApi.getAccessKeySecret()); + } + + @Test + public void testGetAutoUpdateInjectedSpringProperties() { + assertFalse(bootstrapArgsMonitorApi.getAutoUpdateInjectedSpringProperties()); + } + + @Test + public void testGetBootstrapEnabled() { + assertNull(bootstrapArgsMonitorApi.getBootstrapEnabled()); + } + + @Test + public void testGetBootstrapNamespaces() { + assertEquals("", bootstrapArgsMonitorApi.getBootstrapNamespaces()); + } + + @Test + public void testGetBootstrapEagerLoadEnabled() { + assertNull(bootstrapArgsMonitorApi.getBootstrapEagerLoadEnabled()); + } + + @Test + public void testGetOverrideSystemProperties() { + assertNull(bootstrapArgsMonitorApi.getOverrideSystemProperties()); + } + + @Test + public void testGetCacheDir() { + assertEquals("", bootstrapArgsMonitorApi.getCacheDir()); + } + + @Test + public void testGetCluster() { + assertEquals("", bootstrapArgsMonitorApi.getCluster()); + } + + @Test + public void testGetConfigService() { + assertEquals("", bootstrapArgsMonitorApi.getConfigService()); + } + + @Test + public void testGetClientMonitorEnabled() { + assertNull(bootstrapArgsMonitorApi.getClientMonitorEnabled()); + } + + @Test + public void testGetClientMonitorJmxEnabled() { + assertNull(bootstrapArgsMonitorApi.getClientMonitorJmxEnabled()); + } + + @Test + public void testGetClientMonitorExternalForm() { + assertEquals("", bootstrapArgsMonitorApi.getClientMonitorExternalForm()); + } + + @Test + public void testGetClientMonitorExternalExportPeriod() { + assertEquals(0, bootstrapArgsMonitorApi.getClientMonitorExternalExportPeriod()); + } + + @Test + public void testGetClientMonitorExceptionSaveSize() { + assertEquals(0, bootstrapArgsMonitorApi.getClientMonitorExceptionSaveSize()); + } + + @Test + public void testGetApolloMeta() { + assertEquals("", bootstrapArgsMonitorApi.getApolloMeta()); + } + + @Test + public void testGetMetaLatestFreshTime() { + assertEquals("", bootstrapArgsMonitorApi.getMetaLatestFreshTime()); + } + + @Test + public void testGetPropertyNamesCacheEnable() { + assertNull(bootstrapArgsMonitorApi.getPropertyNamesCacheEnable()); + } + + @Test + public void testGetPropertyOrderEnable() { + assertNull(bootstrapArgsMonitorApi.getPropertyOrderEnable()); + } + + @Test + public void testGetVersion() { + assertEquals("", bootstrapArgsMonitorApi.getVersion()); + } + + @Test + public void testGetEnv() { + assertEquals("", bootstrapArgsMonitorApi.getEnv()); + } + + @Test + public void testGetAppId() { + assertEquals("", bootstrapArgsMonitorApi.getAppId()); + } + + @Test + public void testGetBootstrapArgs() { + Map bootstrapArgs = bootstrapArgsMonitorApi.getBootstrapArgs(); + + assertNotNull(bootstrapArgs); + assertTrue(bootstrapArgs.isEmpty()); + } +} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientExceptionMonitorApiTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientExceptionMonitorApiTest.java new file mode 100644 index 00000000..1412358d --- /dev/null +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientExceptionMonitorApiTest.java @@ -0,0 +1,50 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.listener.impl; + +import static org.junit.Assert.*; + +import org.junit.Before; +import org.junit.Test; + +import java.util.List; + +public class NullClientExceptionMonitorApiTest { + + private NullClientExceptionMonitorApi exceptionMonitorApi; + + @Before + public void setUp() { + exceptionMonitorApi = new NullClientExceptionMonitorApi(); + } + + @Test + public void testGetApolloConfigExceptionList() { + List exceptionList = exceptionMonitorApi.getApolloConfigExceptionList(); + + assertNotNull(exceptionList); + assertTrue(exceptionList.isEmpty()); + } + + @Test + public void testGetApolloConfigExceptionDetails() { + List exceptionDetails = exceptionMonitorApi.getApolloConfigExceptionDetails(); + + assertNotNull(exceptionDetails); + assertTrue(exceptionDetails.isEmpty()); + } +} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientNamespaceMonitorApiTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientNamespaceMonitorApiTest.java new file mode 100644 index 00000000..cddf6b2c --- /dev/null +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientNamespaceMonitorApiTest.java @@ -0,0 +1,73 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.listener.impl; + +import static org.junit.Assert.*; + +import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientNamespaceApi.NamespaceMetrics; +import org.junit.Before; +import org.junit.Test; + +import java.util.List; +import java.util.Map; + +public class NullClientNamespaceMonitorApiTest { + + private NullClientNamespaceMonitorApi namespaceMonitorApi; + + @Before + public void setUp() { + namespaceMonitorApi = new NullClientNamespaceMonitorApi(); + } + + @Test + public void testGetNamespaceMetrics() { + Map metrics = namespaceMonitorApi.getNamespaceMetrics(); + + assertNotNull(metrics); + assertTrue(metrics.isEmpty()); + } + + @Test + public void testGetNamespaceItemNames() { + Integer testNamespace = namespaceMonitorApi.getNamespaceItemsNum("testNamespace"); + assertEquals(0, testNamespace.intValue()); + + } + + @Test + public void testGetConfigFileNum() { + Integer configFileNum = namespaceMonitorApi.getConfigFileNum(); + assertEquals(0, configFileNum.intValue()); + } + + @Test + public void testGetNotFoundNamespaces() { + List notFoundNamespaces = namespaceMonitorApi.getNotFoundNamespaces(); + + assertNotNull(notFoundNamespaces); + assertTrue(notFoundNamespaces.isEmpty()); + } + + @Test + public void testGetTimeoutNamespaces() { + List timeoutNamespaces = namespaceMonitorApi.getTimeoutNamespaces(); + + assertNotNull(timeoutNamespaces); + assertTrue(timeoutNamespaces.isEmpty()); + } +} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientThreadPoolMonitorApiTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientThreadPoolMonitorApiTest.java new file mode 100644 index 00000000..2bd393f2 --- /dev/null +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientThreadPoolMonitorApiTest.java @@ -0,0 +1,65 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal.listener.impl; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; + +import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientThreadPoolApi.ApolloThreadPoolInfo; +import org.junit.Before; +import org.junit.Test; + +import java.util.Map; + +public class NullClientThreadPoolMonitorApiTest { + + private NullClientThreadPoolMonitorApi monitorApi; + + @Before + public void setUp() { + monitorApi = new NullClientThreadPoolMonitorApi(); + } + + @Test + public void testGetThreadPoolInfo() { + Map threadPoolInfo = monitorApi.getThreadPoolInfo(); + + assertNotNull(threadPoolInfo); + assertTrue(threadPoolInfo.isEmpty()); + } + + @Test + public void testGetRemoteConfigRepositoryThreadPoolInfo() { + ApolloThreadPoolInfo info = monitorApi.getRemoteConfigRepositoryThreadPoolInfo(); + + assertNull(info); + } + + @Test + public void testGetAbstractConfigThreadPoolInfo() { + ApolloThreadPoolInfo info = monitorApi.getAbstractConfigThreadPoolInfo(); + + assertNull(info); + } + + @Test + public void testGetAbstractConfigFileThreadPoolInfo() { + ApolloThreadPoolInfo info = monitorApi.getAbstractConfigFileThreadPoolInfo(); + + assertNull(info); + } +} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMessageProducerCompositeTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMessageProducerCompositeTest.java index f13a9892..b0eb740f 100644 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMessageProducerCompositeTest.java +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMessageProducerCompositeTest.java @@ -31,104 +31,104 @@ public class ApolloClientMessageProducerCompositeTest { - private ApolloClientMessageProducerComposite composite; + private ApolloClientMessageProducerComposite composite; - @Mock - private MessageProducer producer1; + @Mock + private MessageProducer producer1; - @Mock - private MessageProducer producer2; + @Mock + private MessageProducer producer2; - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - List producers = Arrays.asList(producer1, producer2); - composite = new ApolloClientMessageProducerComposite(producers); - } + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + List producers = Arrays.asList(producer1, producer2); + composite = new ApolloClientMessageProducerComposite(producers); + } - @Test - public void testLogError_Throwable() { - Throwable cause = new Exception("Test exception"); + @Test + public void testLogError_Throwable() { + Throwable cause = new Exception("Test exception"); - composite.logError(cause); + composite.logError(cause); - verify(producer1).logError(cause); - verify(producer2).logError(cause); - } + verify(producer1).logError(cause); + verify(producer2).logError(cause); + } - @Test - public void testLogError_String_Throwable() { - String message = "Test error message"; - Throwable cause = new Exception("Test exception"); + @Test + public void testLogError_String_Throwable() { + String message = "Test error message"; + Throwable cause = new Exception("Test exception"); - composite.logError(message, cause); + composite.logError(message, cause); - verify(producer1).logError(message, cause); - verify(producer2).logError(message, cause); - } + verify(producer1).logError(message, cause); + verify(producer2).logError(message, cause); + } - @Test - public void testLogEvent_Type_Name() { - String type = "EVENT_TYPE"; - String name = "EVENT_NAME"; + @Test + public void testLogEvent_Type_Name() { + String type = "EVENT_TYPE"; + String name = "EVENT_NAME"; - composite.logEvent(type, name); + composite.logEvent(type, name); - verify(producer1).logEvent(type, name); - verify(producer2).logEvent(type, name); - } + verify(producer1).logEvent(type, name); + verify(producer2).logEvent(type, name); + } - @Test - public void testLogEvent_Type_Name_Status_NameValuePairs() { - String type = "EVENT_TYPE"; - String name = "EVENT_NAME"; - String status = "SUCCESS"; - String nameValuePairs = "key=value"; + @Test + public void testLogEvent_Type_Name_Status_NameValuePairs() { + String type = "EVENT_TYPE"; + String name = "EVENT_NAME"; + String status = "SUCCESS"; + String nameValuePairs = "key=value"; - composite.logEvent(type, name, status, nameValuePairs); + composite.logEvent(type, name, status, nameValuePairs); - verify(producer1).logEvent(type, name, status, nameValuePairs); - verify(producer2).logEvent(type, name, status, nameValuePairs); - } + verify(producer1).logEvent(type, name, status, nameValuePairs); + verify(producer2).logEvent(type, name, status, nameValuePairs); + } - @Test - public void testLogMetricsForCount() { - String name = "METRIC_NAME"; + @Test + public void testLogMetricsForCount() { + String name = "METRIC_NAME"; - composite.logMetricsForCount(name); + composite.logMetricsForCount(name); - verify(producer1).logMetricsForCount(name); - verify(producer2).logMetricsForCount(name); - } + verify(producer1).logMetricsForCount(name); + verify(producer2).logMetricsForCount(name); + } - @Test - public void testNewTransaction() { - String type = "TRANSACTION_TYPE"; - String name = "TRANSACTION_NAME"; + @Test + public void testNewTransaction() { + String type = "TRANSACTION_TYPE"; + String name = "TRANSACTION_NAME"; - Transaction transaction1 = mock(Transaction.class); - when(producer1.newTransaction(type, name)).thenReturn(null); - when(producer2.newTransaction(type, name)).thenReturn(transaction1); + Transaction transaction1 = mock(Transaction.class); + when(producer1.newTransaction(type, name)).thenReturn(null); + when(producer2.newTransaction(type, name)).thenReturn(transaction1); - Transaction result = composite.newTransaction(type, name); + Transaction result = composite.newTransaction(type, name); - assertEquals(transaction1, result); - verify(producer1).newTransaction(type, name); - verify(producer2).newTransaction(type, name); - } + assertEquals(transaction1, result); + verify(producer1).newTransaction(type, name); + verify(producer2).newTransaction(type, name); + } - @Test - public void testNewTransaction_NoValidTransaction() { - String type = "TRANSACTION_TYPE"; - String name = "TRANSACTION_NAME"; + @Test + public void testNewTransaction_NoValidTransaction() { + String type = "TRANSACTION_TYPE"; + String name = "TRANSACTION_NAME"; - when(producer1.newTransaction(type, name)).thenReturn(null); - when(producer2.newTransaction(type, name)).thenReturn(null); + when(producer1.newTransaction(type, name)).thenReturn(null); + when(producer2.newTransaction(type, name)).thenReturn(null); - Transaction result = composite.newTransaction(type, name); + Transaction result = composite.newTransaction(type, name); - assertEquals(ApolloClientMessageProducerComposite.NULL_TRANSACTION, result); - verify(producer1).newTransaction(type, name); - verify(producer2).newTransaction(type, name); - } + assertEquals(ApolloClientMessageProducerComposite.NULL_TRANSACTION, result); + verify(producer1).newTransaction(type, name); + verify(producer2).newTransaction(type, name); + } } diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMonitorMessageProducerTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMonitorMessageProducerTest.java index 5efc2971..dde82909 100644 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMonitorMessageProducerTest.java +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMonitorMessageProducerTest.java @@ -27,57 +27,57 @@ public class ApolloClientMonitorMessageProducerTest { - private ApolloClientMonitorMessageProducer producer; + private ApolloClientMonitorMessageProducer producer; - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - - producer = new ApolloClientMonitorMessageProducer(); - } + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); - @Test - public void testLogError_Throwable() { - Throwable cause = new Exception("Test exception"); + producer = new ApolloClientMonitorMessageProducer(); + } - producer.logError(cause); - } + @Test + public void testLogError_Throwable() { + Throwable cause = new Exception("Test exception"); - @Test - public void testLogError_String_Throwable() { - String message = "Test error message"; - Throwable cause = new Exception("Test exception"); + producer.logError(cause); + } - producer.logError(message, cause); - } + @Test + public void testLogError_String_Throwable() { + String message = "Test error message"; + Throwable cause = new Exception("Test exception"); - @Test - public void testLogEvent_TaggedEvent() { - String type = ApolloClientMonitorMessageProducer.TAGS.get(0); // APOLLO_CLIENT_CONFIGCHANGES - String name = "Test event"; + producer.logError(message, cause); + } - producer.logEvent(type, name); - } + @Test + public void testLogEvent_TaggedEvent() { + String type = ApolloClientMonitorMessageProducer.TAGS.get(0); // APOLLO_CLIENT_CONFIGCHANGES + String name = "Test event"; - @Test - public void testLogEvent_ClientConfigEvent() { - String type = APOLLO_CLIENT_CONFIGS + "namespace"; - String name = "Test config"; + producer.logEvent(type, name); + } - producer.logEvent(type, name); - } + @Test + public void testLogEvent_ClientConfigEvent() { + String type = APOLLO_CLIENT_CONFIGS + "namespace"; + String name = "Test config"; - @Test - public void testLogMetricsForCount() { - String name = APOLLO_CLIENT_NAMESPACE_USAGE + ":testNamespace"; + producer.logEvent(type, name); + } - producer.logMetricsForCount(name); - } + @Test + public void testLogMetricsForCount() { + String name = APOLLO_CLIENT_NAMESPACE_USAGE + ":testNamespace"; - @Test - public void testNewTransaction() { - Transaction result = producer.newTransaction("type", "name"); + producer.logMetricsForCount(name); + } - assertEquals(ApolloClientMessageProducerComposite.NULL_TRANSACTION, result); - } + @Test + public void testNewTransaction() { + Transaction result = producer.newTransaction("type", "name"); + + assertEquals(ApolloClientMessageProducerComposite.NULL_TRANSACTION, result); + } } \ No newline at end of file diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/stress/ApolloClientMonitorStressTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/stress/ApolloClientMonitorStressTest.java index 7d5171cf..4e4149e3 100644 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/stress/ApolloClientMonitorStressTest.java +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/stress/ApolloClientMonitorStressTest.java @@ -15,7 +15,9 @@ * */ package com.ctrip.framework.apollo.monitor.stress; + import static com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorConstant.*; + import com.ctrip.framework.apollo.ConfigService; import com.ctrip.framework.apollo.monitor.internal.event.ApolloClientMonitorEventFactory; import com.github.noconnor.junitperf.JUnitPerfRule; @@ -30,21 +32,22 @@ @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = ApolloClientMonitorStressTest.class) @ActiveProfiles("stress-test") -public class ApolloClientMonitorStressTest { +public class ApolloClientMonitorStressTest { + @Rule public JUnitPerfRule perfTestRule = new JUnitPerfRule(); - + @Test @JUnitPerfTest(threads = 25, durationMs = 10000, warmUpMs = 1000, maxExecutionsPerSecond = 1000) - public void testConfigMonitor(){ + public void testConfigMonitor() { String exporterData = ConfigService.getConfigMonitor().getExporterData(); } - + @Test @JUnitPerfTest(threads = 50, durationMs = 10000, warmUpMs = 1000, maxExecutionsPerSecond = 1000) - public void testPublishEvent(){ + public void testPublishEvent() { ApolloClientMonitorEventFactory.getInstance() .createEvent(APOLLO_CLIENT_NAMESPACE_USAGE) - .putAttachment(NAMESPACE,"application").publish(); + .putAttachment(NAMESPACE, "application").publish(); } } diff --git a/apollo-plugin/apollo-plugin-client-prometheus/src/main/java/com/ctrip/framework/apollo/plugin/prometheus/PrometheusApolloClientMetricsExporter.java b/apollo-plugin/apollo-plugin-client-prometheus/src/main/java/com/ctrip/framework/apollo/plugin/prometheus/PrometheusApolloClientMetricsExporter.java new file mode 100644 index 00000000..df518054 --- /dev/null +++ b/apollo-plugin/apollo-plugin-client-prometheus/src/main/java/com/ctrip/framework/apollo/plugin/prometheus/PrometheusApolloClientMetricsExporter.java @@ -0,0 +1,94 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.plugin.prometheus; + +import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory; +import com.ctrip.framework.apollo.monitor.internal.exporter.AbstractApolloClientMetricsExporter; +import com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporter; +import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientNamespaceApi; +import io.prometheus.client.Collector; +import io.prometheus.client.CollectorRegistry; +import io.prometheus.client.Counter; +import io.prometheus.client.Gauge; +import io.prometheus.client.exporter.common.TextFormat; +import java.io.IOException; +import java.io.StringWriter; +import java.util.HashMap; +import java.util.Map; +import org.slf4j.Logger; + +/** + * @author Rawven + */ +public class PrometheusApolloClientMetricsExporter extends + AbstractApolloClientMetricsExporter implements ApolloClientMetricsExporter { + private final Logger logger = DeferredLoggerFactory.getLogger( + DefaultApolloClientNamespaceApi.class); + private static final String PROMETHEUS = "prometheus"; + private final CollectorRegistry registry; + private final Map map = new HashMap<>(); + + + public PrometheusApolloClientMetricsExporter() { + this.registry = new CollectorRegistry(); + } + + @Override + public void doInit() { + + } + + @Override + public boolean isSupport(String form) { + return PROMETHEUS.equals(form); + } + + + @Override + public void registerOrUpdateCounterSample(String name, Map tags, double incrValue) { + Counter counter = (Counter) map.computeIfAbsent(name, k -> Counter.build() + .name(name) + .help("apollo") + .labelNames(tags.keySet().toArray(new String[0])) + .register(registry)); + counter.labels(tags.values().toArray(new String[0])).inc(incrValue); +} + + + @Override + public void registerOrUpdateGaugeSample(String name, Map tags, double value) { + Gauge gauge = (Gauge) map.computeIfAbsent(name, k -> Gauge.build() + .name(name) + .help("apollo") + .labelNames(tags.keySet().toArray(new String[0])) + .register(registry)); + gauge.labels(tags.values().toArray(new String[0])).set(value); + } + + + @Override + public String response() { + try (StringWriter writer = new StringWriter()){ + TextFormat.writeFormat(TextFormat.CONTENT_TYPE_OPENMETRICS_100, writer, registry.metricFamilySamples()); + return writer.toString(); + } catch (IOException e) { + logger.error("Write metrics to Prometheus format failed", e); + return ""; + } + } +} + \ No newline at end of file From a4da39531f15c1e18de54056a465b9361acea431 Mon Sep 17 00:00:00 2001 From: Rawven <121878866+rawven@users.noreply.github.com> Date: Sat, 31 Aug 2024 21:50:59 +0800 Subject: [PATCH 5/8] feat(): refactor --- .../internals/ConfigMonitorInitializer.java | 106 +++++------- .../apollo/internals/DefaultInjector.java | 6 +- .../internals/RemoteConfigRepository.java | 2 +- .../ApolloClientBootstrapArgsMonitorApi.java | 160 +++++++++++------- .../api/ApolloClientExceptionMonitorApi.java | 5 +- .../api/ApolloClientNamespaceMonitorApi.java | 51 +++++- .../api/ApolloClientThreadPoolMonitorApi.java | 53 +++++- .../internal/ApolloClientMonitorConstant.java | 39 +++-- .../internal/ApolloClientMonitorContext.java | 96 +++++++++++ .../internal/DefaultConfigMonitor.java | 36 +--- .../{MeterEnums.java => MetricTypeEnums.java} | 2 +- .../event/ApolloClientMonitorEvent.java | 9 +- .../ApolloClientMonitorEventPublisher.java | 12 +- .../AbstractApolloClientMetricsExporter.java | 6 +- ...ultApolloClientMetricsExporterFactory.java | 3 - .../impl/NullApolloClientMetricsExporter.java | 9 +- .../ApolloClientJmxBootstrapArgsMBean.java | 11 +- .../mbean/ApolloClientJmxExceptionMBean.java | 4 +- .../mbean/ApolloClientJmxNamespaceMBean.java | 73 +++++++- ...tractApolloClientMonitorEventListener.java | 71 +++++--- .../ApolloClientMonitorEventListener.java | 4 +- ...olloClientMonitorEventListenerManager.java | 36 ---- ...olloClientMonitorEventListenerManager.java | 43 ----- .../DefaultApolloClientBootstrapArgsApi.java | 122 +------------ .../impl/DefaultApolloClientExceptionApi.java | 43 ++--- .../impl/DefaultApolloClientNamespaceApi.java | 103 ++++------- .../DefaultApolloClientThreadPoolApi.java | 105 +++--------- .../NullClientBootstrapArgsMonitorApi.java | 117 +------------ .../impl/NullClientExceptionMonitorApi.java | 5 + .../impl/NullClientNamespaceMonitorApi.java | 12 +- .../impl/NullClientThreadPoolMonitorApi.java | 11 +- .../monitor/internal/model/CounterModel.java | 4 +- .../monitor/internal/model/GaugeModel.java | 5 +- .../monitor/internal/model/SampleModel.java | 12 +- .../ApolloClientMessageProducerComposite.java | 1 - .../ApolloClientMonitorMessageProducer.java | 104 ++++++------ .../framework/apollo/util/ConfigUtil.java | 7 +- .../ConfigMonitorInitializerTest.java | 117 ------------- .../internal/DefaultConfigMonitorTest.java | 90 ---------- ...ApolloClientMonitorEventPublisherTest.java | 18 +- ...stractApolloClientMetricsExporterTest.java | 4 +- ...polloClientMetricsExporterFactoryTest.java | 4 +- ...tApolloClientMonitorEventListenerTest.java | 112 ------------ ...ClientMonitorEventListenerManagerTest.java | 67 -------- ...faultApolloClientBootstrapArgsApiTest.java | 2 +- .../DefaultApolloClientNamespaceApiTest.java | 12 +- .../DefaultApolloClientThreadPoolApiTest.java | 8 +- ...NullClientBootstrapArgsMonitorApiTest.java | 32 ++-- .../NullClientNamespaceMonitorApiTest.java | 13 +- .../NullClientThreadPoolMonitorApiTest.java | 22 +-- .../stress/ApolloClientMonitorStressTest.java | 15 +- .../resources/application-stress-test.yml | 17 -- ...PrometheusApolloClientMetricsExporter.java | 18 +- ...PrometheusApolloClientMetricsExporter.java | 94 ---------- 54 files changed, 767 insertions(+), 1366 deletions(-) create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/ApolloClientMonitorContext.java rename apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/enums/{MeterEnums.java => MetricTypeEnums.java} (96%) delete mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/ApolloClientMonitorEventListenerManager.java delete mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/DefaultApolloClientMonitorEventListenerManager.java delete mode 100644 apollo-client/src/test/java/com/ctrip/framework/apollo/internals/ConfigMonitorInitializerTest.java delete mode 100644 apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/DefaultConfigMonitorTest.java delete mode 100644 apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/AbstractApolloClientMonitorEventListenerTest.java delete mode 100644 apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/DefaultApolloClientMonitorEventListenerManagerTest.java delete mode 100644 apollo-client/src/test/resources/application-stress-test.yml delete mode 100644 apollo-plugin/apollo-plugin-client-prometheus/src/main/java/com/ctrip/framework/apollo/plugin/prometheus/PrometheusApolloClientMetricsExporter.java diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigMonitorInitializer.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigMonitorInitializer.java index a6d50f5f..20ab2640 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigMonitorInitializer.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigMonitorInitializer.java @@ -20,18 +20,14 @@ import com.ctrip.framework.apollo.build.ApolloInjector; import com.ctrip.framework.apollo.core.utils.ClassLoaderUtil; -import com.ctrip.framework.apollo.monitor.api.ConfigMonitor; -import com.ctrip.framework.apollo.monitor.internal.DefaultConfigMonitor; import com.ctrip.framework.apollo.monitor.internal.exporter.AbstractApolloClientMetricsExporter; +import com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporter; import com.ctrip.framework.apollo.monitor.internal.jmx.ApolloClientJmxMBeanRegister; -import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMonitorEventListener; -import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMonitorEventListenerManager; +import com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorContext; import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientBootstrapArgsApi; import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientExceptionApi; import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientNamespaceApi; import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientThreadPoolApi; -import com.ctrip.framework.apollo.monitor.internal.listener.DefaultApolloClientMonitorEventListenerManager; -import com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporter; import com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporterFactory; import com.ctrip.framework.apollo.monitor.internal.tracer.ApolloClientMonitorMessageProducer; import com.ctrip.framework.apollo.monitor.internal.tracer.ApolloClientMessageProducerComposite; @@ -41,91 +37,75 @@ import com.ctrip.framework.apollo.tracer.spi.MessageProducer; import com.ctrip.framework.apollo.util.ConfigUtil; import com.ctrip.framework.foundation.internals.ServiceBootstrap; -import com.google.common.collect.Lists; import java.util.List; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** * ConfigMonitorInitializer initializes the Apollo Config Monitor. */ public class ConfigMonitorInitializer { - private static final Logger logger = LoggerFactory.getLogger(ConfigMonitorInitializer.class); protected static boolean hasInitialized = false; - private static ConfigUtil CONFIG_UTIL = ApolloInjector.getInstance(ConfigUtil.class); + private static ConfigUtil m_configUtil = ApolloInjector.getInstance(ConfigUtil.class); + private static ApolloClientMonitorContext monitorContext = ApolloInjector.getInstance( + ApolloClientMonitorContext.class); public static void initialize() { - if (CONFIG_UTIL.getClientMonitorEnabled() && !hasInitialized) { - hasInitialized = true; - logger.debug("Initializing ConfigMonitor"); - DefaultApolloClientMonitorEventListenerManager manager = initializeMetricsEventListenerManager(); - List collectors = initializeCollectors(manager); - ApolloClientMetricsExporter metricsExporter = initializeMetricsExporter(collectors); - initializeJmxMonitoring(collectors); - initializeConfigMonitor(collectors, metricsExporter); - logger.debug("ConfigMonitor initialized successfully."); + if (m_configUtil.isClientMonitorEnabled() && !hasInitialized) { + synchronized (ConfigMonitorInitializer.class) { + if (!hasInitialized) { + doInit(); + hasInitialized = true; + } + } } } - protected static DefaultApolloClientMonitorEventListenerManager initializeMetricsEventListenerManager() { - return (DefaultApolloClientMonitorEventListenerManager) ApolloInjector.getInstance( - ApolloClientMonitorEventListenerManager.class); + private static void doInit() { + initializeMetricsEventListener(); + initializeMetricsExporter(); + initializeJmxMonitoring(); + hasInitialized = true; } - - protected static void initializeJmxMonitoring(List collectors) { - if (CONFIG_UTIL.getClientMonitorJmxEnabled()) { - collectors.forEach(metricsCollector -> + + + private static void initializeJmxMonitoring() { + if (m_configUtil.isClientMonitorJmxEnabled()) { + monitorContext.getCollectors().forEach(metricsCollector -> ApolloClientJmxMBeanRegister.register( - MBEAN_NAME + metricsCollector.mBeanName(), metricsCollector) + MBEAN_NAME + metricsCollector.getName(), metricsCollector) ); } } - protected static List initializeCollectors( - DefaultApolloClientMonitorEventListenerManager manager) { - + private static void initializeMetricsEventListener() { DefaultConfigManager configManager = (DefaultConfigManager) ApolloInjector.getInstance( ConfigManager.class); - - List collectors = Lists.newArrayList( - new DefaultApolloClientExceptionApi(), - new DefaultApolloClientNamespaceApi(configManager.m_configs, configManager.m_configFiles), - new DefaultApolloClientThreadPoolApi(RemoteConfigRepository.m_executorService, - AbstractConfig.m_executorService, AbstractConfigFile.m_executorService, - AbstractApolloClientMetricsExporter.m_executorService), - new DefaultApolloClientBootstrapArgsApi(CONFIG_UTIL) - ); - - manager.setCollectors(collectors); - return collectors; + monitorContext.setApolloClientBootstrapArgsMonitorApi(new DefaultApolloClientBootstrapArgsApi( + m_configUtil)); + monitorContext.setApolloClientExceptionMonitorApi(new DefaultApolloClientExceptionApi()); + monitorContext.setApolloClientNamespaceMonitorApi(new DefaultApolloClientNamespaceApi( + configManager.m_configs, configManager.m_configFiles)); + monitorContext.setApolloClientThreadPoolMonitorApi(new DefaultApolloClientThreadPoolApi( + RemoteConfigRepository.m_executorService, + AbstractConfig.m_executorService, AbstractConfigFile.m_executorService, + AbstractApolloClientMetricsExporter.m_executorService)); } - protected static ApolloClientMetricsExporter initializeMetricsExporter( - List collectors) { + private static void initializeMetricsExporter( + ) { ApolloClientMetricsExporterFactory exporterFactory = ApolloInjector.getInstance( ApolloClientMetricsExporterFactory.class); - return exporterFactory.getMetricsReporter(collectors); - } - - protected static void initializeConfigMonitor(List collectors, - ApolloClientMetricsExporter metricsExporter) { - - DefaultConfigMonitor configMonitor = (DefaultConfigMonitor) ApolloInjector.getInstance( - ConfigMonitor.class); - configMonitor.init( - (DefaultApolloClientNamespaceApi) collectors.get(1), - (DefaultApolloClientThreadPoolApi) collectors.get(2), - (DefaultApolloClientExceptionApi) collectors.get(0), - (DefaultApolloClientBootstrapArgsApi) collectors.get(3), - metricsExporter - ); + ApolloClientMetricsExporter metricsReporter = exporterFactory.getMetricsReporter( + monitorContext.getCollectors()); + if(metricsReporter != null) { + monitorContext.setApolloClientMetricsExporter(metricsReporter); + } } public static ApolloClientMessageProducerComposite initializeMessageProducerComposite() { List producers = ServiceBootstrap.loadAllOrdered(MessageProducer.class); - if (CONFIG_UTIL.getClientMonitorEnabled()) { + if (m_configUtil.isClientMonitorEnabled()) { producers.add(new ApolloClientMonitorMessageProducer()); } @@ -139,11 +119,11 @@ public static ApolloClientMessageProducerComposite initializeMessageProducerComp return new ApolloClientMessageProducerComposite(producers); } - + // for test only protected static void reset() { hasInitialized = false; - CONFIG_UTIL = ApolloInjector.getInstance(ConfigUtil.class); + m_configUtil = ApolloInjector.getInstance(ConfigUtil.class); } } \ No newline at end of file diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultInjector.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultInjector.java index a4d0fca8..f561d278 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultInjector.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultInjector.java @@ -20,8 +20,7 @@ import com.ctrip.framework.apollo.monitor.api.ConfigMonitor; import com.ctrip.framework.apollo.monitor.internal.DefaultConfigMonitor; import com.ctrip.framework.apollo.monitor.internal.exporter.impl.DefaultApolloClientMetricsExporterFactory; -import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMonitorEventListenerManager; -import com.ctrip.framework.apollo.monitor.internal.listener.DefaultApolloClientMonitorEventListenerManager; +import com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorContext; import com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporterFactory; import com.ctrip.framework.apollo.spi.ApolloInjectorCustomizer; import com.ctrip.framework.apollo.spi.ConfigFactory; @@ -113,8 +112,7 @@ protected void configure() { bind(YamlParser.class).in(Singleton.class); bind(PropertiesFactory.class).to(DefaultPropertiesFactory.class).in(Singleton.class); bind(ConfigMonitor.class).to(DefaultConfigMonitor.class).in(Singleton.class); - bind(ApolloClientMonitorEventListenerManager.class).to( - DefaultApolloClientMonitorEventListenerManager.class).in(Singleton.class); + bind(ApolloClientMonitorContext.class).in(Singleton.class); bind(ApolloClientMetricsExporterFactory.class).to(DefaultApolloClientMetricsExporterFactory.class).in(Singleton.class); } } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigRepository.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigRepository.java index be19f42e..dd4f63ee 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigRepository.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigRepository.java @@ -115,7 +115,7 @@ public Properties getConfig() { if (m_configCache.get() == null) { long start = System.currentTimeMillis(); this.sync(); - Tracer.logEvent(APOLLO_CLIENT_NAMESPACE_FIRST_LOAD_SPEND+m_namespace, + Tracer.logEvent(APOLLO_CLIENT_NAMESPACE_FIRST_LOAD_SPEND+":"+m_namespace, String.valueOf(System.currentTimeMillis() - start)); } return transformApolloConfigToProperties(m_configCache.get()); diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientBootstrapArgsMonitorApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientBootstrapArgsMonitorApi.java index 5b0e0adb..cd5c33cc 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientBootstrapArgsMonitorApi.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientBootstrapArgsMonitorApi.java @@ -16,6 +16,12 @@ */ package com.ctrip.framework.apollo.monitor.api; +import static com.ctrip.framework.apollo.core.ApolloClientSystemConsts.*; +import static com.ctrip.framework.apollo.core.ConfigConsts.APOLLO_AUTO_UPDATE_INJECTED_SPRING_PROPERTIES; +import static com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorConstant.*; +import static com.ctrip.framework.apollo.spring.config.PropertySourcesConstants.*; + +import java.util.Collections; import java.util.Map; /** @@ -23,66 +29,106 @@ */ public interface ApolloClientBootstrapArgsMonitorApi { - /** - * get bootstrap args map - */ - Map getBootstrapArgs(); - /** * get startup params by key */ - String getStartupParams(String key); - - /** - * config service url - */ - String getConfigServiceUrl(); + default Object getStartupArg(String key) { + return getBootstrapArgs().get(key); + } /** - * access key secret - */ - String getAccessKeySecret(); - - /** - * auto update injected spring properties + * get bootstrap args map */ - Boolean getAutoUpdateInjectedSpringProperties(); - - Boolean getBootstrapEnabled(); - - String getBootstrapNamespaces(); - - Boolean getBootstrapEagerLoadEnabled(); - - Boolean getOverrideSystemProperties(); - - String getCacheDir(); - - String getCluster(); - - String getConfigService(); - - Boolean getClientMonitorEnabled(); - - Boolean getClientMonitorJmxEnabled(); - - String getClientMonitorExternalForm(); - - long getClientMonitorExternalExportPeriod(); - - int getClientMonitorExceptionSaveSize(); - - String getApolloMeta(); - - String getMetaLatestFreshTime(); - - Boolean getPropertyNamesCacheEnable(); - - Boolean getPropertyOrderEnable(); - - String getVersion(); - - String getEnv(); - - String getAppId(); -} + default Map getBootstrapArgs() { + return Collections.emptyMap(); + } + + default String getConfigServiceUrl() { + return (String) getBootstrapArgs().getOrDefault(CONFIG_SERVICE_URL, ""); + } + + default String getAccessKeySecret() { + return (String) getBootstrapArgs().getOrDefault(APOLLO_ACCESS_KEY_SECRET, ""); + } + + default Boolean getAutoUpdateInjectedSpringProperties() { + return (Boolean) getBootstrapArgs().getOrDefault(APOLLO_AUTO_UPDATE_INJECTED_SPRING_PROPERTIES, + false); + } + + default Boolean isBootstrapEnabled() { + return (Boolean) getBootstrapArgs().getOrDefault(APOLLO_BOOTSTRAP_ENABLED, false); + } + + default String getBootstrapNamespaces() { + return (String) getBootstrapArgs().getOrDefault(APOLLO_BOOTSTRAP_NAMESPACES, ""); + } + + default Boolean isBootstrapEagerLoadEnabled() { + return (Boolean) getBootstrapArgs().getOrDefault(APOLLO_BOOTSTRAP_EAGER_LOAD_ENABLED, false); + } + + default Boolean isOverrideSystemProperties() { + return (Boolean) getBootstrapArgs().getOrDefault(APOLLO_OVERRIDE_SYSTEM_PROPERTIES, false); + } + + default String getCacheDir() { + return (String) getBootstrapArgs().getOrDefault(APOLLO_CACHE_DIR, ""); + } + + default String getCluster() { + return (String) getBootstrapArgs().getOrDefault(APOLLO_CLUSTER, ""); + } + + default String getConfigService() { + return (String) getBootstrapArgs().getOrDefault(APOLLO_CONFIG_SERVICE, ""); + } + + default String getClientMonitorExternalForm() { + return (String) getBootstrapArgs().getOrDefault(APOLLO_CLIENT_MONITOR_EXTERNAL_TYPE, ""); + } + + default Boolean isClientMonitorEnabled() { + return (Boolean) getBootstrapArgs().getOrDefault(APOLLO_CLIENT_MONITOR_ENABLED, false); + } + + default Boolean isClientMonitorJmxEnabled() { + return (Boolean) getBootstrapArgs().getOrDefault(APOLLO_CLIENT_MONITOR_JMX_ENABLED, false); + } + + default long getClientMonitorExternalExportPeriod() { + return (Long) getBootstrapArgs().getOrDefault(APOLLO_CLIENT_MONITOR_EXTERNAL_EXPORT_PERIOD, 0L); + } + + default int getClientMonitorExceptionSaveSize() { + return (Integer) getBootstrapArgs().getOrDefault(APOLLO_CLIENT_MONITOR_EXCEPTION_QUEUE_SIZE, 0); + } + + default String getApolloMeta() { + return (String) getBootstrapArgs().getOrDefault(APOLLO_META, ""); + } + + default String getMetaLatestFreshTime() { + return (String) getBootstrapArgs().getOrDefault(META_FRESH, ""); + } + + default Boolean isPropertyNamesCacheEnable() { + return (Boolean) getBootstrapArgs().getOrDefault(APOLLO_PROPERTY_NAMES_CACHE_ENABLE, false); + } + + default Boolean isPropertyOrderEnable() { + return (Boolean) getBootstrapArgs().getOrDefault(APOLLO_PROPERTY_ORDER_ENABLE, false); + } + + default String getVersion() { + return (String) getBootstrapArgs().getOrDefault(VERSION, ""); + } + + default String getEnv() { + return (String) getBootstrapArgs().getOrDefault(ENV, ""); + } + + default String getAppId() { + return (String) getBootstrapArgs().getOrDefault(APP_ID, ""); + } +} \ No newline at end of file diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientExceptionMonitorApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientExceptionMonitorApi.java index 14b45d49..29d2b207 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientExceptionMonitorApi.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientExceptionMonitorApi.java @@ -24,8 +24,11 @@ public interface ApolloClientExceptionMonitorApi { /** - * get ApolloConfigException details + * Get exception information the number is limited and can be configured through + * apollo.client.monitor.exception-queue-size */ List getApolloConfigExceptionList(); + Integer getExceptionCountFromStartup(); + } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientNamespaceMonitorApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientNamespaceMonitorApi.java index 57d5efe6..78ac35f3 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientNamespaceMonitorApi.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientNamespaceMonitorApi.java @@ -16,7 +16,7 @@ */ package com.ctrip.framework.apollo.monitor.api; -import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientNamespaceApi.NamespaceMetrics; +import java.time.LocalDateTime; import java.util.List; import java.util.Map; @@ -31,14 +31,14 @@ public interface ApolloClientNamespaceMonitorApi { Map getNamespaceMetrics(); /** - * get Namespace Config.ItemsNum + * get Namespace Config.ItemsNum */ - Integer getNamespaceItemsNum(String namespace); + Integer getNamespacePropertySize(String namespace); /** - * get ConfigFile num + * get ConfigFile namespaces */ - Integer getConfigFileNum(); + List getConfigFileNamespaces(); /** * get not found namespaces @@ -51,4 +51,45 @@ public interface ApolloClientNamespaceMonitorApi { List getTimeoutNamespaces(); + class NamespaceMetrics { + + private int usageCount; + private long firstLoadTimeSpendInMs; + private LocalDateTime latestUpdateTime = LocalDateTime.now(); + private String releaseKey = ""; + + public String getReleaseKey() { + return releaseKey; + } + + public void setReleaseKey(String releaseKey) { + this.releaseKey = releaseKey; + } + + public int getUsageCount() { + return usageCount; + } + + public void incrementUsageCount() { + usageCount++; + } + + public long getFirstLoadTimeSpendInMs() { + return firstLoadTimeSpendInMs; + } + + public void setFirstLoadTimeSpendInMs(long firstLoadTimeSpendInMs) { + this.firstLoadTimeSpendInMs = firstLoadTimeSpendInMs; + } + + public LocalDateTime getLatestUpdateTime() { + return latestUpdateTime; + } + + public void setLatestUpdateTime(LocalDateTime latestUpdateTime) { + this.latestUpdateTime = latestUpdateTime; + } + } + + } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientThreadPoolMonitorApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientThreadPoolMonitorApi.java index db3315d7..d38555e4 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientThreadPoolMonitorApi.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientThreadPoolMonitorApi.java @@ -16,8 +16,8 @@ */ package com.ctrip.framework.apollo.monitor.api; -import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientThreadPoolApi.ApolloThreadPoolInfo; import java.util.Map; +import java.util.concurrent.ThreadPoolExecutor; /** * @author Rawven @@ -48,4 +48,55 @@ public interface ApolloClientThreadPoolMonitorApi { * AbstractApolloClientMetricsExporter.m_executorService */ ApolloThreadPoolInfo getMetricsExporterThreadPoolInfo(); + + + class ApolloThreadPoolInfo { + + private ThreadPoolExecutor executor; + + public ApolloThreadPoolInfo(ThreadPoolExecutor executor) { + this.executor = executor; + } + + public ApolloThreadPoolInfo() { + } + + + public int getActiveTaskCount() { + return executor != null ? executor.getActiveCount() : 0; + } + + public int getQueueSize() { + return executor != null ? executor.getQueue().size() : 0; + } + + public int getCorePoolSize() { + return executor != null ? executor.getCorePoolSize() : 0; + } + + public int getMaximumPoolSize() { + return executor != null ? executor.getMaximumPoolSize() : 0; + } + + public int getPoolSize() { + return executor != null ? executor.getPoolSize() : 0; + } + + public long getTotalTaskCount() { + return executor != null ? executor.getTaskCount() : 0; + } + + public long getCompletedTaskCount() { + return executor != null ? executor.getCompletedTaskCount() : 0; + } + + public int getLargestPoolSize() { + return executor != null ? executor.getLargestPoolSize() : 0; + } + + public int getQueueRemainingCapacity() { + return executor != null ? executor.getQueue().remainingCapacity() : 0; + } + + } } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/ApolloClientMonitorConstant.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/ApolloClientMonitorConstant.java index 4f615c7d..68512392 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/ApolloClientMonitorConstant.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/ApolloClientMonitorConstant.java @@ -38,7 +38,6 @@ public class ApolloClientMonitorConstant { public static final String TIMESTAMP = "timestamp"; public static final String THROWABLE = "throwable"; public static final String NAMESPACE_RELEASE_KEY = "releaseKey"; - public static final String APOLLO_CLIENT = "apollo_client_"; public static final String ENV = "env"; public static final String VERSION = "version"; public static final String META_FRESH = "metaFreshTime"; @@ -53,13 +52,13 @@ public class ApolloClientMonitorConstant { public static final String APOLLO_CONFIG_SERVICES = "Apollo.Config.Services"; public static final String APOLLO_CLIENT_VERSION = "Apollo.Client.Version"; public static final String APOLLO_CONFIGSERVICE = "Apollo.ConfigService"; + public static final String APOLLO_CONFIGSERVICE_HELP_STR = "periodicRefresh: "; public static final String APOLLO_CLIENT_CONFIGS = "Apollo.Client.Configs."; public static final String APOLLO_CLIENT_CONFIGMETA = "Apollo.Client.ConfigMeta"; public static final String APOLLO_CLIENT_NAMESPACE_NOT_FOUND = "Apollo.Client.NamespaceNotFound"; public static final String APOLLO_CLIENT_NAMESPACE_TIMEOUT = "Apollo.Client.NamespaceTimeout"; public static final String APOLLO_CLIENT_NAMESPACE_USAGE = "Apollo.Client.NamespaceUsage"; public static final String APOLLO_CLIENT_NAMESPACE_FIRST_LOAD_SPEND = "Apollo.Client.NamespaceFirstLoadSpendTime"; - public static final String HELP_STR = "periodicRefresh: "; /** * collector tag @@ -72,22 +71,22 @@ public class ApolloClientMonitorConstant { /** * metrics */ - public static final String METRICS_NAMESPACE_LATEST_UPDATE_TIME = "namespace_latest_update_time"; - public static final String METRICS_NAMESPACE_ITEM_NUM = "namespace_item_num"; - public static final String METRICS_CONFIG_FILE_NUM = "config_file_num"; - public static final String METRICS_EXCEPTION_NUM = "exception_num"; - public static final String METRICS_NAMESPACE_FIRST_LOAD_SPEND = "namespace_first_load_spend"; - public static final String METRICS_NAMESPACE_USAGE = "namespace_usage"; - public static final String METRICS_NAMESPACE_NOT_FOUND = "namespace_not_found"; - public static final String METRICS_NAMESPACE_TIMEOUT = "namespace_timeout"; - public static final String METRICS_THREAD_POOL = "thread_pool_"; - public static final String[] METRICS_THREAD_POOL_PARAMS = new String[]{ - METRICS_THREAD_POOL + "name", - METRICS_THREAD_POOL + "active_task_count", METRICS_THREAD_POOL + "queue_size", - METRICS_THREAD_POOL + "completed_task_count", - METRICS_THREAD_POOL + "pool_size", METRICS_THREAD_POOL + "total_task_count", - METRICS_THREAD_POOL + "core_pool_size", METRICS_THREAD_POOL + "maximum_pool_size", - METRICS_THREAD_POOL + "largest_pool_size", - METRICS_THREAD_POOL + "queue_capacity", METRICS_THREAD_POOL + "queue_remaining_capacity", - METRICS_THREAD_POOL + "current_load"}; + public static final String METRICS_NAMESPACE_LATEST_UPDATE_TIME = "apollo_client_namespace_latest_update_time"; + public static final String METRICS_NAMESPACE_ITEM_NUM = "apollo_client_namespace_item_num"; + public static final String METRICS_CONFIG_FILE_NUM = "apollo_client_config_file_num"; + public static final String METRICS_EXCEPTION_NUM = "apollo_client_exception_num"; + public static final String METRICS_NAMESPACE_FIRST_LOAD_SPEND = "apollo_client_namespace_first_load_time_spend_in_ms"; + public static final String METRICS_NAMESPACE_USAGE = "apollo_client_namespace_usage"; + public static final String METRICS_NAMESPACE_NOT_FOUND = "apollo_client_namespace_not_found"; + public static final String METRICS_NAMESPACE_TIMEOUT = "apollo_client_namespace_timeout"; + public static final String METRICS_THREAD_POOL_NAME = "thread_pool_name"; + public static final String METRICS_THREAD_POOL_ACTIVE_TASK_COUNT = "apollo_client_thread_pool_active_task_count"; + public static final String METRICS_THREAD_POOL_QUEUE_SIZE = "apollo_client_thread_pool_queue_size"; + public static final String METRICS_THREAD_POOL_COMPLETED_TASK_COUNT = "apollo_client_thread_pool_completed_task_count"; + public static final String METRICS_THREAD_POOL_POOL_SIZE = "apollo_client_thread_pool_pool_size"; + public static final String METRICS_THREAD_POOL_TOTAL_TASK_COUNT = "apollo_client_thread_pool_total_task_count"; + public static final String METRICS_THREAD_POOL_CORE_POOL_SIZE = "apollo_client_thread_pool_core_pool_size"; + public static final String METRICS_THREAD_POOL_MAXIMUM_POOL_SIZE = "apollo_client_thread_pool_maximum_pool_size"; + public static final String METRICS_THREAD_POOL_LARGEST_POOL_SIZE = "apollo_client_thread_pool_largest_pool_size"; + public static final String METRICS_THREAD_POOL_QUEUE_REMAINING_CAPACITY = "apollo_client_thread_pool_queue_remaining_capacity"; } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/ApolloClientMonitorContext.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/ApolloClientMonitorContext.java new file mode 100644 index 00000000..a036a2a2 --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/ApolloClientMonitorContext.java @@ -0,0 +1,96 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal; + +import com.ctrip.framework.apollo.monitor.api.ApolloClientBootstrapArgsMonitorApi; +import com.ctrip.framework.apollo.monitor.api.ApolloClientExceptionMonitorApi; +import com.ctrip.framework.apollo.monitor.api.ApolloClientNamespaceMonitorApi; +import com.ctrip.framework.apollo.monitor.api.ApolloClientThreadPoolMonitorApi; +import com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporter; +import com.ctrip.framework.apollo.monitor.internal.exporter.impl.NullApolloClientMetricsExporter; +import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMonitorEventListener; +import com.ctrip.framework.apollo.monitor.internal.listener.impl.NullClientBootstrapArgsMonitorApi; +import com.ctrip.framework.apollo.monitor.internal.listener.impl.NullClientExceptionMonitorApi; +import com.ctrip.framework.apollo.monitor.internal.listener.impl.NullClientNamespaceMonitorApi; +import com.ctrip.framework.apollo.monitor.internal.listener.impl.NullClientThreadPoolMonitorApi; +import com.google.common.collect.Lists; +import java.util.List; + +/** + * @author Rawven + */ +public class ApolloClientMonitorContext { + + private ApolloClientExceptionMonitorApi apolloClientExceptionMonitorApi = new NullClientExceptionMonitorApi(); + private ApolloClientNamespaceMonitorApi apolloClientNamespaceMonitorApi = new NullClientNamespaceMonitorApi(); + private ApolloClientBootstrapArgsMonitorApi apolloClientBootstrapArgsMonitorApi = new NullClientBootstrapArgsMonitorApi(); + private ApolloClientThreadPoolMonitorApi apolloClientThreadPoolMonitorApi = new NullClientThreadPoolMonitorApi(); + private ApolloClientMetricsExporter apolloClientMetricsExporter = new NullApolloClientMetricsExporter(); + + public void setApolloClientExceptionMonitorApi( + ApolloClientExceptionMonitorApi apolloClientExceptionMonitorApi) { + this.apolloClientExceptionMonitorApi = apolloClientExceptionMonitorApi; + } + + public void setApolloClientNamespaceMonitorApi( + ApolloClientNamespaceMonitorApi apolloClientNamespaceMonitorApi) { + this.apolloClientNamespaceMonitorApi = apolloClientNamespaceMonitorApi; + } + + public void setApolloClientBootstrapArgsMonitorApi( + ApolloClientBootstrapArgsMonitorApi apolloClientBootstrapArgsMonitorApi) { + this.apolloClientBootstrapArgsMonitorApi = apolloClientBootstrapArgsMonitorApi; + } + + public void setApolloClientThreadPoolMonitorApi( + ApolloClientThreadPoolMonitorApi apolloClientThreadPoolMonitorApi) { + this.apolloClientThreadPoolMonitorApi = apolloClientThreadPoolMonitorApi; + } + + public void setApolloClientMetricsExporter( + ApolloClientMetricsExporter apolloClientMetricsExporter) { + this.apolloClientMetricsExporter = apolloClientMetricsExporter; + } + + public List getCollectors() { + return Lists.newArrayList( + (ApolloClientMonitorEventListener) apolloClientBootstrapArgsMonitorApi, + (ApolloClientMonitorEventListener) apolloClientThreadPoolMonitorApi, + (ApolloClientMonitorEventListener) apolloClientExceptionMonitorApi, + (ApolloClientMonitorEventListener) apolloClientNamespaceMonitorApi); + } + + public ApolloClientExceptionMonitorApi getExceptionApi() { + return apolloClientExceptionMonitorApi; + } + + public ApolloClientNamespaceMonitorApi getNamespaceApi() { + return apolloClientNamespaceMonitorApi; + } + + public ApolloClientBootstrapArgsMonitorApi getBootstrapArgsApi() { + return apolloClientBootstrapArgsMonitorApi; + } + + public ApolloClientThreadPoolMonitorApi getThreadPoolApi() { + return apolloClientThreadPoolMonitorApi; + } + + public ApolloClientMetricsExporter getMetricsExporter() { + return apolloClientMetricsExporter; + } +} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/DefaultConfigMonitor.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/DefaultConfigMonitor.java index c296496d..4925f408 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/DefaultConfigMonitor.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/DefaultConfigMonitor.java @@ -16,17 +16,12 @@ */ package com.ctrip.framework.apollo.monitor.internal; +import com.ctrip.framework.apollo.build.ApolloInjector; import com.ctrip.framework.apollo.monitor.api.ApolloClientBootstrapArgsMonitorApi; import com.ctrip.framework.apollo.monitor.api.ApolloClientExceptionMonitorApi; import com.ctrip.framework.apollo.monitor.api.ApolloClientNamespaceMonitorApi; import com.ctrip.framework.apollo.monitor.api.ApolloClientThreadPoolMonitorApi; import com.ctrip.framework.apollo.monitor.api.ConfigMonitor; -import com.ctrip.framework.apollo.monitor.internal.listener.impl.NullClientBootstrapArgsMonitorApi; -import com.ctrip.framework.apollo.monitor.internal.listener.impl.NullClientExceptionMonitorApi; -import com.ctrip.framework.apollo.monitor.internal.listener.impl.NullClientNamespaceMonitorApi; -import com.ctrip.framework.apollo.monitor.internal.listener.impl.NullClientThreadPoolMonitorApi; -import com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporter; -import com.ctrip.framework.apollo.monitor.internal.exporter.impl.NullApolloClientMetricsExporter; /** * exposes all collected data through ConfigService @@ -35,46 +30,31 @@ */ public class DefaultConfigMonitor implements ConfigMonitor { - private ApolloClientMetricsExporter reporter = new NullApolloClientMetricsExporter(); - private ApolloClientThreadPoolMonitorApi threadPoolMonitorApi = new NullClientThreadPoolMonitorApi(); - private ApolloClientExceptionMonitorApi exceptionMonitorApi = new NullClientExceptionMonitorApi(); - private ApolloClientNamespaceMonitorApi apolloClientNamespaceMonitorApi = new NullClientNamespaceMonitorApi(); - private ApolloClientBootstrapArgsMonitorApi apolloClientBootstrapArgsMonitorApi = new NullClientBootstrapArgsMonitorApi(); + private ApolloClientMonitorContext apolloClientMonitorContext = ApolloInjector.getInstance( + ApolloClientMonitorContext.class); @Override public ApolloClientThreadPoolMonitorApi getThreadPoolMonitorApi() { - return threadPoolMonitorApi; + return apolloClientMonitorContext.getThreadPoolApi(); } @Override public ApolloClientExceptionMonitorApi getExceptionMonitorApi() { - return exceptionMonitorApi; + return apolloClientMonitorContext.getExceptionApi(); } @Override public ApolloClientNamespaceMonitorApi getNamespaceMonitorApi() { - return apolloClientNamespaceMonitorApi; + return apolloClientMonitorContext.getNamespaceApi(); } @Override public ApolloClientBootstrapArgsMonitorApi getRunningParamsMonitorApi() { - return apolloClientBootstrapArgsMonitorApi; + return apolloClientMonitorContext.getBootstrapArgsApi(); } @Override public String getExporterData() { - return reporter.response(); - } - - public void init(ApolloClientNamespaceMonitorApi apolloClientNamespaceMonitorApi, - ApolloClientThreadPoolMonitorApi threadPoolMonitorApi, - ApolloClientExceptionMonitorApi exceptionMonitorApi, - ApolloClientBootstrapArgsMonitorApi apolloClientBootstrapArgsMonitorApi, - ApolloClientMetricsExporter reporter) { - this.apolloClientNamespaceMonitorApi = apolloClientNamespaceMonitorApi; - this.threadPoolMonitorApi = threadPoolMonitorApi; - this.exceptionMonitorApi = exceptionMonitorApi; - this.apolloClientBootstrapArgsMonitorApi = apolloClientBootstrapArgsMonitorApi; - this.reporter = reporter; + return apolloClientMonitorContext.getMetricsExporter().response(); } } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/enums/MeterEnums.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/enums/MetricTypeEnums.java similarity index 96% rename from apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/enums/MeterEnums.java rename to apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/enums/MetricTypeEnums.java index 1009d3ed..c4c73440 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/enums/MeterEnums.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/enums/MetricTypeEnums.java @@ -19,7 +19,7 @@ /** * @author Rawven */ -public enum MeterEnums { +public enum MetricTypeEnums { /** * counter */ diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/event/ApolloClientMonitorEvent.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/event/ApolloClientMonitorEvent.java index 91c6eb4b..e7b4f077 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/event/ApolloClientMonitorEvent.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/event/ApolloClientMonitorEvent.java @@ -16,6 +16,7 @@ */ package com.ctrip.framework.apollo.monitor.internal.event; +import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -31,7 +32,7 @@ public class ApolloClientMonitorEvent { public ApolloClientMonitorEvent(String name, String tag, Map attachments) { this.name = name; this.tag = tag; - this.attachments = attachments != null ? new HashMap<>(attachments) : new HashMap<>(); + this.attachments = attachments != null ? new HashMap<>(attachments) : Collections.emptyMap(); } public ApolloClientMonitorEvent withTag(String tag) { @@ -65,10 +66,4 @@ public T getAttachmentValue(String key) { throw new IllegalArgumentException("Value for key " + key + " is not of expected type", e); } } - - - public void publish() { - ApolloClientMonitorEventPublisher.publish(this); - } - } \ No newline at end of file diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/event/ApolloClientMonitorEventPublisher.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/event/ApolloClientMonitorEventPublisher.java index 7388b888..e6843a72 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/event/ApolloClientMonitorEventPublisher.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/event/ApolloClientMonitorEventPublisher.java @@ -18,7 +18,7 @@ import com.ctrip.framework.apollo.build.ApolloInjector; import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMonitorEventListener; -import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMonitorEventListenerManager; +import com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorContext; import com.ctrip.framework.apollo.util.ConfigUtil; /** @@ -26,14 +26,14 @@ */ public class ApolloClientMonitorEventPublisher { - private static ApolloClientMonitorEventListenerManager COLLECTOR_MANAGER = ApolloInjector.getInstance( - ApolloClientMonitorEventListenerManager.class); + private static ApolloClientMonitorContext COLLECTOR_MANAGER = ApolloInjector.getInstance( + ApolloClientMonitorContext.class); private static ConfigUtil m_configUtil = ApolloInjector.getInstance(ConfigUtil.class); public static void publish(ApolloClientMonitorEvent event) { - if (m_configUtil.getClientMonitorEnabled()) { + if (m_configUtil.isClientMonitorEnabled()) { for (ApolloClientMonitorEventListener collector : COLLECTOR_MANAGER.getCollectors()) { - if (collector.isSupport(event)) { + if (collector.isSupported(event)) { collector.collect(event); return; } @@ -43,7 +43,7 @@ public static void publish(ApolloClientMonitorEvent event) { protected static void reset() { COLLECTOR_MANAGER = ApolloInjector.getInstance( - ApolloClientMonitorEventListenerManager.class); + ApolloClientMonitorContext.class); m_configUtil = ApolloInjector.getInstance(ConfigUtil.class); } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractApolloClientMetricsExporter.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractApolloClientMetricsExporter.java index c85625ce..50550ad5 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractApolloClientMetricsExporter.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractApolloClientMetricsExporter.java @@ -33,15 +33,15 @@ */ public abstract class AbstractApolloClientMetricsExporter implements ApolloClientMetricsExporter { + public static final ScheduledExecutorService m_executorService; private static final Logger log = DeferredLoggerFactory.getLogger( AbstractApolloClientMetricsExporter.class); - public static final ScheduledExecutorService m_executorService; private static final long INITIAL_DELAY = 5L; private static final int THREAD_POOL_SIZE = 1; static { m_executorService = Executors.newScheduledThreadPool(THREAD_POOL_SIZE, - ApolloThreadFactory.create("MetricsReporter", true)); + ApolloThreadFactory.create(ApolloClientMetricsExporter.class.getName(), true)); } protected List collectors; @@ -75,7 +75,7 @@ protected void updateMetricsData() { log.debug("Start to update metrics data job"); collectors.forEach(collector -> { if (collector.isMetricsSampleUpdated()) { - log.debug("Collector {} has updated samples.", collector.mBeanName()); + log.debug("Collector {} has updated samples.", collector.getName()); collector.export().forEach(this::registerSample); } }); diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/impl/DefaultApolloClientMetricsExporterFactory.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/impl/DefaultApolloClientMetricsExporterFactory.java index 3476a0c5..a9a280e9 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/impl/DefaultApolloClientMetricsExporterFactory.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/impl/DefaultApolloClientMetricsExporterFactory.java @@ -16,15 +16,12 @@ */ package com.ctrip.framework.apollo.monitor.internal.exporter.impl; -import static com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorConstant.MBEAN_NAME; - import com.ctrip.framework.apollo.build.ApolloInjector; import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory; import com.ctrip.framework.apollo.exceptions.ApolloConfigException; import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMonitorEventListener; import com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporter; import com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporterFactory; -import com.ctrip.framework.apollo.monitor.internal.jmx.ApolloClientJmxMBeanRegister; import com.ctrip.framework.apollo.tracer.Tracer; import com.ctrip.framework.apollo.util.ConfigUtil; import com.ctrip.framework.foundation.internals.ServiceBootstrap; diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/impl/NullApolloClientMetricsExporter.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/impl/NullApolloClientMetricsExporter.java index 6c3214ef..237f024f 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/impl/NullApolloClientMetricsExporter.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/impl/NullApolloClientMetricsExporter.java @@ -16,16 +16,22 @@ */ package com.ctrip.framework.apollo.monitor.internal.exporter.impl; +import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory; +import com.ctrip.framework.apollo.monitor.internal.exporter.AbstractApolloClientMetricsExporter; import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMonitorEventListener; import com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporter; import java.util.List; import java.util.Map; +import org.slf4j.Logger; /** * @author Rawven */ public class NullApolloClientMetricsExporter implements ApolloClientMetricsExporter { + private static final Logger log = DeferredLoggerFactory.getLogger( + AbstractApolloClientMetricsExporter.class); + @Override public void init(List collectors, long collectPeriod) { } @@ -48,6 +54,7 @@ public void registerOrUpdateGaugeSample(String name, Map tag, do @Override public String response() { - return "No Reporter Use"; + log.warn("No metrics exporter found, response empty string"); + return ""; } } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/jmx/mbean/ApolloClientJmxBootstrapArgsMBean.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/jmx/mbean/ApolloClientJmxBootstrapArgsMBean.java index 024cbd8c..d00597b5 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/jmx/mbean/ApolloClientJmxBootstrapArgsMBean.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/jmx/mbean/ApolloClientJmxBootstrapArgsMBean.java @@ -16,13 +16,20 @@ */ package com.ctrip.framework.apollo.monitor.internal.jmx.mbean; -import com.ctrip.framework.apollo.monitor.api.ApolloClientBootstrapArgsMonitorApi; +import java.util.Map; import javax.management.MXBean; /** * @author Rawven */ @MXBean -public interface ApolloClientJmxBootstrapArgsMBean extends ApolloClientBootstrapArgsMonitorApi { +public interface ApolloClientJmxBootstrapArgsMBean { + // Because JMX does not support all type return values + // declare the interface separately. + + /** + * get bootstrap args map + */ + Map getBootstrapArgsString(); } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/jmx/mbean/ApolloClientJmxExceptionMBean.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/jmx/mbean/ApolloClientJmxExceptionMBean.java index 016c5451..076b8639 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/jmx/mbean/ApolloClientJmxExceptionMBean.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/jmx/mbean/ApolloClientJmxExceptionMBean.java @@ -24,11 +24,13 @@ */ @MXBean public interface ApolloClientJmxExceptionMBean { - // Because JMX does not support Exception type return values + // Because JMX does not support all type return values // declare the interface separately. /** * get exception details */ List getApolloConfigExceptionDetails(); + + Integer getExceptionCountFromStartup(); } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/jmx/mbean/ApolloClientJmxNamespaceMBean.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/jmx/mbean/ApolloClientJmxNamespaceMBean.java index 569a6a2a..1290344a 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/jmx/mbean/ApolloClientJmxNamespaceMBean.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/jmx/mbean/ApolloClientJmxNamespaceMBean.java @@ -16,13 +16,82 @@ */ package com.ctrip.framework.apollo.monitor.internal.jmx.mbean; -import com.ctrip.framework.apollo.monitor.api.ApolloClientNamespaceMonitorApi; +import java.util.List; +import java.util.Map; import javax.management.MXBean; /** * @author Rawven */ @MXBean -public interface ApolloClientJmxNamespaceMBean extends ApolloClientNamespaceMonitorApi { +public interface ApolloClientJmxNamespaceMBean { + // Because JMX does not support all type return values + // declare the interface separately. + + /** + * NamespaceMetrics: 1.usageCount 2.firstLoadSpend 3.latestUpdateTime 4.releaseKey + */ + Map getNamespaceMetricsString(); + + /** + * get Namespace Config.ItemsNum + */ + Integer getNamespacePropertySize(String namespace); + + /** + * get ConfigFile namespaces + */ + List getConfigFileNamespaces(); + + /** + * get not found namespaces + */ + List getNotFoundNamespaces(); + + /** + * get timeout namespaces + */ + List getTimeoutNamespaces(); + + + class NamespaceMetricsString { + + private int usageCount; + private long firstLoadTimeSpendInMs; + private String latestUpdateTime; + private String releaseKey = ""; + + public int getUsageCount() { + return usageCount; + } + + public void setUsageCount(int usageCount) { + this.usageCount = usageCount; + } + + public long getFirstLoadTimeSpendInMs() { + return firstLoadTimeSpendInMs; + } + + public void setFirstLoadTimeSpendInMs(long firstLoadTimeSpendInMs) { + this.firstLoadTimeSpendInMs = firstLoadTimeSpendInMs; + } + + public String getLatestUpdateTime() { + return latestUpdateTime; + } + + public void setLatestUpdateTime(String latestUpdateTime) { + this.latestUpdateTime = latestUpdateTime; + } + + public String getReleaseKey() { + return releaseKey; + } + + public void setReleaseKey(String releaseKey) { + this.releaseKey = releaseKey; + } + } } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/AbstractApolloClientMonitorEventListener.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/AbstractApolloClientMonitorEventListener.java index bffb55ed..847410f7 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/AbstractApolloClientMonitorEventListener.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/AbstractApolloClientMonitorEventListener.java @@ -22,13 +22,13 @@ import com.ctrip.framework.apollo.monitor.internal.model.SampleModel; import com.google.common.collect.Maps; import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; /** - * 抽象的 Metrics 收集器 用于收集数据和导出指标样本 - * * @author Rawven */ public abstract class AbstractApolloClientMonitorEventListener implements @@ -44,12 +44,12 @@ public AbstractApolloClientMonitorEventListener(String tag) { } @Override - public String mBeanName() { + public String getName() { return tag; } @Override - public boolean isSupport(ApolloClientMonitorEvent event) { + public boolean isSupported(ApolloClientMonitorEvent event) { return tag.equals(event.getTag()); } @@ -71,42 +71,67 @@ public List export() { samples.addAll(gaugeSamples.values()); return samples; } - + /** * Specific collection logic */ - protected void collect0(ApolloClientMonitorEvent event){} + protected void collect0(ApolloClientMonitorEvent event) { + } /** * Convenient for indicators that can only be obtained from the status object */ - protected void export0(){} - + protected void export0() { + } /** * tool method for updating indicator model */ - public void createOrUpdateGaugeSample(String mapKey, String metricsName, Map tags, + public void createOrUpdateGaugeSample(String metricsName, String[] tagKeys, String[] tagValues, double value) { - if (!gaugeSamples.containsKey(mapKey)) { - GaugeModel builder = (GaugeModel) GaugeModel.create(metricsName, 0).putTags(tags); - gaugeSamples.put(mapKey, builder); - } - gaugeSamples.get(mapKey).setValue(value); + createOrUpdateSample(metricsName, tagKeys, tagValues, value, false); } - /** - * tool method for updating indicator model - */ - public void createOrUpdateCounterSample(String mapKey, String metricsName, - Map tags, + public void createOrUpdateGaugeSample(String metricsName, double value) { + createOrUpdateSample(metricsName, null, null, value, false); + } + + public void createOrUpdateCounterSample(String metricsName, String[] tagKeys, String[] tagValues, double increaseValue) { - if (!counterSamples.containsKey(mapKey)) { - CounterModel builder = (CounterModel) CounterModel.create(metricsName, 0).putTags(tags); - counterSamples.put(mapKey, builder); + createOrUpdateSample(metricsName, tagKeys, tagValues, increaseValue, true); + } + + public void createOrUpdateCounterSample(String metricsName, double increaseValue) { + createOrUpdateSample(metricsName, null, null, increaseValue, true); + } + + private void createOrUpdateSample(String metricsName, String[] tagKeys, String[] tagValues, + double value, boolean isCounter) { + String mapKey = metricsName + (tagValues != null ? Arrays.toString(tagValues) : ""); + + if (isCounter) { + CounterModel counter = counterSamples.computeIfAbsent(mapKey, + key -> (CounterModel) CounterModel.create(metricsName, 0) + .putTags(getTags(tagKeys, tagValues))); + counter.increase(value); + } else { + GaugeModel gauge = gaugeSamples.computeIfAbsent(mapKey, + key -> (GaugeModel) GaugeModel.create(metricsName, 0) + .putTags(getTags(tagKeys, tagValues))); + gauge.setValue(value); + } + } + + private Map getTags(String[] tagKeys, String[] tagValues) { + if (tagKeys != null && tagValues != null && tagKeys.length == tagValues.length) { + Map tags = Maps.newHashMap(); + for (int i = 0; i < tagKeys.length; i++) { + tags.put(tagKeys[i], tagValues[i]); + } + return tags; } - counterSamples.get(mapKey).increase(increaseValue); + return Collections.emptyMap(); } } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/ApolloClientMonitorEventListener.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/ApolloClientMonitorEventListener.java index 000fd480..d808d24d 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/ApolloClientMonitorEventListener.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/ApolloClientMonitorEventListener.java @@ -29,12 +29,12 @@ public interface ApolloClientMonitorEventListener { /** * mbean name */ - String mBeanName(); + String getName(); /** * is support the event */ - boolean isSupport(ApolloClientMonitorEvent event); + boolean isSupported(ApolloClientMonitorEvent event); /** * collect metrics from event diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/ApolloClientMonitorEventListenerManager.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/ApolloClientMonitorEventListenerManager.java deleted file mode 100644 index 4b72834b..00000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/ApolloClientMonitorEventListenerManager.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2022 Apollo Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.ctrip.framework.apollo.monitor.internal.listener; - -import com.ctrip.framework.apollo.core.spi.Ordered; -import java.util.List; - -/** - * @author Rawven - */ -public interface ApolloClientMonitorEventListenerManager extends Ordered { - - /** - * get collectors - */ - List getCollectors(); - - @Override - default int getOrder() { - return 0; - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/DefaultApolloClientMonitorEventListenerManager.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/DefaultApolloClientMonitorEventListenerManager.java deleted file mode 100644 index 8cc0444f..00000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/DefaultApolloClientMonitorEventListenerManager.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2022 Apollo Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.ctrip.framework.apollo.monitor.internal.listener; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author Rawven - */ -public class DefaultApolloClientMonitorEventListenerManager implements - ApolloClientMonitorEventListenerManager { - - private List collectors = new ArrayList<>(); - - public DefaultApolloClientMonitorEventListenerManager() { - } - - @Override - public List getCollectors() { - return collectors; - } - - public void setCollectors(List collectors) { - this.collectors.clear(); - this.collectors.addAll(collectors); - } - -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientBootstrapArgsApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientBootstrapArgsApi.java index b1fd2256..19ca9b30 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientBootstrapArgsApi.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientBootstrapArgsApi.java @@ -30,7 +30,6 @@ import com.ctrip.framework.apollo.util.ConfigUtil; import com.google.common.collect.Maps; import java.util.Map; -import java.util.Optional; import org.slf4j.Logger; /** @@ -62,13 +61,13 @@ public DefaultApolloClientBootstrapArgsApi(ConfigUtil configUtil) { bootstrapArgs.put(APOLLO_CONFIG_SERVICE, System.getProperty(APOLLO_CONFIG_SERVICE)); bootstrapArgs.put(APOLLO_CLIENT_MONITOR_EXTERNAL_TYPE, configUtil.getMonitorExternalType()); - bootstrapArgs.put(APOLLO_CLIENT_MONITOR_ENABLED, configUtil.getClientMonitorEnabled()); + bootstrapArgs.put(APOLLO_CLIENT_MONITOR_ENABLED, configUtil.isClientMonitorEnabled()); bootstrapArgs.put(APOLLO_CLIENT_MONITOR_EXTERNAL_EXPORT_PERIOD, configUtil.getMonitorExternalExportPeriod()); bootstrapArgs.put(APOLLO_META, configUtil.getMetaServerDomainName()); bootstrapArgs.put(APOLLO_PROPERTY_NAMES_CACHE_ENABLE, configUtil.isPropertyNamesCacheEnabled()); bootstrapArgs.put(APOLLO_PROPERTY_ORDER_ENABLE, configUtil.isPropertiesOrderEnabled()); - bootstrapArgs.put(APOLLO_CLIENT_MONITOR_JMX_ENABLED, configUtil.getClientMonitorJmxEnabled()); + bootstrapArgs.put(APOLLO_CLIENT_MONITOR_JMX_ENABLED, configUtil.isClientMonitorJmxEnabled()); bootstrapArgs.put(APOLLO_CLIENT_MONITOR_EXCEPTION_QUEUE_SIZE, configUtil.getMonitorExceptionQueueSize()); bootstrapArgs.put(APP_ID, configUtil.getAppId()); @@ -98,123 +97,12 @@ public boolean isMetricsSampleUpdated() { } @Override - public String getStartupParams(String key) { - return Optional.ofNullable(bootstrapArgs.get(key)).orElse("").toString(); + public Map getBootstrapArgs() { + return bootstrapArgs; } @Override - public String getConfigServiceUrl() { - return bootstrapArgs.get(CONFIG_SERVICE_URL).toString(); - } - - - @Override - public String getAccessKeySecret() { - return bootstrapArgs.getOrDefault(APOLLO_ACCESS_KEY_SECRET, "").toString(); - } - - @Override - public Boolean getAutoUpdateInjectedSpringProperties() { - return (Boolean) bootstrapArgs.get(APOLLO_AUTO_UPDATE_INJECTED_SPRING_PROPERTIES); - } - - @Override - public Boolean getBootstrapEnabled() { - return (Boolean) bootstrapArgs.get(APOLLO_BOOTSTRAP_ENABLED); - } - - @Override - public String getBootstrapNamespaces() { - return (String) bootstrapArgs.get(APOLLO_BOOTSTRAP_NAMESPACES); - } - - @Override - public Boolean getBootstrapEagerLoadEnabled() { - return (Boolean) bootstrapArgs.get(APOLLO_BOOTSTRAP_EAGER_LOAD_ENABLED); - } - - @Override - public Boolean getOverrideSystemProperties() { - return (Boolean) bootstrapArgs.get(APOLLO_OVERRIDE_SYSTEM_PROPERTIES); - } - - @Override - public String getCacheDir() { - return bootstrapArgs.get(APOLLO_CACHE_DIR).toString(); - } - - @Override - public String getCluster() { - return bootstrapArgs.get(APOLLO_CLUSTER).toString(); - } - - @Override - public String getConfigService() { - return bootstrapArgs.get(APOLLO_CONFIG_SERVICE).toString(); - } - - @Override - public String getClientMonitorExternalForm() { - return bootstrapArgs.get(APOLLO_CLIENT_MONITOR_EXTERNAL_TYPE).toString(); - } - - @Override - public Boolean getClientMonitorEnabled() { - return (Boolean) bootstrapArgs.get(APOLLO_CLIENT_MONITOR_ENABLED); - } - - @Override - public Boolean getClientMonitorJmxEnabled() { - return (Boolean) bootstrapArgs.get(APOLLO_CLIENT_MONITOR_JMX_ENABLED); - } - - @Override - public long getClientMonitorExternalExportPeriod() { - return (Long) bootstrapArgs.get(APOLLO_CLIENT_MONITOR_EXTERNAL_EXPORT_PERIOD); - } - - @Override - public int getClientMonitorExceptionSaveSize() { - return (int) bootstrapArgs.get(APOLLO_CLIENT_MONITOR_EXCEPTION_QUEUE_SIZE); - } - - @Override - public String getApolloMeta() { - return bootstrapArgs.get(APOLLO_META).toString(); - } - - @Override - public Boolean getPropertyNamesCacheEnable() { - return (Boolean) bootstrapArgs.get(APOLLO_PROPERTY_NAMES_CACHE_ENABLE); - } - - @Override - public Boolean getPropertyOrderEnable() { - return (Boolean) bootstrapArgs.get(APOLLO_PROPERTY_ORDER_ENABLE); - } - - @Override - public String getMetaLatestFreshTime() { - return bootstrapArgs.get(META_FRESH).toString(); - } - - @Override - public String getVersion() { - return bootstrapArgs.get(VERSION).toString(); - } - - @Override - public String getEnv() { - return bootstrapArgs.get(ENV).toString(); - } - - @Override - public String getAppId() { - return bootstrapArgs.get(APP_ID).toString(); - } - - @Override - public Map getBootstrapArgs() { + public Map getBootstrapArgsString() { return bootstrapArgsString; } } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientExceptionApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientExceptionApi.java index f39f6ba0..c7897c1c 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientExceptionApi.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientExceptionApi.java @@ -27,11 +27,11 @@ import com.ctrip.framework.apollo.monitor.internal.listener.AbstractApolloClientMonitorEventListener; import com.ctrip.framework.apollo.monitor.internal.event.ApolloClientMonitorEvent; import com.ctrip.framework.apollo.util.ConfigUtil; +import com.google.common.collect.EvictingQueue; +import com.google.common.collect.Queues; import java.util.ArrayList; -import java.util.Collections; import java.util.List; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.BlockingQueue; +import java.util.Queue; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; @@ -42,48 +42,41 @@ public class DefaultApolloClientExceptionApi extends AbstractApolloClientMonitorEventListener implements ApolloClientExceptionMonitorApi, ApolloClientJmxExceptionMBean { - private final AtomicInteger exceptionNum = new AtomicInteger(0); - private int monitorExceptionQueueSize; - private final BlockingQueue exceptions; + private final AtomicInteger exceptionCountFromStartup = new AtomicInteger(0); + private final Queue exceptionsQueue; public DefaultApolloClientExceptionApi() { super(TAG_ERROR); - monitorExceptionQueueSize = ApolloInjector.getInstance(ConfigUtil.class) + int monitorExceptionQueueSize = ApolloInjector.getInstance(ConfigUtil.class) .getMonitorExceptionQueueSize(); - if (monitorExceptionQueueSize <= 0) { - monitorExceptionQueueSize = 25; - } - exceptions = new ArrayBlockingQueue<>( + EvictingQueue evictingQueue = EvictingQueue.create( monitorExceptionQueueSize); + exceptionsQueue = Queues.synchronizedQueue(evictingQueue); } @Override public List getApolloConfigExceptionList() { - return new ArrayList<>(exceptions); + return new ArrayList<>(exceptionsQueue); + } + + @Override + public Integer getExceptionCountFromStartup() { + return exceptionCountFromStartup.get(); } @Override public void collect0(ApolloClientMonitorEvent event) { ApolloConfigException exception = event.getAttachmentValue(THROWABLE); if (exception != null) { - addExceptionToQueue(exception); - exceptionNum.incrementAndGet(); - createOrUpdateCounterSample(METRICS_EXCEPTION_NUM, METRICS_EXCEPTION_NUM, - Collections.emptyMap(), - 1); - } - } - - private void addExceptionToQueue(ApolloConfigException exception) { - if (exceptions.size() >= monitorExceptionQueueSize) { - exceptions.poll(); + exceptionsQueue.add(exception); + exceptionCountFromStartup.incrementAndGet(); + createOrUpdateCounterSample(METRICS_EXCEPTION_NUM, 1); } - exceptions.add(exception); } @Override public List getApolloConfigExceptionDetails() { - return exceptions.stream() + return exceptionsQueue.stream() .map(ApolloConfigException::getMessage) .collect(Collectors.toList()); } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientNamespaceApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientNamespaceApi.java index 3fc072ed..a28ee09f 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientNamespaceApi.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientNamespaceApi.java @@ -29,6 +29,7 @@ import com.ctrip.framework.apollo.monitor.internal.event.ApolloClientMonitorEvent; import com.google.common.collect.Maps; import com.google.common.collect.Sets; +import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -77,14 +78,6 @@ public void collect0(ApolloClientMonitorEvent event) { } } - private void handleNamespaceNotFound(String namespace) { - namespace404.add(namespace); - } - - private void handleNamespaceTimeout(String namespace) { - namespaceTimeout.add(namespace); - } - private void handleNormalNamespace(String namespace, ApolloClientMonitorEvent event) { namespace404.remove(namespace); namespaceTimeout.remove(namespace); @@ -115,23 +108,30 @@ private void collectMetrics(ApolloClientMonitorEvent event, NamespaceMetrics nam } } + private void handleNamespaceNotFound(String namespace) { + namespace404.add(namespace); + } + + private void handleNamespaceTimeout(String namespace) { + namespaceTimeout.add(namespace); + } + + private void handleUsageEvent(NamespaceMetrics namespaceMetrics, String namespace) { namespaceMetrics.incrementUsageCount(); - String mapKey = namespace + ApolloClientMonitorConstant.METRICS_NAMESPACE_USAGE; - createOrUpdateCounterSample(mapKey, ApolloClientMonitorConstant.METRICS_NAMESPACE_USAGE, - Collections.singletonMap(NAMESPACE, namespace), 1); + createOrUpdateCounterSample(ApolloClientMonitorConstant.METRICS_NAMESPACE_USAGE, + new String[]{NAMESPACE}, new String[]{namespace}, 1); } private void handleUpdateTimeEvent(ApolloClientMonitorEvent event, NamespaceMetrics namespaceMetrics) { - long updateTime = event.getAttachmentValue(ApolloClientMonitorConstant.TIMESTAMP); - namespaceMetrics.setLatestUpdateTime(updateTime); + namespaceMetrics.setLatestUpdateTime(LocalDateTime.now()); } private void handleFirstLoadSpendEvent(ApolloClientMonitorEvent event, NamespaceMetrics namespaceMetrics) { long firstLoadSpendTime = event.getAttachmentValue(ApolloClientMonitorConstant.TIMESTAMP); - namespaceMetrics.setFirstLoadSpend(firstLoadSpendTime); + namespaceMetrics.setFirstLoadTimeSpendInMs(firstLoadSpendTime); } private void handleReleaseKeyEvent(ApolloClientMonitorEvent event, @@ -144,32 +144,26 @@ private void handleReleaseKeyEvent(ApolloClientMonitorEvent event, public void export0() { namespaces.forEach((namespace, metrics) -> { // update NamespaceMetrics - createOrUpdateGaugeSample(namespace + METRICS_NAMESPACE_FIRST_LOAD_SPEND, + createOrUpdateGaugeSample( METRICS_NAMESPACE_FIRST_LOAD_SPEND, - Collections.singletonMap(NAMESPACE, namespace), - metrics.getFirstLoadSpend()); + new String[]{NAMESPACE}, new String[]{namespace}, + metrics.getFirstLoadTimeSpendInMs()); - createOrUpdateGaugeSample(namespace + METRICS_NAMESPACE_ITEM_NUM, + createOrUpdateGaugeSample( METRICS_NAMESPACE_ITEM_NUM, - Collections.singletonMap(NAMESPACE, namespace), + new String[]{NAMESPACE}, new String[]{namespace}, m_configs.get(namespace).getPropertyNames().size()); }); // update ConfigFile num createOrUpdateGaugeSample(METRICS_CONFIG_FILE_NUM, - METRICS_CONFIG_FILE_NUM, - Collections.emptyMap(), m_configFiles.size()); // update NamespaceStatus metrics createOrUpdateGaugeSample(METRICS_NAMESPACE_NOT_FOUND, - METRICS_NAMESPACE_NOT_FOUND, - Collections.emptyMap(), namespace404.size()); createOrUpdateGaugeSample(METRICS_NAMESPACE_TIMEOUT, - METRICS_NAMESPACE_TIMEOUT, - Collections.emptyMap(), namespaceTimeout.size()); } @@ -189,53 +183,28 @@ public List getTimeoutNamespaces() { } @Override - public Integer getNamespaceItemsNum(String namespace) { + public Map getNamespaceMetricsString() { + Map namespaceMetricsStringMap = Maps.newHashMap(); + namespaces.forEach((namespace, metrics) -> { + NamespaceMetricsString namespaceMetricsString = new NamespaceMetricsString(); + namespaceMetricsString.setFirstLoadTimeSpendInMs(metrics.getFirstLoadTimeSpendInMs()); + namespaceMetricsString.setLatestUpdateTime(metrics.getLatestUpdateTime().toString()); + namespaceMetricsString.setUsageCount(metrics.getUsageCount()); + namespaceMetricsString.setReleaseKey(metrics.getReleaseKey()); + namespaceMetricsStringMap.put(namespace, namespaceMetricsString); + }); + return namespaceMetricsStringMap; + } + + @Override + public Integer getNamespacePropertySize(String namespace) { Config config = m_configs.get(namespace); return (config != null) ? config.getPropertyNames().size() : 0; } @Override - public Integer getConfigFileNum() { - return m_configFiles.size(); + public List getConfigFileNamespaces() { + return new ArrayList<>(m_configFiles.keySet()); } - public static class NamespaceMetrics { - - private int usageCount; - private long firstLoadSpend; - private long latestUpdateTime = System.currentTimeMillis(); - private String releaseKey = ""; - - public String getReleaseKey() { - return releaseKey; - } - - public void setReleaseKey(String releaseKey) { - this.releaseKey = releaseKey; - } - - public int getUsageCount() { - return usageCount; - } - - public void incrementUsageCount() { - usageCount++; - } - - public long getFirstLoadSpend() { - return firstLoadSpend; - } - - public void setFirstLoadSpend(long firstLoadSpend) { - this.firstLoadSpend = firstLoadSpend; - } - - public long getLatestUpdateTime() { - return latestUpdateTime; - } - - public void setLatestUpdateTime(long latestUpdateTime) { - this.latestUpdateTime = latestUpdateTime; - } - } } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientThreadPoolApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientThreadPoolApi.java index 91113eca..84316629 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientThreadPoolApi.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientThreadPoolApi.java @@ -25,11 +25,7 @@ import com.ctrip.framework.apollo.monitor.internal.exporter.AbstractApolloClientMetricsExporter; import com.ctrip.framework.apollo.monitor.internal.jmx.mbean.ApolloClientJmxThreadPoolMBean; import com.ctrip.framework.apollo.monitor.internal.listener.AbstractApolloClientMonitorEventListener; -import com.ctrip.framework.apollo.monitor.internal.event.ApolloClientMonitorEvent; import com.google.common.collect.Maps; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadPoolExecutor; @@ -68,26 +64,34 @@ public void export0() { executorMap.forEach((key, value) -> exportThreadPoolMetrics(value, key)); } - private void exportThreadPoolMetrics(ApolloThreadPoolInfo info, String name) { - List metrics = Arrays.asList( - (double) info.getActiveTaskCount(), - (double) info.getQueueSize(), - (double) info.getCompletedTaskCount(), - (double) info.getPoolSize(), - (double) info.getTotalTaskCount(), - (double) info.getCorePoolSize(), - (double) info.getMaximumPoolSize(), - (double) info.getLargestPoolSize(), - (double) info.getQueueCapacity(), - (double) info.getQueueRemainingCapacity(), - info.getCurrentLoad() - ); - - for (int i = 0; i < metrics.size(); i++) { - String key = name + METRICS_THREAD_POOL_PARAMS[i + 1]; - createOrUpdateGaugeSample(key, METRICS_THREAD_POOL_PARAMS[i + 1], - Collections.singletonMap(METRICS_THREAD_POOL_PARAMS[0], name), metrics.get(i)); - } + private void exportThreadPoolMetrics(ApolloThreadPoolInfo info, String threadPoolName) { + + createOrUpdateGaugeSample(METRICS_THREAD_POOL_ACTIVE_TASK_COUNT, + new String[]{METRICS_THREAD_POOL_NAME}, new String[]{threadPoolName}, + info.getActiveTaskCount()); + createOrUpdateGaugeSample(METRICS_THREAD_POOL_QUEUE_SIZE, + new String[]{METRICS_THREAD_POOL_NAME}, new String[]{threadPoolName}, + info.getQueueSize()); + createOrUpdateGaugeSample(METRICS_THREAD_POOL_COMPLETED_TASK_COUNT, + new String[]{METRICS_THREAD_POOL_NAME}, new String[]{threadPoolName}, + (double) info.getCompletedTaskCount()); + createOrUpdateGaugeSample(METRICS_THREAD_POOL_POOL_SIZE, new String[]{METRICS_THREAD_POOL_NAME}, + new String[]{threadPoolName}, info.getPoolSize()); + createOrUpdateGaugeSample(METRICS_THREAD_POOL_TOTAL_TASK_COUNT, + new String[]{METRICS_THREAD_POOL_NAME}, new String[]{threadPoolName}, + (double) info.getTotalTaskCount()); + createOrUpdateGaugeSample(METRICS_THREAD_POOL_CORE_POOL_SIZE, + new String[]{METRICS_THREAD_POOL_NAME}, new String[]{threadPoolName}, + info.getCorePoolSize()); + createOrUpdateGaugeSample(METRICS_THREAD_POOL_MAXIMUM_POOL_SIZE, + new String[]{METRICS_THREAD_POOL_NAME}, new String[]{threadPoolName}, + info.getMaximumPoolSize()); + createOrUpdateGaugeSample(METRICS_THREAD_POOL_LARGEST_POOL_SIZE, + new String[]{METRICS_THREAD_POOL_NAME}, new String[]{threadPoolName}, + info.getLargestPoolSize()); + createOrUpdateGaugeSample(METRICS_THREAD_POOL_QUEUE_REMAINING_CAPACITY, + new String[]{METRICS_THREAD_POOL_NAME}, new String[]{threadPoolName}, + info.getQueueRemainingCapacity()); } @@ -121,57 +125,4 @@ public ApolloThreadPoolInfo getAbstractConfigFileThreadPoolInfo() { public ApolloThreadPoolInfo getMetricsExporterThreadPoolInfo() { return executorMap.get(METRICS_EXPORTER); } - - public static class ApolloThreadPoolInfo { - - private final ThreadPoolExecutor executor; - - public ApolloThreadPoolInfo(ThreadPoolExecutor executor) { - this.executor = executor; - } - - public int getActiveTaskCount() { - return executor.getActiveCount(); - } - - public int getQueueSize() { - return executor.getQueue().size(); - } - - public int getCorePoolSize() { - return executor.getCorePoolSize(); - } - - public int getMaximumPoolSize() { - return executor.getMaximumPoolSize(); - } - - public int getPoolSize() { - return executor.getPoolSize(); - } - - public long getTotalTaskCount() { - return executor.getTaskCount(); - } - - public long getCompletedTaskCount() { - return executor.getCompletedTaskCount(); - } - - public int getLargestPoolSize() { - return executor.getLargestPoolSize(); - } - - public int getQueueCapacity() { - return executor.getQueue().remainingCapacity() + executor.getQueue().size(); - } - - public int getQueueRemainingCapacity() { - return executor.getQueue().remainingCapacity(); - } - - public double getCurrentLoad() { - return (double) executor.getPoolSize() / executor.getMaximumPoolSize(); - } - } } \ No newline at end of file diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientBootstrapArgsMonitorApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientBootstrapArgsMonitorApi.java index f7b442f1..88ddd7b8 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientBootstrapArgsMonitorApi.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientBootstrapArgsMonitorApi.java @@ -28,122 +28,7 @@ public class NullClientBootstrapArgsMonitorApi implements ApolloClientBootstrapA ApolloClientJmxBootstrapArgsMBean { @Override - public String getStartupParams(String key) { - return ""; - } - - @Override - public String getConfigServiceUrl() { - return ""; - } - - @Override - public String getAccessKeySecret() { - return ""; - } - - @Override - public Boolean getAutoUpdateInjectedSpringProperties() { - return false; - } - - @Override - public Boolean getBootstrapEnabled() { - return null; - } - - @Override - public String getBootstrapNamespaces() { - return ""; - } - - @Override - public Boolean getBootstrapEagerLoadEnabled() { - return null; - } - - @Override - public Boolean getOverrideSystemProperties() { - return null; - } - - @Override - public String getCacheDir() { - return ""; - } - - @Override - public String getCluster() { - return ""; - } - - @Override - public String getConfigService() { - return ""; - } - - @Override - public Boolean getClientMonitorEnabled() { - return null; - } - - @Override - public Boolean getClientMonitorJmxEnabled() { - return null; - } - - @Override - public String getClientMonitorExternalForm() { - return ""; - } - - @Override - public long getClientMonitorExternalExportPeriod() { - return 0; - } - - @Override - public int getClientMonitorExceptionSaveSize() { - return 0; - } - - @Override - public String getApolloMeta() { - return ""; - } - - @Override - public String getMetaLatestFreshTime() { - return ""; - } - - @Override - public Boolean getPropertyNamesCacheEnable() { - return null; - } - - @Override - public Boolean getPropertyOrderEnable() { - return null; - } - - @Override - public String getVersion() { - return ""; - } - - @Override - public String getEnv() { - return ""; - } - - @Override - public String getAppId() { - return ""; - } - - @Override - public Map getBootstrapArgs() { + public Map getBootstrapArgsString() { return Collections.emptyMap(); } } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientExceptionMonitorApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientExceptionMonitorApi.java index 3f0a4bdd..5a21f802 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientExceptionMonitorApi.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientExceptionMonitorApi.java @@ -32,6 +32,11 @@ public List getApolloConfigExceptionList() { return Collections.emptyList(); } + @Override + public Integer getExceptionCountFromStartup() { + return 0; + } + @Override public List getApolloConfigExceptionDetails() { return Collections.emptyList(); diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientNamespaceMonitorApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientNamespaceMonitorApi.java index 051d00d3..9585823b 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientNamespaceMonitorApi.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientNamespaceMonitorApi.java @@ -18,7 +18,6 @@ import com.ctrip.framework.apollo.monitor.api.ApolloClientNamespaceMonitorApi; import com.ctrip.framework.apollo.monitor.internal.jmx.mbean.ApolloClientJmxNamespaceMBean; -import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientNamespaceApi.NamespaceMetrics; import java.util.Collections; import java.util.List; import java.util.Map; @@ -46,13 +45,18 @@ public List getTimeoutNamespaces() { } @Override - public Integer getNamespaceItemsNum(String namespace) { - return 0; + public Map getNamespaceMetricsString() { + return Collections.emptyMap(); } @Override - public Integer getConfigFileNum() { + public Integer getNamespacePropertySize(String namespace) { return 0; } + @Override + public List getConfigFileNamespaces() { + return Collections.emptyList(); + } + } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientThreadPoolMonitorApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientThreadPoolMonitorApi.java index 0a779adf..03e5c1b5 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientThreadPoolMonitorApi.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientThreadPoolMonitorApi.java @@ -18,7 +18,6 @@ import com.ctrip.framework.apollo.monitor.api.ApolloClientThreadPoolMonitorApi; import com.ctrip.framework.apollo.monitor.internal.jmx.mbean.ApolloClientJmxThreadPoolMBean; -import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientThreadPoolApi.ApolloThreadPoolInfo; import java.util.Collections; import java.util.Map; @@ -28,6 +27,8 @@ public class NullClientThreadPoolMonitorApi implements ApolloClientThreadPoolMonitorApi, ApolloClientJmxThreadPoolMBean { + private final ApolloThreadPoolInfo NULL_THREAD_POOL_INFO = new ApolloThreadPoolInfo(); + @Override public Map getThreadPoolInfo() { return Collections.emptyMap(); @@ -35,21 +36,21 @@ public Map getThreadPoolInfo() { @Override public ApolloThreadPoolInfo getRemoteConfigRepositoryThreadPoolInfo() { - return null; + return NULL_THREAD_POOL_INFO; } @Override public ApolloThreadPoolInfo getAbstractConfigThreadPoolInfo() { - return null; + return NULL_THREAD_POOL_INFO; } @Override public ApolloThreadPoolInfo getAbstractConfigFileThreadPoolInfo() { - return null; + return NULL_THREAD_POOL_INFO; } @Override public ApolloThreadPoolInfo getMetricsExporterThreadPoolInfo() { - return null; + return NULL_THREAD_POOL_INFO; } } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/CounterModel.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/CounterModel.java index 610d61cd..566ce718 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/CounterModel.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/CounterModel.java @@ -16,7 +16,7 @@ */ package com.ctrip.framework.apollo.monitor.internal.model; -import com.ctrip.framework.apollo.monitor.internal.enums.MeterEnums; +import com.ctrip.framework.apollo.monitor.internal.enums.MetricTypeEnums; /** * @author Rawven @@ -31,7 +31,7 @@ private CounterModel(String name, double num) { throw new IllegalArgumentException("Number must be a valid double"); } setName(name); - setType(MeterEnums.COUNTER); + setType(MetricTypeEnums.COUNTER); this.value.set(num); } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/GaugeModel.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/GaugeModel.java index 91150100..0abf0699 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/GaugeModel.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/GaugeModel.java @@ -16,8 +16,7 @@ */ package com.ctrip.framework.apollo.monitor.internal.model; -import com.ctrip.framework.apollo.monitor.internal.enums.MeterEnums; -import com.google.common.util.concurrent.AtomicDouble; +import com.ctrip.framework.apollo.monitor.internal.enums.MetricTypeEnums; /** * @author Rawven @@ -29,7 +28,7 @@ private GaugeModel(String name, double value) { throw new IllegalArgumentException("Name cannot be null or empty"); } setName(name); - setType(MeterEnums.GAUGE); + setType(MetricTypeEnums.GAUGE); this.value.set(value); } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/SampleModel.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/SampleModel.java index c59c80b4..177d7bd3 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/SampleModel.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/SampleModel.java @@ -16,9 +16,7 @@ */ package com.ctrip.framework.apollo.monitor.internal.model; -import static com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorConstant.APOLLO_CLIENT; - -import com.ctrip.framework.apollo.monitor.internal.enums.MeterEnums; +import com.ctrip.framework.apollo.monitor.internal.enums.MetricTypeEnums; import com.google.common.util.concurrent.AtomicDouble; import java.util.Collections; import java.util.HashMap; @@ -32,14 +30,14 @@ public class SampleModel { protected final AtomicDouble value = new AtomicDouble(); private final Map tags = new HashMap<>(1); private String name; - private MeterEnums type; + private MetricTypeEnums type; public String getName() { return name; } public void setName(String name) { - this.name = APOLLO_CLIENT + name; + this.name = name; } public SampleModel putTag(String key, String value) { @@ -52,11 +50,11 @@ public SampleModel putTags(Map tags) { return this; } - public MeterEnums getType() { + public MetricTypeEnums getType() { return type; } - public void setType(MeterEnums type) { + public void setType(MetricTypeEnums type) { this.type = type; } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMessageProducerComposite.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMessageProducerComposite.java index 319baa38..8ae27a72 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMessageProducerComposite.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMessageProducerComposite.java @@ -20,7 +20,6 @@ import com.ctrip.framework.apollo.tracer.spi.MessageProducer; import com.ctrip.framework.apollo.tracer.spi.Transaction; import java.util.List; -import java.util.Objects; /** * message producer composite diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMonitorMessageProducer.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMonitorMessageProducer.java index 9397b5e5..6fb681c7 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMonitorMessageProducer.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMonitorMessageProducer.java @@ -21,8 +21,8 @@ import com.ctrip.framework.apollo.exceptions.ApolloConfigException; -import com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorConstant; import com.ctrip.framework.apollo.monitor.internal.event.ApolloClientMonitorEventFactory; +import com.ctrip.framework.apollo.monitor.internal.event.ApolloClientMonitorEventPublisher; import com.ctrip.framework.apollo.tracer.spi.MessageProducer; import com.ctrip.framework.apollo.tracer.spi.Transaction; import java.time.Instant; @@ -69,17 +69,10 @@ public void logEvent(String type, String name) { } } - private void publishErrorEvent(String tag, Throwable cause) { - ApolloClientMonitorEventFactory.getInstance().createEvent(tag) - .withTag(tag) - .putAttachment(THROWABLE, cause) - .publish(); - } - private void handleTaggedEvent(String type, String name) { switch (type) { case APOLLO_CONFIGSERVICE: - name = name.substring(HELP_STR.length()); + name = name.substring(APOLLO_CONFIGSERVICE_HELP_STR.length()); // fall through case APOLLO_CLIENT_CONFIGCHANGES: publishConfigChangeEvent(name); @@ -110,68 +103,76 @@ private void handleTaggedEvent(String type, String name) { } } + + private void publishErrorEvent(String tag, Throwable cause) { + ApolloClientMonitorEventPublisher.publish( + ApolloClientMonitorEventFactory.getInstance().createEvent(tag) + .withTag(tag) + .putAttachment(THROWABLE, cause)); + } + private void publishConfigChangeEvent(String name) { - ApolloClientMonitorEventFactory.getInstance() - .createEvent(METRICS_NAMESPACE_LATEST_UPDATE_TIME) - .putAttachment(NAMESPACE, name) - .putAttachment(TIMESTAMP, System.currentTimeMillis()) - .withTag(TAG_NAMESPACE) - .publish(); + ApolloClientMonitorEventPublisher.publish( + ApolloClientMonitorEventFactory.getInstance() + .createEvent(METRICS_NAMESPACE_LATEST_UPDATE_TIME) + .putAttachment(NAMESPACE, name) + .withTag(TAG_NAMESPACE)); } private void publishMetaServiceEvent() { - ApolloClientMonitorEventFactory.getInstance().createEvent(META_FRESH) - .withTag(TAG_BOOTSTRAP) - .putAttachment(META_FRESH, DATE_FORMATTER.format(Instant.now())) - .publish(); + ApolloClientMonitorEventPublisher.publish( + ApolloClientMonitorEventFactory.getInstance().createEvent(META_FRESH) + .withTag(TAG_BOOTSTRAP) + .putAttachment(META_FRESH, DATE_FORMATTER.format(Instant.now()))); } private void publishConfigServiceEvent(String name) { - ApolloClientMonitorEventFactory.getInstance().createEvent(CONFIG_SERVICE_URL) - .withTag(TAG_BOOTSTRAP) - .putAttachment(CONFIG_SERVICE_URL, name) - .publish(); + ApolloClientMonitorEventPublisher.publish( + ApolloClientMonitorEventFactory.getInstance().createEvent(CONFIG_SERVICE_URL) + .withTag(TAG_BOOTSTRAP) + .putAttachment(CONFIG_SERVICE_URL, name)); } private void publishClientVersionEvent(String name) { - ApolloClientMonitorEventFactory.getInstance().createEvent(VERSION) - .withTag(TAG_BOOTSTRAP) - .putAttachment(VERSION, name) - .publish(); + ApolloClientMonitorEventPublisher.publish( + ApolloClientMonitorEventFactory.getInstance().createEvent(VERSION) + .withTag(TAG_BOOTSTRAP) + .putAttachment(VERSION, name)); } private void publishNamespaceTimeoutEvent(String name) { - ApolloClientMonitorEventFactory.getInstance().createEvent(APOLLO_CLIENT_NAMESPACE_TIMEOUT) - .putAttachment(NAMESPACE, name) - .withTag(TAG_NAMESPACE) - .publish(); + ApolloClientMonitorEventPublisher.publish( + ApolloClientMonitorEventFactory.getInstance().createEvent(APOLLO_CLIENT_NAMESPACE_TIMEOUT) + .putAttachment(NAMESPACE, name) + .withTag(TAG_NAMESPACE)); } private void publishNamespaceNotFoundEvent(String name) { - ApolloClientMonitorEventFactory.getInstance().createEvent(APOLLO_CLIENT_NAMESPACE_NOT_FOUND) - .withTag(TAG_NAMESPACE) - .putAttachment(NAMESPACE, name) - .publish(); + ApolloClientMonitorEventPublisher.publish( + ApolloClientMonitorEventFactory.getInstance().createEvent(APOLLO_CLIENT_NAMESPACE_NOT_FOUND) + .withTag(TAG_NAMESPACE) + .putAttachment(NAMESPACE, name)); } private void handleClientConfigEvent(String type, String name) { String namespace = type.substring(APOLLO_CLIENT_CONFIGS.length()); - ApolloClientMonitorEventFactory.getInstance().createEvent(NAMESPACE_RELEASE_KEY) - .withTag(TAG_NAMESPACE) - .putAttachment(NAMESPACE_RELEASE_KEY, name) - .putAttachment(NAMESPACE, namespace) - .publish(); + ApolloClientMonitorEventPublisher.publish( + ApolloClientMonitorEventFactory.getInstance().createEvent(NAMESPACE_RELEASE_KEY) + .withTag(TAG_NAMESPACE) + .putAttachment(NAMESPACE_RELEASE_KEY, name) + .putAttachment(NAMESPACE, namespace)); } private void handleFirstLoadTimeEvent(String type, String name) { - String namespace = type.substring(APOLLO_CLIENT_NAMESPACE_FIRST_LOAD_SPEND.length()); + String[] split = type.split(":"); + String namespace = split[1]; long firstLoadTime = Long.parseLong(name); - ApolloClientMonitorEventFactory.getInstance() - .createEvent(APOLLO_CLIENT_NAMESPACE_FIRST_LOAD_SPEND) - .putAttachment(NAMESPACE, namespace) - .putAttachment(TIMESTAMP, firstLoadTime) - .withTag(TAG_NAMESPACE) - .publish(); + ApolloClientMonitorEventPublisher.publish( + ApolloClientMonitorEventFactory.getInstance() + .createEvent(APOLLO_CLIENT_NAMESPACE_FIRST_LOAD_SPEND) + .putAttachment(NAMESPACE, namespace) + .putAttachment(TIMESTAMP, firstLoadTime) + .withTag(TAG_NAMESPACE)); } @Override @@ -183,10 +184,11 @@ public void logEvent(String type, String name, String status, String nameValuePa public void logMetricsForCount(String name) { String[] split = name.split(":"); if (split.length == 2 && APOLLO_CLIENT_NAMESPACE_USAGE.equals(split[0])) { - ApolloClientMonitorEventFactory.getInstance().createEvent(APOLLO_CLIENT_NAMESPACE_USAGE) - .putAttachment(ApolloClientMonitorConstant.NAMESPACE, split[1]) - .withTag(TAG_NAMESPACE) - .publish(); + ApolloClientMonitorEventPublisher.publish( + ApolloClientMonitorEventFactory.getInstance() + .createEvent(APOLLO_CLIENT_NAMESPACE_USAGE) + .putAttachment(NAMESPACE, split[1]) + .withTag(TAG_NAMESPACE)); } } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/util/ConfigUtil.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/util/ConfigUtil.java index 123c69df..ec2bb85f 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/util/ConfigUtil.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/util/ConfigUtil.java @@ -543,7 +543,7 @@ private void initClientMonitorEnabled() { clientMonitorEnabled = Boolean.parseBoolean(enabled); } - public boolean getClientMonitorEnabled() { + public boolean isClientMonitorEnabled() { return clientMonitorEnabled; } @@ -555,7 +555,7 @@ private void initClientMonitorJmxEnabled() { } clientMonitorJmxEnabled = Boolean.parseBoolean(enabled); } - public boolean getClientMonitorJmxEnabled() { + public boolean isClientMonitorJmxEnabled() { return clientMonitorJmxEnabled; } private void initClientMonitorExceptionQueueSize() { @@ -566,6 +566,9 @@ private void initClientMonitorExceptionQueueSize() { } } public int getMonitorExceptionQueueSize() { + if(monitorExceptionQueueSize <= 0){ + monitorExceptionQueueSize = 25; + } return monitorExceptionQueueSize; } diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/ConfigMonitorInitializerTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/ConfigMonitorInitializerTest.java deleted file mode 100644 index 6db638c7..00000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/ConfigMonitorInitializerTest.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright 2022 Apollo Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.ctrip.framework.apollo.internals; - -import static org.mockito.Mockito.*; -import static org.junit.Assert.*; - -import com.ctrip.framework.apollo.build.MockInjector; -import com.ctrip.framework.apollo.monitor.api.ConfigMonitor; -import com.ctrip.framework.apollo.monitor.internal.DefaultConfigMonitor; -import com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporter; -import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMonitorEventListener; -import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMonitorEventListenerManager; -import com.ctrip.framework.apollo.monitor.internal.listener.DefaultApolloClientMonitorEventListenerManager; -import com.ctrip.framework.apollo.monitor.internal.tracer.ApolloClientMessageProducerComposite; -import com.ctrip.framework.apollo.util.ConfigUtil; -import java.util.Collections; -import java.util.List; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.Logger; - -public class ConfigMonitorInitializerTest { - - private ConfigUtil mockConfigUtil; - private Logger mockLogger; - private DefaultApolloClientMonitorEventListenerManager mockManager; - private ApolloClientMetricsExporter mockMetricsExporter; - private DefaultConfigManager mockConfigManager; - private DefaultConfigMonitor mockConfigMonitor; - - @Before - public void setUp() { - mockConfigUtil = mock(ConfigUtil.class); - when(mockConfigUtil.getMonitorExceptionQueueSize()).thenReturn(100); - when(mockConfigUtil.getClientMonitorEnabled()).thenReturn(false); - mockLogger = mock(Logger.class); - mockManager = mock(DefaultApolloClientMonitorEventListenerManager.class); - mockMetricsExporter = mock(ApolloClientMetricsExporter.class); - mockConfigManager = mock(DefaultConfigManager.class); - mockConfigMonitor = mock(DefaultConfigMonitor.class); - - - // Mock static methods - MockInjector.setInstance(ConfigUtil.class, mockConfigUtil); - MockInjector.setInstance(ApolloClientMonitorEventListenerManager.class, mockManager); - MockInjector.setInstance(ConfigManager.class, mockConfigManager); - MockInjector.setInstance(ConfigMonitor.class, mockConfigMonitor); - - // Reset static state before each test - ConfigMonitorInitializer.reset(); - } - - @Test - public void testInitialize_WhenEnabledAndNotInitialized() { - when(mockManager.getCollectors()).thenReturn(Collections.emptyList()); - doReturn(true).when(mockConfigUtil).getClientMonitorEnabled(); - ConfigMonitorInitializer.initialize(); - - verify(mockManager).setCollectors(anyList()); - verify(mockConfigMonitor).init(any(), any(), any(), any(), any()); - assertTrue(ConfigMonitorInitializer.hasInitialized); // Check hasInitialized flag - } - - @Test - public void testInitialize_WhenAlreadyInitialized() { - ConfigMonitorInitializer.hasInitialized = true; - - ConfigMonitorInitializer.initialize(); - - verify(mockConfigMonitor, never()).init(any(), any(), any(), any(), any()); - } - - @Test - public void testInitialize_WhenClientMonitorDisabled() { - when(mockConfigUtil.getClientMonitorEnabled()).thenReturn(false); - - ConfigMonitorInitializer.initialize(); - - verify(mockManager, never()).setCollectors(anyList()); - verify(mockConfigMonitor, never()).init(any(), any(), any(), any(), any()); - } - - @Test - public void testInitializeMessageProducerComposite() { - when(mockConfigUtil.getClientMonitorEnabled()).thenReturn(true); - - ApolloClientMessageProducerComposite composite = ConfigMonitorInitializer.initializeMessageProducerComposite(); - - assertNotNull(composite); - // Additional assertions can be added based on expected behavior - } - @Test - public void testInitializeJmxMonitoring() { - when(mockConfigUtil.getClientMonitorJmxEnabled()).thenReturn(true); - ApolloClientMonitorEventListener metricsCollector = mock(ApolloClientMonitorEventListener.class); - List collectors = Collections.singletonList(metricsCollector); - - ConfigMonitorInitializer.initializeJmxMonitoring(collectors); - verify(metricsCollector).mBeanName(); - } - -} \ No newline at end of file diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/DefaultConfigMonitorTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/DefaultConfigMonitorTest.java deleted file mode 100644 index beeaf45c..00000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/DefaultConfigMonitorTest.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright 2022 Apollo Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.ctrip.framework.apollo.monitor.internal; - -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; - -import com.ctrip.framework.apollo.monitor.api.ApolloClientBootstrapArgsMonitorApi; -import com.ctrip.framework.apollo.monitor.api.ApolloClientExceptionMonitorApi; -import com.ctrip.framework.apollo.monitor.api.ApolloClientNamespaceMonitorApi; -import com.ctrip.framework.apollo.monitor.api.ApolloClientThreadPoolMonitorApi; -import com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporter; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -public class DefaultConfigMonitorTest { - - private DefaultConfigMonitor configMonitor; - - @Mock - private ApolloClientMetricsExporter reporter; - - @Mock - private ApolloClientThreadPoolMonitorApi threadPoolMonitorApi; - - @Mock - private ApolloClientExceptionMonitorApi exceptionMonitorApi; - - @Mock - private ApolloClientNamespaceMonitorApi namespaceMonitorApi; - - @Mock - private ApolloClientBootstrapArgsMonitorApi bootstrapArgsMonitorApi; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - configMonitor = new DefaultConfigMonitor(); - } - - @Test - public void testInit() { - configMonitor.init(namespaceMonitorApi, threadPoolMonitorApi, exceptionMonitorApi, - bootstrapArgsMonitorApi, reporter); - - assertEquals(namespaceMonitorApi, configMonitor.getNamespaceMonitorApi()); - assertEquals(threadPoolMonitorApi, configMonitor.getThreadPoolMonitorApi()); - assertEquals(exceptionMonitorApi, configMonitor.getExceptionMonitorApi()); - assertEquals(bootstrapArgsMonitorApi, configMonitor.getRunningParamsMonitorApi()); - } - - @Test - public void testGetExporterData() { - when(reporter.response()).thenReturn("exporter data"); - - configMonitor.init(namespaceMonitorApi, threadPoolMonitorApi, exceptionMonitorApi, - bootstrapArgsMonitorApi, reporter); - - String result = configMonitor.getExporterData(); - - assertEquals("exporter data", result); - verify(reporter).response(); - } - - @Test - public void testDefaultInstances() { - assertNotNull(configMonitor.getThreadPoolMonitorApi()); - assertNotNull(configMonitor.getExceptionMonitorApi()); - assertNotNull(configMonitor.getNamespaceMonitorApi()); - assertNotNull(configMonitor.getRunningParamsMonitorApi()); - assertEquals("No Reporter Use", - configMonitor.getExporterData()); // Assuming NullApolloClientMetricsExporter returns "null" - } -} \ No newline at end of file diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/event/ApolloClientMonitorEventPublisherTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/event/ApolloClientMonitorEventPublisherTest.java index 2119b25a..aed0cdd9 100644 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/event/ApolloClientMonitorEventPublisherTest.java +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/event/ApolloClientMonitorEventPublisherTest.java @@ -20,7 +20,7 @@ import com.ctrip.framework.apollo.build.MockInjector; import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMonitorEventListener; -import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMonitorEventListenerManager; +import com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorContext; import com.ctrip.framework.apollo.util.ConfigUtil; import org.junit.Before; import org.junit.Test; @@ -29,29 +29,29 @@ public class ApolloClientMonitorEventPublisherTest { - private ApolloClientMonitorEventListenerManager mockCollectorManager; + private ApolloClientMonitorContext mockCollectorManager; private ConfigUtil mockConfigUtil; private ApolloClientMonitorEventListener mockCollector; private ApolloClientMonitorEvent mockEvent; @Before public void setUp() { - mockCollectorManager = mock(ApolloClientMonitorEventListenerManager.class); + mockCollectorManager = mock(ApolloClientMonitorContext.class); mockConfigUtil = mock(ConfigUtil.class); mockCollector = mock(ApolloClientMonitorEventListener.class); mockEvent = mock(ApolloClientMonitorEvent.class); // 使用 Mockito 来模拟静态方法 - MockInjector.setInstance(ApolloClientMonitorEventListenerManager.class, mockCollectorManager); + MockInjector.setInstance(ApolloClientMonitorContext.class, mockCollectorManager); MockInjector.setInstance(ConfigUtil.class, mockConfigUtil); ApolloClientMonitorEventPublisher.reset(); } @Test public void testPublish_WhenClientMonitorEnabled_CollectorSupportsEvent() { - when(mockConfigUtil.getClientMonitorEnabled()).thenReturn(true); + when(mockConfigUtil.isClientMonitorEnabled()).thenReturn(true); when(mockCollectorManager.getCollectors()).thenReturn(Collections.singletonList(mockCollector)); - when(mockCollector.isSupport(mockEvent)).thenReturn(true); + when(mockCollector.isSupported(mockEvent)).thenReturn(true); ApolloClientMonitorEventPublisher.publish(mockEvent); @@ -60,9 +60,9 @@ public void testPublish_WhenClientMonitorEnabled_CollectorSupportsEvent() { @Test public void testPublish_WhenClientMonitorEnabled_CollectorDoesNotSupportEvent() { - when(mockConfigUtil.getClientMonitorEnabled()).thenReturn(true); + when(mockConfigUtil.isClientMonitorEnabled()).thenReturn(true); when(mockCollectorManager.getCollectors()).thenReturn(Collections.singletonList(mockCollector)); - when(mockCollector.isSupport(mockEvent)).thenReturn(false); + when(mockCollector.isSupported(mockEvent)).thenReturn(false); ApolloClientMonitorEventPublisher.publish(mockEvent); @@ -71,7 +71,7 @@ public void testPublish_WhenClientMonitorEnabled_CollectorDoesNotSupportEvent() @Test public void testPublish_WhenClientMonitorDisabled() { - when(mockConfigUtil.getClientMonitorEnabled()).thenReturn(false); + when(mockConfigUtil.isClientMonitorEnabled()).thenReturn(false); ApolloClientMonitorEventPublisher.publish(mockEvent); diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractApolloClientMetricsExporterTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractApolloClientMetricsExporterTest.java index 8728c0c2..15df2204 100644 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractApolloClientMetricsExporterTest.java +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractApolloClientMetricsExporterTest.java @@ -19,7 +19,7 @@ import static org.junit.Assert.*; import static org.mockito.Mockito.*; -import com.ctrip.framework.apollo.monitor.internal.enums.MeterEnums; +import com.ctrip.framework.apollo.monitor.internal.enums.MetricTypeEnums; import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMonitorEventListener; import com.ctrip.framework.apollo.monitor.internal.model.CounterModel; import com.ctrip.framework.apollo.monitor.internal.model.GaugeModel; @@ -58,7 +58,7 @@ public void testInit() { public void testUpdateMetricsData() { List samples = new ArrayList<>(); GaugeModel gauge = mock(GaugeModel.class); - when(gauge.getType()).thenReturn(MeterEnums.GAUGE); + when(gauge.getType()).thenReturn(MetricTypeEnums.GAUGE); when(gauge.getName()).thenReturn("testGauge"); when(gauge.getValue()).thenReturn(10.0); samples.add(gauge); diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/DefaultApolloClientMetricsExporterFactoryTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/DefaultApolloClientMetricsExporterFactoryTest.java index f8c32b0d..57908315 100644 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/DefaultApolloClientMetricsExporterFactoryTest.java +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/DefaultApolloClientMetricsExporterFactoryTest.java @@ -61,9 +61,9 @@ public void testGetMetricsReporter_NoExternalSystemType() { @Test public void testGetMetricsReporter_ExporterFound() { when(configUtil.getMonitorExternalType()).thenReturn("mocktheus"); - when(configUtil.getClientMonitorJmxEnabled()).thenReturn(true); + when(configUtil.isClientMonitorJmxEnabled()).thenReturn(true); when(configUtil.getMonitorExternalExportPeriod()).thenReturn(1000L); - when(metricsCollector.mBeanName()).thenReturn("testMBean"); + when(metricsCollector.getName()).thenReturn("testMBean"); List collectors = Collections.singletonList(metricsCollector); ApolloClientMetricsExporter result = factory.getMetricsReporter(collectors); diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/AbstractApolloClientMonitorEventListenerTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/AbstractApolloClientMonitorEventListenerTest.java deleted file mode 100644 index 1a60c02f..00000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/AbstractApolloClientMonitorEventListenerTest.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright 2022 Apollo Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.ctrip.framework.apollo.monitor.internal.listener; - -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; - -import com.ctrip.framework.apollo.monitor.internal.event.ApolloClientMonitorEvent; -import com.ctrip.framework.apollo.monitor.internal.model.CounterModel; -import com.ctrip.framework.apollo.monitor.internal.model.GaugeModel; -import com.ctrip.framework.apollo.monitor.internal.model.SampleModel; -import org.junit.Before; -import org.junit.Test; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class AbstractApolloClientMonitorEventListenerTest { - - private TestMonitorEventListener listener; - private ApolloClientMonitorEvent event; - - @Before - public void setUp() { - listener = new TestMonitorEventListener("testTag"); - event = mock(ApolloClientMonitorEvent.class); - when(event.getTag()).thenReturn("testTag"); - } - - @Test - public void testCollect() { - listener.collect(event); - assertTrue(listener.isMetricsSampleUpdated()); - } - - @Test - public void testIsSupport() { - assertTrue(listener.isSupport(event)); - when(event.getTag()).thenReturn("otherTag"); - assertFalse(listener.isSupport(event)); - } - - @Test - public void testExport() { - listener.collect(event); - List samples = listener.export(); - assertNotNull(samples); - assertTrue(samples.isEmpty()); // 应为空,因为尚未添加样本 - } - - @Test - public void testCreateOrUpdateGaugeSample() { - String mapKey = "gauge1"; - String metricsName = "testGauge"; - Map tags = new HashMap<>(); - tags.put("key", "value"); - - listener.createOrUpdateGaugeSample(mapKey, metricsName, tags, 42.0); - - List samples = listener.export(); - assertEquals(1, samples.size()); - assertTrue(samples.get(0) instanceof GaugeModel); - assertEquals(42.0, ((GaugeModel) samples.get(0)).getValue(), 0.01); - } - - @Test - public void testCreateOrUpdateCounterSample() { - String mapKey = "counter1"; - String metricsName = "testCounter"; - Map tags = new HashMap<>(); - tags.put("key", "value"); - - listener.createOrUpdateCounterSample(mapKey, metricsName, tags, 5.0); - - List samples = listener.export(); - assertEquals(1, samples.size()); - assertTrue(samples.get(0) instanceof CounterModel); - assertEquals(5.0, ((CounterModel) samples.get(0)).getValue(), 0.01); - } - - private class TestMonitorEventListener extends AbstractApolloClientMonitorEventListener { - - public TestMonitorEventListener(String tag) { - super(tag); - } - - @Override - protected void collect0(ApolloClientMonitorEvent event) { - // 简单的收集逻辑 - } - - @Override - protected void export0() { - // 模拟导出逻辑 - } - } -} \ No newline at end of file diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/DefaultApolloClientMonitorEventListenerManagerTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/DefaultApolloClientMonitorEventListenerManagerTest.java deleted file mode 100644 index 46e3cf8e..00000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/DefaultApolloClientMonitorEventListenerManagerTest.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2022 Apollo Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.ctrip.framework.apollo.monitor.internal.listener; - -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; - -import org.junit.Before; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -public class DefaultApolloClientMonitorEventListenerManagerTest { - - private DefaultApolloClientMonitorEventListenerManager manager; - - @Before - public void setUp() { - manager = new DefaultApolloClientMonitorEventListenerManager(); - } - - @Test - public void testInitialCollectors() { - List collectors = manager.getCollectors(); - assertNotNull(collectors); - assertTrue(collectors.isEmpty()); // 初始状态应该为空列表 - } - - @Test - public void testSetCollectors() { - ApolloClientMonitorEventListener mockListener = mock(ApolloClientMonitorEventListener.class); - List newCollectors = new ArrayList<>(); - newCollectors.add(mockListener); - - manager.setCollectors(newCollectors); - List collectors = manager.getCollectors(); - - assertNotNull(collectors); - assertEquals(1, collectors.size()); - assertEquals(mockListener, collectors.get(0)); // 验证设置的监听器 - } - - @Test - public void testSetEmptyCollectors() { - manager.setCollectors(Collections.emptyList()); - List collectors = manager.getCollectors(); - - assertNotNull(collectors); - assertTrue(collectors.isEmpty()); // 设置为空列表后应该为空 - } -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientBootstrapArgsApiTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientBootstrapArgsApiTest.java index 12a1b63b..c37699e1 100644 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientBootstrapArgsApiTest.java +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientBootstrapArgsApiTest.java @@ -83,7 +83,7 @@ public void testUnhandledEvent() { @Test public void testGetBootstrapArgs() { - Map bootstrapArgs = api.getBootstrapArgs(); + Map bootstrapArgs = api.getBootstrapArgs(); assertNotNull(bootstrapArgs); assertTrue(bootstrapArgs.containsKey(APOLLO_ACCESS_KEY_SECRET)); } diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientNamespaceApiTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientNamespaceApiTest.java index 11fd102b..73621a13 100644 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientNamespaceApiTest.java +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientNamespaceApiTest.java @@ -26,6 +26,8 @@ import com.ctrip.framework.apollo.Config; import com.ctrip.framework.apollo.ConfigFile; import com.ctrip.framework.apollo.monitor.internal.event.ApolloClientMonitorEvent; +import java.util.List; +import java.util.Set; import org.junit.Before; import org.junit.Test; @@ -82,19 +84,19 @@ public void testCollectNamespaceUsage() { } @Test - public void testGetNamespaceItemsNum() { + public void testGetNamespacePropertySize() { Config mockConfig = mock(Config.class); when(mockConfig.getPropertyNames()).thenReturn(Sets.newSet("key1", "key2")); configs.put("testNamespace", mockConfig); - Integer testNamespace = api.getNamespaceItemsNum("testNamespace"); + Integer testNamespace = api.getNamespacePropertySize("testNamespace"); assertEquals(2, testNamespace.intValue()); } @Test - public void testGetConfigFileNum() { + public void testGetConfigFileNamespaces() { ConfigFile mockConfigFile = mock(ConfigFile.class); configFiles.put("testNamespace", mockConfigFile); - Integer testNamespace = api.getConfigFileNum(); - assertEquals(1, testNamespace.intValue()); + List configFileNum = api.getConfigFileNamespaces(); + assertEquals(1, configFileNum.size()); } } \ No newline at end of file diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientThreadPoolApiTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientThreadPoolApiTest.java index 9c12fdfe..f1d93b23 100644 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientThreadPoolApiTest.java +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientThreadPoolApiTest.java @@ -16,15 +16,13 @@ */ package com.ctrip.framework.apollo.monitor.internal.listener.impl; -import static org.mockito.Mockito.*; import static org.junit.Assert.*; -import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientThreadPoolApi.ApolloThreadPoolInfo; +import com.ctrip.framework.apollo.monitor.api.ApolloClientThreadPoolMonitorApi.ApolloThreadPoolInfo; import lombok.SneakyThrows; import org.junit.Before; import org.junit.Test; -import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; @@ -89,6 +87,6 @@ public void testGetAbstractConfigFileThreadPoolInfo() { ApolloThreadPoolInfo info = threadPoolApi.getAbstractConfigFileThreadPoolInfo(); assertNotNull(info); } - - + + } diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientBootstrapArgsMonitorApiTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientBootstrapArgsMonitorApiTest.java index 04304a55..d8ece6a1 100644 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientBootstrapArgsMonitorApiTest.java +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientBootstrapArgsMonitorApiTest.java @@ -34,7 +34,7 @@ public void setUp() { @Test public void testGetStartupParams() { - assertEquals("", bootstrapArgsMonitorApi.getStartupParams("testKey")); + assertEquals(null, bootstrapArgsMonitorApi.getStartupArg("testKey")); } @Test @@ -53,8 +53,8 @@ public void testGetAutoUpdateInjectedSpringProperties() { } @Test - public void testGetBootstrapEnabled() { - assertNull(bootstrapArgsMonitorApi.getBootstrapEnabled()); + public void testIsBootstrapEnabled() { + assertFalse(bootstrapArgsMonitorApi.isBootstrapEnabled()); } @Test @@ -63,13 +63,13 @@ public void testGetBootstrapNamespaces() { } @Test - public void testGetBootstrapEagerLoadEnabled() { - assertNull(bootstrapArgsMonitorApi.getBootstrapEagerLoadEnabled()); + public void testIsBootstrapEagerLoadEnabled() { + assertFalse(bootstrapArgsMonitorApi.isBootstrapEagerLoadEnabled()); } @Test - public void testGetOverrideSystemProperties() { - assertNull(bootstrapArgsMonitorApi.getOverrideSystemProperties()); + public void testIsOverrideSystemProperties() { + assertFalse(bootstrapArgsMonitorApi.isOverrideSystemProperties()); } @Test @@ -88,13 +88,13 @@ public void testGetConfigService() { } @Test - public void testGetClientMonitorEnabled() { - assertNull(bootstrapArgsMonitorApi.getClientMonitorEnabled()); + public void testIsClientMonitorEnabled() { + assertFalse(bootstrapArgsMonitorApi.isClientMonitorEnabled()); } @Test - public void testGetClientMonitorJmxEnabled() { - assertNull(bootstrapArgsMonitorApi.getClientMonitorJmxEnabled()); + public void testIsClientMonitorJmxEnabled() { + assertFalse(bootstrapArgsMonitorApi.isClientMonitorJmxEnabled()); } @Test @@ -123,13 +123,13 @@ public void testGetMetaLatestFreshTime() { } @Test - public void testGetPropertyNamesCacheEnable() { - assertNull(bootstrapArgsMonitorApi.getPropertyNamesCacheEnable()); + public void testIsPropertyNamesCacheEnable() { + assertFalse(bootstrapArgsMonitorApi.isPropertyNamesCacheEnable()); } @Test - public void testGetPropertyOrderEnable() { - assertNull(bootstrapArgsMonitorApi.getPropertyOrderEnable()); + public void testIsPropertyOrderEnable() { + assertFalse(bootstrapArgsMonitorApi.isPropertyOrderEnable()); } @Test @@ -149,7 +149,7 @@ public void testGetAppId() { @Test public void testGetBootstrapArgs() { - Map bootstrapArgs = bootstrapArgsMonitorApi.getBootstrapArgs(); + Map bootstrapArgs = bootstrapArgsMonitorApi.getBootstrapArgs(); assertNotNull(bootstrapArgs); assertTrue(bootstrapArgs.isEmpty()); diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientNamespaceMonitorApiTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientNamespaceMonitorApiTest.java index cddf6b2c..8bfea39e 100644 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientNamespaceMonitorApiTest.java +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientNamespaceMonitorApiTest.java @@ -18,7 +18,8 @@ import static org.junit.Assert.*; -import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientNamespaceApi.NamespaceMetrics; +import com.ctrip.framework.apollo.monitor.api.ApolloClientNamespaceMonitorApi.NamespaceMetrics; +import java.util.Set; import org.junit.Before; import org.junit.Test; @@ -44,15 +45,15 @@ public void testGetNamespaceMetrics() { @Test public void testGetNamespaceItemNames() { - Integer testNamespace = namespaceMonitorApi.getNamespaceItemsNum("testNamespace"); + Integer testNamespace = namespaceMonitorApi.getNamespacePropertySize("testNamespace"); assertEquals(0, testNamespace.intValue()); } - + @Test - public void testGetConfigFileNum() { - Integer configFileNum = namespaceMonitorApi.getConfigFileNum(); - assertEquals(0, configFileNum.intValue()); + public void testGetConfigFileNamespaces() { + List configFileNamespaces = namespaceMonitorApi.getConfigFileNamespaces(); + assertEquals(0, configFileNamespaces.size()); } @Test diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientThreadPoolMonitorApiTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientThreadPoolMonitorApiTest.java index 2bd393f2..81f812c7 100644 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientThreadPoolMonitorApiTest.java +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientThreadPoolMonitorApiTest.java @@ -17,9 +17,8 @@ package com.ctrip.framework.apollo.monitor.internal.listener.impl; import static org.junit.Assert.*; -import static org.mockito.Mockito.*; -import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientThreadPoolApi.ApolloThreadPoolInfo; +import com.ctrip.framework.apollo.monitor.api.ApolloClientThreadPoolMonitorApi.ApolloThreadPoolInfo; import org.junit.Before; import org.junit.Test; @@ -45,21 +44,8 @@ public void testGetThreadPoolInfo() { @Test public void testGetRemoteConfigRepositoryThreadPoolInfo() { ApolloThreadPoolInfo info = monitorApi.getRemoteConfigRepositoryThreadPoolInfo(); - - assertNull(info); - } - - @Test - public void testGetAbstractConfigThreadPoolInfo() { - ApolloThreadPoolInfo info = monitorApi.getAbstractConfigThreadPoolInfo(); - - assertNull(info); - } - - @Test - public void testGetAbstractConfigFileThreadPoolInfo() { - ApolloThreadPoolInfo info = monitorApi.getAbstractConfigFileThreadPoolInfo(); - - assertNull(info); + assertNotNull(info); + assertEquals(0, info.getPoolSize()); } + } diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/stress/ApolloClientMonitorStressTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/stress/ApolloClientMonitorStressTest.java index 4e4149e3..778bd527 100644 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/stress/ApolloClientMonitorStressTest.java +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/stress/ApolloClientMonitorStressTest.java @@ -20,18 +20,19 @@ import com.ctrip.framework.apollo.ConfigService; import com.ctrip.framework.apollo.monitor.internal.event.ApolloClientMonitorEventFactory; +import com.ctrip.framework.apollo.monitor.internal.event.ApolloClientMonitorEventPublisher; import com.github.noconnor.junitperf.JUnitPerfRule; import com.github.noconnor.junitperf.JUnitPerfTest; +import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +@Ignore("Stress test") @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = ApolloClientMonitorStressTest.class) -@ActiveProfiles("stress-test") public class ApolloClientMonitorStressTest { @Rule @@ -40,14 +41,16 @@ public class ApolloClientMonitorStressTest { @Test @JUnitPerfTest(threads = 25, durationMs = 10000, warmUpMs = 1000, maxExecutionsPerSecond = 1000) public void testConfigMonitor() { - String exporterData = ConfigService.getConfigMonitor().getExporterData(); + System.out.println("abcdeft"); + ConfigService.getConfigMonitor().getExporterData(); } @Test @JUnitPerfTest(threads = 50, durationMs = 10000, warmUpMs = 1000, maxExecutionsPerSecond = 1000) public void testPublishEvent() { - ApolloClientMonitorEventFactory.getInstance() - .createEvent(APOLLO_CLIENT_NAMESPACE_USAGE) - .putAttachment(NAMESPACE, "application").publish(); + ApolloClientMonitorEventPublisher.publish( + ApolloClientMonitorEventFactory.getInstance() + .createEvent(APOLLO_CLIENT_NAMESPACE_USAGE) + .putAttachment(NAMESPACE, "application")); } } diff --git a/apollo-client/src/test/resources/application-stress-test.yml b/apollo-client/src/test/resources/application-stress-test.yml deleted file mode 100644 index 430bf695..00000000 --- a/apollo-client/src/test/resources/application-stress-test.yml +++ /dev/null @@ -1,17 +0,0 @@ -# -# Copyright 2022 Apollo Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -# just for apollo client monitor stress test \ No newline at end of file diff --git a/apollo-plugin/apollo-plugin-client-prometheus/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/impl/PrometheusApolloClientMetricsExporter.java b/apollo-plugin/apollo-plugin-client-prometheus/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/impl/PrometheusApolloClientMetricsExporter.java index d6f56401..a07e3209 100644 --- a/apollo-plugin/apollo-plugin-client-prometheus/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/impl/PrometheusApolloClientMetricsExporter.java +++ b/apollo-plugin/apollo-plugin-client-prometheus/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/impl/PrometheusApolloClientMetricsExporter.java @@ -20,6 +20,7 @@ import com.ctrip.framework.apollo.monitor.internal.exporter.AbstractApolloClientMetricsExporter; import com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporter; import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientNamespaceApi; +import com.google.common.collect.Maps; import io.prometheus.client.Collector; import io.prometheus.client.CollectorRegistry; import io.prometheus.client.Counter; @@ -41,12 +42,12 @@ public class PrometheusApolloClientMetricsExporter extends private final Logger logger = DeferredLoggerFactory.getLogger( DefaultApolloClientNamespaceApi.class); protected CollectorRegistry registry; - protected Map map; + protected Map map; @Override public void doInit() { registry = new CollectorRegistry(); - map = new HashMap<>(); + map = Maps.newConcurrentMap(); } @Override @@ -58,11 +59,8 @@ public boolean isSupport(String form) { @Override public void registerOrUpdateCounterSample(String name, Map tags, double incrValue) { - Counter counter = (Counter) map.get(name); - if (counter == null) { - counter = createCounter(name, tags); - map.put(name, counter); - } + Counter counter = (Counter) map.computeIfAbsent(name, + key -> createCounter(key, tags)); counter.labels(tags.values().toArray(new String[0])).inc(incrValue); } @@ -76,11 +74,7 @@ private Counter createCounter(String name, Map tags) { @Override public void registerOrUpdateGaugeSample(String name, Map tags, double value) { - Gauge gauge = (Gauge) map.get(name); - if (gauge == null) { - gauge = createGauge(name, tags); - map.put(name, gauge); - } + Gauge gauge = (Gauge) map.computeIfAbsent(name, key -> createGauge(key, tags)); gauge.labels(tags.values().toArray(new String[0])).set(value); } diff --git a/apollo-plugin/apollo-plugin-client-prometheus/src/main/java/com/ctrip/framework/apollo/plugin/prometheus/PrometheusApolloClientMetricsExporter.java b/apollo-plugin/apollo-plugin-client-prometheus/src/main/java/com/ctrip/framework/apollo/plugin/prometheus/PrometheusApolloClientMetricsExporter.java deleted file mode 100644 index df518054..00000000 --- a/apollo-plugin/apollo-plugin-client-prometheus/src/main/java/com/ctrip/framework/apollo/plugin/prometheus/PrometheusApolloClientMetricsExporter.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright 2022 Apollo Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.ctrip.framework.apollo.plugin.prometheus; - -import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory; -import com.ctrip.framework.apollo.monitor.internal.exporter.AbstractApolloClientMetricsExporter; -import com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporter; -import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientNamespaceApi; -import io.prometheus.client.Collector; -import io.prometheus.client.CollectorRegistry; -import io.prometheus.client.Counter; -import io.prometheus.client.Gauge; -import io.prometheus.client.exporter.common.TextFormat; -import java.io.IOException; -import java.io.StringWriter; -import java.util.HashMap; -import java.util.Map; -import org.slf4j.Logger; - -/** - * @author Rawven - */ -public class PrometheusApolloClientMetricsExporter extends - AbstractApolloClientMetricsExporter implements ApolloClientMetricsExporter { - private final Logger logger = DeferredLoggerFactory.getLogger( - DefaultApolloClientNamespaceApi.class); - private static final String PROMETHEUS = "prometheus"; - private final CollectorRegistry registry; - private final Map map = new HashMap<>(); - - - public PrometheusApolloClientMetricsExporter() { - this.registry = new CollectorRegistry(); - } - - @Override - public void doInit() { - - } - - @Override - public boolean isSupport(String form) { - return PROMETHEUS.equals(form); - } - - - @Override - public void registerOrUpdateCounterSample(String name, Map tags, double incrValue) { - Counter counter = (Counter) map.computeIfAbsent(name, k -> Counter.build() - .name(name) - .help("apollo") - .labelNames(tags.keySet().toArray(new String[0])) - .register(registry)); - counter.labels(tags.values().toArray(new String[0])).inc(incrValue); -} - - - @Override - public void registerOrUpdateGaugeSample(String name, Map tags, double value) { - Gauge gauge = (Gauge) map.computeIfAbsent(name, k -> Gauge.build() - .name(name) - .help("apollo") - .labelNames(tags.keySet().toArray(new String[0])) - .register(registry)); - gauge.labels(tags.values().toArray(new String[0])).set(value); - } - - - @Override - public String response() { - try (StringWriter writer = new StringWriter()){ - TextFormat.writeFormat(TextFormat.CONTENT_TYPE_OPENMETRICS_100, writer, registry.metricFamilySamples()); - return writer.toString(); - } catch (IOException e) { - logger.error("Write metrics to Prometheus format failed", e); - return ""; - } - } -} - \ No newline at end of file From 8a09ec8897c9cc3fb0bad7be29674bed1631c644 Mon Sep 17 00:00:00 2001 From: Rawven <121878866+rawven@users.noreply.github.com> Date: Sat, 31 Aug 2024 21:50:59 +0800 Subject: [PATCH 6/8] feat(): refactor --- .../internals/ConfigMonitorInitializer.java | 106 +++++------- .../apollo/internals/DefaultInjector.java | 6 +- .../internals/RemoteConfigRepository.java | 2 +- .../ApolloClientBootstrapArgsMonitorApi.java | 160 +++++++++++------- .../api/ApolloClientExceptionMonitorApi.java | 5 +- .../api/ApolloClientNamespaceMonitorApi.java | 51 +++++- .../api/ApolloClientThreadPoolMonitorApi.java | 53 +++++- .../internal/ApolloClientMonitorConstant.java | 45 +++-- .../internal/ApolloClientMonitorContext.java | 96 +++++++++++ .../internal/DefaultConfigMonitor.java | 36 +--- .../{MeterEnums.java => MetricTypeEnums.java} | 2 +- .../event/ApolloClientMonitorEvent.java | 9 +- .../ApolloClientMonitorEventPublisher.java | 12 +- .../AbstractApolloClientMetricsExporter.java | 6 +- ...ultApolloClientMetricsExporterFactory.java | 3 - .../impl/NullApolloClientMetricsExporter.java | 9 +- .../ApolloClientJmxBootstrapArgsMBean.java | 11 +- .../mbean/ApolloClientJmxExceptionMBean.java | 4 +- .../mbean/ApolloClientJmxNamespaceMBean.java | 73 +++++++- ...tractApolloClientMonitorEventListener.java | 71 +++++--- .../ApolloClientMonitorEventListener.java | 4 +- ...olloClientMonitorEventListenerManager.java | 36 ---- ...olloClientMonitorEventListenerManager.java | 43 ----- .../DefaultApolloClientBootstrapArgsApi.java | 122 +------------ .../impl/DefaultApolloClientExceptionApi.java | 43 ++--- .../impl/DefaultApolloClientNamespaceApi.java | 103 ++++------- .../DefaultApolloClientThreadPoolApi.java | 105 +++--------- .../NullClientBootstrapArgsMonitorApi.java | 117 +------------ .../impl/NullClientExceptionMonitorApi.java | 5 + .../impl/NullClientNamespaceMonitorApi.java | 12 +- .../impl/NullClientThreadPoolMonitorApi.java | 11 +- .../monitor/internal/model/CounterModel.java | 4 +- .../monitor/internal/model/GaugeModel.java | 5 +- .../monitor/internal/model/SampleModel.java | 12 +- .../ApolloClientMessageProducerComposite.java | 1 - .../ApolloClientMonitorMessageProducer.java | 111 ++++++------ .../framework/apollo/util/ConfigUtil.java | 118 +++++++------ .../ConfigMonitorInitializerTest.java | 153 +++++++---------- .../ApolloClientMonitorContextTest.java | 99 +++++++++++ .../internal/DefaultConfigMonitorTest.java | 69 ++++---- ...ApolloClientMonitorEventPublisherTest.java | 18 +- ...stractApolloClientMetricsExporterTest.java | 4 +- ...polloClientMetricsExporterFactoryTest.java | 4 +- ...tApolloClientMonitorEventListenerTest.java | 112 ------------ ...ClientMonitorEventListenerManagerTest.java | 67 -------- ...faultApolloClientBootstrapArgsApiTest.java | 2 +- .../DefaultApolloClientExceptionApiTest.java | 9 +- .../DefaultApolloClientNamespaceApiTest.java | 12 +- .../DefaultApolloClientThreadPoolApiTest.java | 8 +- ...NullClientBootstrapArgsMonitorApiTest.java | 32 ++-- .../NullClientNamespaceMonitorApiTest.java | 13 +- .../NullClientThreadPoolMonitorApiTest.java | 22 +-- .../stress/ApolloClientMonitorStressTest.java | 15 +- .../framework/apollo/util/ConfigUtilTest.java | 86 ++++++++++ .../resources/application-stress-test.yml | 17 -- ...PrometheusApolloClientMetricsExporter.java | 18 +- ...PrometheusApolloClientMetricsExporter.java | 94 ---------- 57 files changed, 1111 insertions(+), 1355 deletions(-) create mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/ApolloClientMonitorContext.java rename apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/enums/{MeterEnums.java => MetricTypeEnums.java} (96%) delete mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/ApolloClientMonitorEventListenerManager.java delete mode 100644 apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/DefaultApolloClientMonitorEventListenerManager.java create mode 100644 apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/ApolloClientMonitorContextTest.java delete mode 100644 apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/AbstractApolloClientMonitorEventListenerTest.java delete mode 100644 apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/DefaultApolloClientMonitorEventListenerManagerTest.java delete mode 100644 apollo-client/src/test/resources/application-stress-test.yml delete mode 100644 apollo-plugin/apollo-plugin-client-prometheus/src/main/java/com/ctrip/framework/apollo/plugin/prometheus/PrometheusApolloClientMetricsExporter.java diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigMonitorInitializer.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigMonitorInitializer.java index a6d50f5f..20ab2640 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigMonitorInitializer.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigMonitorInitializer.java @@ -20,18 +20,14 @@ import com.ctrip.framework.apollo.build.ApolloInjector; import com.ctrip.framework.apollo.core.utils.ClassLoaderUtil; -import com.ctrip.framework.apollo.monitor.api.ConfigMonitor; -import com.ctrip.framework.apollo.monitor.internal.DefaultConfigMonitor; import com.ctrip.framework.apollo.monitor.internal.exporter.AbstractApolloClientMetricsExporter; +import com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporter; import com.ctrip.framework.apollo.monitor.internal.jmx.ApolloClientJmxMBeanRegister; -import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMonitorEventListener; -import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMonitorEventListenerManager; +import com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorContext; import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientBootstrapArgsApi; import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientExceptionApi; import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientNamespaceApi; import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientThreadPoolApi; -import com.ctrip.framework.apollo.monitor.internal.listener.DefaultApolloClientMonitorEventListenerManager; -import com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporter; import com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporterFactory; import com.ctrip.framework.apollo.monitor.internal.tracer.ApolloClientMonitorMessageProducer; import com.ctrip.framework.apollo.monitor.internal.tracer.ApolloClientMessageProducerComposite; @@ -41,91 +37,75 @@ import com.ctrip.framework.apollo.tracer.spi.MessageProducer; import com.ctrip.framework.apollo.util.ConfigUtil; import com.ctrip.framework.foundation.internals.ServiceBootstrap; -import com.google.common.collect.Lists; import java.util.List; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** * ConfigMonitorInitializer initializes the Apollo Config Monitor. */ public class ConfigMonitorInitializer { - private static final Logger logger = LoggerFactory.getLogger(ConfigMonitorInitializer.class); protected static boolean hasInitialized = false; - private static ConfigUtil CONFIG_UTIL = ApolloInjector.getInstance(ConfigUtil.class); + private static ConfigUtil m_configUtil = ApolloInjector.getInstance(ConfigUtil.class); + private static ApolloClientMonitorContext monitorContext = ApolloInjector.getInstance( + ApolloClientMonitorContext.class); public static void initialize() { - if (CONFIG_UTIL.getClientMonitorEnabled() && !hasInitialized) { - hasInitialized = true; - logger.debug("Initializing ConfigMonitor"); - DefaultApolloClientMonitorEventListenerManager manager = initializeMetricsEventListenerManager(); - List collectors = initializeCollectors(manager); - ApolloClientMetricsExporter metricsExporter = initializeMetricsExporter(collectors); - initializeJmxMonitoring(collectors); - initializeConfigMonitor(collectors, metricsExporter); - logger.debug("ConfigMonitor initialized successfully."); + if (m_configUtil.isClientMonitorEnabled() && !hasInitialized) { + synchronized (ConfigMonitorInitializer.class) { + if (!hasInitialized) { + doInit(); + hasInitialized = true; + } + } } } - protected static DefaultApolloClientMonitorEventListenerManager initializeMetricsEventListenerManager() { - return (DefaultApolloClientMonitorEventListenerManager) ApolloInjector.getInstance( - ApolloClientMonitorEventListenerManager.class); + private static void doInit() { + initializeMetricsEventListener(); + initializeMetricsExporter(); + initializeJmxMonitoring(); + hasInitialized = true; } - - protected static void initializeJmxMonitoring(List collectors) { - if (CONFIG_UTIL.getClientMonitorJmxEnabled()) { - collectors.forEach(metricsCollector -> + + + private static void initializeJmxMonitoring() { + if (m_configUtil.isClientMonitorJmxEnabled()) { + monitorContext.getCollectors().forEach(metricsCollector -> ApolloClientJmxMBeanRegister.register( - MBEAN_NAME + metricsCollector.mBeanName(), metricsCollector) + MBEAN_NAME + metricsCollector.getName(), metricsCollector) ); } } - protected static List initializeCollectors( - DefaultApolloClientMonitorEventListenerManager manager) { - + private static void initializeMetricsEventListener() { DefaultConfigManager configManager = (DefaultConfigManager) ApolloInjector.getInstance( ConfigManager.class); - - List collectors = Lists.newArrayList( - new DefaultApolloClientExceptionApi(), - new DefaultApolloClientNamespaceApi(configManager.m_configs, configManager.m_configFiles), - new DefaultApolloClientThreadPoolApi(RemoteConfigRepository.m_executorService, - AbstractConfig.m_executorService, AbstractConfigFile.m_executorService, - AbstractApolloClientMetricsExporter.m_executorService), - new DefaultApolloClientBootstrapArgsApi(CONFIG_UTIL) - ); - - manager.setCollectors(collectors); - return collectors; + monitorContext.setApolloClientBootstrapArgsMonitorApi(new DefaultApolloClientBootstrapArgsApi( + m_configUtil)); + monitorContext.setApolloClientExceptionMonitorApi(new DefaultApolloClientExceptionApi()); + monitorContext.setApolloClientNamespaceMonitorApi(new DefaultApolloClientNamespaceApi( + configManager.m_configs, configManager.m_configFiles)); + monitorContext.setApolloClientThreadPoolMonitorApi(new DefaultApolloClientThreadPoolApi( + RemoteConfigRepository.m_executorService, + AbstractConfig.m_executorService, AbstractConfigFile.m_executorService, + AbstractApolloClientMetricsExporter.m_executorService)); } - protected static ApolloClientMetricsExporter initializeMetricsExporter( - List collectors) { + private static void initializeMetricsExporter( + ) { ApolloClientMetricsExporterFactory exporterFactory = ApolloInjector.getInstance( ApolloClientMetricsExporterFactory.class); - return exporterFactory.getMetricsReporter(collectors); - } - - protected static void initializeConfigMonitor(List collectors, - ApolloClientMetricsExporter metricsExporter) { - - DefaultConfigMonitor configMonitor = (DefaultConfigMonitor) ApolloInjector.getInstance( - ConfigMonitor.class); - configMonitor.init( - (DefaultApolloClientNamespaceApi) collectors.get(1), - (DefaultApolloClientThreadPoolApi) collectors.get(2), - (DefaultApolloClientExceptionApi) collectors.get(0), - (DefaultApolloClientBootstrapArgsApi) collectors.get(3), - metricsExporter - ); + ApolloClientMetricsExporter metricsReporter = exporterFactory.getMetricsReporter( + monitorContext.getCollectors()); + if(metricsReporter != null) { + monitorContext.setApolloClientMetricsExporter(metricsReporter); + } } public static ApolloClientMessageProducerComposite initializeMessageProducerComposite() { List producers = ServiceBootstrap.loadAllOrdered(MessageProducer.class); - if (CONFIG_UTIL.getClientMonitorEnabled()) { + if (m_configUtil.isClientMonitorEnabled()) { producers.add(new ApolloClientMonitorMessageProducer()); } @@ -139,11 +119,11 @@ public static ApolloClientMessageProducerComposite initializeMessageProducerComp return new ApolloClientMessageProducerComposite(producers); } - + // for test only protected static void reset() { hasInitialized = false; - CONFIG_UTIL = ApolloInjector.getInstance(ConfigUtil.class); + m_configUtil = ApolloInjector.getInstance(ConfigUtil.class); } } \ No newline at end of file diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultInjector.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultInjector.java index a4d0fca8..f561d278 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultInjector.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultInjector.java @@ -20,8 +20,7 @@ import com.ctrip.framework.apollo.monitor.api.ConfigMonitor; import com.ctrip.framework.apollo.monitor.internal.DefaultConfigMonitor; import com.ctrip.framework.apollo.monitor.internal.exporter.impl.DefaultApolloClientMetricsExporterFactory; -import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMonitorEventListenerManager; -import com.ctrip.framework.apollo.monitor.internal.listener.DefaultApolloClientMonitorEventListenerManager; +import com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorContext; import com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporterFactory; import com.ctrip.framework.apollo.spi.ApolloInjectorCustomizer; import com.ctrip.framework.apollo.spi.ConfigFactory; @@ -113,8 +112,7 @@ protected void configure() { bind(YamlParser.class).in(Singleton.class); bind(PropertiesFactory.class).to(DefaultPropertiesFactory.class).in(Singleton.class); bind(ConfigMonitor.class).to(DefaultConfigMonitor.class).in(Singleton.class); - bind(ApolloClientMonitorEventListenerManager.class).to( - DefaultApolloClientMonitorEventListenerManager.class).in(Singleton.class); + bind(ApolloClientMonitorContext.class).in(Singleton.class); bind(ApolloClientMetricsExporterFactory.class).to(DefaultApolloClientMetricsExporterFactory.class).in(Singleton.class); } } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigRepository.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigRepository.java index be19f42e..dd4f63ee 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigRepository.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigRepository.java @@ -115,7 +115,7 @@ public Properties getConfig() { if (m_configCache.get() == null) { long start = System.currentTimeMillis(); this.sync(); - Tracer.logEvent(APOLLO_CLIENT_NAMESPACE_FIRST_LOAD_SPEND+m_namespace, + Tracer.logEvent(APOLLO_CLIENT_NAMESPACE_FIRST_LOAD_SPEND+":"+m_namespace, String.valueOf(System.currentTimeMillis() - start)); } return transformApolloConfigToProperties(m_configCache.get()); diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientBootstrapArgsMonitorApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientBootstrapArgsMonitorApi.java index 5b0e0adb..cd5c33cc 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientBootstrapArgsMonitorApi.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientBootstrapArgsMonitorApi.java @@ -16,6 +16,12 @@ */ package com.ctrip.framework.apollo.monitor.api; +import static com.ctrip.framework.apollo.core.ApolloClientSystemConsts.*; +import static com.ctrip.framework.apollo.core.ConfigConsts.APOLLO_AUTO_UPDATE_INJECTED_SPRING_PROPERTIES; +import static com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorConstant.*; +import static com.ctrip.framework.apollo.spring.config.PropertySourcesConstants.*; + +import java.util.Collections; import java.util.Map; /** @@ -23,66 +29,106 @@ */ public interface ApolloClientBootstrapArgsMonitorApi { - /** - * get bootstrap args map - */ - Map getBootstrapArgs(); - /** * get startup params by key */ - String getStartupParams(String key); - - /** - * config service url - */ - String getConfigServiceUrl(); + default Object getStartupArg(String key) { + return getBootstrapArgs().get(key); + } /** - * access key secret - */ - String getAccessKeySecret(); - - /** - * auto update injected spring properties + * get bootstrap args map */ - Boolean getAutoUpdateInjectedSpringProperties(); - - Boolean getBootstrapEnabled(); - - String getBootstrapNamespaces(); - - Boolean getBootstrapEagerLoadEnabled(); - - Boolean getOverrideSystemProperties(); - - String getCacheDir(); - - String getCluster(); - - String getConfigService(); - - Boolean getClientMonitorEnabled(); - - Boolean getClientMonitorJmxEnabled(); - - String getClientMonitorExternalForm(); - - long getClientMonitorExternalExportPeriod(); - - int getClientMonitorExceptionSaveSize(); - - String getApolloMeta(); - - String getMetaLatestFreshTime(); - - Boolean getPropertyNamesCacheEnable(); - - Boolean getPropertyOrderEnable(); - - String getVersion(); - - String getEnv(); - - String getAppId(); -} + default Map getBootstrapArgs() { + return Collections.emptyMap(); + } + + default String getConfigServiceUrl() { + return (String) getBootstrapArgs().getOrDefault(CONFIG_SERVICE_URL, ""); + } + + default String getAccessKeySecret() { + return (String) getBootstrapArgs().getOrDefault(APOLLO_ACCESS_KEY_SECRET, ""); + } + + default Boolean getAutoUpdateInjectedSpringProperties() { + return (Boolean) getBootstrapArgs().getOrDefault(APOLLO_AUTO_UPDATE_INJECTED_SPRING_PROPERTIES, + false); + } + + default Boolean isBootstrapEnabled() { + return (Boolean) getBootstrapArgs().getOrDefault(APOLLO_BOOTSTRAP_ENABLED, false); + } + + default String getBootstrapNamespaces() { + return (String) getBootstrapArgs().getOrDefault(APOLLO_BOOTSTRAP_NAMESPACES, ""); + } + + default Boolean isBootstrapEagerLoadEnabled() { + return (Boolean) getBootstrapArgs().getOrDefault(APOLLO_BOOTSTRAP_EAGER_LOAD_ENABLED, false); + } + + default Boolean isOverrideSystemProperties() { + return (Boolean) getBootstrapArgs().getOrDefault(APOLLO_OVERRIDE_SYSTEM_PROPERTIES, false); + } + + default String getCacheDir() { + return (String) getBootstrapArgs().getOrDefault(APOLLO_CACHE_DIR, ""); + } + + default String getCluster() { + return (String) getBootstrapArgs().getOrDefault(APOLLO_CLUSTER, ""); + } + + default String getConfigService() { + return (String) getBootstrapArgs().getOrDefault(APOLLO_CONFIG_SERVICE, ""); + } + + default String getClientMonitorExternalForm() { + return (String) getBootstrapArgs().getOrDefault(APOLLO_CLIENT_MONITOR_EXTERNAL_TYPE, ""); + } + + default Boolean isClientMonitorEnabled() { + return (Boolean) getBootstrapArgs().getOrDefault(APOLLO_CLIENT_MONITOR_ENABLED, false); + } + + default Boolean isClientMonitorJmxEnabled() { + return (Boolean) getBootstrapArgs().getOrDefault(APOLLO_CLIENT_MONITOR_JMX_ENABLED, false); + } + + default long getClientMonitorExternalExportPeriod() { + return (Long) getBootstrapArgs().getOrDefault(APOLLO_CLIENT_MONITOR_EXTERNAL_EXPORT_PERIOD, 0L); + } + + default int getClientMonitorExceptionSaveSize() { + return (Integer) getBootstrapArgs().getOrDefault(APOLLO_CLIENT_MONITOR_EXCEPTION_QUEUE_SIZE, 0); + } + + default String getApolloMeta() { + return (String) getBootstrapArgs().getOrDefault(APOLLO_META, ""); + } + + default String getMetaLatestFreshTime() { + return (String) getBootstrapArgs().getOrDefault(META_FRESH, ""); + } + + default Boolean isPropertyNamesCacheEnable() { + return (Boolean) getBootstrapArgs().getOrDefault(APOLLO_PROPERTY_NAMES_CACHE_ENABLE, false); + } + + default Boolean isPropertyOrderEnable() { + return (Boolean) getBootstrapArgs().getOrDefault(APOLLO_PROPERTY_ORDER_ENABLE, false); + } + + default String getVersion() { + return (String) getBootstrapArgs().getOrDefault(VERSION, ""); + } + + default String getEnv() { + return (String) getBootstrapArgs().getOrDefault(ENV, ""); + } + + default String getAppId() { + return (String) getBootstrapArgs().getOrDefault(APP_ID, ""); + } +} \ No newline at end of file diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientExceptionMonitorApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientExceptionMonitorApi.java index 14b45d49..29d2b207 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientExceptionMonitorApi.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientExceptionMonitorApi.java @@ -24,8 +24,11 @@ public interface ApolloClientExceptionMonitorApi { /** - * get ApolloConfigException details + * Get exception information the number is limited and can be configured through + * apollo.client.monitor.exception-queue-size */ List getApolloConfigExceptionList(); + Integer getExceptionCountFromStartup(); + } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientNamespaceMonitorApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientNamespaceMonitorApi.java index 57d5efe6..78ac35f3 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientNamespaceMonitorApi.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientNamespaceMonitorApi.java @@ -16,7 +16,7 @@ */ package com.ctrip.framework.apollo.monitor.api; -import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientNamespaceApi.NamespaceMetrics; +import java.time.LocalDateTime; import java.util.List; import java.util.Map; @@ -31,14 +31,14 @@ public interface ApolloClientNamespaceMonitorApi { Map getNamespaceMetrics(); /** - * get Namespace Config.ItemsNum + * get Namespace Config.ItemsNum */ - Integer getNamespaceItemsNum(String namespace); + Integer getNamespacePropertySize(String namespace); /** - * get ConfigFile num + * get ConfigFile namespaces */ - Integer getConfigFileNum(); + List getConfigFileNamespaces(); /** * get not found namespaces @@ -51,4 +51,45 @@ public interface ApolloClientNamespaceMonitorApi { List getTimeoutNamespaces(); + class NamespaceMetrics { + + private int usageCount; + private long firstLoadTimeSpendInMs; + private LocalDateTime latestUpdateTime = LocalDateTime.now(); + private String releaseKey = ""; + + public String getReleaseKey() { + return releaseKey; + } + + public void setReleaseKey(String releaseKey) { + this.releaseKey = releaseKey; + } + + public int getUsageCount() { + return usageCount; + } + + public void incrementUsageCount() { + usageCount++; + } + + public long getFirstLoadTimeSpendInMs() { + return firstLoadTimeSpendInMs; + } + + public void setFirstLoadTimeSpendInMs(long firstLoadTimeSpendInMs) { + this.firstLoadTimeSpendInMs = firstLoadTimeSpendInMs; + } + + public LocalDateTime getLatestUpdateTime() { + return latestUpdateTime; + } + + public void setLatestUpdateTime(LocalDateTime latestUpdateTime) { + this.latestUpdateTime = latestUpdateTime; + } + } + + } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientThreadPoolMonitorApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientThreadPoolMonitorApi.java index db3315d7..d38555e4 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientThreadPoolMonitorApi.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ApolloClientThreadPoolMonitorApi.java @@ -16,8 +16,8 @@ */ package com.ctrip.framework.apollo.monitor.api; -import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientThreadPoolApi.ApolloThreadPoolInfo; import java.util.Map; +import java.util.concurrent.ThreadPoolExecutor; /** * @author Rawven @@ -48,4 +48,55 @@ public interface ApolloClientThreadPoolMonitorApi { * AbstractApolloClientMetricsExporter.m_executorService */ ApolloThreadPoolInfo getMetricsExporterThreadPoolInfo(); + + + class ApolloThreadPoolInfo { + + private ThreadPoolExecutor executor; + + public ApolloThreadPoolInfo(ThreadPoolExecutor executor) { + this.executor = executor; + } + + public ApolloThreadPoolInfo() { + } + + + public int getActiveTaskCount() { + return executor != null ? executor.getActiveCount() : 0; + } + + public int getQueueSize() { + return executor != null ? executor.getQueue().size() : 0; + } + + public int getCorePoolSize() { + return executor != null ? executor.getCorePoolSize() : 0; + } + + public int getMaximumPoolSize() { + return executor != null ? executor.getMaximumPoolSize() : 0; + } + + public int getPoolSize() { + return executor != null ? executor.getPoolSize() : 0; + } + + public long getTotalTaskCount() { + return executor != null ? executor.getTaskCount() : 0; + } + + public long getCompletedTaskCount() { + return executor != null ? executor.getCompletedTaskCount() : 0; + } + + public int getLargestPoolSize() { + return executor != null ? executor.getLargestPoolSize() : 0; + } + + public int getQueueRemainingCapacity() { + return executor != null ? executor.getQueue().remainingCapacity() : 0; + } + + } } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/ApolloClientMonitorConstant.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/ApolloClientMonitorConstant.java index 4f615c7d..de9ea0c6 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/ApolloClientMonitorConstant.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/ApolloClientMonitorConstant.java @@ -24,12 +24,6 @@ */ public class ApolloClientMonitorConstant { - /** - * util - */ - public static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern( - "yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault()); - /** * common */ @@ -38,7 +32,6 @@ public class ApolloClientMonitorConstant { public static final String TIMESTAMP = "timestamp"; public static final String THROWABLE = "throwable"; public static final String NAMESPACE_RELEASE_KEY = "releaseKey"; - public static final String APOLLO_CLIENT = "apollo_client_"; public static final String ENV = "env"; public static final String VERSION = "version"; public static final String META_FRESH = "metaFreshTime"; @@ -53,13 +46,13 @@ public class ApolloClientMonitorConstant { public static final String APOLLO_CONFIG_SERVICES = "Apollo.Config.Services"; public static final String APOLLO_CLIENT_VERSION = "Apollo.Client.Version"; public static final String APOLLO_CONFIGSERVICE = "Apollo.ConfigService"; + public static final String APOLLO_CONFIGSERVICE_HELP_STR = "periodicRefresh: "; public static final String APOLLO_CLIENT_CONFIGS = "Apollo.Client.Configs."; public static final String APOLLO_CLIENT_CONFIGMETA = "Apollo.Client.ConfigMeta"; public static final String APOLLO_CLIENT_NAMESPACE_NOT_FOUND = "Apollo.Client.NamespaceNotFound"; public static final String APOLLO_CLIENT_NAMESPACE_TIMEOUT = "Apollo.Client.NamespaceTimeout"; public static final String APOLLO_CLIENT_NAMESPACE_USAGE = "Apollo.Client.NamespaceUsage"; public static final String APOLLO_CLIENT_NAMESPACE_FIRST_LOAD_SPEND = "Apollo.Client.NamespaceFirstLoadSpendTime"; - public static final String HELP_STR = "periodicRefresh: "; /** * collector tag @@ -72,22 +65,22 @@ public class ApolloClientMonitorConstant { /** * metrics */ - public static final String METRICS_NAMESPACE_LATEST_UPDATE_TIME = "namespace_latest_update_time"; - public static final String METRICS_NAMESPACE_ITEM_NUM = "namespace_item_num"; - public static final String METRICS_CONFIG_FILE_NUM = "config_file_num"; - public static final String METRICS_EXCEPTION_NUM = "exception_num"; - public static final String METRICS_NAMESPACE_FIRST_LOAD_SPEND = "namespace_first_load_spend"; - public static final String METRICS_NAMESPACE_USAGE = "namespace_usage"; - public static final String METRICS_NAMESPACE_NOT_FOUND = "namespace_not_found"; - public static final String METRICS_NAMESPACE_TIMEOUT = "namespace_timeout"; - public static final String METRICS_THREAD_POOL = "thread_pool_"; - public static final String[] METRICS_THREAD_POOL_PARAMS = new String[]{ - METRICS_THREAD_POOL + "name", - METRICS_THREAD_POOL + "active_task_count", METRICS_THREAD_POOL + "queue_size", - METRICS_THREAD_POOL + "completed_task_count", - METRICS_THREAD_POOL + "pool_size", METRICS_THREAD_POOL + "total_task_count", - METRICS_THREAD_POOL + "core_pool_size", METRICS_THREAD_POOL + "maximum_pool_size", - METRICS_THREAD_POOL + "largest_pool_size", - METRICS_THREAD_POOL + "queue_capacity", METRICS_THREAD_POOL + "queue_remaining_capacity", - METRICS_THREAD_POOL + "current_load"}; + public static final String METRICS_NAMESPACE_LATEST_UPDATE_TIME = "apollo_client_namespace_latest_update_time"; + public static final String METRICS_NAMESPACE_ITEM_NUM = "apollo_client_namespace_item_num"; + public static final String METRICS_CONFIG_FILE_NUM = "apollo_client_config_file_num"; + public static final String METRICS_EXCEPTION_NUM = "apollo_client_exception_num"; + public static final String METRICS_NAMESPACE_FIRST_LOAD_SPEND = "apollo_client_namespace_first_load_time_spend_in_ms"; + public static final String METRICS_NAMESPACE_USAGE = "apollo_client_namespace_usage"; + public static final String METRICS_NAMESPACE_NOT_FOUND = "apollo_client_namespace_not_found"; + public static final String METRICS_NAMESPACE_TIMEOUT = "apollo_client_namespace_timeout"; + public static final String METRICS_THREAD_POOL_NAME = "thread_pool_name"; + public static final String METRICS_THREAD_POOL_ACTIVE_TASK_COUNT = "apollo_client_thread_pool_active_task_count"; + public static final String METRICS_THREAD_POOL_QUEUE_SIZE = "apollo_client_thread_pool_queue_size"; + public static final String METRICS_THREAD_POOL_COMPLETED_TASK_COUNT = "apollo_client_thread_pool_completed_task_count"; + public static final String METRICS_THREAD_POOL_POOL_SIZE = "apollo_client_thread_pool_pool_size"; + public static final String METRICS_THREAD_POOL_TOTAL_TASK_COUNT = "apollo_client_thread_pool_total_task_count"; + public static final String METRICS_THREAD_POOL_CORE_POOL_SIZE = "apollo_client_thread_pool_core_pool_size"; + public static final String METRICS_THREAD_POOL_MAXIMUM_POOL_SIZE = "apollo_client_thread_pool_maximum_pool_size"; + public static final String METRICS_THREAD_POOL_LARGEST_POOL_SIZE = "apollo_client_thread_pool_largest_pool_size"; + public static final String METRICS_THREAD_POOL_QUEUE_REMAINING_CAPACITY = "apollo_client_thread_pool_queue_remaining_capacity"; } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/ApolloClientMonitorContext.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/ApolloClientMonitorContext.java new file mode 100644 index 00000000..a036a2a2 --- /dev/null +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/ApolloClientMonitorContext.java @@ -0,0 +1,96 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal; + +import com.ctrip.framework.apollo.monitor.api.ApolloClientBootstrapArgsMonitorApi; +import com.ctrip.framework.apollo.monitor.api.ApolloClientExceptionMonitorApi; +import com.ctrip.framework.apollo.monitor.api.ApolloClientNamespaceMonitorApi; +import com.ctrip.framework.apollo.monitor.api.ApolloClientThreadPoolMonitorApi; +import com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporter; +import com.ctrip.framework.apollo.monitor.internal.exporter.impl.NullApolloClientMetricsExporter; +import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMonitorEventListener; +import com.ctrip.framework.apollo.monitor.internal.listener.impl.NullClientBootstrapArgsMonitorApi; +import com.ctrip.framework.apollo.monitor.internal.listener.impl.NullClientExceptionMonitorApi; +import com.ctrip.framework.apollo.monitor.internal.listener.impl.NullClientNamespaceMonitorApi; +import com.ctrip.framework.apollo.monitor.internal.listener.impl.NullClientThreadPoolMonitorApi; +import com.google.common.collect.Lists; +import java.util.List; + +/** + * @author Rawven + */ +public class ApolloClientMonitorContext { + + private ApolloClientExceptionMonitorApi apolloClientExceptionMonitorApi = new NullClientExceptionMonitorApi(); + private ApolloClientNamespaceMonitorApi apolloClientNamespaceMonitorApi = new NullClientNamespaceMonitorApi(); + private ApolloClientBootstrapArgsMonitorApi apolloClientBootstrapArgsMonitorApi = new NullClientBootstrapArgsMonitorApi(); + private ApolloClientThreadPoolMonitorApi apolloClientThreadPoolMonitorApi = new NullClientThreadPoolMonitorApi(); + private ApolloClientMetricsExporter apolloClientMetricsExporter = new NullApolloClientMetricsExporter(); + + public void setApolloClientExceptionMonitorApi( + ApolloClientExceptionMonitorApi apolloClientExceptionMonitorApi) { + this.apolloClientExceptionMonitorApi = apolloClientExceptionMonitorApi; + } + + public void setApolloClientNamespaceMonitorApi( + ApolloClientNamespaceMonitorApi apolloClientNamespaceMonitorApi) { + this.apolloClientNamespaceMonitorApi = apolloClientNamespaceMonitorApi; + } + + public void setApolloClientBootstrapArgsMonitorApi( + ApolloClientBootstrapArgsMonitorApi apolloClientBootstrapArgsMonitorApi) { + this.apolloClientBootstrapArgsMonitorApi = apolloClientBootstrapArgsMonitorApi; + } + + public void setApolloClientThreadPoolMonitorApi( + ApolloClientThreadPoolMonitorApi apolloClientThreadPoolMonitorApi) { + this.apolloClientThreadPoolMonitorApi = apolloClientThreadPoolMonitorApi; + } + + public void setApolloClientMetricsExporter( + ApolloClientMetricsExporter apolloClientMetricsExporter) { + this.apolloClientMetricsExporter = apolloClientMetricsExporter; + } + + public List getCollectors() { + return Lists.newArrayList( + (ApolloClientMonitorEventListener) apolloClientBootstrapArgsMonitorApi, + (ApolloClientMonitorEventListener) apolloClientThreadPoolMonitorApi, + (ApolloClientMonitorEventListener) apolloClientExceptionMonitorApi, + (ApolloClientMonitorEventListener) apolloClientNamespaceMonitorApi); + } + + public ApolloClientExceptionMonitorApi getExceptionApi() { + return apolloClientExceptionMonitorApi; + } + + public ApolloClientNamespaceMonitorApi getNamespaceApi() { + return apolloClientNamespaceMonitorApi; + } + + public ApolloClientBootstrapArgsMonitorApi getBootstrapArgsApi() { + return apolloClientBootstrapArgsMonitorApi; + } + + public ApolloClientThreadPoolMonitorApi getThreadPoolApi() { + return apolloClientThreadPoolMonitorApi; + } + + public ApolloClientMetricsExporter getMetricsExporter() { + return apolloClientMetricsExporter; + } +} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/DefaultConfigMonitor.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/DefaultConfigMonitor.java index c296496d..4925f408 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/DefaultConfigMonitor.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/DefaultConfigMonitor.java @@ -16,17 +16,12 @@ */ package com.ctrip.framework.apollo.monitor.internal; +import com.ctrip.framework.apollo.build.ApolloInjector; import com.ctrip.framework.apollo.monitor.api.ApolloClientBootstrapArgsMonitorApi; import com.ctrip.framework.apollo.monitor.api.ApolloClientExceptionMonitorApi; import com.ctrip.framework.apollo.monitor.api.ApolloClientNamespaceMonitorApi; import com.ctrip.framework.apollo.monitor.api.ApolloClientThreadPoolMonitorApi; import com.ctrip.framework.apollo.monitor.api.ConfigMonitor; -import com.ctrip.framework.apollo.monitor.internal.listener.impl.NullClientBootstrapArgsMonitorApi; -import com.ctrip.framework.apollo.monitor.internal.listener.impl.NullClientExceptionMonitorApi; -import com.ctrip.framework.apollo.monitor.internal.listener.impl.NullClientNamespaceMonitorApi; -import com.ctrip.framework.apollo.monitor.internal.listener.impl.NullClientThreadPoolMonitorApi; -import com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporter; -import com.ctrip.framework.apollo.monitor.internal.exporter.impl.NullApolloClientMetricsExporter; /** * exposes all collected data through ConfigService @@ -35,46 +30,31 @@ */ public class DefaultConfigMonitor implements ConfigMonitor { - private ApolloClientMetricsExporter reporter = new NullApolloClientMetricsExporter(); - private ApolloClientThreadPoolMonitorApi threadPoolMonitorApi = new NullClientThreadPoolMonitorApi(); - private ApolloClientExceptionMonitorApi exceptionMonitorApi = new NullClientExceptionMonitorApi(); - private ApolloClientNamespaceMonitorApi apolloClientNamespaceMonitorApi = new NullClientNamespaceMonitorApi(); - private ApolloClientBootstrapArgsMonitorApi apolloClientBootstrapArgsMonitorApi = new NullClientBootstrapArgsMonitorApi(); + private ApolloClientMonitorContext apolloClientMonitorContext = ApolloInjector.getInstance( + ApolloClientMonitorContext.class); @Override public ApolloClientThreadPoolMonitorApi getThreadPoolMonitorApi() { - return threadPoolMonitorApi; + return apolloClientMonitorContext.getThreadPoolApi(); } @Override public ApolloClientExceptionMonitorApi getExceptionMonitorApi() { - return exceptionMonitorApi; + return apolloClientMonitorContext.getExceptionApi(); } @Override public ApolloClientNamespaceMonitorApi getNamespaceMonitorApi() { - return apolloClientNamespaceMonitorApi; + return apolloClientMonitorContext.getNamespaceApi(); } @Override public ApolloClientBootstrapArgsMonitorApi getRunningParamsMonitorApi() { - return apolloClientBootstrapArgsMonitorApi; + return apolloClientMonitorContext.getBootstrapArgsApi(); } @Override public String getExporterData() { - return reporter.response(); - } - - public void init(ApolloClientNamespaceMonitorApi apolloClientNamespaceMonitorApi, - ApolloClientThreadPoolMonitorApi threadPoolMonitorApi, - ApolloClientExceptionMonitorApi exceptionMonitorApi, - ApolloClientBootstrapArgsMonitorApi apolloClientBootstrapArgsMonitorApi, - ApolloClientMetricsExporter reporter) { - this.apolloClientNamespaceMonitorApi = apolloClientNamespaceMonitorApi; - this.threadPoolMonitorApi = threadPoolMonitorApi; - this.exceptionMonitorApi = exceptionMonitorApi; - this.apolloClientBootstrapArgsMonitorApi = apolloClientBootstrapArgsMonitorApi; - this.reporter = reporter; + return apolloClientMonitorContext.getMetricsExporter().response(); } } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/enums/MeterEnums.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/enums/MetricTypeEnums.java similarity index 96% rename from apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/enums/MeterEnums.java rename to apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/enums/MetricTypeEnums.java index 1009d3ed..c4c73440 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/enums/MeterEnums.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/enums/MetricTypeEnums.java @@ -19,7 +19,7 @@ /** * @author Rawven */ -public enum MeterEnums { +public enum MetricTypeEnums { /** * counter */ diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/event/ApolloClientMonitorEvent.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/event/ApolloClientMonitorEvent.java index 91c6eb4b..e7b4f077 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/event/ApolloClientMonitorEvent.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/event/ApolloClientMonitorEvent.java @@ -16,6 +16,7 @@ */ package com.ctrip.framework.apollo.monitor.internal.event; +import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -31,7 +32,7 @@ public class ApolloClientMonitorEvent { public ApolloClientMonitorEvent(String name, String tag, Map attachments) { this.name = name; this.tag = tag; - this.attachments = attachments != null ? new HashMap<>(attachments) : new HashMap<>(); + this.attachments = attachments != null ? new HashMap<>(attachments) : Collections.emptyMap(); } public ApolloClientMonitorEvent withTag(String tag) { @@ -65,10 +66,4 @@ public T getAttachmentValue(String key) { throw new IllegalArgumentException("Value for key " + key + " is not of expected type", e); } } - - - public void publish() { - ApolloClientMonitorEventPublisher.publish(this); - } - } \ No newline at end of file diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/event/ApolloClientMonitorEventPublisher.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/event/ApolloClientMonitorEventPublisher.java index 7388b888..e6843a72 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/event/ApolloClientMonitorEventPublisher.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/event/ApolloClientMonitorEventPublisher.java @@ -18,7 +18,7 @@ import com.ctrip.framework.apollo.build.ApolloInjector; import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMonitorEventListener; -import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMonitorEventListenerManager; +import com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorContext; import com.ctrip.framework.apollo.util.ConfigUtil; /** @@ -26,14 +26,14 @@ */ public class ApolloClientMonitorEventPublisher { - private static ApolloClientMonitorEventListenerManager COLLECTOR_MANAGER = ApolloInjector.getInstance( - ApolloClientMonitorEventListenerManager.class); + private static ApolloClientMonitorContext COLLECTOR_MANAGER = ApolloInjector.getInstance( + ApolloClientMonitorContext.class); private static ConfigUtil m_configUtil = ApolloInjector.getInstance(ConfigUtil.class); public static void publish(ApolloClientMonitorEvent event) { - if (m_configUtil.getClientMonitorEnabled()) { + if (m_configUtil.isClientMonitorEnabled()) { for (ApolloClientMonitorEventListener collector : COLLECTOR_MANAGER.getCollectors()) { - if (collector.isSupport(event)) { + if (collector.isSupported(event)) { collector.collect(event); return; } @@ -43,7 +43,7 @@ public static void publish(ApolloClientMonitorEvent event) { protected static void reset() { COLLECTOR_MANAGER = ApolloInjector.getInstance( - ApolloClientMonitorEventListenerManager.class); + ApolloClientMonitorContext.class); m_configUtil = ApolloInjector.getInstance(ConfigUtil.class); } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractApolloClientMetricsExporter.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractApolloClientMetricsExporter.java index c85625ce..50550ad5 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractApolloClientMetricsExporter.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractApolloClientMetricsExporter.java @@ -33,15 +33,15 @@ */ public abstract class AbstractApolloClientMetricsExporter implements ApolloClientMetricsExporter { + public static final ScheduledExecutorService m_executorService; private static final Logger log = DeferredLoggerFactory.getLogger( AbstractApolloClientMetricsExporter.class); - public static final ScheduledExecutorService m_executorService; private static final long INITIAL_DELAY = 5L; private static final int THREAD_POOL_SIZE = 1; static { m_executorService = Executors.newScheduledThreadPool(THREAD_POOL_SIZE, - ApolloThreadFactory.create("MetricsReporter", true)); + ApolloThreadFactory.create(ApolloClientMetricsExporter.class.getName(), true)); } protected List collectors; @@ -75,7 +75,7 @@ protected void updateMetricsData() { log.debug("Start to update metrics data job"); collectors.forEach(collector -> { if (collector.isMetricsSampleUpdated()) { - log.debug("Collector {} has updated samples.", collector.mBeanName()); + log.debug("Collector {} has updated samples.", collector.getName()); collector.export().forEach(this::registerSample); } }); diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/impl/DefaultApolloClientMetricsExporterFactory.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/impl/DefaultApolloClientMetricsExporterFactory.java index 3476a0c5..a9a280e9 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/impl/DefaultApolloClientMetricsExporterFactory.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/impl/DefaultApolloClientMetricsExporterFactory.java @@ -16,15 +16,12 @@ */ package com.ctrip.framework.apollo.monitor.internal.exporter.impl; -import static com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorConstant.MBEAN_NAME; - import com.ctrip.framework.apollo.build.ApolloInjector; import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory; import com.ctrip.framework.apollo.exceptions.ApolloConfigException; import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMonitorEventListener; import com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporter; import com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporterFactory; -import com.ctrip.framework.apollo.monitor.internal.jmx.ApolloClientJmxMBeanRegister; import com.ctrip.framework.apollo.tracer.Tracer; import com.ctrip.framework.apollo.util.ConfigUtil; import com.ctrip.framework.foundation.internals.ServiceBootstrap; diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/impl/NullApolloClientMetricsExporter.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/impl/NullApolloClientMetricsExporter.java index 6c3214ef..237f024f 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/impl/NullApolloClientMetricsExporter.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/impl/NullApolloClientMetricsExporter.java @@ -16,16 +16,22 @@ */ package com.ctrip.framework.apollo.monitor.internal.exporter.impl; +import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory; +import com.ctrip.framework.apollo.monitor.internal.exporter.AbstractApolloClientMetricsExporter; import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMonitorEventListener; import com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporter; import java.util.List; import java.util.Map; +import org.slf4j.Logger; /** * @author Rawven */ public class NullApolloClientMetricsExporter implements ApolloClientMetricsExporter { + private static final Logger log = DeferredLoggerFactory.getLogger( + AbstractApolloClientMetricsExporter.class); + @Override public void init(List collectors, long collectPeriod) { } @@ -48,6 +54,7 @@ public void registerOrUpdateGaugeSample(String name, Map tag, do @Override public String response() { - return "No Reporter Use"; + log.warn("No metrics exporter found, response empty string"); + return ""; } } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/jmx/mbean/ApolloClientJmxBootstrapArgsMBean.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/jmx/mbean/ApolloClientJmxBootstrapArgsMBean.java index 024cbd8c..d00597b5 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/jmx/mbean/ApolloClientJmxBootstrapArgsMBean.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/jmx/mbean/ApolloClientJmxBootstrapArgsMBean.java @@ -16,13 +16,20 @@ */ package com.ctrip.framework.apollo.monitor.internal.jmx.mbean; -import com.ctrip.framework.apollo.monitor.api.ApolloClientBootstrapArgsMonitorApi; +import java.util.Map; import javax.management.MXBean; /** * @author Rawven */ @MXBean -public interface ApolloClientJmxBootstrapArgsMBean extends ApolloClientBootstrapArgsMonitorApi { +public interface ApolloClientJmxBootstrapArgsMBean { + // Because JMX does not support all type return values + // declare the interface separately. + + /** + * get bootstrap args map + */ + Map getBootstrapArgsString(); } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/jmx/mbean/ApolloClientJmxExceptionMBean.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/jmx/mbean/ApolloClientJmxExceptionMBean.java index 016c5451..076b8639 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/jmx/mbean/ApolloClientJmxExceptionMBean.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/jmx/mbean/ApolloClientJmxExceptionMBean.java @@ -24,11 +24,13 @@ */ @MXBean public interface ApolloClientJmxExceptionMBean { - // Because JMX does not support Exception type return values + // Because JMX does not support all type return values // declare the interface separately. /** * get exception details */ List getApolloConfigExceptionDetails(); + + Integer getExceptionCountFromStartup(); } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/jmx/mbean/ApolloClientJmxNamespaceMBean.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/jmx/mbean/ApolloClientJmxNamespaceMBean.java index 569a6a2a..1290344a 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/jmx/mbean/ApolloClientJmxNamespaceMBean.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/jmx/mbean/ApolloClientJmxNamespaceMBean.java @@ -16,13 +16,82 @@ */ package com.ctrip.framework.apollo.monitor.internal.jmx.mbean; -import com.ctrip.framework.apollo.monitor.api.ApolloClientNamespaceMonitorApi; +import java.util.List; +import java.util.Map; import javax.management.MXBean; /** * @author Rawven */ @MXBean -public interface ApolloClientJmxNamespaceMBean extends ApolloClientNamespaceMonitorApi { +public interface ApolloClientJmxNamespaceMBean { + // Because JMX does not support all type return values + // declare the interface separately. + + /** + * NamespaceMetrics: 1.usageCount 2.firstLoadSpend 3.latestUpdateTime 4.releaseKey + */ + Map getNamespaceMetricsString(); + + /** + * get Namespace Config.ItemsNum + */ + Integer getNamespacePropertySize(String namespace); + + /** + * get ConfigFile namespaces + */ + List getConfigFileNamespaces(); + + /** + * get not found namespaces + */ + List getNotFoundNamespaces(); + + /** + * get timeout namespaces + */ + List getTimeoutNamespaces(); + + + class NamespaceMetricsString { + + private int usageCount; + private long firstLoadTimeSpendInMs; + private String latestUpdateTime; + private String releaseKey = ""; + + public int getUsageCount() { + return usageCount; + } + + public void setUsageCount(int usageCount) { + this.usageCount = usageCount; + } + + public long getFirstLoadTimeSpendInMs() { + return firstLoadTimeSpendInMs; + } + + public void setFirstLoadTimeSpendInMs(long firstLoadTimeSpendInMs) { + this.firstLoadTimeSpendInMs = firstLoadTimeSpendInMs; + } + + public String getLatestUpdateTime() { + return latestUpdateTime; + } + + public void setLatestUpdateTime(String latestUpdateTime) { + this.latestUpdateTime = latestUpdateTime; + } + + public String getReleaseKey() { + return releaseKey; + } + + public void setReleaseKey(String releaseKey) { + this.releaseKey = releaseKey; + } + } } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/AbstractApolloClientMonitorEventListener.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/AbstractApolloClientMonitorEventListener.java index bffb55ed..847410f7 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/AbstractApolloClientMonitorEventListener.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/AbstractApolloClientMonitorEventListener.java @@ -22,13 +22,13 @@ import com.ctrip.framework.apollo.monitor.internal.model.SampleModel; import com.google.common.collect.Maps; import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; /** - * 抽象的 Metrics 收集器 用于收集数据和导出指标样本 - * * @author Rawven */ public abstract class AbstractApolloClientMonitorEventListener implements @@ -44,12 +44,12 @@ public AbstractApolloClientMonitorEventListener(String tag) { } @Override - public String mBeanName() { + public String getName() { return tag; } @Override - public boolean isSupport(ApolloClientMonitorEvent event) { + public boolean isSupported(ApolloClientMonitorEvent event) { return tag.equals(event.getTag()); } @@ -71,42 +71,67 @@ public List export() { samples.addAll(gaugeSamples.values()); return samples; } - + /** * Specific collection logic */ - protected void collect0(ApolloClientMonitorEvent event){} + protected void collect0(ApolloClientMonitorEvent event) { + } /** * Convenient for indicators that can only be obtained from the status object */ - protected void export0(){} - + protected void export0() { + } /** * tool method for updating indicator model */ - public void createOrUpdateGaugeSample(String mapKey, String metricsName, Map tags, + public void createOrUpdateGaugeSample(String metricsName, String[] tagKeys, String[] tagValues, double value) { - if (!gaugeSamples.containsKey(mapKey)) { - GaugeModel builder = (GaugeModel) GaugeModel.create(metricsName, 0).putTags(tags); - gaugeSamples.put(mapKey, builder); - } - gaugeSamples.get(mapKey).setValue(value); + createOrUpdateSample(metricsName, tagKeys, tagValues, value, false); } - /** - * tool method for updating indicator model - */ - public void createOrUpdateCounterSample(String mapKey, String metricsName, - Map tags, + public void createOrUpdateGaugeSample(String metricsName, double value) { + createOrUpdateSample(metricsName, null, null, value, false); + } + + public void createOrUpdateCounterSample(String metricsName, String[] tagKeys, String[] tagValues, double increaseValue) { - if (!counterSamples.containsKey(mapKey)) { - CounterModel builder = (CounterModel) CounterModel.create(metricsName, 0).putTags(tags); - counterSamples.put(mapKey, builder); + createOrUpdateSample(metricsName, tagKeys, tagValues, increaseValue, true); + } + + public void createOrUpdateCounterSample(String metricsName, double increaseValue) { + createOrUpdateSample(metricsName, null, null, increaseValue, true); + } + + private void createOrUpdateSample(String metricsName, String[] tagKeys, String[] tagValues, + double value, boolean isCounter) { + String mapKey = metricsName + (tagValues != null ? Arrays.toString(tagValues) : ""); + + if (isCounter) { + CounterModel counter = counterSamples.computeIfAbsent(mapKey, + key -> (CounterModel) CounterModel.create(metricsName, 0) + .putTags(getTags(tagKeys, tagValues))); + counter.increase(value); + } else { + GaugeModel gauge = gaugeSamples.computeIfAbsent(mapKey, + key -> (GaugeModel) GaugeModel.create(metricsName, 0) + .putTags(getTags(tagKeys, tagValues))); + gauge.setValue(value); + } + } + + private Map getTags(String[] tagKeys, String[] tagValues) { + if (tagKeys != null && tagValues != null && tagKeys.length == tagValues.length) { + Map tags = Maps.newHashMap(); + for (int i = 0; i < tagKeys.length; i++) { + tags.put(tagKeys[i], tagValues[i]); + } + return tags; } - counterSamples.get(mapKey).increase(increaseValue); + return Collections.emptyMap(); } } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/ApolloClientMonitorEventListener.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/ApolloClientMonitorEventListener.java index 000fd480..d808d24d 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/ApolloClientMonitorEventListener.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/ApolloClientMonitorEventListener.java @@ -29,12 +29,12 @@ public interface ApolloClientMonitorEventListener { /** * mbean name */ - String mBeanName(); + String getName(); /** * is support the event */ - boolean isSupport(ApolloClientMonitorEvent event); + boolean isSupported(ApolloClientMonitorEvent event); /** * collect metrics from event diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/ApolloClientMonitorEventListenerManager.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/ApolloClientMonitorEventListenerManager.java deleted file mode 100644 index 4b72834b..00000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/ApolloClientMonitorEventListenerManager.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2022 Apollo Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.ctrip.framework.apollo.monitor.internal.listener; - -import com.ctrip.framework.apollo.core.spi.Ordered; -import java.util.List; - -/** - * @author Rawven - */ -public interface ApolloClientMonitorEventListenerManager extends Ordered { - - /** - * get collectors - */ - List getCollectors(); - - @Override - default int getOrder() { - return 0; - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/DefaultApolloClientMonitorEventListenerManager.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/DefaultApolloClientMonitorEventListenerManager.java deleted file mode 100644 index 8cc0444f..00000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/DefaultApolloClientMonitorEventListenerManager.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2022 Apollo Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.ctrip.framework.apollo.monitor.internal.listener; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author Rawven - */ -public class DefaultApolloClientMonitorEventListenerManager implements - ApolloClientMonitorEventListenerManager { - - private List collectors = new ArrayList<>(); - - public DefaultApolloClientMonitorEventListenerManager() { - } - - @Override - public List getCollectors() { - return collectors; - } - - public void setCollectors(List collectors) { - this.collectors.clear(); - this.collectors.addAll(collectors); - } - -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientBootstrapArgsApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientBootstrapArgsApi.java index b1fd2256..19ca9b30 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientBootstrapArgsApi.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientBootstrapArgsApi.java @@ -30,7 +30,6 @@ import com.ctrip.framework.apollo.util.ConfigUtil; import com.google.common.collect.Maps; import java.util.Map; -import java.util.Optional; import org.slf4j.Logger; /** @@ -62,13 +61,13 @@ public DefaultApolloClientBootstrapArgsApi(ConfigUtil configUtil) { bootstrapArgs.put(APOLLO_CONFIG_SERVICE, System.getProperty(APOLLO_CONFIG_SERVICE)); bootstrapArgs.put(APOLLO_CLIENT_MONITOR_EXTERNAL_TYPE, configUtil.getMonitorExternalType()); - bootstrapArgs.put(APOLLO_CLIENT_MONITOR_ENABLED, configUtil.getClientMonitorEnabled()); + bootstrapArgs.put(APOLLO_CLIENT_MONITOR_ENABLED, configUtil.isClientMonitorEnabled()); bootstrapArgs.put(APOLLO_CLIENT_MONITOR_EXTERNAL_EXPORT_PERIOD, configUtil.getMonitorExternalExportPeriod()); bootstrapArgs.put(APOLLO_META, configUtil.getMetaServerDomainName()); bootstrapArgs.put(APOLLO_PROPERTY_NAMES_CACHE_ENABLE, configUtil.isPropertyNamesCacheEnabled()); bootstrapArgs.put(APOLLO_PROPERTY_ORDER_ENABLE, configUtil.isPropertiesOrderEnabled()); - bootstrapArgs.put(APOLLO_CLIENT_MONITOR_JMX_ENABLED, configUtil.getClientMonitorJmxEnabled()); + bootstrapArgs.put(APOLLO_CLIENT_MONITOR_JMX_ENABLED, configUtil.isClientMonitorJmxEnabled()); bootstrapArgs.put(APOLLO_CLIENT_MONITOR_EXCEPTION_QUEUE_SIZE, configUtil.getMonitorExceptionQueueSize()); bootstrapArgs.put(APP_ID, configUtil.getAppId()); @@ -98,123 +97,12 @@ public boolean isMetricsSampleUpdated() { } @Override - public String getStartupParams(String key) { - return Optional.ofNullable(bootstrapArgs.get(key)).orElse("").toString(); + public Map getBootstrapArgs() { + return bootstrapArgs; } @Override - public String getConfigServiceUrl() { - return bootstrapArgs.get(CONFIG_SERVICE_URL).toString(); - } - - - @Override - public String getAccessKeySecret() { - return bootstrapArgs.getOrDefault(APOLLO_ACCESS_KEY_SECRET, "").toString(); - } - - @Override - public Boolean getAutoUpdateInjectedSpringProperties() { - return (Boolean) bootstrapArgs.get(APOLLO_AUTO_UPDATE_INJECTED_SPRING_PROPERTIES); - } - - @Override - public Boolean getBootstrapEnabled() { - return (Boolean) bootstrapArgs.get(APOLLO_BOOTSTRAP_ENABLED); - } - - @Override - public String getBootstrapNamespaces() { - return (String) bootstrapArgs.get(APOLLO_BOOTSTRAP_NAMESPACES); - } - - @Override - public Boolean getBootstrapEagerLoadEnabled() { - return (Boolean) bootstrapArgs.get(APOLLO_BOOTSTRAP_EAGER_LOAD_ENABLED); - } - - @Override - public Boolean getOverrideSystemProperties() { - return (Boolean) bootstrapArgs.get(APOLLO_OVERRIDE_SYSTEM_PROPERTIES); - } - - @Override - public String getCacheDir() { - return bootstrapArgs.get(APOLLO_CACHE_DIR).toString(); - } - - @Override - public String getCluster() { - return bootstrapArgs.get(APOLLO_CLUSTER).toString(); - } - - @Override - public String getConfigService() { - return bootstrapArgs.get(APOLLO_CONFIG_SERVICE).toString(); - } - - @Override - public String getClientMonitorExternalForm() { - return bootstrapArgs.get(APOLLO_CLIENT_MONITOR_EXTERNAL_TYPE).toString(); - } - - @Override - public Boolean getClientMonitorEnabled() { - return (Boolean) bootstrapArgs.get(APOLLO_CLIENT_MONITOR_ENABLED); - } - - @Override - public Boolean getClientMonitorJmxEnabled() { - return (Boolean) bootstrapArgs.get(APOLLO_CLIENT_MONITOR_JMX_ENABLED); - } - - @Override - public long getClientMonitorExternalExportPeriod() { - return (Long) bootstrapArgs.get(APOLLO_CLIENT_MONITOR_EXTERNAL_EXPORT_PERIOD); - } - - @Override - public int getClientMonitorExceptionSaveSize() { - return (int) bootstrapArgs.get(APOLLO_CLIENT_MONITOR_EXCEPTION_QUEUE_SIZE); - } - - @Override - public String getApolloMeta() { - return bootstrapArgs.get(APOLLO_META).toString(); - } - - @Override - public Boolean getPropertyNamesCacheEnable() { - return (Boolean) bootstrapArgs.get(APOLLO_PROPERTY_NAMES_CACHE_ENABLE); - } - - @Override - public Boolean getPropertyOrderEnable() { - return (Boolean) bootstrapArgs.get(APOLLO_PROPERTY_ORDER_ENABLE); - } - - @Override - public String getMetaLatestFreshTime() { - return bootstrapArgs.get(META_FRESH).toString(); - } - - @Override - public String getVersion() { - return bootstrapArgs.get(VERSION).toString(); - } - - @Override - public String getEnv() { - return bootstrapArgs.get(ENV).toString(); - } - - @Override - public String getAppId() { - return bootstrapArgs.get(APP_ID).toString(); - } - - @Override - public Map getBootstrapArgs() { + public Map getBootstrapArgsString() { return bootstrapArgsString; } } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientExceptionApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientExceptionApi.java index f39f6ba0..c7897c1c 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientExceptionApi.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientExceptionApi.java @@ -27,11 +27,11 @@ import com.ctrip.framework.apollo.monitor.internal.listener.AbstractApolloClientMonitorEventListener; import com.ctrip.framework.apollo.monitor.internal.event.ApolloClientMonitorEvent; import com.ctrip.framework.apollo.util.ConfigUtil; +import com.google.common.collect.EvictingQueue; +import com.google.common.collect.Queues; import java.util.ArrayList; -import java.util.Collections; import java.util.List; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.BlockingQueue; +import java.util.Queue; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; @@ -42,48 +42,41 @@ public class DefaultApolloClientExceptionApi extends AbstractApolloClientMonitorEventListener implements ApolloClientExceptionMonitorApi, ApolloClientJmxExceptionMBean { - private final AtomicInteger exceptionNum = new AtomicInteger(0); - private int monitorExceptionQueueSize; - private final BlockingQueue exceptions; + private final AtomicInteger exceptionCountFromStartup = new AtomicInteger(0); + private final Queue exceptionsQueue; public DefaultApolloClientExceptionApi() { super(TAG_ERROR); - monitorExceptionQueueSize = ApolloInjector.getInstance(ConfigUtil.class) + int monitorExceptionQueueSize = ApolloInjector.getInstance(ConfigUtil.class) .getMonitorExceptionQueueSize(); - if (monitorExceptionQueueSize <= 0) { - monitorExceptionQueueSize = 25; - } - exceptions = new ArrayBlockingQueue<>( + EvictingQueue evictingQueue = EvictingQueue.create( monitorExceptionQueueSize); + exceptionsQueue = Queues.synchronizedQueue(evictingQueue); } @Override public List getApolloConfigExceptionList() { - return new ArrayList<>(exceptions); + return new ArrayList<>(exceptionsQueue); + } + + @Override + public Integer getExceptionCountFromStartup() { + return exceptionCountFromStartup.get(); } @Override public void collect0(ApolloClientMonitorEvent event) { ApolloConfigException exception = event.getAttachmentValue(THROWABLE); if (exception != null) { - addExceptionToQueue(exception); - exceptionNum.incrementAndGet(); - createOrUpdateCounterSample(METRICS_EXCEPTION_NUM, METRICS_EXCEPTION_NUM, - Collections.emptyMap(), - 1); - } - } - - private void addExceptionToQueue(ApolloConfigException exception) { - if (exceptions.size() >= monitorExceptionQueueSize) { - exceptions.poll(); + exceptionsQueue.add(exception); + exceptionCountFromStartup.incrementAndGet(); + createOrUpdateCounterSample(METRICS_EXCEPTION_NUM, 1); } - exceptions.add(exception); } @Override public List getApolloConfigExceptionDetails() { - return exceptions.stream() + return exceptionsQueue.stream() .map(ApolloConfigException::getMessage) .collect(Collectors.toList()); } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientNamespaceApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientNamespaceApi.java index 3fc072ed..a28ee09f 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientNamespaceApi.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientNamespaceApi.java @@ -29,6 +29,7 @@ import com.ctrip.framework.apollo.monitor.internal.event.ApolloClientMonitorEvent; import com.google.common.collect.Maps; import com.google.common.collect.Sets; +import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -77,14 +78,6 @@ public void collect0(ApolloClientMonitorEvent event) { } } - private void handleNamespaceNotFound(String namespace) { - namespace404.add(namespace); - } - - private void handleNamespaceTimeout(String namespace) { - namespaceTimeout.add(namespace); - } - private void handleNormalNamespace(String namespace, ApolloClientMonitorEvent event) { namespace404.remove(namespace); namespaceTimeout.remove(namespace); @@ -115,23 +108,30 @@ private void collectMetrics(ApolloClientMonitorEvent event, NamespaceMetrics nam } } + private void handleNamespaceNotFound(String namespace) { + namespace404.add(namespace); + } + + private void handleNamespaceTimeout(String namespace) { + namespaceTimeout.add(namespace); + } + + private void handleUsageEvent(NamespaceMetrics namespaceMetrics, String namespace) { namespaceMetrics.incrementUsageCount(); - String mapKey = namespace + ApolloClientMonitorConstant.METRICS_NAMESPACE_USAGE; - createOrUpdateCounterSample(mapKey, ApolloClientMonitorConstant.METRICS_NAMESPACE_USAGE, - Collections.singletonMap(NAMESPACE, namespace), 1); + createOrUpdateCounterSample(ApolloClientMonitorConstant.METRICS_NAMESPACE_USAGE, + new String[]{NAMESPACE}, new String[]{namespace}, 1); } private void handleUpdateTimeEvent(ApolloClientMonitorEvent event, NamespaceMetrics namespaceMetrics) { - long updateTime = event.getAttachmentValue(ApolloClientMonitorConstant.TIMESTAMP); - namespaceMetrics.setLatestUpdateTime(updateTime); + namespaceMetrics.setLatestUpdateTime(LocalDateTime.now()); } private void handleFirstLoadSpendEvent(ApolloClientMonitorEvent event, NamespaceMetrics namespaceMetrics) { long firstLoadSpendTime = event.getAttachmentValue(ApolloClientMonitorConstant.TIMESTAMP); - namespaceMetrics.setFirstLoadSpend(firstLoadSpendTime); + namespaceMetrics.setFirstLoadTimeSpendInMs(firstLoadSpendTime); } private void handleReleaseKeyEvent(ApolloClientMonitorEvent event, @@ -144,32 +144,26 @@ private void handleReleaseKeyEvent(ApolloClientMonitorEvent event, public void export0() { namespaces.forEach((namespace, metrics) -> { // update NamespaceMetrics - createOrUpdateGaugeSample(namespace + METRICS_NAMESPACE_FIRST_LOAD_SPEND, + createOrUpdateGaugeSample( METRICS_NAMESPACE_FIRST_LOAD_SPEND, - Collections.singletonMap(NAMESPACE, namespace), - metrics.getFirstLoadSpend()); + new String[]{NAMESPACE}, new String[]{namespace}, + metrics.getFirstLoadTimeSpendInMs()); - createOrUpdateGaugeSample(namespace + METRICS_NAMESPACE_ITEM_NUM, + createOrUpdateGaugeSample( METRICS_NAMESPACE_ITEM_NUM, - Collections.singletonMap(NAMESPACE, namespace), + new String[]{NAMESPACE}, new String[]{namespace}, m_configs.get(namespace).getPropertyNames().size()); }); // update ConfigFile num createOrUpdateGaugeSample(METRICS_CONFIG_FILE_NUM, - METRICS_CONFIG_FILE_NUM, - Collections.emptyMap(), m_configFiles.size()); // update NamespaceStatus metrics createOrUpdateGaugeSample(METRICS_NAMESPACE_NOT_FOUND, - METRICS_NAMESPACE_NOT_FOUND, - Collections.emptyMap(), namespace404.size()); createOrUpdateGaugeSample(METRICS_NAMESPACE_TIMEOUT, - METRICS_NAMESPACE_TIMEOUT, - Collections.emptyMap(), namespaceTimeout.size()); } @@ -189,53 +183,28 @@ public List getTimeoutNamespaces() { } @Override - public Integer getNamespaceItemsNum(String namespace) { + public Map getNamespaceMetricsString() { + Map namespaceMetricsStringMap = Maps.newHashMap(); + namespaces.forEach((namespace, metrics) -> { + NamespaceMetricsString namespaceMetricsString = new NamespaceMetricsString(); + namespaceMetricsString.setFirstLoadTimeSpendInMs(metrics.getFirstLoadTimeSpendInMs()); + namespaceMetricsString.setLatestUpdateTime(metrics.getLatestUpdateTime().toString()); + namespaceMetricsString.setUsageCount(metrics.getUsageCount()); + namespaceMetricsString.setReleaseKey(metrics.getReleaseKey()); + namespaceMetricsStringMap.put(namespace, namespaceMetricsString); + }); + return namespaceMetricsStringMap; + } + + @Override + public Integer getNamespacePropertySize(String namespace) { Config config = m_configs.get(namespace); return (config != null) ? config.getPropertyNames().size() : 0; } @Override - public Integer getConfigFileNum() { - return m_configFiles.size(); + public List getConfigFileNamespaces() { + return new ArrayList<>(m_configFiles.keySet()); } - public static class NamespaceMetrics { - - private int usageCount; - private long firstLoadSpend; - private long latestUpdateTime = System.currentTimeMillis(); - private String releaseKey = ""; - - public String getReleaseKey() { - return releaseKey; - } - - public void setReleaseKey(String releaseKey) { - this.releaseKey = releaseKey; - } - - public int getUsageCount() { - return usageCount; - } - - public void incrementUsageCount() { - usageCount++; - } - - public long getFirstLoadSpend() { - return firstLoadSpend; - } - - public void setFirstLoadSpend(long firstLoadSpend) { - this.firstLoadSpend = firstLoadSpend; - } - - public long getLatestUpdateTime() { - return latestUpdateTime; - } - - public void setLatestUpdateTime(long latestUpdateTime) { - this.latestUpdateTime = latestUpdateTime; - } - } } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientThreadPoolApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientThreadPoolApi.java index 91113eca..84316629 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientThreadPoolApi.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientThreadPoolApi.java @@ -25,11 +25,7 @@ import com.ctrip.framework.apollo.monitor.internal.exporter.AbstractApolloClientMetricsExporter; import com.ctrip.framework.apollo.monitor.internal.jmx.mbean.ApolloClientJmxThreadPoolMBean; import com.ctrip.framework.apollo.monitor.internal.listener.AbstractApolloClientMonitorEventListener; -import com.ctrip.framework.apollo.monitor.internal.event.ApolloClientMonitorEvent; import com.google.common.collect.Maps; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadPoolExecutor; @@ -68,26 +64,34 @@ public void export0() { executorMap.forEach((key, value) -> exportThreadPoolMetrics(value, key)); } - private void exportThreadPoolMetrics(ApolloThreadPoolInfo info, String name) { - List metrics = Arrays.asList( - (double) info.getActiveTaskCount(), - (double) info.getQueueSize(), - (double) info.getCompletedTaskCount(), - (double) info.getPoolSize(), - (double) info.getTotalTaskCount(), - (double) info.getCorePoolSize(), - (double) info.getMaximumPoolSize(), - (double) info.getLargestPoolSize(), - (double) info.getQueueCapacity(), - (double) info.getQueueRemainingCapacity(), - info.getCurrentLoad() - ); - - for (int i = 0; i < metrics.size(); i++) { - String key = name + METRICS_THREAD_POOL_PARAMS[i + 1]; - createOrUpdateGaugeSample(key, METRICS_THREAD_POOL_PARAMS[i + 1], - Collections.singletonMap(METRICS_THREAD_POOL_PARAMS[0], name), metrics.get(i)); - } + private void exportThreadPoolMetrics(ApolloThreadPoolInfo info, String threadPoolName) { + + createOrUpdateGaugeSample(METRICS_THREAD_POOL_ACTIVE_TASK_COUNT, + new String[]{METRICS_THREAD_POOL_NAME}, new String[]{threadPoolName}, + info.getActiveTaskCount()); + createOrUpdateGaugeSample(METRICS_THREAD_POOL_QUEUE_SIZE, + new String[]{METRICS_THREAD_POOL_NAME}, new String[]{threadPoolName}, + info.getQueueSize()); + createOrUpdateGaugeSample(METRICS_THREAD_POOL_COMPLETED_TASK_COUNT, + new String[]{METRICS_THREAD_POOL_NAME}, new String[]{threadPoolName}, + (double) info.getCompletedTaskCount()); + createOrUpdateGaugeSample(METRICS_THREAD_POOL_POOL_SIZE, new String[]{METRICS_THREAD_POOL_NAME}, + new String[]{threadPoolName}, info.getPoolSize()); + createOrUpdateGaugeSample(METRICS_THREAD_POOL_TOTAL_TASK_COUNT, + new String[]{METRICS_THREAD_POOL_NAME}, new String[]{threadPoolName}, + (double) info.getTotalTaskCount()); + createOrUpdateGaugeSample(METRICS_THREAD_POOL_CORE_POOL_SIZE, + new String[]{METRICS_THREAD_POOL_NAME}, new String[]{threadPoolName}, + info.getCorePoolSize()); + createOrUpdateGaugeSample(METRICS_THREAD_POOL_MAXIMUM_POOL_SIZE, + new String[]{METRICS_THREAD_POOL_NAME}, new String[]{threadPoolName}, + info.getMaximumPoolSize()); + createOrUpdateGaugeSample(METRICS_THREAD_POOL_LARGEST_POOL_SIZE, + new String[]{METRICS_THREAD_POOL_NAME}, new String[]{threadPoolName}, + info.getLargestPoolSize()); + createOrUpdateGaugeSample(METRICS_THREAD_POOL_QUEUE_REMAINING_CAPACITY, + new String[]{METRICS_THREAD_POOL_NAME}, new String[]{threadPoolName}, + info.getQueueRemainingCapacity()); } @@ -121,57 +125,4 @@ public ApolloThreadPoolInfo getAbstractConfigFileThreadPoolInfo() { public ApolloThreadPoolInfo getMetricsExporterThreadPoolInfo() { return executorMap.get(METRICS_EXPORTER); } - - public static class ApolloThreadPoolInfo { - - private final ThreadPoolExecutor executor; - - public ApolloThreadPoolInfo(ThreadPoolExecutor executor) { - this.executor = executor; - } - - public int getActiveTaskCount() { - return executor.getActiveCount(); - } - - public int getQueueSize() { - return executor.getQueue().size(); - } - - public int getCorePoolSize() { - return executor.getCorePoolSize(); - } - - public int getMaximumPoolSize() { - return executor.getMaximumPoolSize(); - } - - public int getPoolSize() { - return executor.getPoolSize(); - } - - public long getTotalTaskCount() { - return executor.getTaskCount(); - } - - public long getCompletedTaskCount() { - return executor.getCompletedTaskCount(); - } - - public int getLargestPoolSize() { - return executor.getLargestPoolSize(); - } - - public int getQueueCapacity() { - return executor.getQueue().remainingCapacity() + executor.getQueue().size(); - } - - public int getQueueRemainingCapacity() { - return executor.getQueue().remainingCapacity(); - } - - public double getCurrentLoad() { - return (double) executor.getPoolSize() / executor.getMaximumPoolSize(); - } - } } \ No newline at end of file diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientBootstrapArgsMonitorApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientBootstrapArgsMonitorApi.java index f7b442f1..88ddd7b8 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientBootstrapArgsMonitorApi.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientBootstrapArgsMonitorApi.java @@ -28,122 +28,7 @@ public class NullClientBootstrapArgsMonitorApi implements ApolloClientBootstrapA ApolloClientJmxBootstrapArgsMBean { @Override - public String getStartupParams(String key) { - return ""; - } - - @Override - public String getConfigServiceUrl() { - return ""; - } - - @Override - public String getAccessKeySecret() { - return ""; - } - - @Override - public Boolean getAutoUpdateInjectedSpringProperties() { - return false; - } - - @Override - public Boolean getBootstrapEnabled() { - return null; - } - - @Override - public String getBootstrapNamespaces() { - return ""; - } - - @Override - public Boolean getBootstrapEagerLoadEnabled() { - return null; - } - - @Override - public Boolean getOverrideSystemProperties() { - return null; - } - - @Override - public String getCacheDir() { - return ""; - } - - @Override - public String getCluster() { - return ""; - } - - @Override - public String getConfigService() { - return ""; - } - - @Override - public Boolean getClientMonitorEnabled() { - return null; - } - - @Override - public Boolean getClientMonitorJmxEnabled() { - return null; - } - - @Override - public String getClientMonitorExternalForm() { - return ""; - } - - @Override - public long getClientMonitorExternalExportPeriod() { - return 0; - } - - @Override - public int getClientMonitorExceptionSaveSize() { - return 0; - } - - @Override - public String getApolloMeta() { - return ""; - } - - @Override - public String getMetaLatestFreshTime() { - return ""; - } - - @Override - public Boolean getPropertyNamesCacheEnable() { - return null; - } - - @Override - public Boolean getPropertyOrderEnable() { - return null; - } - - @Override - public String getVersion() { - return ""; - } - - @Override - public String getEnv() { - return ""; - } - - @Override - public String getAppId() { - return ""; - } - - @Override - public Map getBootstrapArgs() { + public Map getBootstrapArgsString() { return Collections.emptyMap(); } } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientExceptionMonitorApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientExceptionMonitorApi.java index 3f0a4bdd..5a21f802 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientExceptionMonitorApi.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientExceptionMonitorApi.java @@ -32,6 +32,11 @@ public List getApolloConfigExceptionList() { return Collections.emptyList(); } + @Override + public Integer getExceptionCountFromStartup() { + return 0; + } + @Override public List getApolloConfigExceptionDetails() { return Collections.emptyList(); diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientNamespaceMonitorApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientNamespaceMonitorApi.java index 051d00d3..9585823b 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientNamespaceMonitorApi.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientNamespaceMonitorApi.java @@ -18,7 +18,6 @@ import com.ctrip.framework.apollo.monitor.api.ApolloClientNamespaceMonitorApi; import com.ctrip.framework.apollo.monitor.internal.jmx.mbean.ApolloClientJmxNamespaceMBean; -import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientNamespaceApi.NamespaceMetrics; import java.util.Collections; import java.util.List; import java.util.Map; @@ -46,13 +45,18 @@ public List getTimeoutNamespaces() { } @Override - public Integer getNamespaceItemsNum(String namespace) { - return 0; + public Map getNamespaceMetricsString() { + return Collections.emptyMap(); } @Override - public Integer getConfigFileNum() { + public Integer getNamespacePropertySize(String namespace) { return 0; } + @Override + public List getConfigFileNamespaces() { + return Collections.emptyList(); + } + } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientThreadPoolMonitorApi.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientThreadPoolMonitorApi.java index 0a779adf..03e5c1b5 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientThreadPoolMonitorApi.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientThreadPoolMonitorApi.java @@ -18,7 +18,6 @@ import com.ctrip.framework.apollo.monitor.api.ApolloClientThreadPoolMonitorApi; import com.ctrip.framework.apollo.monitor.internal.jmx.mbean.ApolloClientJmxThreadPoolMBean; -import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientThreadPoolApi.ApolloThreadPoolInfo; import java.util.Collections; import java.util.Map; @@ -28,6 +27,8 @@ public class NullClientThreadPoolMonitorApi implements ApolloClientThreadPoolMonitorApi, ApolloClientJmxThreadPoolMBean { + private final ApolloThreadPoolInfo NULL_THREAD_POOL_INFO = new ApolloThreadPoolInfo(); + @Override public Map getThreadPoolInfo() { return Collections.emptyMap(); @@ -35,21 +36,21 @@ public Map getThreadPoolInfo() { @Override public ApolloThreadPoolInfo getRemoteConfigRepositoryThreadPoolInfo() { - return null; + return NULL_THREAD_POOL_INFO; } @Override public ApolloThreadPoolInfo getAbstractConfigThreadPoolInfo() { - return null; + return NULL_THREAD_POOL_INFO; } @Override public ApolloThreadPoolInfo getAbstractConfigFileThreadPoolInfo() { - return null; + return NULL_THREAD_POOL_INFO; } @Override public ApolloThreadPoolInfo getMetricsExporterThreadPoolInfo() { - return null; + return NULL_THREAD_POOL_INFO; } } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/CounterModel.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/CounterModel.java index 610d61cd..566ce718 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/CounterModel.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/CounterModel.java @@ -16,7 +16,7 @@ */ package com.ctrip.framework.apollo.monitor.internal.model; -import com.ctrip.framework.apollo.monitor.internal.enums.MeterEnums; +import com.ctrip.framework.apollo.monitor.internal.enums.MetricTypeEnums; /** * @author Rawven @@ -31,7 +31,7 @@ private CounterModel(String name, double num) { throw new IllegalArgumentException("Number must be a valid double"); } setName(name); - setType(MeterEnums.COUNTER); + setType(MetricTypeEnums.COUNTER); this.value.set(num); } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/GaugeModel.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/GaugeModel.java index 91150100..0abf0699 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/GaugeModel.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/GaugeModel.java @@ -16,8 +16,7 @@ */ package com.ctrip.framework.apollo.monitor.internal.model; -import com.ctrip.framework.apollo.monitor.internal.enums.MeterEnums; -import com.google.common.util.concurrent.AtomicDouble; +import com.ctrip.framework.apollo.monitor.internal.enums.MetricTypeEnums; /** * @author Rawven @@ -29,7 +28,7 @@ private GaugeModel(String name, double value) { throw new IllegalArgumentException("Name cannot be null or empty"); } setName(name); - setType(MeterEnums.GAUGE); + setType(MetricTypeEnums.GAUGE); this.value.set(value); } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/SampleModel.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/SampleModel.java index c59c80b4..177d7bd3 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/SampleModel.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/model/SampleModel.java @@ -16,9 +16,7 @@ */ package com.ctrip.framework.apollo.monitor.internal.model; -import static com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorConstant.APOLLO_CLIENT; - -import com.ctrip.framework.apollo.monitor.internal.enums.MeterEnums; +import com.ctrip.framework.apollo.monitor.internal.enums.MetricTypeEnums; import com.google.common.util.concurrent.AtomicDouble; import java.util.Collections; import java.util.HashMap; @@ -32,14 +30,14 @@ public class SampleModel { protected final AtomicDouble value = new AtomicDouble(); private final Map tags = new HashMap<>(1); private String name; - private MeterEnums type; + private MetricTypeEnums type; public String getName() { return name; } public void setName(String name) { - this.name = APOLLO_CLIENT + name; + this.name = name; } public SampleModel putTag(String key, String value) { @@ -52,11 +50,11 @@ public SampleModel putTags(Map tags) { return this; } - public MeterEnums getType() { + public MetricTypeEnums getType() { return type; } - public void setType(MeterEnums type) { + public void setType(MetricTypeEnums type) { this.type = type; } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMessageProducerComposite.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMessageProducerComposite.java index 319baa38..8ae27a72 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMessageProducerComposite.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMessageProducerComposite.java @@ -20,7 +20,6 @@ import com.ctrip.framework.apollo.tracer.spi.MessageProducer; import com.ctrip.framework.apollo.tracer.spi.Transaction; import java.util.List; -import java.util.Objects; /** * message producer composite diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMonitorMessageProducer.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMonitorMessageProducer.java index 9397b5e5..b744ce2d 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMonitorMessageProducer.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMonitorMessageProducer.java @@ -21,11 +21,12 @@ import com.ctrip.framework.apollo.exceptions.ApolloConfigException; -import com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorConstant; import com.ctrip.framework.apollo.monitor.internal.event.ApolloClientMonitorEventFactory; +import com.ctrip.framework.apollo.monitor.internal.event.ApolloClientMonitorEventPublisher; import com.ctrip.framework.apollo.tracer.spi.MessageProducer; import com.ctrip.framework.apollo.tracer.spi.Transaction; -import java.time.Instant; + +import java.time.LocalDate; import java.util.Arrays; import java.util.Collections; import java.util.List; @@ -50,12 +51,12 @@ public class ApolloClientMonitorMessageProducer implements MessageProducer { @Override public void logError(Throwable cause) { - publishErrorEvent(TAG_ERROR, cause); + publishErrorEvent(cause); } @Override public void logError(String message, Throwable cause) { - publishErrorEvent(TAG_ERROR, cause); + publishErrorEvent(cause); } @Override @@ -69,17 +70,10 @@ public void logEvent(String type, String name) { } } - private void publishErrorEvent(String tag, Throwable cause) { - ApolloClientMonitorEventFactory.getInstance().createEvent(tag) - .withTag(tag) - .putAttachment(THROWABLE, cause) - .publish(); - } - private void handleTaggedEvent(String type, String name) { switch (type) { case APOLLO_CONFIGSERVICE: - name = name.substring(HELP_STR.length()); + name = name.substring(APOLLO_CONFIGSERVICE_HELP_STR.length()); // fall through case APOLLO_CLIENT_CONFIGCHANGES: publishConfigChangeEvent(name); @@ -110,68 +104,76 @@ private void handleTaggedEvent(String type, String name) { } } + + private void publishErrorEvent(Throwable cause) { + ApolloClientMonitorEventPublisher.publish( + ApolloClientMonitorEventFactory.getInstance().createEvent(TAG_ERROR) + .withTag(TAG_ERROR) + .putAttachment(THROWABLE, cause)); + } + private void publishConfigChangeEvent(String name) { - ApolloClientMonitorEventFactory.getInstance() - .createEvent(METRICS_NAMESPACE_LATEST_UPDATE_TIME) - .putAttachment(NAMESPACE, name) - .putAttachment(TIMESTAMP, System.currentTimeMillis()) - .withTag(TAG_NAMESPACE) - .publish(); + ApolloClientMonitorEventPublisher.publish( + ApolloClientMonitorEventFactory.getInstance() + .createEvent(METRICS_NAMESPACE_LATEST_UPDATE_TIME) + .putAttachment(NAMESPACE, name) + .withTag(TAG_NAMESPACE)); } private void publishMetaServiceEvent() { - ApolloClientMonitorEventFactory.getInstance().createEvent(META_FRESH) - .withTag(TAG_BOOTSTRAP) - .putAttachment(META_FRESH, DATE_FORMATTER.format(Instant.now())) - .publish(); + ApolloClientMonitorEventPublisher.publish( + ApolloClientMonitorEventFactory.getInstance().createEvent(META_FRESH) + .withTag(TAG_BOOTSTRAP) + .putAttachment(META_FRESH, LocalDate.now().toString())); } private void publishConfigServiceEvent(String name) { - ApolloClientMonitorEventFactory.getInstance().createEvent(CONFIG_SERVICE_URL) - .withTag(TAG_BOOTSTRAP) - .putAttachment(CONFIG_SERVICE_URL, name) - .publish(); + ApolloClientMonitorEventPublisher.publish( + ApolloClientMonitorEventFactory.getInstance().createEvent(CONFIG_SERVICE_URL) + .withTag(TAG_BOOTSTRAP) + .putAttachment(CONFIG_SERVICE_URL, name)); } private void publishClientVersionEvent(String name) { - ApolloClientMonitorEventFactory.getInstance().createEvent(VERSION) - .withTag(TAG_BOOTSTRAP) - .putAttachment(VERSION, name) - .publish(); + ApolloClientMonitorEventPublisher.publish( + ApolloClientMonitorEventFactory.getInstance().createEvent(VERSION) + .withTag(TAG_BOOTSTRAP) + .putAttachment(VERSION, name)); } private void publishNamespaceTimeoutEvent(String name) { - ApolloClientMonitorEventFactory.getInstance().createEvent(APOLLO_CLIENT_NAMESPACE_TIMEOUT) - .putAttachment(NAMESPACE, name) - .withTag(TAG_NAMESPACE) - .publish(); + ApolloClientMonitorEventPublisher.publish( + ApolloClientMonitorEventFactory.getInstance().createEvent(APOLLO_CLIENT_NAMESPACE_TIMEOUT) + .putAttachment(NAMESPACE, name) + .withTag(TAG_NAMESPACE)); } private void publishNamespaceNotFoundEvent(String name) { - ApolloClientMonitorEventFactory.getInstance().createEvent(APOLLO_CLIENT_NAMESPACE_NOT_FOUND) - .withTag(TAG_NAMESPACE) - .putAttachment(NAMESPACE, name) - .publish(); + ApolloClientMonitorEventPublisher.publish( + ApolloClientMonitorEventFactory.getInstance().createEvent(APOLLO_CLIENT_NAMESPACE_NOT_FOUND) + .withTag(TAG_NAMESPACE) + .putAttachment(NAMESPACE, name)); } private void handleClientConfigEvent(String type, String name) { String namespace = type.substring(APOLLO_CLIENT_CONFIGS.length()); - ApolloClientMonitorEventFactory.getInstance().createEvent(NAMESPACE_RELEASE_KEY) - .withTag(TAG_NAMESPACE) - .putAttachment(NAMESPACE_RELEASE_KEY, name) - .putAttachment(NAMESPACE, namespace) - .publish(); + ApolloClientMonitorEventPublisher.publish( + ApolloClientMonitorEventFactory.getInstance().createEvent(NAMESPACE_RELEASE_KEY) + .withTag(TAG_NAMESPACE) + .putAttachment(NAMESPACE_RELEASE_KEY, name) + .putAttachment(NAMESPACE, namespace)); } private void handleFirstLoadTimeEvent(String type, String name) { - String namespace = type.substring(APOLLO_CLIENT_NAMESPACE_FIRST_LOAD_SPEND.length()); + String[] split = type.split(":"); + String namespace = split[1]; long firstLoadTime = Long.parseLong(name); - ApolloClientMonitorEventFactory.getInstance() - .createEvent(APOLLO_CLIENT_NAMESPACE_FIRST_LOAD_SPEND) - .putAttachment(NAMESPACE, namespace) - .putAttachment(TIMESTAMP, firstLoadTime) - .withTag(TAG_NAMESPACE) - .publish(); + ApolloClientMonitorEventPublisher.publish( + ApolloClientMonitorEventFactory.getInstance() + .createEvent(APOLLO_CLIENT_NAMESPACE_FIRST_LOAD_SPEND) + .putAttachment(NAMESPACE, namespace) + .putAttachment(TIMESTAMP, firstLoadTime) + .withTag(TAG_NAMESPACE)); } @Override @@ -183,10 +185,11 @@ public void logEvent(String type, String name, String status, String nameValuePa public void logMetricsForCount(String name) { String[] split = name.split(":"); if (split.length == 2 && APOLLO_CLIENT_NAMESPACE_USAGE.equals(split[0])) { - ApolloClientMonitorEventFactory.getInstance().createEvent(APOLLO_CLIENT_NAMESPACE_USAGE) - .putAttachment(ApolloClientMonitorConstant.NAMESPACE, split[1]) - .withTag(TAG_NAMESPACE) - .publish(); + ApolloClientMonitorEventPublisher.publish( + ApolloClientMonitorEventFactory.getInstance() + .createEvent(APOLLO_CLIENT_NAMESPACE_USAGE) + .putAttachment(NAMESPACE, split[1]) + .withTag(TAG_NAMESPACE)); } } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/util/ConfigUtil.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/util/ConfigUtil.java index 123c69df..24f674e6 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/util/ConfigUtil.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/util/ConfigUtil.java @@ -38,21 +38,18 @@ public class ConfigUtil { private static final Logger logger = LoggerFactory.getLogger(ConfigUtil.class); - private final RateLimiter warnLogRateLimiter; + /** * qps limit: discovery config service from meta *

* 1 times per second */ private int discoveryQPS = 1; - /** - * 1 second - */ + /** 1 second */ private int discoveryConnectTimeout = 1000; - /** - * 1 second - */ + /** 1 second */ private int discoveryReadTimeout = 1000; + private int refreshInterval = 5; private TimeUnit refreshIntervalTimeUnit = TimeUnit.MINUTES; private int connectTimeout = 1000; //1 second @@ -69,6 +66,7 @@ public class ConfigUtil { private TimeUnit configCacheExpireTimeUnit = TimeUnit.MINUTES;//1 minute private long longPollingInitialDelayInMills = 2000;//2 seconds private boolean autoUpdateInjectedSpringProperties = true; + private final RateLimiter warnLogRateLimiter; private boolean propertiesOrdered = false; private boolean propertyNamesCacheEnabled = false; private boolean propertyFileCacheEnabled = true; @@ -100,19 +98,6 @@ public ConfigUtil() { initClientMonitorExceptionQueueSize(); } - - static Integer getCustomizedIntegerValue(String systemKey) { - String customizedValue = System.getProperty(systemKey); - if (!Strings.isNullOrEmpty(customizedValue)) { - try { - return Integer.parseInt(customizedValue); - } catch (Throwable ex) { - logger.error("Config for {} is invalid: {}", systemKey, customizedValue); - } - } - return null; - } - /** * Get the app id for the current application. * @@ -247,6 +232,18 @@ public TimeUnit getRefreshIntervalTimeUnit() { return refreshIntervalTimeUnit; } + static Integer getCustomizedIntegerValue(String systemKey) { + String customizedValue = System.getProperty(systemKey); + if (!Strings.isNullOrEmpty(customizedValue)) { + try { + return Integer.parseInt(customizedValue); + } catch (Throwable ex) { + logger.error("Config for {} is invalid: {}", systemKey, customizedValue); + } + } + return null; + } + private void initQPS() { { Integer value = getCustomizedIntegerValue("apollo.discoveryConnectTimeout"); @@ -353,8 +350,7 @@ private String getDeprecatedCustomizedCacheRoot() { } if (Strings.isNullOrEmpty(cacheRoot)) { // 2. Get from OS environment variable - cacheRoot = System.getenv( - ApolloClientSystemConsts.DEPRECATED_APOLLO_CACHE_DIR_ENVIRONMENT_VARIABLES); + cacheRoot = System.getenv(ApolloClientSystemConsts.DEPRECATED_APOLLO_CACHE_DIR_ENVIRONMENT_VARIABLES); if (!Strings.isNullOrEmpty(cacheRoot)) { DeprecatedPropertyNotifyUtil .warn(ApolloClientSystemConsts.DEPRECATED_APOLLO_CACHE_DIR_ENVIRONMENT_VARIABLES, @@ -363,8 +359,7 @@ private String getDeprecatedCustomizedCacheRoot() { } if (Strings.isNullOrEmpty(cacheRoot)) { // 3. Get from server.properties - cacheRoot = Foundation.server() - .getProperty(ApolloClientSystemConsts.DEPRECATED_APOLLO_CACHE_DIR, null); + cacheRoot = Foundation.server().getProperty(ApolloClientSystemConsts.DEPRECATED_APOLLO_CACHE_DIR, null); if (!Strings.isNullOrEmpty(cacheRoot)) { DeprecatedPropertyNotifyUtil.warn(ApolloClientSystemConsts.DEPRECATED_APOLLO_CACHE_DIR, ApolloClientSystemConsts.APOLLO_CACHE_DIR); @@ -372,8 +367,7 @@ private String getDeprecatedCustomizedCacheRoot() { } if (Strings.isNullOrEmpty(cacheRoot)) { // 4. Get from app.properties - cacheRoot = Foundation.app() - .getProperty(ApolloClientSystemConsts.DEPRECATED_APOLLO_CACHE_DIR, null); + cacheRoot = Foundation.app().getProperty(ApolloClientSystemConsts.DEPRECATED_APOLLO_CACHE_DIR, null); if (!Strings.isNullOrEmpty(cacheRoot)) { DeprecatedPropertyNotifyUtil.warn(ApolloClientSystemConsts.DEPRECATED_APOLLO_CACHE_DIR, ApolloClientSystemConsts.APOLLO_CACHE_DIR); @@ -490,30 +484,30 @@ public boolean isOverrideSystemProperties() { } private void initPropertyNamesCacheEnabled() { - propertyNamesCacheEnabled = getPropertyBoolean( - ApolloClientSystemConsts.APOLLO_PROPERTY_NAMES_CACHE_ENABLE, - ApolloClientSystemConsts.APOLLO_PROPERTY_NAMES_CACHE_ENABLE_ENVIRONMENT_VARIABLES, - propertyNamesCacheEnabled); + propertyNamesCacheEnabled = getPropertyBoolean(ApolloClientSystemConsts.APOLLO_PROPERTY_NAMES_CACHE_ENABLE, + ApolloClientSystemConsts.APOLLO_PROPERTY_NAMES_CACHE_ENABLE_ENVIRONMENT_VARIABLES, + propertyNamesCacheEnabled); } private void initPropertyFileCacheEnabled() { propertyFileCacheEnabled = getPropertyBoolean(ApolloClientSystemConsts.APOLLO_CACHE_FILE_ENABLE, - ApolloClientSystemConsts.APOLLO_CACHE_FILE_ENABLE_ENVIRONMENT_VARIABLES, - propertyFileCacheEnabled); + ApolloClientSystemConsts.APOLLO_CACHE_FILE_ENABLE_ENVIRONMENT_VARIABLES, + propertyFileCacheEnabled); } private void initOverrideSystemProperties() { - overrideSystemProperties = getPropertyBoolean( - ApolloClientSystemConsts.APOLLO_OVERRIDE_SYSTEM_PROPERTIES, - ApolloClientSystemConsts.APOLLO_OVERRIDE_SYSTEM_PROPERTIES, - overrideSystemProperties); + overrideSystemProperties = getPropertyBoolean(ApolloClientSystemConsts.APOLLO_OVERRIDE_SYSTEM_PROPERTIES, + ApolloClientSystemConsts.APOLLO_OVERRIDE_SYSTEM_PROPERTIES, + overrideSystemProperties); } - + + private void initClientMonitorExternalType() { monitorExternalType = System.getProperty(ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_EXTERNAL_TYPE); + if (Strings.isNullOrEmpty(monitorExternalType)) { monitorExternalType = Foundation.app() - .getProperty(ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_EXTERNAL_TYPE, null); + .getProperty(ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_EXTERNAL_TYPE, null); } } @@ -522,10 +516,15 @@ public String getMonitorExternalType() { } private void initClientMonitorExternalCollectPeriod() { - Integer value = getCustomizedIntegerValue( - ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_EXTERNAL_EXPORT_PERIOD); - if (null != value){ - monitorExternalExportPeriod = value; + Integer value = getCustomizedIntegerValue(ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_EXTERNAL_EXPORT_PERIOD); + + if (value != null) { + if (value <= 0) { + logger.warn("Config for {} is invalid: {}, remain default value: 10", + ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_EXTERNAL_EXPORT_PERIOD, value); + } else { + monitorExternalExportPeriod = value; + } } } @@ -533,42 +532,53 @@ public long getMonitorExternalExportPeriod() { return monitorExternalExportPeriod; } - private void initClientMonitorEnabled() { String enabled = System.getProperty(ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_ENABLED); + if (enabled == null) { enabled = Foundation.app() - .getProperty(ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_ENABLED, "false"); + .getProperty(ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_ENABLED, "false"); } + clientMonitorEnabled = Boolean.parseBoolean(enabled); } - public boolean getClientMonitorEnabled() { + public boolean isClientMonitorEnabled() { return clientMonitorEnabled; } private void initClientMonitorJmxEnabled() { String enabled = System.getProperty(ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_JMX_ENABLED); + if (enabled == null) { enabled = Foundation.app() - .getProperty(ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_JMX_ENABLED, "false"); + .getProperty(ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_JMX_ENABLED, "false"); } + clientMonitorJmxEnabled = Boolean.parseBoolean(enabled); } - public boolean getClientMonitorJmxEnabled() { + + public boolean isClientMonitorJmxEnabled() { return clientMonitorJmxEnabled; } + private void initClientMonitorExceptionQueueSize() { - Integer value = getCustomizedIntegerValue( - ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_EXCEPTION_QUEUE_SIZE); - if (null != value){ - monitorExceptionQueueSize = value; + Integer value = getCustomizedIntegerValue(ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_EXCEPTION_QUEUE_SIZE); + + if (value != null) { + if (value <= 0) { + logger.warn("Config for {} is invalid: {}, remain default value: 25", + ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_EXCEPTION_QUEUE_SIZE, value); + } else { + monitorExceptionQueueSize = value; + } } } + public int getMonitorExceptionQueueSize() { return monitorExceptionQueueSize; } - + private boolean getPropertyBoolean(String propertyName, String envName, boolean defaultVal) { String enablePropertyNamesCache = System.getProperty(propertyName); if (Strings.isNullOrEmpty(enablePropertyNamesCache)) { @@ -582,9 +592,9 @@ private boolean getPropertyBoolean(String propertyName, String envName, boolean return Boolean.parseBoolean(enablePropertyNamesCache); } catch (Throwable ex) { logger.warn("Config for {} is invalid: {}, set default value: {}", - propertyName, enablePropertyNamesCache, defaultVal); + propertyName, enablePropertyNamesCache, defaultVal); } } return defaultVal; } -} +} \ No newline at end of file diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/ConfigMonitorInitializerTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/ConfigMonitorInitializerTest.java index 6db638c7..25be1005 100644 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/ConfigMonitorInitializerTest.java +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/ConfigMonitorInitializerTest.java @@ -16,102 +16,71 @@ */ package com.ctrip.framework.apollo.internals; -import static org.mockito.Mockito.*; -import static org.junit.Assert.*; - import com.ctrip.framework.apollo.build.MockInjector; -import com.ctrip.framework.apollo.monitor.api.ConfigMonitor; -import com.ctrip.framework.apollo.monitor.internal.DefaultConfigMonitor; -import com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporter; -import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMonitorEventListener; -import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMonitorEventListenerManager; -import com.ctrip.framework.apollo.monitor.internal.listener.DefaultApolloClientMonitorEventListenerManager; -import com.ctrip.framework.apollo.monitor.internal.tracer.ApolloClientMessageProducerComposite; +import com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorContext; +import com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporterFactory; import com.ctrip.framework.apollo.util.ConfigUtil; -import java.util.Collections; -import java.util.List; import org.junit.Before; import org.junit.Test; -import org.slf4j.Logger; - -public class ConfigMonitorInitializerTest { - - private ConfigUtil mockConfigUtil; - private Logger mockLogger; - private DefaultApolloClientMonitorEventListenerManager mockManager; - private ApolloClientMetricsExporter mockMetricsExporter; - private DefaultConfigManager mockConfigManager; - private DefaultConfigMonitor mockConfigMonitor; - - @Before - public void setUp() { - mockConfigUtil = mock(ConfigUtil.class); - when(mockConfigUtil.getMonitorExceptionQueueSize()).thenReturn(100); - when(mockConfigUtil.getClientMonitorEnabled()).thenReturn(false); - mockLogger = mock(Logger.class); - mockManager = mock(DefaultApolloClientMonitorEventListenerManager.class); - mockMetricsExporter = mock(ApolloClientMetricsExporter.class); - mockConfigManager = mock(DefaultConfigManager.class); - mockConfigMonitor = mock(DefaultConfigMonitor.class); - - - // Mock static methods - MockInjector.setInstance(ConfigUtil.class, mockConfigUtil); - MockInjector.setInstance(ApolloClientMonitorEventListenerManager.class, mockManager); - MockInjector.setInstance(ConfigManager.class, mockConfigManager); - MockInjector.setInstance(ConfigMonitor.class, mockConfigMonitor); - - // Reset static state before each test - ConfigMonitorInitializer.reset(); - } - - @Test - public void testInitialize_WhenEnabledAndNotInitialized() { - when(mockManager.getCollectors()).thenReturn(Collections.emptyList()); - doReturn(true).when(mockConfigUtil).getClientMonitorEnabled(); - ConfigMonitorInitializer.initialize(); - - verify(mockManager).setCollectors(anyList()); - verify(mockConfigMonitor).init(any(), any(), any(), any(), any()); - assertTrue(ConfigMonitorInitializer.hasInitialized); // Check hasInitialized flag - } +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; - @Test - public void testInitialize_WhenAlreadyInitialized() { - ConfigMonitorInitializer.hasInitialized = true; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; - ConfigMonitorInitializer.initialize(); - - verify(mockConfigMonitor, never()).init(any(), any(), any(), any(), any()); - } - - @Test - public void testInitialize_WhenClientMonitorDisabled() { - when(mockConfigUtil.getClientMonitorEnabled()).thenReturn(false); - - ConfigMonitorInitializer.initialize(); - - verify(mockManager, never()).setCollectors(anyList()); - verify(mockConfigMonitor, never()).init(any(), any(), any(), any(), any()); - } - - @Test - public void testInitializeMessageProducerComposite() { - when(mockConfigUtil.getClientMonitorEnabled()).thenReturn(true); - - ApolloClientMessageProducerComposite composite = ConfigMonitorInitializer.initializeMessageProducerComposite(); - - assertNotNull(composite); - // Additional assertions can be added based on expected behavior - } - @Test - public void testInitializeJmxMonitoring() { - when(mockConfigUtil.getClientMonitorJmxEnabled()).thenReturn(true); - ApolloClientMonitorEventListener metricsCollector = mock(ApolloClientMonitorEventListener.class); - List collectors = Collections.singletonList(metricsCollector); +public class ConfigMonitorInitializerTest { - ConfigMonitorInitializer.initializeJmxMonitoring(collectors); - verify(metricsCollector).mBeanName(); - } - -} \ No newline at end of file + @Mock + private ConfigUtil mockConfigUtil; + @Mock + private ApolloClientMonitorContext mockMonitorContext; + @Mock + private ApolloClientMetricsExporterFactory mockExporterFactory; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + MockInjector.setInstance(ConfigUtil.class, mockConfigUtil); + MockInjector.setInstance(ApolloClientMonitorContext.class, mockMonitorContext); + MockInjector.setInstance(ApolloClientMetricsExporterFactory.class, mockExporterFactory); + resetConfigMonitorInitializer(); + } + + @Test + public void testInitializeWhenMonitorEnabledAndNotInitialized() { + when(mockConfigUtil.isClientMonitorEnabled()).thenReturn(true); + ConfigMonitorInitializer.initialize(); + assertTrue(ConfigMonitorInitializer.hasInitialized); + //ConfigMonitorInitializer.53line + DefaultApolloClientBootstrapArgsApi.64line + verify(mockConfigUtil, times(2)).isClientMonitorEnabled(); + } + + @Test + public void testInitializeWhenMonitorDisabled() { + when(mockConfigUtil.isClientMonitorEnabled()).thenReturn(false); + ConfigMonitorInitializer.initialize(); + assertFalse(ConfigMonitorInitializer.hasInitialized); + } + + @Test + public void testInitializeWhenAlreadyInitialized() { + when(mockConfigUtil.isClientMonitorEnabled()).thenReturn(true); + ConfigMonitorInitializer.hasInitialized = true; + ConfigMonitorInitializer.initialize(); + verify(mockConfigUtil, times(1)).isClientMonitorEnabled(); + } + + @Test + public void testReset() { + ConfigMonitorInitializer.reset(); + assertFalse(ConfigMonitorInitializer.hasInitialized); + } + + private void resetConfigMonitorInitializer() { + ConfigMonitorInitializer.reset(); + } + +} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/ApolloClientMonitorContextTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/ApolloClientMonitorContextTest.java new file mode 100644 index 00000000..f2fad224 --- /dev/null +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/ApolloClientMonitorContextTest.java @@ -0,0 +1,99 @@ +/* + * Copyright 2022 Apollo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.ctrip.framework.apollo.monitor.internal; +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; + +import com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporter; +import com.ctrip.framework.apollo.monitor.internal.exporter.impl.NullApolloClientMetricsExporter; +import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMonitorEventListener; +import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientBootstrapArgsApi; +import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientExceptionApi; +import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientNamespaceApi; +import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientThreadPoolApi; +import com.ctrip.framework.apollo.monitor.internal.listener.impl.NullClientBootstrapArgsMonitorApi; +import com.ctrip.framework.apollo.monitor.internal.listener.impl.NullClientExceptionMonitorApi; +import com.ctrip.framework.apollo.monitor.internal.listener.impl.NullClientNamespaceMonitorApi; +import com.ctrip.framework.apollo.monitor.internal.listener.impl.NullClientThreadPoolMonitorApi; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import java.util.List; + +public class ApolloClientMonitorContextTest { + + @Mock + private DefaultApolloClientExceptionApi exceptionMonitorApi; + @Mock + private DefaultApolloClientNamespaceApi namespaceMonitorApi; + @Mock + private DefaultApolloClientBootstrapArgsApi bootstrapArgsMonitorApi; + @Mock + private DefaultApolloClientThreadPoolApi threadPoolMonitorApi; + @Mock + private ApolloClientMetricsExporter metricsExporter; + + private ApolloClientMonitorContext monitorContext; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + monitorContext = new ApolloClientMonitorContext(); + } + + @Test + public void testInitContext(){ + assertTrue(monitorContext.getBootstrapArgsApi() instanceof NullClientBootstrapArgsMonitorApi); + assertTrue(monitorContext.getNamespaceApi() instanceof NullClientNamespaceMonitorApi); + assertTrue(monitorContext.getThreadPoolApi() instanceof NullClientThreadPoolMonitorApi); + assertTrue(monitorContext.getExceptionApi() instanceof NullClientExceptionMonitorApi); + assertTrue(monitorContext.getMetricsExporter() instanceof NullApolloClientMetricsExporter); + } + + @Test + public void testSettingAndGettingApis() { + monitorContext.setApolloClientExceptionMonitorApi(exceptionMonitorApi); + monitorContext.setApolloClientNamespaceMonitorApi(namespaceMonitorApi); + monitorContext.setApolloClientBootstrapArgsMonitorApi(bootstrapArgsMonitorApi); + monitorContext.setApolloClientThreadPoolMonitorApi(threadPoolMonitorApi); + monitorContext.setApolloClientMetricsExporter(metricsExporter); + + assertSame(exceptionMonitorApi, monitorContext.getExceptionApi()); + assertSame(namespaceMonitorApi, monitorContext.getNamespaceApi()); + assertSame(bootstrapArgsMonitorApi, monitorContext.getBootstrapArgsApi()); + assertSame(threadPoolMonitorApi, monitorContext.getThreadPoolApi()); + assertSame(metricsExporter, monitorContext.getMetricsExporter()); + } + + @Test + public void testGetCollectors() { + monitorContext.setApolloClientExceptionMonitorApi(exceptionMonitorApi); + monitorContext.setApolloClientNamespaceMonitorApi(namespaceMonitorApi); + monitorContext.setApolloClientBootstrapArgsMonitorApi(bootstrapArgsMonitorApi); + monitorContext.setApolloClientThreadPoolMonitorApi(threadPoolMonitorApi); + + List collectors = monitorContext.getCollectors(); + + assertEquals(4, collectors.size()); + assertTrue(collectors.contains(exceptionMonitorApi)); + assertTrue(collectors.contains(namespaceMonitorApi)); + assertTrue(collectors.contains(bootstrapArgsMonitorApi)); + assertTrue(collectors.contains(threadPoolMonitorApi)); + } +} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/DefaultConfigMonitorTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/DefaultConfigMonitorTest.java index beeaf45c..2f1ffc6c 100644 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/DefaultConfigMonitorTest.java +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/DefaultConfigMonitorTest.java @@ -15,10 +15,11 @@ * */ package com.ctrip.framework.apollo.monitor.internal; - import static org.junit.Assert.*; import static org.mockito.Mockito.*; +import com.ctrip.framework.apollo.build.ApolloInjector; +import com.ctrip.framework.apollo.build.MockInjector; import com.ctrip.framework.apollo.monitor.api.ApolloClientBootstrapArgsMonitorApi; import com.ctrip.framework.apollo.monitor.api.ApolloClientExceptionMonitorApi; import com.ctrip.framework.apollo.monitor.api.ApolloClientNamespaceMonitorApi; @@ -31,60 +32,48 @@ public class DefaultConfigMonitorTest { - private DefaultConfigMonitor configMonitor; - - @Mock - private ApolloClientMetricsExporter reporter; - - @Mock - private ApolloClientThreadPoolMonitorApi threadPoolMonitorApi; - @Mock private ApolloClientExceptionMonitorApi exceptionMonitorApi; - @Mock private ApolloClientNamespaceMonitorApi namespaceMonitorApi; - @Mock private ApolloClientBootstrapArgsMonitorApi bootstrapArgsMonitorApi; + @Mock + private ApolloClientThreadPoolMonitorApi threadPoolMonitorApi; + @Mock + private ApolloClientMetricsExporter metricsExporter; + @Mock + private ApolloClientMonitorContext monitorContext; + + private DefaultConfigMonitor configMonitor; @Before - public void setUp() { + public void setUp(){ MockitoAnnotations.initMocks(this); + when(monitorContext.getExceptionApi()).thenReturn(exceptionMonitorApi); + when(monitorContext.getNamespaceApi()).thenReturn(namespaceMonitorApi); + when(monitorContext.getBootstrapArgsApi()).thenReturn(bootstrapArgsMonitorApi); + when(monitorContext.getThreadPoolApi()).thenReturn(threadPoolMonitorApi); + when(monitorContext.getMetricsExporter()).thenReturn(metricsExporter); + MockInjector.setInstance(ApolloClientMonitorContext.class, monitorContext); + configMonitor = new DefaultConfigMonitor(); - } - @Test - public void testInit() { - configMonitor.init(namespaceMonitorApi, threadPoolMonitorApi, exceptionMonitorApi, - bootstrapArgsMonitorApi, reporter); - - assertEquals(namespaceMonitorApi, configMonitor.getNamespaceMonitorApi()); - assertEquals(threadPoolMonitorApi, configMonitor.getThreadPoolMonitorApi()); - assertEquals(exceptionMonitorApi, configMonitor.getExceptionMonitorApi()); - assertEquals(bootstrapArgsMonitorApi, configMonitor.getRunningParamsMonitorApi()); } @Test - public void testGetExporterData() { - when(reporter.response()).thenReturn("exporter data"); - - configMonitor.init(namespaceMonitorApi, threadPoolMonitorApi, exceptionMonitorApi, - bootstrapArgsMonitorApi, reporter); - - String result = configMonitor.getExporterData(); - - assertEquals("exporter data", result); - verify(reporter).response(); + public void testApis(){ + assertSame(exceptionMonitorApi, configMonitor.getExceptionMonitorApi()); + assertSame(namespaceMonitorApi, configMonitor.getNamespaceMonitorApi()); + assertSame(bootstrapArgsMonitorApi, configMonitor.getRunningParamsMonitorApi()); + assertSame(threadPoolMonitorApi, configMonitor.getThreadPoolMonitorApi()); } @Test - public void testDefaultInstances() { - assertNotNull(configMonitor.getThreadPoolMonitorApi()); - assertNotNull(configMonitor.getExceptionMonitorApi()); - assertNotNull(configMonitor.getNamespaceMonitorApi()); - assertNotNull(configMonitor.getRunningParamsMonitorApi()); - assertEquals("No Reporter Use", - configMonitor.getExporterData()); // Assuming NullApolloClientMetricsExporter returns "null" + public void testExporterData(){ + String data = "data"; + when(metricsExporter.response()).thenReturn(data); + + assertEquals(data, configMonitor.getExporterData()); } -} \ No newline at end of file +} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/event/ApolloClientMonitorEventPublisherTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/event/ApolloClientMonitorEventPublisherTest.java index 2119b25a..aed0cdd9 100644 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/event/ApolloClientMonitorEventPublisherTest.java +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/event/ApolloClientMonitorEventPublisherTest.java @@ -20,7 +20,7 @@ import com.ctrip.framework.apollo.build.MockInjector; import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMonitorEventListener; -import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMonitorEventListenerManager; +import com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorContext; import com.ctrip.framework.apollo.util.ConfigUtil; import org.junit.Before; import org.junit.Test; @@ -29,29 +29,29 @@ public class ApolloClientMonitorEventPublisherTest { - private ApolloClientMonitorEventListenerManager mockCollectorManager; + private ApolloClientMonitorContext mockCollectorManager; private ConfigUtil mockConfigUtil; private ApolloClientMonitorEventListener mockCollector; private ApolloClientMonitorEvent mockEvent; @Before public void setUp() { - mockCollectorManager = mock(ApolloClientMonitorEventListenerManager.class); + mockCollectorManager = mock(ApolloClientMonitorContext.class); mockConfigUtil = mock(ConfigUtil.class); mockCollector = mock(ApolloClientMonitorEventListener.class); mockEvent = mock(ApolloClientMonitorEvent.class); // 使用 Mockito 来模拟静态方法 - MockInjector.setInstance(ApolloClientMonitorEventListenerManager.class, mockCollectorManager); + MockInjector.setInstance(ApolloClientMonitorContext.class, mockCollectorManager); MockInjector.setInstance(ConfigUtil.class, mockConfigUtil); ApolloClientMonitorEventPublisher.reset(); } @Test public void testPublish_WhenClientMonitorEnabled_CollectorSupportsEvent() { - when(mockConfigUtil.getClientMonitorEnabled()).thenReturn(true); + when(mockConfigUtil.isClientMonitorEnabled()).thenReturn(true); when(mockCollectorManager.getCollectors()).thenReturn(Collections.singletonList(mockCollector)); - when(mockCollector.isSupport(mockEvent)).thenReturn(true); + when(mockCollector.isSupported(mockEvent)).thenReturn(true); ApolloClientMonitorEventPublisher.publish(mockEvent); @@ -60,9 +60,9 @@ public void testPublish_WhenClientMonitorEnabled_CollectorSupportsEvent() { @Test public void testPublish_WhenClientMonitorEnabled_CollectorDoesNotSupportEvent() { - when(mockConfigUtil.getClientMonitorEnabled()).thenReturn(true); + when(mockConfigUtil.isClientMonitorEnabled()).thenReturn(true); when(mockCollectorManager.getCollectors()).thenReturn(Collections.singletonList(mockCollector)); - when(mockCollector.isSupport(mockEvent)).thenReturn(false); + when(mockCollector.isSupported(mockEvent)).thenReturn(false); ApolloClientMonitorEventPublisher.publish(mockEvent); @@ -71,7 +71,7 @@ public void testPublish_WhenClientMonitorEnabled_CollectorDoesNotSupportEvent() @Test public void testPublish_WhenClientMonitorDisabled() { - when(mockConfigUtil.getClientMonitorEnabled()).thenReturn(false); + when(mockConfigUtil.isClientMonitorEnabled()).thenReturn(false); ApolloClientMonitorEventPublisher.publish(mockEvent); diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractApolloClientMetricsExporterTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractApolloClientMetricsExporterTest.java index 8728c0c2..15df2204 100644 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractApolloClientMetricsExporterTest.java +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/AbstractApolloClientMetricsExporterTest.java @@ -19,7 +19,7 @@ import static org.junit.Assert.*; import static org.mockito.Mockito.*; -import com.ctrip.framework.apollo.monitor.internal.enums.MeterEnums; +import com.ctrip.framework.apollo.monitor.internal.enums.MetricTypeEnums; import com.ctrip.framework.apollo.monitor.internal.listener.ApolloClientMonitorEventListener; import com.ctrip.framework.apollo.monitor.internal.model.CounterModel; import com.ctrip.framework.apollo.monitor.internal.model.GaugeModel; @@ -58,7 +58,7 @@ public void testInit() { public void testUpdateMetricsData() { List samples = new ArrayList<>(); GaugeModel gauge = mock(GaugeModel.class); - when(gauge.getType()).thenReturn(MeterEnums.GAUGE); + when(gauge.getType()).thenReturn(MetricTypeEnums.GAUGE); when(gauge.getName()).thenReturn("testGauge"); when(gauge.getValue()).thenReturn(10.0); samples.add(gauge); diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/DefaultApolloClientMetricsExporterFactoryTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/DefaultApolloClientMetricsExporterFactoryTest.java index f8c32b0d..57908315 100644 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/DefaultApolloClientMetricsExporterFactoryTest.java +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/exporter/DefaultApolloClientMetricsExporterFactoryTest.java @@ -61,9 +61,9 @@ public void testGetMetricsReporter_NoExternalSystemType() { @Test public void testGetMetricsReporter_ExporterFound() { when(configUtil.getMonitorExternalType()).thenReturn("mocktheus"); - when(configUtil.getClientMonitorJmxEnabled()).thenReturn(true); + when(configUtil.isClientMonitorJmxEnabled()).thenReturn(true); when(configUtil.getMonitorExternalExportPeriod()).thenReturn(1000L); - when(metricsCollector.mBeanName()).thenReturn("testMBean"); + when(metricsCollector.getName()).thenReturn("testMBean"); List collectors = Collections.singletonList(metricsCollector); ApolloClientMetricsExporter result = factory.getMetricsReporter(collectors); diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/AbstractApolloClientMonitorEventListenerTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/AbstractApolloClientMonitorEventListenerTest.java deleted file mode 100644 index 1a60c02f..00000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/AbstractApolloClientMonitorEventListenerTest.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright 2022 Apollo Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.ctrip.framework.apollo.monitor.internal.listener; - -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; - -import com.ctrip.framework.apollo.monitor.internal.event.ApolloClientMonitorEvent; -import com.ctrip.framework.apollo.monitor.internal.model.CounterModel; -import com.ctrip.framework.apollo.monitor.internal.model.GaugeModel; -import com.ctrip.framework.apollo.monitor.internal.model.SampleModel; -import org.junit.Before; -import org.junit.Test; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class AbstractApolloClientMonitorEventListenerTest { - - private TestMonitorEventListener listener; - private ApolloClientMonitorEvent event; - - @Before - public void setUp() { - listener = new TestMonitorEventListener("testTag"); - event = mock(ApolloClientMonitorEvent.class); - when(event.getTag()).thenReturn("testTag"); - } - - @Test - public void testCollect() { - listener.collect(event); - assertTrue(listener.isMetricsSampleUpdated()); - } - - @Test - public void testIsSupport() { - assertTrue(listener.isSupport(event)); - when(event.getTag()).thenReturn("otherTag"); - assertFalse(listener.isSupport(event)); - } - - @Test - public void testExport() { - listener.collect(event); - List samples = listener.export(); - assertNotNull(samples); - assertTrue(samples.isEmpty()); // 应为空,因为尚未添加样本 - } - - @Test - public void testCreateOrUpdateGaugeSample() { - String mapKey = "gauge1"; - String metricsName = "testGauge"; - Map tags = new HashMap<>(); - tags.put("key", "value"); - - listener.createOrUpdateGaugeSample(mapKey, metricsName, tags, 42.0); - - List samples = listener.export(); - assertEquals(1, samples.size()); - assertTrue(samples.get(0) instanceof GaugeModel); - assertEquals(42.0, ((GaugeModel) samples.get(0)).getValue(), 0.01); - } - - @Test - public void testCreateOrUpdateCounterSample() { - String mapKey = "counter1"; - String metricsName = "testCounter"; - Map tags = new HashMap<>(); - tags.put("key", "value"); - - listener.createOrUpdateCounterSample(mapKey, metricsName, tags, 5.0); - - List samples = listener.export(); - assertEquals(1, samples.size()); - assertTrue(samples.get(0) instanceof CounterModel); - assertEquals(5.0, ((CounterModel) samples.get(0)).getValue(), 0.01); - } - - private class TestMonitorEventListener extends AbstractApolloClientMonitorEventListener { - - public TestMonitorEventListener(String tag) { - super(tag); - } - - @Override - protected void collect0(ApolloClientMonitorEvent event) { - // 简单的收集逻辑 - } - - @Override - protected void export0() { - // 模拟导出逻辑 - } - } -} \ No newline at end of file diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/DefaultApolloClientMonitorEventListenerManagerTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/DefaultApolloClientMonitorEventListenerManagerTest.java deleted file mode 100644 index 46e3cf8e..00000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/DefaultApolloClientMonitorEventListenerManagerTest.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2022 Apollo Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.ctrip.framework.apollo.monitor.internal.listener; - -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; - -import org.junit.Before; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -public class DefaultApolloClientMonitorEventListenerManagerTest { - - private DefaultApolloClientMonitorEventListenerManager manager; - - @Before - public void setUp() { - manager = new DefaultApolloClientMonitorEventListenerManager(); - } - - @Test - public void testInitialCollectors() { - List collectors = manager.getCollectors(); - assertNotNull(collectors); - assertTrue(collectors.isEmpty()); // 初始状态应该为空列表 - } - - @Test - public void testSetCollectors() { - ApolloClientMonitorEventListener mockListener = mock(ApolloClientMonitorEventListener.class); - List newCollectors = new ArrayList<>(); - newCollectors.add(mockListener); - - manager.setCollectors(newCollectors); - List collectors = manager.getCollectors(); - - assertNotNull(collectors); - assertEquals(1, collectors.size()); - assertEquals(mockListener, collectors.get(0)); // 验证设置的监听器 - } - - @Test - public void testSetEmptyCollectors() { - manager.setCollectors(Collections.emptyList()); - List collectors = manager.getCollectors(); - - assertNotNull(collectors); - assertTrue(collectors.isEmpty()); // 设置为空列表后应该为空 - } -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientBootstrapArgsApiTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientBootstrapArgsApiTest.java index 12a1b63b..c37699e1 100644 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientBootstrapArgsApiTest.java +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientBootstrapArgsApiTest.java @@ -83,7 +83,7 @@ public void testUnhandledEvent() { @Test public void testGetBootstrapArgs() { - Map bootstrapArgs = api.getBootstrapArgs(); + Map bootstrapArgs = api.getBootstrapArgs(); assertNotNull(bootstrapArgs); assertTrue(bootstrapArgs.containsKey(APOLLO_ACCESS_KEY_SECRET)); } diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientExceptionApiTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientExceptionApiTest.java index 2391e2bd..f683993a 100644 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientExceptionApiTest.java +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientExceptionApiTest.java @@ -20,6 +20,7 @@ import static org.mockito.Mockito.*; import static org.junit.Assert.*; +import com.ctrip.framework.apollo.core.ApolloClientSystemConsts; import com.ctrip.framework.apollo.monitor.internal.event.ApolloClientMonitorEvent; import com.ctrip.framework.apollo.exceptions.ApolloConfigException; import org.junit.Before; @@ -33,6 +34,8 @@ public class DefaultApolloClientExceptionApiTest { @Before public void setUp() { + int someQueueSize = 10; + System.setProperty(ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_EXCEPTION_QUEUE_SIZE, String.valueOf(someQueueSize)); exceptionApi = new DefaultApolloClientExceptionApi(); } @@ -83,14 +86,14 @@ public void testGetApolloConfigExceptionDetails() { @Test public void testCollect0_HandlesMaxQueueSize() { - for (int i = 0; i < 25; i++) { + for (int i = 0; i < 10; i++) { ApolloClientMonitorEvent event = mock(ApolloClientMonitorEvent.class); when(event.getAttachmentValue(THROWABLE)).thenReturn( new ApolloConfigException("Exception " + i)); exceptionApi.collect0(event); } - assertEquals(25, exceptionApi.getApolloConfigExceptionList().size()); + assertEquals(10, exceptionApi.getApolloConfigExceptionList().size()); // Add one more to exceed the size. ApolloClientMonitorEvent overflowEvent = mock(ApolloClientMonitorEvent.class); @@ -98,6 +101,6 @@ public void testCollect0_HandlesMaxQueueSize() { new ApolloConfigException("Overflow Exception")); exceptionApi.collect0(overflowEvent); - assertEquals(25, exceptionApi.getApolloConfigExceptionList().size()); + assertEquals(10, exceptionApi.getApolloConfigExceptionList().size()); } } \ No newline at end of file diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientNamespaceApiTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientNamespaceApiTest.java index 11fd102b..73621a13 100644 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientNamespaceApiTest.java +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientNamespaceApiTest.java @@ -26,6 +26,8 @@ import com.ctrip.framework.apollo.Config; import com.ctrip.framework.apollo.ConfigFile; import com.ctrip.framework.apollo.monitor.internal.event.ApolloClientMonitorEvent; +import java.util.List; +import java.util.Set; import org.junit.Before; import org.junit.Test; @@ -82,19 +84,19 @@ public void testCollectNamespaceUsage() { } @Test - public void testGetNamespaceItemsNum() { + public void testGetNamespacePropertySize() { Config mockConfig = mock(Config.class); when(mockConfig.getPropertyNames()).thenReturn(Sets.newSet("key1", "key2")); configs.put("testNamespace", mockConfig); - Integer testNamespace = api.getNamespaceItemsNum("testNamespace"); + Integer testNamespace = api.getNamespacePropertySize("testNamespace"); assertEquals(2, testNamespace.intValue()); } @Test - public void testGetConfigFileNum() { + public void testGetConfigFileNamespaces() { ConfigFile mockConfigFile = mock(ConfigFile.class); configFiles.put("testNamespace", mockConfigFile); - Integer testNamespace = api.getConfigFileNum(); - assertEquals(1, testNamespace.intValue()); + List configFileNum = api.getConfigFileNamespaces(); + assertEquals(1, configFileNum.size()); } } \ No newline at end of file diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientThreadPoolApiTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientThreadPoolApiTest.java index 9c12fdfe..f1d93b23 100644 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientThreadPoolApiTest.java +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientThreadPoolApiTest.java @@ -16,15 +16,13 @@ */ package com.ctrip.framework.apollo.monitor.internal.listener.impl; -import static org.mockito.Mockito.*; import static org.junit.Assert.*; -import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientThreadPoolApi.ApolloThreadPoolInfo; +import com.ctrip.framework.apollo.monitor.api.ApolloClientThreadPoolMonitorApi.ApolloThreadPoolInfo; import lombok.SneakyThrows; import org.junit.Before; import org.junit.Test; -import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; @@ -89,6 +87,6 @@ public void testGetAbstractConfigFileThreadPoolInfo() { ApolloThreadPoolInfo info = threadPoolApi.getAbstractConfigFileThreadPoolInfo(); assertNotNull(info); } - - + + } diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientBootstrapArgsMonitorApiTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientBootstrapArgsMonitorApiTest.java index 04304a55..d8ece6a1 100644 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientBootstrapArgsMonitorApiTest.java +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientBootstrapArgsMonitorApiTest.java @@ -34,7 +34,7 @@ public void setUp() { @Test public void testGetStartupParams() { - assertEquals("", bootstrapArgsMonitorApi.getStartupParams("testKey")); + assertEquals(null, bootstrapArgsMonitorApi.getStartupArg("testKey")); } @Test @@ -53,8 +53,8 @@ public void testGetAutoUpdateInjectedSpringProperties() { } @Test - public void testGetBootstrapEnabled() { - assertNull(bootstrapArgsMonitorApi.getBootstrapEnabled()); + public void testIsBootstrapEnabled() { + assertFalse(bootstrapArgsMonitorApi.isBootstrapEnabled()); } @Test @@ -63,13 +63,13 @@ public void testGetBootstrapNamespaces() { } @Test - public void testGetBootstrapEagerLoadEnabled() { - assertNull(bootstrapArgsMonitorApi.getBootstrapEagerLoadEnabled()); + public void testIsBootstrapEagerLoadEnabled() { + assertFalse(bootstrapArgsMonitorApi.isBootstrapEagerLoadEnabled()); } @Test - public void testGetOverrideSystemProperties() { - assertNull(bootstrapArgsMonitorApi.getOverrideSystemProperties()); + public void testIsOverrideSystemProperties() { + assertFalse(bootstrapArgsMonitorApi.isOverrideSystemProperties()); } @Test @@ -88,13 +88,13 @@ public void testGetConfigService() { } @Test - public void testGetClientMonitorEnabled() { - assertNull(bootstrapArgsMonitorApi.getClientMonitorEnabled()); + public void testIsClientMonitorEnabled() { + assertFalse(bootstrapArgsMonitorApi.isClientMonitorEnabled()); } @Test - public void testGetClientMonitorJmxEnabled() { - assertNull(bootstrapArgsMonitorApi.getClientMonitorJmxEnabled()); + public void testIsClientMonitorJmxEnabled() { + assertFalse(bootstrapArgsMonitorApi.isClientMonitorJmxEnabled()); } @Test @@ -123,13 +123,13 @@ public void testGetMetaLatestFreshTime() { } @Test - public void testGetPropertyNamesCacheEnable() { - assertNull(bootstrapArgsMonitorApi.getPropertyNamesCacheEnable()); + public void testIsPropertyNamesCacheEnable() { + assertFalse(bootstrapArgsMonitorApi.isPropertyNamesCacheEnable()); } @Test - public void testGetPropertyOrderEnable() { - assertNull(bootstrapArgsMonitorApi.getPropertyOrderEnable()); + public void testIsPropertyOrderEnable() { + assertFalse(bootstrapArgsMonitorApi.isPropertyOrderEnable()); } @Test @@ -149,7 +149,7 @@ public void testGetAppId() { @Test public void testGetBootstrapArgs() { - Map bootstrapArgs = bootstrapArgsMonitorApi.getBootstrapArgs(); + Map bootstrapArgs = bootstrapArgsMonitorApi.getBootstrapArgs(); assertNotNull(bootstrapArgs); assertTrue(bootstrapArgs.isEmpty()); diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientNamespaceMonitorApiTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientNamespaceMonitorApiTest.java index cddf6b2c..8bfea39e 100644 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientNamespaceMonitorApiTest.java +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientNamespaceMonitorApiTest.java @@ -18,7 +18,8 @@ import static org.junit.Assert.*; -import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientNamespaceApi.NamespaceMetrics; +import com.ctrip.framework.apollo.monitor.api.ApolloClientNamespaceMonitorApi.NamespaceMetrics; +import java.util.Set; import org.junit.Before; import org.junit.Test; @@ -44,15 +45,15 @@ public void testGetNamespaceMetrics() { @Test public void testGetNamespaceItemNames() { - Integer testNamespace = namespaceMonitorApi.getNamespaceItemsNum("testNamespace"); + Integer testNamespace = namespaceMonitorApi.getNamespacePropertySize("testNamespace"); assertEquals(0, testNamespace.intValue()); } - + @Test - public void testGetConfigFileNum() { - Integer configFileNum = namespaceMonitorApi.getConfigFileNum(); - assertEquals(0, configFileNum.intValue()); + public void testGetConfigFileNamespaces() { + List configFileNamespaces = namespaceMonitorApi.getConfigFileNamespaces(); + assertEquals(0, configFileNamespaces.size()); } @Test diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientThreadPoolMonitorApiTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientThreadPoolMonitorApiTest.java index 2bd393f2..81f812c7 100644 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientThreadPoolMonitorApiTest.java +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/NullClientThreadPoolMonitorApiTest.java @@ -17,9 +17,8 @@ package com.ctrip.framework.apollo.monitor.internal.listener.impl; import static org.junit.Assert.*; -import static org.mockito.Mockito.*; -import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientThreadPoolApi.ApolloThreadPoolInfo; +import com.ctrip.framework.apollo.monitor.api.ApolloClientThreadPoolMonitorApi.ApolloThreadPoolInfo; import org.junit.Before; import org.junit.Test; @@ -45,21 +44,8 @@ public void testGetThreadPoolInfo() { @Test public void testGetRemoteConfigRepositoryThreadPoolInfo() { ApolloThreadPoolInfo info = monitorApi.getRemoteConfigRepositoryThreadPoolInfo(); - - assertNull(info); - } - - @Test - public void testGetAbstractConfigThreadPoolInfo() { - ApolloThreadPoolInfo info = monitorApi.getAbstractConfigThreadPoolInfo(); - - assertNull(info); - } - - @Test - public void testGetAbstractConfigFileThreadPoolInfo() { - ApolloThreadPoolInfo info = monitorApi.getAbstractConfigFileThreadPoolInfo(); - - assertNull(info); + assertNotNull(info); + assertEquals(0, info.getPoolSize()); } + } diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/stress/ApolloClientMonitorStressTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/stress/ApolloClientMonitorStressTest.java index 4e4149e3..778bd527 100644 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/stress/ApolloClientMonitorStressTest.java +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/stress/ApolloClientMonitorStressTest.java @@ -20,18 +20,19 @@ import com.ctrip.framework.apollo.ConfigService; import com.ctrip.framework.apollo.monitor.internal.event.ApolloClientMonitorEventFactory; +import com.ctrip.framework.apollo.monitor.internal.event.ApolloClientMonitorEventPublisher; import com.github.noconnor.junitperf.JUnitPerfRule; import com.github.noconnor.junitperf.JUnitPerfTest; +import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +@Ignore("Stress test") @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = ApolloClientMonitorStressTest.class) -@ActiveProfiles("stress-test") public class ApolloClientMonitorStressTest { @Rule @@ -40,14 +41,16 @@ public class ApolloClientMonitorStressTest { @Test @JUnitPerfTest(threads = 25, durationMs = 10000, warmUpMs = 1000, maxExecutionsPerSecond = 1000) public void testConfigMonitor() { - String exporterData = ConfigService.getConfigMonitor().getExporterData(); + System.out.println("abcdeft"); + ConfigService.getConfigMonitor().getExporterData(); } @Test @JUnitPerfTest(threads = 50, durationMs = 10000, warmUpMs = 1000, maxExecutionsPerSecond = 1000) public void testPublishEvent() { - ApolloClientMonitorEventFactory.getInstance() - .createEvent(APOLLO_CLIENT_NAMESPACE_USAGE) - .putAttachment(NAMESPACE, "application").publish(); + ApolloClientMonitorEventPublisher.publish( + ApolloClientMonitorEventFactory.getInstance() + .createEvent(APOLLO_CLIENT_NAMESPACE_USAGE) + .putAttachment(NAMESPACE, "application")); } } diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/util/ConfigUtilTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/util/ConfigUtilTest.java index 23a37362..18cda2dd 100644 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/util/ConfigUtilTest.java +++ b/apollo-client/src/test/java/com/ctrip/framework/apollo/util/ConfigUtilTest.java @@ -255,6 +255,92 @@ public void testCustomizePropertiesOrdered() { configUtil.isPropertiesOrderEnabled()); } + @Test + public void testMonitorExternalType() { + String someMonitorExternalType = "someType"; + System.setProperty(ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_EXTERNAL_TYPE, someMonitorExternalType); + + ConfigUtil configUtil = new ConfigUtil(); + + assertEquals(someMonitorExternalType, configUtil.getMonitorExternalType()); + } + + @Test + public void testCustomizeMonitorExternalCollectPeriod() { + int somePeriod = 5; + System.setProperty(ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_EXTERNAL_EXPORT_PERIOD, String.valueOf(somePeriod)); + + ConfigUtil configUtil = new ConfigUtil(); + + assertEquals(somePeriod, configUtil.getMonitorExternalExportPeriod()); + } + + @Test + public void testCustomizeInvalidMonitorExternalCollectPeriod() { + String someInvalidPeriod = "a"; + System.setProperty(ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_EXTERNAL_EXPORT_PERIOD, someInvalidPeriod); + + ConfigUtil configUtil = new ConfigUtil(); + + assertEquals(10, configUtil.getMonitorExternalExportPeriod()); // Default value + } + + @Test + public void testClientMonitorEnabled() { + System.setProperty(ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_ENABLED, "true"); + + ConfigUtil configUtil = new ConfigUtil(); + + assertTrue(configUtil.isClientMonitorEnabled()); + } + + @Test + public void testClientMonitorEnabledDefault() { + System.clearProperty(ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_ENABLED); + + ConfigUtil configUtil = new ConfigUtil(); + + assertFalse(configUtil.isClientMonitorEnabled()); // Default value + } + + @Test + public void testClientMonitorJmxEnabled() { + System.setProperty(ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_JMX_ENABLED, "true"); + + ConfigUtil configUtil = new ConfigUtil(); + + assertTrue(configUtil.isClientMonitorJmxEnabled()); + } + + @Test + public void testClientMonitorJmxEnabledDefault() { + System.clearProperty(ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_JMX_ENABLED); + + ConfigUtil configUtil = new ConfigUtil(); + + assertFalse(configUtil.isClientMonitorJmxEnabled()); // Default value + } + + @Test + public void testCustomizeMonitorExceptionQueueSize() { + int someQueueSize = 10; + System.setProperty(ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_EXCEPTION_QUEUE_SIZE, String.valueOf(someQueueSize)); + + ConfigUtil configUtil = new ConfigUtil(); + + assertEquals(someQueueSize, configUtil.getMonitorExceptionQueueSize()); + } + + @Test + public void testCustomizeInvalidMonitorExceptionQueueSize() { + String someInvalidQueueSize = "a"; + System.setProperty(ApolloClientSystemConsts.APOLLO_CLIENT_MONITOR_EXCEPTION_QUEUE_SIZE, someInvalidQueueSize); + + ConfigUtil configUtil = new ConfigUtil(); + + assertEquals(25, configUtil.getMonitorExceptionQueueSize()); // Default value + } + @Test public void test() { ConfigUtil configUtil = new ConfigUtil(); diff --git a/apollo-client/src/test/resources/application-stress-test.yml b/apollo-client/src/test/resources/application-stress-test.yml deleted file mode 100644 index 430bf695..00000000 --- a/apollo-client/src/test/resources/application-stress-test.yml +++ /dev/null @@ -1,17 +0,0 @@ -# -# Copyright 2022 Apollo Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -# just for apollo client monitor stress test \ No newline at end of file diff --git a/apollo-plugin/apollo-plugin-client-prometheus/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/impl/PrometheusApolloClientMetricsExporter.java b/apollo-plugin/apollo-plugin-client-prometheus/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/impl/PrometheusApolloClientMetricsExporter.java index d6f56401..a07e3209 100644 --- a/apollo-plugin/apollo-plugin-client-prometheus/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/impl/PrometheusApolloClientMetricsExporter.java +++ b/apollo-plugin/apollo-plugin-client-prometheus/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/impl/PrometheusApolloClientMetricsExporter.java @@ -20,6 +20,7 @@ import com.ctrip.framework.apollo.monitor.internal.exporter.AbstractApolloClientMetricsExporter; import com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporter; import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientNamespaceApi; +import com.google.common.collect.Maps; import io.prometheus.client.Collector; import io.prometheus.client.CollectorRegistry; import io.prometheus.client.Counter; @@ -41,12 +42,12 @@ public class PrometheusApolloClientMetricsExporter extends private final Logger logger = DeferredLoggerFactory.getLogger( DefaultApolloClientNamespaceApi.class); protected CollectorRegistry registry; - protected Map map; + protected Map map; @Override public void doInit() { registry = new CollectorRegistry(); - map = new HashMap<>(); + map = Maps.newConcurrentMap(); } @Override @@ -58,11 +59,8 @@ public boolean isSupport(String form) { @Override public void registerOrUpdateCounterSample(String name, Map tags, double incrValue) { - Counter counter = (Counter) map.get(name); - if (counter == null) { - counter = createCounter(name, tags); - map.put(name, counter); - } + Counter counter = (Counter) map.computeIfAbsent(name, + key -> createCounter(key, tags)); counter.labels(tags.values().toArray(new String[0])).inc(incrValue); } @@ -76,11 +74,7 @@ private Counter createCounter(String name, Map tags) { @Override public void registerOrUpdateGaugeSample(String name, Map tags, double value) { - Gauge gauge = (Gauge) map.get(name); - if (gauge == null) { - gauge = createGauge(name, tags); - map.put(name, gauge); - } + Gauge gauge = (Gauge) map.computeIfAbsent(name, key -> createGauge(key, tags)); gauge.labels(tags.values().toArray(new String[0])).set(value); } diff --git a/apollo-plugin/apollo-plugin-client-prometheus/src/main/java/com/ctrip/framework/apollo/plugin/prometheus/PrometheusApolloClientMetricsExporter.java b/apollo-plugin/apollo-plugin-client-prometheus/src/main/java/com/ctrip/framework/apollo/plugin/prometheus/PrometheusApolloClientMetricsExporter.java deleted file mode 100644 index df518054..00000000 --- a/apollo-plugin/apollo-plugin-client-prometheus/src/main/java/com/ctrip/framework/apollo/plugin/prometheus/PrometheusApolloClientMetricsExporter.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright 2022 Apollo Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.ctrip.framework.apollo.plugin.prometheus; - -import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory; -import com.ctrip.framework.apollo.monitor.internal.exporter.AbstractApolloClientMetricsExporter; -import com.ctrip.framework.apollo.monitor.internal.exporter.ApolloClientMetricsExporter; -import com.ctrip.framework.apollo.monitor.internal.listener.impl.DefaultApolloClientNamespaceApi; -import io.prometheus.client.Collector; -import io.prometheus.client.CollectorRegistry; -import io.prometheus.client.Counter; -import io.prometheus.client.Gauge; -import io.prometheus.client.exporter.common.TextFormat; -import java.io.IOException; -import java.io.StringWriter; -import java.util.HashMap; -import java.util.Map; -import org.slf4j.Logger; - -/** - * @author Rawven - */ -public class PrometheusApolloClientMetricsExporter extends - AbstractApolloClientMetricsExporter implements ApolloClientMetricsExporter { - private final Logger logger = DeferredLoggerFactory.getLogger( - DefaultApolloClientNamespaceApi.class); - private static final String PROMETHEUS = "prometheus"; - private final CollectorRegistry registry; - private final Map map = new HashMap<>(); - - - public PrometheusApolloClientMetricsExporter() { - this.registry = new CollectorRegistry(); - } - - @Override - public void doInit() { - - } - - @Override - public boolean isSupport(String form) { - return PROMETHEUS.equals(form); - } - - - @Override - public void registerOrUpdateCounterSample(String name, Map tags, double incrValue) { - Counter counter = (Counter) map.computeIfAbsent(name, k -> Counter.build() - .name(name) - .help("apollo") - .labelNames(tags.keySet().toArray(new String[0])) - .register(registry)); - counter.labels(tags.values().toArray(new String[0])).inc(incrValue); -} - - - @Override - public void registerOrUpdateGaugeSample(String name, Map tags, double value) { - Gauge gauge = (Gauge) map.computeIfAbsent(name, k -> Gauge.build() - .name(name) - .help("apollo") - .labelNames(tags.keySet().toArray(new String[0])) - .register(registry)); - gauge.labels(tags.values().toArray(new String[0])).set(value); - } - - - @Override - public String response() { - try (StringWriter writer = new StringWriter()){ - TextFormat.writeFormat(TextFormat.CONTENT_TYPE_OPENMETRICS_100, writer, registry.metricFamilySamples()); - return writer.toString(); - } catch (IOException e) { - logger.error("Write metrics to Prometheus format failed", e); - return ""; - } - } -} - \ No newline at end of file From 75ad161c77da6ed74a9634da49ebc8a0c9ffff70 Mon Sep 17 00:00:00 2001 From: liu Date: Wed, 9 Oct 2024 00:28:56 +0800 Subject: [PATCH 7/8] refactor(): rollback meaningless change --- apollo-client/pom.xml | 22 ++++++------- .../apollo/internals/ConfigManager.java | 2 -- .../internals/ConfigServiceLocator.java | 31 ++++++++++--------- .../internals/DefaultConfigManager.java | 19 ++++++------ .../apollo/internals/DefaultInjector.java | 2 -- .../RemoteConfigLongPollService.java | 2 +- .../internals/RemoteConfigRepository.java | 2 -- 7 files changed, 38 insertions(+), 42 deletions(-) diff --git a/apollo-client/pom.xml b/apollo-client/pom.xml index f53ff8d9..f643256a 100644 --- a/apollo-client/pom.xml +++ b/apollo-client/pom.xml @@ -97,17 +97,17 @@ mockserver-netty test - - com.github.noconnor - junitperf - test - - - ch.qos.logback - logback-classic - - - + + com.github.noconnor + junitperf + test + + + ch.qos.logback + logback-classic + + + diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigManager.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigManager.java index e7252a58..0fedcbea 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigManager.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigManager.java @@ -38,6 +38,4 @@ public interface ConfigManager { * @return the config file instance for the namespace */ ConfigFile getConfigFile(String namespace, ConfigFileFormat configFileFormat); - - } diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigServiceLocator.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigServiceLocator.java index ebccd7e5..0ea8e07c 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigServiceLocator.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigServiceLocator.java @@ -17,38 +17,41 @@ package com.ctrip.framework.apollo.internals; import static com.ctrip.framework.apollo.monitor.internal.ApolloClientMonitorConstant.*; -import com.ctrip.framework.apollo.build.ApolloInjector; + import com.ctrip.framework.apollo.core.ApolloClientSystemConsts; import com.ctrip.framework.apollo.core.ServiceNameConsts; -import com.ctrip.framework.apollo.core.dto.ServiceDTO; -import com.ctrip.framework.apollo.core.utils.ApolloThreadFactory; import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory; import com.ctrip.framework.apollo.core.utils.DeprecatedPropertyNotifyUtil; +import com.ctrip.framework.foundation.Foundation; +import com.google.common.util.concurrent.RateLimiter; +import java.lang.reflect.Type; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; + +import org.slf4j.Logger; + +import com.ctrip.framework.apollo.build.ApolloInjector; +import com.ctrip.framework.apollo.core.dto.ServiceDTO; +import com.ctrip.framework.apollo.core.utils.ApolloThreadFactory; import com.ctrip.framework.apollo.exceptions.ApolloConfigException; import com.ctrip.framework.apollo.tracer.Tracer; import com.ctrip.framework.apollo.tracer.spi.Transaction; import com.ctrip.framework.apollo.util.ConfigUtil; import com.ctrip.framework.apollo.util.ExceptionUtil; -import com.ctrip.framework.apollo.util.http.HttpClient; import com.ctrip.framework.apollo.util.http.HttpRequest; import com.ctrip.framework.apollo.util.http.HttpResponse; -import com.ctrip.framework.foundation.Foundation; +import com.ctrip.framework.apollo.util.http.HttpClient; import com.google.common.base.Joiner; import com.google.common.base.Strings; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.escape.Escaper; import com.google.common.net.UrlEscapers; -import com.google.common.util.concurrent.RateLimiter; import com.google.gson.reflect.TypeToken; -import java.lang.reflect.Type; -import java.util.List; -import java.util.Map; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; -import org.slf4j.Logger; public class ConfigServiceLocator { private static final Logger logger = DeferredLoggerFactory.getLogger(ConfigServiceLocator.class); diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultConfigManager.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultConfigManager.java index c2b8c20c..81c4081c 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultConfigManager.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultConfigManager.java @@ -33,21 +33,21 @@ * @author Jason Song(song_s@ctrip.com) */ public class DefaultConfigManager implements ConfigManager { - - protected Map m_configs = Maps.newConcurrentMap(); - protected Map m_configLocks = Maps.newConcurrentMap(); - protected Map m_configFiles = Maps.newConcurrentMap(); - protected Map m_configFileLocks = Maps.newConcurrentMap(); private ConfigFactoryManager m_factoryManager; + private Map m_configs = Maps.newConcurrentMap(); + private Map m_configLocks = Maps.newConcurrentMap(); + private Map m_configFiles = Maps.newConcurrentMap(); + private Map m_configFileLocks = Maps.newConcurrentMap(); + public DefaultConfigManager() { m_factoryManager = ApolloInjector.getInstance(ConfigFactoryManager.class); - } @Override public Config getConfig(String namespace) { Config config = m_configs.get(namespace); + if (config == null) { Object lock = m_configLocks.computeIfAbsent(namespace, key -> new Object()); synchronized (lock) { @@ -61,16 +61,15 @@ public Config getConfig(String namespace) { } } } - if(!ConfigSourceType.NONE.equals(config.getSourceType())) { - Tracer.logMetricsForCount(APOLLO_CLIENT_NAMESPACE_USAGE+":"+namespace); + if (!ConfigSourceType.NONE.equals(config.getSourceType())) { + Tracer.logMetricsForCount(APOLLO_CLIENT_NAMESPACE_USAGE + ":" + namespace); } return config; } @Override - public ConfigFile getConfigFile(String namespace, - ConfigFileFormat configFileFormat) { + public ConfigFile getConfigFile(String namespace, ConfigFileFormat configFileFormat) { String namespaceFileName = String.format("%s.%s", namespace, configFileFormat.getValue()); ConfigFile configFile = m_configFiles.get(namespaceFileName); diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultInjector.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultInjector.java index f561d278..5d414070 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultInjector.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultInjector.java @@ -42,8 +42,6 @@ import com.google.inject.Singleton; import java.util.List; -; - /** * Guice injector * @author Jason Song(song_s@ctrip.com) diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigLongPollService.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigLongPollService.java index fde34ca1..ccc75576 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigLongPollService.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigLongPollService.java @@ -215,7 +215,7 @@ private void doLongPollingRefresh(String appId, String cluster, String dataCente transaction.setStatus(ex); long sleepTimeInSecond = m_longPollFailSchedulePolicyInSecond.fail(); if (ex.getCause() instanceof SocketTimeoutException) { - Tracer.logEvent(APOLLO_CLIENT_NAMESPACE_TIMEOUT,assembleNamespaces()); + Tracer.logEvent(APOLLO_CLIENT_NAMESPACE_TIMEOUT, assembleNamespaces()); } logger.warn( "Long polling failed, will retry in {} seconds. appId: {}, cluster: {}, namespaces: {}, long polling url: {}, reason: {}", diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigRepository.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigRepository.java index dd4f63ee..879f243c 100644 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigRepository.java +++ b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigRepository.java @@ -152,7 +152,6 @@ protected synchronized void sync() { Transaction transaction = Tracer.newTransaction("Apollo.ConfigService", "syncRemoteConfig"); try { - ApolloConfig previous = m_configCache.get(); ApolloConfig current = loadApolloConfig(); @@ -161,7 +160,6 @@ protected synchronized void sync() { logger.debug("Remote Config refreshed!"); m_configCache.set(current); this.fireRepositoryChange(m_namespace, this.getConfig()); - } if (current != null) { From 004df5241d0a66a8bfa330ee04a869b410929142 Mon Sep 17 00:00:00 2001 From: liu Date: Sat, 12 Oct 2024 22:28:42 +0800 Subject: [PATCH 8/8] docs(): add CHANGES.md --- CHANGES.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGES.md b/CHANGES.md index 105cc277..231243ad 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -6,6 +6,6 @@ Apollo Java 2.4.0 ------------------ * [Fix the Cannot enhance @Configuration bean definition issue](https://github.com/apolloconfig/apollo-java/pull/82) - +* [Add more observability in apollo config client](https://github.com/apolloconfig/apollo-java/pull/74) ------------------ All issues and pull requests are [here](https://github.com/apolloconfig/apollo-java/milestone/4?closed=1) \ No newline at end of file