From ad3d103776b87c4c256d35aa9804c38b7b9010e8 Mon Sep 17 00:00:00 2001 From: yanrongzhen Date: Thu, 11 May 2023 09:32:02 +0800 Subject: [PATCH 1/3] Complete the agent development under SpringBoot2.x version. (#1241) * Complete the agent development under SpringBoot2.x version. * Rename the '@SpringBootPluginConfig' annotation. --- hippo4j-agent/config/agent.config | 6 +- hippo4j-agent/hippo4j-agent-bootstrap/pom.xml | 2 +- .../boot/SpringBootConfigInitializer.java | 2 +- ...tConfig.java => SpringBootConfigNode.java} | 2 +- .../core/plugin/loader/AgentClassLoader.java | 4 +- .../apollo/define/ApolloInstrumentation.java | 2 +- .../DefaultConfigConstructorInterceptor.java | 2 +- .../spring-boot-1.x-plugin/pom.xml | 13 --- ...ynamicThreadPoolChangeHandlerSpring1x.java | 69 ++++++++++++++++ ...tPublishingRunListenerInstrumentation.java | 4 +- .../SpringApplicationRunInstrumentation.java | 68 ---------------- .../EventPublishingFinishedInterceptor.java | 64 +++++++++++++++ .../src/main/resources/hippo4j-plugin.def | 3 +- .../spring-boot-2.x-plugin/pom.xml | 8 +- ...ynamicThreadPoolChangeHandlerSpring2x.java | 44 ++++++++++ ...tPublishingRunListenerInstrumentation.java | 20 ++++- .../EventPublishingStartedInterceptor.java | 15 +++- .../spring-plugin-common/pom.xml | 25 ++++++ .../spring/common/conf/SpringBootConfig.java} | 10 +-- ...istenerEnvironmentPreparedInterceptor.java | 4 +- ...DynamicThreadPoolChangeHandlerSpring.java} | 80 ++++--------------- ...IDynamicThreadPoolChangeHandlerSpring.java | 24 ++++++ .../SpringEnvironmentSupport.java | 2 +- .../{ => support}/SpringPropertiesLoader.java | 2 +- .../SpringThreadPoolRegisterSupport.java} | 32 ++------ .../ThreadPoolExecutorInstrumentation.java | 2 +- ...lExecutorConstructorMethodInterceptor.java | 2 +- .../pom.xml | 17 ++++ .../MicrometerMonitorAutoConfiguration.java | 1 + 29 files changed, 330 insertions(+), 199 deletions(-) rename hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/boot/{SpringBootConfig.java => SpringBootConfigNode.java} (96%) rename hippo4j-agent/hippo4j-agent-plugin/apollo-plugin/src/main/java/cn/hippo4j/agent/plugin/apollo/{ => interceptor}/DefaultConfigConstructorInterceptor.java (95%) create mode 100644 hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/DynamicThreadPoolChangeHandlerSpring1x.java delete mode 100644 hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/define/SpringApplicationRunInstrumentation.java create mode 100644 hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/interceptor/EventPublishingFinishedInterceptor.java create mode 100644 hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-2.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v2/DynamicThreadPoolChangeHandlerSpring2x.java rename hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-2.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v2/{ => interceptor}/EventPublishingStartedInterceptor.java (72%) rename hippo4j-agent/hippo4j-agent-plugin/spring-plugins/{spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/ApolloSpringBootProperties.java => spring-plugin-common/src/main/java/cn/hippo4j/agent/plugin/spring/common/conf/SpringBootConfig.java} (80%) rename hippo4j-agent/hippo4j-agent-plugin/spring-plugins/{spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1 => spring-plugin-common/src/main/java/cn/hippo4j/agent/plugin/spring/common/interceptor}/EventPublishingRunListenerEnvironmentPreparedInterceptor.java (94%) rename hippo4j-agent/hippo4j-agent-plugin/spring-plugins/{spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/EventPublishingFinishedInterceptor.java => spring-plugin-common/src/main/java/cn/hippo4j/agent/plugin/spring/common/support/AbstractDynamicThreadPoolChangeHandlerSpring.java} (80%) create mode 100644 hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-plugin-common/src/main/java/cn/hippo4j/agent/plugin/spring/common/support/IDynamicThreadPoolChangeHandlerSpring.java rename hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-plugin-common/src/main/java/cn/hippo4j/agent/plugin/spring/common/{ => support}/SpringEnvironmentSupport.java (96%) rename hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-plugin-common/src/main/java/cn/hippo4j/agent/plugin/spring/common/{ => support}/SpringPropertiesLoader.java (98%) rename hippo4j-agent/hippo4j-agent-plugin/spring-plugins/{spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/SpringApplicationRunInterceptor.java => spring-plugin-common/src/main/java/cn/hippo4j/agent/plugin/spring/common/support/SpringThreadPoolRegisterSupport.java} (77%) rename hippo4j-agent/hippo4j-agent-plugin/thread-pool-plugin/src/main/java/cn/hippo4j/agent/plugin/thread/pool/{ => interceptor}/ThreadPoolExecutorConstructorMethodInterceptor.java (98%) diff --git a/hippo4j-agent/config/agent.config b/hippo4j-agent/config/agent.config index e3d54559..d810e55e 100755 --- a/hippo4j-agent/config/agent.config +++ b/hippo4j-agent/config/agent.config @@ -111,11 +111,11 @@ collector.is_resolve_dns_periodically=${SW_AGENT_COLLECTOR_IS_RESOLVE_DNS_PERIOD # Logging level logging.level=${SW_LOGGING_LEVEL:INFO} # Logging file_name -logging.file_name=${SW_LOGGING_FILE_NAME:skywalking-api.log} +logging.file_name=${SW_LOGGING_FILE_NAME:hippo4j-api.log} # Log output. Default is FILE. Use CONSOLE means output to stdout. logging.output=${SW_LOGGING_OUTPUT:FILE} -# Log files directory. Default is blank string, meaning use "{theSkywalkingAgentJarDir}/logs " to output logs. -# {theSkywalkingAgentJarDir} is the directory where the skywalking agent jar file is located +# Log files directory. Default is blank string, meaning use "{theHippo4jAgentJarDir}/logs " to output logs. +# {theHippo4jAgentJarDir} is the directory where the hippo4j agent jar file is located logging.dir=${SW_LOGGING_DIR:} # Logger resolver: PATTERN or JSON. The default is PATTERN, which uses logging.pattern to print traditional text logs. # JSON resolver prints logs in JSON format. diff --git a/hippo4j-agent/hippo4j-agent-bootstrap/pom.xml b/hippo4j-agent/hippo4j-agent-bootstrap/pom.xml index d313f6c9..51e2cb1e 100644 --- a/hippo4j-agent/hippo4j-agent-bootstrap/pom.xml +++ b/hippo4j-agent/hippo4j-agent-bootstrap/pom.xml @@ -96,7 +96,7 @@ - + diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/boot/SpringBootConfigInitializer.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/boot/SpringBootConfigInitializer.java index a8d33aed..eb2eafef 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/boot/SpringBootConfigInitializer.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/boot/SpringBootConfigInitializer.java @@ -48,7 +48,7 @@ public class SpringBootConfigInitializer { return SPRING_PROPERTIES == null || SPRING_PROPERTIES.isEmpty(); } - public static synchronized void initializeConfig(SpringBootConfig springBootConfig) { + public static synchronized void initializeConfig(SpringBootConfigNode springBootConfig) { if (SPRING_PROPERTIES != null) { try { LOG.info("initialize Spring Config Class {}.", springBootConfig.root()); diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/boot/SpringBootConfig.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/boot/SpringBootConfigNode.java similarity index 96% rename from hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/boot/SpringBootConfig.java rename to hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/boot/SpringBootConfigNode.java index bfdebf59..01350ca2 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/boot/SpringBootConfig.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/boot/SpringBootConfigNode.java @@ -24,7 +24,7 @@ import java.lang.annotation.Target; @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) -public @interface SpringBootConfig { +public @interface SpringBootConfigNode { /** * @return Class as the root to do config initialization. diff --git a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/loader/AgentClassLoader.java b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/loader/AgentClassLoader.java index 24cca2b6..3fec67cc 100644 --- a/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/loader/AgentClassLoader.java +++ b/hippo4j-agent/hippo4j-agent-core/src/main/java/cn/hippo4j/agent/core/plugin/loader/AgentClassLoader.java @@ -20,7 +20,7 @@ package cn.hippo4j.agent.core.plugin.loader; import cn.hippo4j.agent.core.boot.AgentPackageNotFoundException; import cn.hippo4j.agent.core.boot.AgentPackagePath; import cn.hippo4j.agent.core.boot.PluginConfig; -import cn.hippo4j.agent.core.boot.SpringBootConfig; +import cn.hippo4j.agent.core.boot.SpringBootConfigNode; import cn.hippo4j.agent.core.boot.SpringBootConfigInitializer; import cn.hippo4j.agent.core.conf.Config; import cn.hippo4j.agent.core.conf.SnifferConfigInitializer; @@ -171,7 +171,7 @@ public class AgentClassLoader extends ClassLoader { SnifferConfigInitializer.initializeConfig(pluginConfig.root()); } - final SpringBootConfig springBootConfig = loadedClass.getAnnotation(SpringBootConfig.class); + final SpringBootConfigNode springBootConfig = loadedClass.getAnnotation(SpringBootConfigNode.class); if (springBootConfig != null) { // Set up the plugin config when loaded by spring environment is prepared, just scan in here. // Agent class loader just loaded limited classes in the plugin jar(s), so the cost of this diff --git a/hippo4j-agent/hippo4j-agent-plugin/apollo-plugin/src/main/java/cn/hippo4j/agent/plugin/apollo/define/ApolloInstrumentation.java b/hippo4j-agent/hippo4j-agent-plugin/apollo-plugin/src/main/java/cn/hippo4j/agent/plugin/apollo/define/ApolloInstrumentation.java index 6ae9d63c..8f139aeb 100644 --- a/hippo4j-agent/hippo4j-agent-plugin/apollo-plugin/src/main/java/cn/hippo4j/agent/plugin/apollo/define/ApolloInstrumentation.java +++ b/hippo4j-agent/hippo4j-agent-plugin/apollo-plugin/src/main/java/cn/hippo4j/agent/plugin/apollo/define/ApolloInstrumentation.java @@ -31,7 +31,7 @@ public class ApolloInstrumentation extends ClassInstanceMethodsEnhancePluginDefi private static final String ENHANCE_CLASS = "com.ctrip.framework.apollo.internals.DefaultConfig"; - private static final String CONSTRUCTOR_INTERCEPT_CLASS = "cn.hippo4j.agent.plugin.apollo.DefaultConfigConstructorInterceptor"; + private static final String CONSTRUCTOR_INTERCEPT_CLASS = "cn.hippo4j.agent.plugin.apollo.interceptor.DefaultConfigConstructorInterceptor"; @Override protected ClassMatch enhanceClass() { diff --git a/hippo4j-agent/hippo4j-agent-plugin/apollo-plugin/src/main/java/cn/hippo4j/agent/plugin/apollo/DefaultConfigConstructorInterceptor.java b/hippo4j-agent/hippo4j-agent-plugin/apollo-plugin/src/main/java/cn/hippo4j/agent/plugin/apollo/interceptor/DefaultConfigConstructorInterceptor.java similarity index 95% rename from hippo4j-agent/hippo4j-agent-plugin/apollo-plugin/src/main/java/cn/hippo4j/agent/plugin/apollo/DefaultConfigConstructorInterceptor.java rename to hippo4j-agent/hippo4j-agent-plugin/apollo-plugin/src/main/java/cn/hippo4j/agent/plugin/apollo/interceptor/DefaultConfigConstructorInterceptor.java index 007e661f..f316cdf4 100644 --- a/hippo4j-agent/hippo4j-agent-plugin/apollo-plugin/src/main/java/cn/hippo4j/agent/plugin/apollo/DefaultConfigConstructorInterceptor.java +++ b/hippo4j-agent/hippo4j-agent-plugin/apollo-plugin/src/main/java/cn/hippo4j/agent/plugin/apollo/interceptor/DefaultConfigConstructorInterceptor.java @@ -15,7 +15,7 @@ * limitations under the License. */ -package cn.hippo4j.agent.plugin.apollo; +package cn.hippo4j.agent.plugin.apollo.interceptor; import cn.hippo4j.agent.core.plugin.interceptor.enhance.EnhancedInstance; import cn.hippo4j.agent.core.plugin.interceptor.enhance.InstanceConstructorInterceptor; diff --git a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/pom.xml b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/pom.xml index e144cf35..5817f6b3 100644 --- a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/pom.xml +++ b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/pom.xml @@ -42,19 +42,6 @@ provided - - com.ctrip.framework.apollo - apollo-client - ${apollo.version} - provided - - - - org.projectlombok - lombok - provided - - cn.hippo4j hippo4j-config-spring-boot-1x-starter diff --git a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/DynamicThreadPoolChangeHandlerSpring1x.java b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/DynamicThreadPoolChangeHandlerSpring1x.java new file mode 100644 index 00000000..3c332819 --- /dev/null +++ b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/DynamicThreadPoolChangeHandlerSpring1x.java @@ -0,0 +1,69 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cn.hippo4j.agent.plugin.spring.boot.v1; + +import cn.hippo4j.agent.plugin.spring.common.support.AbstractDynamicThreadPoolChangeHandlerSpring; +import cn.hippo4j.common.toolkit.MapUtil; +import cn.hippo4j.config.springboot.starter.config.BootstrapConfigProperties; +import org.springframework.beans.PropertyValues; +import org.springframework.beans.support.ResourceEditorRegistrar; +import org.springframework.boot.bind.CustomPropertyNamePatternsMatcher; +import org.springframework.boot.bind.RelaxedDataBinder; +import org.springframework.boot.bind.RelaxedNames; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.env.MapPropertySource; +import org.springframework.core.env.MutablePropertySources; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import static cn.hippo4j.config.springboot1x.starter.refresher.SpringBoot1xBootstrapConfigPropertiesBinderAdapt.getNames; + +public class DynamicThreadPoolChangeHandlerSpring1x extends AbstractDynamicThreadPoolChangeHandlerSpring { + + public DynamicThreadPoolChangeHandlerSpring1x(ConfigurableApplicationContext context) { + super(context); + } + + protected BootstrapConfigProperties bindProperties(Map configInfo, ApplicationContext applicationContext) { + BootstrapConfigProperties bindableCoreProperties = new BootstrapConfigProperties(); + if (MapUtil.isEmpty(configInfo)) { + return bindableCoreProperties; + } + RelaxedNames relaxedNames = new RelaxedNames(BootstrapConfigProperties.PREFIX); + Set names = getNames(bindableCoreProperties, relaxedNames); + Map stringConfigInfo = new HashMap<>(configInfo.size()); + configInfo.forEach((key, value) -> stringConfigInfo.put(key.toString(), value)); + MapPropertySource test = new MapPropertySource("Hippo4j", stringConfigInfo); + MutablePropertySources propertySources = new MutablePropertySources(); + propertySources.addFirst(test); + PropertyValues propertyValues = CustomPropertyNamePatternsMatcher.getPropertySourcesPropertyValues(names, propertySources); + RelaxedDataBinder dataBinder = new RelaxedDataBinder(bindableCoreProperties, BootstrapConfigProperties.PREFIX); + dataBinder.setAutoGrowCollectionLimit(Integer.MAX_VALUE); + dataBinder.setIgnoreNestedProperties(false); + dataBinder.setIgnoreInvalidFields(false); + dataBinder.setIgnoreUnknownFields(true); + ResourceEditorRegistrar resourceEditorRegistrar = new ResourceEditorRegistrar(applicationContext, applicationContext.getEnvironment()); + resourceEditorRegistrar.registerCustomEditors(dataBinder); + dataBinder.bind(propertyValues); + return bindableCoreProperties; + } + +} diff --git a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/define/EventPublishingRunListenerInstrumentation.java b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/define/EventPublishingRunListenerInstrumentation.java index c4b5cc31..e8f5d73f 100644 --- a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/define/EventPublishingRunListenerInstrumentation.java +++ b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/define/EventPublishingRunListenerInstrumentation.java @@ -31,8 +31,8 @@ public class EventPublishingRunListenerInstrumentation extends ClassInstanceMeth private static final String ENHANCE_CLASS = "org.springframework.boot.context.event.EventPublishingRunListener"; - private static final String EVENT_PUBLISHING_FINISHED_INTERCEPTOR = "cn.hippo4j.agent.plugin.spring.boot.v1.EventPublishingFinishedInterceptor"; - private static final String EVENT_PUBLISHING_ENVIRONMENT_PREPARED_INTERCEPTOR = "cn.hippo4j.agent.plugin.spring.boot.v1.EventPublishingRunListenerEnvironmentPreparedInterceptor"; + private static final String EVENT_PUBLISHING_FINISHED_INTERCEPTOR = "cn.hippo4j.agent.plugin.spring.boot.v1.interceptor.EventPublishingFinishedInterceptor"; + private static final String EVENT_PUBLISHING_ENVIRONMENT_PREPARED_INTERCEPTOR = "cn.hippo4j.agent.plugin.spring.common.interceptor.EventPublishingRunListenerEnvironmentPreparedInterceptor"; @Override protected ClassMatch enhanceClass() { diff --git a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/define/SpringApplicationRunInstrumentation.java b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/define/SpringApplicationRunInstrumentation.java deleted file mode 100644 index ea2403a3..00000000 --- a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/define/SpringApplicationRunInstrumentation.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package cn.hippo4j.agent.plugin.spring.boot.v1.define; - -import cn.hippo4j.agent.core.plugin.interceptor.ConstructorInterceptPoint; -import cn.hippo4j.agent.core.plugin.interceptor.InstanceMethodsInterceptPoint; -import cn.hippo4j.agent.core.plugin.interceptor.enhance.ClassInstanceMethodsEnhancePluginDefine; -import cn.hippo4j.agent.core.plugin.match.ClassMatch; -import net.bytebuddy.description.method.MethodDescription; -import net.bytebuddy.matcher.ElementMatcher; - -import static cn.hippo4j.agent.core.plugin.match.NameMatch.byName; -import static net.bytebuddy.matcher.ElementMatchers.named; - -public class SpringApplicationRunInstrumentation extends ClassInstanceMethodsEnhancePluginDefine { - - private static final String ENHANCE_CLASS = "org.springframework.boot.SpringApplication"; - - private static final String SPRING_APPLICATION_RUN_INTERCEPTOR = "cn.hippo4j.agent.plugin.spring.boot.v1.SpringApplicationRunInterceptor"; - - @Override - protected ClassMatch enhanceClass() { - return byName(ENHANCE_CLASS); - } - - @Override - public ConstructorInterceptPoint[] getConstructorsInterceptPoints() { - return new ConstructorInterceptPoint[0]; - } - - @Override - public InstanceMethodsInterceptPoint[] getInstanceMethodsInterceptPoints() { - return new InstanceMethodsInterceptPoint[]{ - new InstanceMethodsInterceptPoint() { - - @Override - public ElementMatcher getMethodsMatcher() { - return named("run"); - } - - @Override - public String getMethodsInterceptor() { - return SPRING_APPLICATION_RUN_INTERCEPTOR; - } - - @Override - public boolean isOverrideArgs() { - return false; - } - } - }; - } -} diff --git a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/interceptor/EventPublishingFinishedInterceptor.java b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/interceptor/EventPublishingFinishedInterceptor.java new file mode 100644 index 00000000..1ab39c2e --- /dev/null +++ b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/interceptor/EventPublishingFinishedInterceptor.java @@ -0,0 +1,64 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cn.hippo4j.agent.plugin.spring.boot.v1.interceptor; + +import cn.hippo4j.agent.core.logging.api.ILog; +import cn.hippo4j.agent.core.logging.api.LogManager; +import cn.hippo4j.agent.core.plugin.interceptor.enhance.EnhancedInstance; +import cn.hippo4j.agent.core.plugin.interceptor.enhance.InstanceMethodsAroundInterceptor; +import cn.hippo4j.agent.core.plugin.interceptor.enhance.MethodInterceptResult; +import cn.hippo4j.agent.plugin.spring.boot.v1.DynamicThreadPoolChangeHandlerSpring1x; +import cn.hippo4j.agent.plugin.spring.common.support.SpringPropertiesLoader; +import cn.hippo4j.agent.plugin.spring.common.support.IDynamicThreadPoolChangeHandlerSpring; +import cn.hippo4j.agent.plugin.spring.common.support.SpringThreadPoolRegisterSupport; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.ConfigurableApplicationContext; + +import java.lang.reflect.Method; + +public class EventPublishingFinishedInterceptor implements InstanceMethodsAroundInterceptor { + + private static final ILog FILE_LOGGER = LogManager.getLogger(EventPublishingFinishedInterceptor.class); + private static final Logger LOGGER = LoggerFactory.getLogger(EventPublishingFinishedInterceptor.class); + + @Override + public void beforeMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class[] argumentsTypes, MethodInterceptResult result) throws Throwable { + + } + + @Override + public Object afterMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class[] argumentsTypes, Object ret) throws Throwable { + ConfigurableApplicationContext context = (ConfigurableApplicationContext) allArguments[0]; + if (context.getParent() != null) { + // After the child container is started, the thread pool registration will be carried out + SpringThreadPoolRegisterSupport.registerThreadPoolInstances(); + return ret; + } + SpringPropertiesLoader.loadSpringProperties(context.getEnvironment()); + IDynamicThreadPoolChangeHandlerSpring handlerSpring1x = new DynamicThreadPoolChangeHandlerSpring1x(context); + handlerSpring1x.registerApolloConfigHandler(); + + return ret; + } + + @Override + public void handleMethodException(EnhancedInstance objInst, Method method, Object[] allArguments, Class[] argumentsTypes, Throwable t) { + + } +} diff --git a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/resources/hippo4j-plugin.def b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/resources/hippo4j-plugin.def index bcea5121..8bb37e3a 100644 --- a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/resources/hippo4j-plugin.def +++ b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/resources/hippo4j-plugin.def @@ -14,5 +14,4 @@ # See the License for the specific language governing permissions and # limitations under the License. -spring-boot-1.x=cn.hippo4j.agent.plugin.spring.boot.v1.define.EventPublishingRunListenerInstrumentation -spring-boot-1.x=cn.hippo4j.agent.plugin.spring.boot.v1.define.SpringApplicationRunInstrumentation \ No newline at end of file +spring-boot-1.x=cn.hippo4j.agent.plugin.spring.boot.v1.define.EventPublishingRunListenerInstrumentation \ No newline at end of file diff --git a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-2.x-plugin/pom.xml b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-2.x-plugin/pom.xml index bf7b5712..c762aac0 100644 --- a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-2.x-plugin/pom.xml +++ b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-2.x-plugin/pom.xml @@ -25,9 +25,15 @@ org.springframework.boot - spring-boot-autoconfigure + spring-boot-starter ${spring.boot.version} provided + + + cn.hippo4j + hippo4j-config-spring-boot-starter + ${project.version} + \ No newline at end of file diff --git a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-2.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v2/DynamicThreadPoolChangeHandlerSpring2x.java b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-2.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v2/DynamicThreadPoolChangeHandlerSpring2x.java new file mode 100644 index 00000000..98becdb8 --- /dev/null +++ b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-2.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v2/DynamicThreadPoolChangeHandlerSpring2x.java @@ -0,0 +1,44 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cn.hippo4j.agent.plugin.spring.boot.v2; + +import cn.hippo4j.agent.plugin.spring.common.support.AbstractDynamicThreadPoolChangeHandlerSpring; +import cn.hippo4j.config.springboot.starter.config.BootstrapConfigProperties; +import org.springframework.boot.context.properties.bind.Bindable; +import org.springframework.boot.context.properties.bind.Binder; +import org.springframework.boot.context.properties.source.ConfigurationPropertySource; +import org.springframework.boot.context.properties.source.MapConfigurationPropertySource; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ConfigurableApplicationContext; + +import java.util.Map; + +public class DynamicThreadPoolChangeHandlerSpring2x extends AbstractDynamicThreadPoolChangeHandlerSpring { + + public DynamicThreadPoolChangeHandlerSpring2x(ConfigurableApplicationContext context) { + super(context); + } + + @Override + protected BootstrapConfigProperties bindProperties(Map configInfo, ApplicationContext applicationContext) { + BootstrapConfigProperties bindableBootstrapConfigProperties = new BootstrapConfigProperties(); + ConfigurationPropertySource sources = new MapConfigurationPropertySource(configInfo); + Binder binder = new Binder(sources); + return binder.bind(BootstrapConfigProperties.PREFIX, Bindable.ofInstance(bindableBootstrapConfigProperties)).get(); + } +} diff --git a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-2.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v2/define/EventPublishingRunListenerInstrumentation.java b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-2.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v2/define/EventPublishingRunListenerInstrumentation.java index c3e46ed6..56c60d5a 100644 --- a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-2.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v2/define/EventPublishingRunListenerInstrumentation.java +++ b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-2.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v2/define/EventPublishingRunListenerInstrumentation.java @@ -31,7 +31,8 @@ public class EventPublishingRunListenerInstrumentation extends ClassInstanceMeth private static final String ENHANCE_CLASS = "org.springframework.boot.context.event.EventPublishingRunListener"; - private static final String EVENT_PUBLISHING_FINISHED_INTERCEPTOR = "cn.hippo4j.agent.plugin.spring.boot.v2.EventPublishingStartedInterceptor"; + private static final String EVENT_PUBLISHING_FINISHED_INTERCEPTOR = "cn.hippo4j.agent.plugin.spring.boot.v2.interceptor.EventPublishingStartedInterceptor"; + private static final String EVENT_PUBLISHING_ENVIRONMENT_PREPARED_INTERCEPTOR = "cn.hippo4j.agent.plugin.spring.common.interceptor.EventPublishingRunListenerEnvironmentPreparedInterceptor"; @Override protected ClassMatch enhanceClass() { @@ -58,6 +59,23 @@ public class EventPublishingRunListenerInstrumentation extends ClassInstanceMeth return EVENT_PUBLISHING_FINISHED_INTERCEPTOR; } + @Override + public boolean isOverrideArgs() { + return false; + } + }, + new InstanceMethodsInterceptPoint() { + + @Override + public ElementMatcher getMethodsMatcher() { + return named("environmentPrepared"); + } + + @Override + public String getMethodsInterceptor() { + return EVENT_PUBLISHING_ENVIRONMENT_PREPARED_INTERCEPTOR; + } + @Override public boolean isOverrideArgs() { return false; diff --git a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-2.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v2/EventPublishingStartedInterceptor.java b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-2.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v2/interceptor/EventPublishingStartedInterceptor.java similarity index 72% rename from hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-2.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v2/EventPublishingStartedInterceptor.java rename to hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-2.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v2/interceptor/EventPublishingStartedInterceptor.java index 762b63a7..1c782722 100644 --- a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-2.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v2/EventPublishingStartedInterceptor.java +++ b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-2.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v2/interceptor/EventPublishingStartedInterceptor.java @@ -15,14 +15,17 @@ * limitations under the License. */ -package cn.hippo4j.agent.plugin.spring.boot.v2; +package cn.hippo4j.agent.plugin.spring.boot.v2.interceptor; import cn.hippo4j.agent.core.logging.api.ILog; import cn.hippo4j.agent.core.logging.api.LogManager; import cn.hippo4j.agent.core.plugin.interceptor.enhance.EnhancedInstance; import cn.hippo4j.agent.core.plugin.interceptor.enhance.InstanceMethodsAroundInterceptor; import cn.hippo4j.agent.core.plugin.interceptor.enhance.MethodInterceptResult; -import cn.hippo4j.agent.plugin.spring.common.SpringPropertiesLoader; +import cn.hippo4j.agent.plugin.spring.boot.v2.DynamicThreadPoolChangeHandlerSpring2x; +import cn.hippo4j.agent.plugin.spring.common.support.SpringPropertiesLoader; +import cn.hippo4j.agent.plugin.spring.common.support.IDynamicThreadPoolChangeHandlerSpring; +import cn.hippo4j.agent.plugin.spring.common.support.SpringThreadPoolRegisterSupport; import org.springframework.context.ConfigurableApplicationContext; import java.lang.reflect.Method; @@ -39,7 +42,15 @@ public class EventPublishingStartedInterceptor implements InstanceMethodsAroundI @Override public Object afterMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class[] argumentsTypes, Object ret) throws Throwable { ConfigurableApplicationContext context = (ConfigurableApplicationContext) allArguments[0]; + if (context.getParent() != null) { + // After the child container is started, the thread pool registration will be carried out + SpringThreadPoolRegisterSupport.registerThreadPoolInstances(); + return ret; + } SpringPropertiesLoader.loadSpringProperties(context.getEnvironment()); + IDynamicThreadPoolChangeHandlerSpring handler = new DynamicThreadPoolChangeHandlerSpring2x(context); + handler.registerApolloConfigHandler(); + return ret; } diff --git a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-plugin-common/pom.xml b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-plugin-common/pom.xml index f6ea99a8..101d9ab9 100644 --- a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-plugin-common/pom.xml +++ b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-plugin-common/pom.xml @@ -17,6 +17,31 @@ spring-core provided + + + org.projectlombok + lombok + provided + + + + org.slf4j + slf4j-api + + + + com.ctrip.framework.apollo + apollo-client + ${apollo.version} + provided + + + + cn.hippo4j + hippo4j-config-spring-boot-starter + ${project.version} + provided + \ No newline at end of file diff --git a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/ApolloSpringBootProperties.java b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-plugin-common/src/main/java/cn/hippo4j/agent/plugin/spring/common/conf/SpringBootConfig.java similarity index 80% rename from hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/ApolloSpringBootProperties.java rename to hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-plugin-common/src/main/java/cn/hippo4j/agent/plugin/spring/common/conf/SpringBootConfig.java index f7b7a128..883cddb3 100644 --- a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/ApolloSpringBootProperties.java +++ b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-plugin-common/src/main/java/cn/hippo4j/agent/plugin/spring/common/conf/SpringBootConfig.java @@ -15,23 +15,23 @@ * limitations under the License. */ -package cn.hippo4j.agent.plugin.spring.boot.v1; +package cn.hippo4j.agent.plugin.spring.common.conf; -import cn.hippo4j.agent.core.boot.SpringBootConfig; +import cn.hippo4j.agent.core.boot.SpringBootConfigNode; import java.util.Arrays; import java.util.List; -public class ApolloSpringBootProperties { +public class SpringBootConfig { public static class Spring { public static class Dynamic { - @SpringBootConfig(root = ApolloSpringBootProperties.class) + @SpringBootConfigNode(root = SpringBootConfig.class) public static class Thread_Pool { - @SpringBootConfig(root = ApolloSpringBootProperties.class) + @SpringBootConfigNode(root = SpringBootConfig.class) public static class Apollo { public static List NAMESPACE = Arrays.asList("application"); diff --git a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/EventPublishingRunListenerEnvironmentPreparedInterceptor.java b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-plugin-common/src/main/java/cn/hippo4j/agent/plugin/spring/common/interceptor/EventPublishingRunListenerEnvironmentPreparedInterceptor.java similarity index 94% rename from hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/EventPublishingRunListenerEnvironmentPreparedInterceptor.java rename to hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-plugin-common/src/main/java/cn/hippo4j/agent/plugin/spring/common/interceptor/EventPublishingRunListenerEnvironmentPreparedInterceptor.java index 1ac06ade..0ff2380c 100644 --- a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/EventPublishingRunListenerEnvironmentPreparedInterceptor.java +++ b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-plugin-common/src/main/java/cn/hippo4j/agent/plugin/spring/common/interceptor/EventPublishingRunListenerEnvironmentPreparedInterceptor.java @@ -15,12 +15,12 @@ * limitations under the License. */ -package cn.hippo4j.agent.plugin.spring.boot.v1; +package cn.hippo4j.agent.plugin.spring.common.interceptor; import cn.hippo4j.agent.core.plugin.interceptor.enhance.EnhancedInstance; import cn.hippo4j.agent.core.plugin.interceptor.enhance.InstanceMethodsAroundInterceptor; import cn.hippo4j.agent.core.plugin.interceptor.enhance.MethodInterceptResult; -import cn.hippo4j.agent.plugin.spring.common.SpringEnvironmentSupport; +import cn.hippo4j.agent.plugin.spring.common.support.SpringEnvironmentSupport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.env.ConfigurableEnvironment; diff --git a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/EventPublishingFinishedInterceptor.java b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-plugin-common/src/main/java/cn/hippo4j/agent/plugin/spring/common/support/AbstractDynamicThreadPoolChangeHandlerSpring.java similarity index 80% rename from hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/EventPublishingFinishedInterceptor.java rename to hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-plugin-common/src/main/java/cn/hippo4j/agent/plugin/spring/common/support/AbstractDynamicThreadPoolChangeHandlerSpring.java index 1017c46b..6db57f2c 100644 --- a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/EventPublishingFinishedInterceptor.java +++ b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-plugin-common/src/main/java/cn/hippo4j/agent/plugin/spring/common/support/AbstractDynamicThreadPoolChangeHandlerSpring.java @@ -15,25 +15,19 @@ * limitations under the License. */ -package cn.hippo4j.agent.plugin.spring.boot.v1; +package cn.hippo4j.agent.plugin.spring.common.support; -import cn.hippo4j.agent.core.logging.api.ILog; -import cn.hippo4j.agent.core.logging.api.LogManager; -import cn.hippo4j.agent.core.plugin.interceptor.enhance.EnhancedInstance; -import cn.hippo4j.agent.core.plugin.interceptor.enhance.InstanceMethodsAroundInterceptor; -import cn.hippo4j.agent.core.plugin.interceptor.enhance.MethodInterceptResult; import cn.hippo4j.agent.core.registry.AgentThreadPoolExecutorHolder; import cn.hippo4j.agent.core.registry.AgentThreadPoolInstanceRegistry; import cn.hippo4j.agent.core.util.ThreadPoolPropertyKey; -import cn.hippo4j.agent.plugin.spring.common.SpringPropertiesLoader; +import cn.hippo4j.agent.plugin.spring.common.conf.SpringBootConfig; +import cn.hippo4j.common.config.ExecutorProperties; import cn.hippo4j.common.executor.support.BlockingQueueTypeEnum; import cn.hippo4j.common.executor.support.RejectedPolicyTypeEnum; import cn.hippo4j.common.executor.support.ResizableCapacityLinkedBlockingQueue; import cn.hippo4j.common.toolkit.CollectionUtil; -import cn.hippo4j.common.toolkit.MapUtil; import cn.hippo4j.common.toolkit.ThreadPoolExecutorUtil; import cn.hippo4j.config.springboot.starter.config.BootstrapConfigProperties; -import cn.hippo4j.common.config.ExecutorProperties; import cn.hippo4j.config.springboot.starter.parser.ConfigFileTypeEnum; import cn.hippo4j.config.springboot.starter.parser.ConfigParserHandler; import cn.hippo4j.core.executor.DynamicThreadPoolExecutor; @@ -45,24 +39,15 @@ import com.ctrip.framework.apollo.core.enums.ConfigFileFormat; import com.ctrip.framework.apollo.model.ConfigChange; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.PropertyValues; -import org.springframework.beans.support.ResourceEditorRegistrar; -import org.springframework.boot.bind.CustomPropertyNamePatternsMatcher; -import org.springframework.boot.bind.RelaxedDataBinder; -import org.springframework.boot.bind.RelaxedNames; import org.springframework.context.ApplicationContext; import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.core.env.MapPropertySource; -import org.springframework.core.env.MutablePropertySources; -import java.lang.reflect.Method; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Properties; -import java.util.Set; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; @@ -70,27 +55,23 @@ import java.util.concurrent.TimeUnit; import static cn.hippo4j.agent.core.conf.Constants.SPRING_BOOT_CONFIG_PREFIX; import static cn.hippo4j.common.constant.ChangeThreadPoolConstants.CHANGE_DELIMITER; import static cn.hippo4j.common.constant.ChangeThreadPoolConstants.CHANGE_THREAD_POOL_TEXT; -import static cn.hippo4j.config.springboot1x.starter.refresher.SpringBoot1xBootstrapConfigPropertiesBinderAdapt.getNames; -public class EventPublishingFinishedInterceptor implements InstanceMethodsAroundInterceptor { +public abstract class AbstractDynamicThreadPoolChangeHandlerSpring implements IDynamicThreadPoolChangeHandlerSpring { - private static final ILog FILE_LOGGER = LogManager.getLogger(EventPublishingFinishedInterceptor.class); - private static final Logger LOGGER = LoggerFactory.getLogger(EventPublishingFinishedInterceptor.class); + private static final Logger LOGGER = LoggerFactory.getLogger(AbstractDynamicThreadPoolChangeHandlerSpring.class); - @Override - public void beforeMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class[] argumentsTypes, MethodInterceptResult result) throws Throwable { + private final ConfigurableApplicationContext applicationContext; + public AbstractDynamicThreadPoolChangeHandlerSpring(ConfigurableApplicationContext context) { + this.applicationContext = context; } - @Override - public Object afterMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class[] argumentsTypes, Object ret) throws Throwable { - ConfigurableApplicationContext context = (ConfigurableApplicationContext) allArguments[0]; - SpringPropertiesLoader.loadSpringProperties(context.getEnvironment()); - - List apolloNamespaces = ApolloSpringBootProperties.Spring.Dynamic.Thread_Pool.Apollo.NAMESPACE; + public void registerApolloConfigHandler() { + List apolloNamespaces = SpringBootConfig.Spring.Dynamic.Thread_Pool.Apollo.NAMESPACE; String namespace = apolloNamespaces.get(0); - String configFileType = ApolloSpringBootProperties.Spring.Dynamic.Thread_Pool.CONFIG_FILE_TYPE; + String configFileType = SpringBootConfig.Spring.Dynamic.Thread_Pool.CONFIG_FILE_TYPE; + com.ctrip.framework.apollo.Config config = ConfigService.getConfig(String.format("%s.%s", namespace, configFileType)); ConfigChangeListener configChangeListener = configChangeEvent -> { String replacedNamespace = namespace.replaceAll("." + configFileType, ""); @@ -102,40 +83,17 @@ public class EventPublishingFinishedInterceptor implements InstanceMethodsAround String newValue = change.getNewValue(); newChangeValueMap.put(each, newValue); }); - dynamicRefresh(configFile.getContent(), newChangeValueMap, context); + dynamicRefresh(configFile.getContent(), newChangeValueMap, applicationContext); }; config.addChangeListener(configChangeListener); - LOGGER.info("Dynamic thread pool refresher, add apollo listener success. namespace: {}", namespace); - return ret; + LOGGER.info("[Hippo4j-Agent] Dynamic thread pool refresher, add apollo listener success. namespace: {}", namespace); } - public BootstrapConfigProperties bindProperties(Map configInfo, ApplicationContext applicationContext) { - BootstrapConfigProperties bindableCoreProperties = new BootstrapConfigProperties(); - if (MapUtil.isEmpty(configInfo)) { - return bindableCoreProperties; - } - RelaxedNames relaxedNames = new RelaxedNames(BootstrapConfigProperties.PREFIX); - Set names = getNames(bindableCoreProperties, relaxedNames); - Map stringConfigInfo = new HashMap<>(configInfo.size()); - configInfo.forEach((key, value) -> stringConfigInfo.put(key.toString(), value)); - MapPropertySource test = new MapPropertySource("Hippo4j", stringConfigInfo); - MutablePropertySources propertySources = new MutablePropertySources(); - propertySources.addFirst(test); - PropertyValues propertyValues = CustomPropertyNamePatternsMatcher.getPropertySourcesPropertyValues(names, propertySources); - RelaxedDataBinder dataBinder = new RelaxedDataBinder(bindableCoreProperties, BootstrapConfigProperties.PREFIX); - dataBinder.setAutoGrowCollectionLimit(Integer.MAX_VALUE); - dataBinder.setIgnoreNestedProperties(false); - dataBinder.setIgnoreInvalidFields(false); - dataBinder.setIgnoreUnknownFields(true); - ResourceEditorRegistrar resourceEditorRegistrar = new ResourceEditorRegistrar(applicationContext, applicationContext.getEnvironment()); - resourceEditorRegistrar.registerCustomEditors(dataBinder); - dataBinder.bind(propertyValues); - return bindableCoreProperties; - } + protected abstract BootstrapConfigProperties bindProperties(Map configInfo, ApplicationContext applicationContext); - public void dynamicRefresh(String configContent, Map newValueChangeMap, ApplicationContext context) { + private void dynamicRefresh(String configContent, Map newValueChangeMap, ApplicationContext context) { try { - String configFileType = ApolloSpringBootProperties.Spring.Dynamic.Thread_Pool.CONFIG_FILE_TYPE; + String configFileType = SpringBootConfig.Spring.Dynamic.Thread_Pool.CONFIG_FILE_TYPE; Map afterConfigMap = ConfigParserHandler.getInstance().parseConfig(configContent, ConfigFileTypeEnum.of(configFileType)); @@ -319,8 +277,4 @@ public class EventPublishingFinishedInterceptor implements InstanceMethodsAround && Objects.equals(BlockingQueueTypeEnum.RESIZABLE_LINKED_BLOCKING_QUEUE.getName(), executor.getQueue().getClass().getSimpleName()))); } - @Override - public void handleMethodException(EnhancedInstance objInst, Method method, Object[] allArguments, Class[] argumentsTypes, Throwable t) { - - } } diff --git a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-plugin-common/src/main/java/cn/hippo4j/agent/plugin/spring/common/support/IDynamicThreadPoolChangeHandlerSpring.java b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-plugin-common/src/main/java/cn/hippo4j/agent/plugin/spring/common/support/IDynamicThreadPoolChangeHandlerSpring.java new file mode 100644 index 00000000..5aebf5a3 --- /dev/null +++ b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-plugin-common/src/main/java/cn/hippo4j/agent/plugin/spring/common/support/IDynamicThreadPoolChangeHandlerSpring.java @@ -0,0 +1,24 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cn.hippo4j.agent.plugin.spring.common.support; + +public interface IDynamicThreadPoolChangeHandlerSpring { + + void registerApolloConfigHandler(); + +} diff --git a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-plugin-common/src/main/java/cn/hippo4j/agent/plugin/spring/common/SpringEnvironmentSupport.java b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-plugin-common/src/main/java/cn/hippo4j/agent/plugin/spring/common/support/SpringEnvironmentSupport.java similarity index 96% rename from hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-plugin-common/src/main/java/cn/hippo4j/agent/plugin/spring/common/SpringEnvironmentSupport.java rename to hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-plugin-common/src/main/java/cn/hippo4j/agent/plugin/spring/common/support/SpringEnvironmentSupport.java index 0d93bae3..e0e10bf8 100644 --- a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-plugin-common/src/main/java/cn/hippo4j/agent/plugin/spring/common/SpringEnvironmentSupport.java +++ b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-plugin-common/src/main/java/cn/hippo4j/agent/plugin/spring/common/support/SpringEnvironmentSupport.java @@ -15,7 +15,7 @@ * limitations under the License. */ -package cn.hippo4j.agent.plugin.spring.common; +package cn.hippo4j.agent.plugin.spring.common.support; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.MapPropertySource; diff --git a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-plugin-common/src/main/java/cn/hippo4j/agent/plugin/spring/common/SpringPropertiesLoader.java b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-plugin-common/src/main/java/cn/hippo4j/agent/plugin/spring/common/support/SpringPropertiesLoader.java similarity index 98% rename from hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-plugin-common/src/main/java/cn/hippo4j/agent/plugin/spring/common/SpringPropertiesLoader.java rename to hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-plugin-common/src/main/java/cn/hippo4j/agent/plugin/spring/common/support/SpringPropertiesLoader.java index 485a7669..822f7022 100644 --- a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-plugin-common/src/main/java/cn/hippo4j/agent/plugin/spring/common/SpringPropertiesLoader.java +++ b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-plugin-common/src/main/java/cn/hippo4j/agent/plugin/spring/common/support/SpringPropertiesLoader.java @@ -15,7 +15,7 @@ * limitations under the License. */ -package cn.hippo4j.agent.plugin.spring.common; +package cn.hippo4j.agent.plugin.spring.common.support; import cn.hippo4j.agent.core.boot.SpringBootConfigInitializer; import cn.hippo4j.agent.core.logging.api.ILog; diff --git a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/SpringApplicationRunInterceptor.java b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-plugin-common/src/main/java/cn/hippo4j/agent/plugin/spring/common/support/SpringThreadPoolRegisterSupport.java similarity index 77% rename from hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/SpringApplicationRunInterceptor.java rename to hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-plugin-common/src/main/java/cn/hippo4j/agent/plugin/spring/common/support/SpringThreadPoolRegisterSupport.java index f75980f4..bde71b97 100644 --- a/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-boot-1.x-plugin/src/main/java/cn/hippo4j/agent/plugin/spring/boot/v1/SpringApplicationRunInterceptor.java +++ b/hippo4j-agent/hippo4j-agent-plugin/spring-plugins/spring-plugin-common/src/main/java/cn/hippo4j/agent/plugin/spring/common/support/SpringThreadPoolRegisterSupport.java @@ -15,11 +15,8 @@ * limitations under the License. */ -package cn.hippo4j.agent.plugin.spring.boot.v1; +package cn.hippo4j.agent.plugin.spring.common.support; -import cn.hippo4j.agent.core.plugin.interceptor.enhance.EnhancedInstance; -import cn.hippo4j.agent.core.plugin.interceptor.enhance.InstanceMethodsAroundInterceptor; -import cn.hippo4j.agent.core.plugin.interceptor.enhance.MethodInterceptResult; import cn.hippo4j.agent.core.registry.AgentThreadPoolInstanceRegistry; import cn.hippo4j.agent.core.util.ReflectUtil; import cn.hippo4j.agent.core.util.ThreadPoolPropertyKey; @@ -30,30 +27,17 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Field; -import java.lang.reflect.Method; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; -public class SpringApplicationRunInterceptor implements InstanceMethodsAroundInterceptor { +public class SpringThreadPoolRegisterSupport { - private static final Logger LOGGER = LoggerFactory.getLogger(SpringApplicationRunInterceptor.class); + private static final Logger LOGGER = LoggerFactory.getLogger(SpringThreadPoolRegisterSupport.class); - @Override - public void beforeMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class[] argumentsTypes, MethodInterceptResult result) throws Throwable { - - } - - @Override - public Object afterMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class[] argumentsTypes, Object ret) throws Throwable { - registerThreadPoolInstances(); - LOGGER.info("[Hippo4j-Agent] Registered thread pool instances successfully."); - return ret; - } - - private void registerThreadPoolInstances() { + public static void registerThreadPoolInstances() { Map> earlyConstructMap = AgentThreadPoolInstanceRegistry.getInstance().earlyConstructMap; for (Map.Entry> entry : earlyConstructMap.entrySet()) { ThreadPoolExecutor enhancedInstance = entry.getKey(); @@ -72,9 +56,10 @@ public class SpringApplicationRunInterceptor implements InstanceMethodsAroundInt } } } + LOGGER.info("[Hippo4j-Agent] Registered thread pool instances successfully."); } - private void register(String threadPoolId, ThreadPoolExecutor executor) { + public static void register(String threadPoolId, ThreadPoolExecutor executor) { // build parameter properties. Properties properties = new Properties(); properties.put(ThreadPoolPropertyKey.THREAD_POOL_ID, threadPoolId); @@ -92,9 +77,4 @@ public class SpringApplicationRunInterceptor implements InstanceMethodsAroundInt AgentThreadPoolInstanceRegistry.getInstance().putHolder(threadPoolId, executor, properties); } - - @Override - public void handleMethodException(EnhancedInstance objInst, Method method, Object[] allArguments, Class[] argumentsTypes, Throwable t) { - - } } diff --git a/hippo4j-agent/hippo4j-agent-plugin/thread-pool-plugin/src/main/java/cn/hippo4j/agent/plugin/thread/pool/define/ThreadPoolExecutorInstrumentation.java b/hippo4j-agent/hippo4j-agent-plugin/thread-pool-plugin/src/main/java/cn/hippo4j/agent/plugin/thread/pool/define/ThreadPoolExecutorInstrumentation.java index d437e0d5..3c1534b5 100644 --- a/hippo4j-agent/hippo4j-agent-plugin/thread-pool-plugin/src/main/java/cn/hippo4j/agent/plugin/thread/pool/define/ThreadPoolExecutorInstrumentation.java +++ b/hippo4j-agent/hippo4j-agent-plugin/thread-pool-plugin/src/main/java/cn/hippo4j/agent/plugin/thread/pool/define/ThreadPoolExecutorInstrumentation.java @@ -31,7 +31,7 @@ public class ThreadPoolExecutorInstrumentation extends ClassInstanceMethodsEnhan private static final String ENHANCE_CLASS = "java.util.concurrent.ThreadPoolExecutor"; - private static final String CONSTRUCTOR_INTERCEPT_CLASS = "cn.hippo4j.agent.plugin.thread.pool.ThreadPoolExecutorConstructorMethodInterceptor"; + private static final String CONSTRUCTOR_INTERCEPT_CLASS = "cn.hippo4j.agent.plugin.thread.pool.interceptor.ThreadPoolExecutorConstructorMethodInterceptor"; private static final int CONSTRUCTOR_INTERCEPT_PARAMETER_LENGTH = 7; diff --git a/hippo4j-agent/hippo4j-agent-plugin/thread-pool-plugin/src/main/java/cn/hippo4j/agent/plugin/thread/pool/ThreadPoolExecutorConstructorMethodInterceptor.java b/hippo4j-agent/hippo4j-agent-plugin/thread-pool-plugin/src/main/java/cn/hippo4j/agent/plugin/thread/pool/interceptor/ThreadPoolExecutorConstructorMethodInterceptor.java similarity index 98% rename from hippo4j-agent/hippo4j-agent-plugin/thread-pool-plugin/src/main/java/cn/hippo4j/agent/plugin/thread/pool/ThreadPoolExecutorConstructorMethodInterceptor.java rename to hippo4j-agent/hippo4j-agent-plugin/thread-pool-plugin/src/main/java/cn/hippo4j/agent/plugin/thread/pool/interceptor/ThreadPoolExecutorConstructorMethodInterceptor.java index 1f6835b4..6c48b311 100644 --- a/hippo4j-agent/hippo4j-agent-plugin/thread-pool-plugin/src/main/java/cn/hippo4j/agent/plugin/thread/pool/ThreadPoolExecutorConstructorMethodInterceptor.java +++ b/hippo4j-agent/hippo4j-agent-plugin/thread-pool-plugin/src/main/java/cn/hippo4j/agent/plugin/thread/pool/interceptor/ThreadPoolExecutorConstructorMethodInterceptor.java @@ -15,7 +15,7 @@ * limitations under the License. */ -package cn.hippo4j.agent.plugin.thread.pool; +package cn.hippo4j.agent.plugin.thread.pool.interceptor; import cn.hippo4j.agent.core.conf.Config; import cn.hippo4j.agent.core.logging.api.ILog; diff --git a/hippo4j-example/hippo4j-config-apollo-spring-boot-starter-example/pom.xml b/hippo4j-example/hippo4j-config-apollo-spring-boot-starter-example/pom.xml index cf9e6e91..eea56b5e 100644 --- a/hippo4j-example/hippo4j-config-apollo-spring-boot-starter-example/pom.xml +++ b/hippo4j-example/hippo4j-config-apollo-spring-boot-starter-example/pom.xml @@ -70,4 +70,21 @@ spring-boot-starter-actuator + + + ${project.artifactId} + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + + + + diff --git a/hippo4j-spring-boot/hippo4j-spring-boot-starter-monitor/hippo4j-spring-boot-starter-monitor-micrometer/src/main/java/cn/hippo4j/springboot/starter/monitor/micrometer/MicrometerMonitorAutoConfiguration.java b/hippo4j-spring-boot/hippo4j-spring-boot-starter-monitor/hippo4j-spring-boot-starter-monitor-micrometer/src/main/java/cn/hippo4j/springboot/starter/monitor/micrometer/MicrometerMonitorAutoConfiguration.java index 1ae9406e..02ea862e 100644 --- a/hippo4j-spring-boot/hippo4j-spring-boot-starter-monitor/hippo4j-spring-boot-starter-monitor-micrometer/src/main/java/cn/hippo4j/springboot/starter/monitor/micrometer/MicrometerMonitorAutoConfiguration.java +++ b/hippo4j-spring-boot/hippo4j-spring-boot-starter-monitor/hippo4j-spring-boot-starter-monitor-micrometer/src/main/java/cn/hippo4j/springboot/starter/monitor/micrometer/MicrometerMonitorAutoConfiguration.java @@ -38,6 +38,7 @@ public class MicrometerMonitorAutoConfiguration { @Bean @ConditionalOnExpression("'${spring.dynamic.thread-pool.monitor.thread-pool-types:}'.contains('dynamic')") + @ConditionalOnProperty(prefix = Constants.CONFIGURATION_PROPERTIES_PREFIX, value = "enable", matchIfMissing = true, havingValue = "true") public DynamicThreadPoolMicrometerMonitorHandler dynamicThreadPoolMicrometerMonitorHandler() { return new DynamicThreadPoolMicrometerMonitorHandler(); } From 0f3b33fbcc68b3cb730577e6ec80b28a607d69e6 Mon Sep 17 00:00:00 2001 From: pizihao <2335715300@qq.com> Date: Thu, 11 May 2023 09:55:59 +0800 Subject: [PATCH 2/3] Modify the file directory prefix (#1239) * fix : HttpUtilsTest modify call fixed website(#1236) * test : Modify the file directory prefix(#1236) * test : check directory(#1236) --- hippo4j-common/pom.xml | 5 + .../common/toolkit/http/HomeServlet.java | 42 ++++++ .../common/toolkit/http/HttpUtilsTest.java | 121 ++++++++++++++---- .../common/toolkit/http/LoginServlet.java | 50 ++++++++ 4 files changed, 195 insertions(+), 23 deletions(-) create mode 100644 hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/http/HomeServlet.java create mode 100644 hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/http/LoginServlet.java diff --git a/hippo4j-common/pom.xml b/hippo4j-common/pom.xml index e5be28cf..aeff902a 100644 --- a/hippo4j-common/pom.xml +++ b/hippo4j-common/pom.xml @@ -77,5 +77,10 @@ org.springframework.boot spring-boot-configuration-processor + + org.apache.tomcat.embed + tomcat-embed-core + test + diff --git a/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/http/HomeServlet.java b/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/http/HomeServlet.java new file mode 100644 index 00000000..1f377b0b --- /dev/null +++ b/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/http/HomeServlet.java @@ -0,0 +1,42 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cn.hippo4j.common.toolkit.http; + +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.PrintWriter; + +/** + * Implement HttpServlet and receive post and get requests
+ * This HttpServlet represents the home page + */ +public class HomeServlet extends HttpServlet { + + int status = 200; + String result = "success"; + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { + resp.setStatus(status); + PrintWriter writer = resp.getWriter(); + writer.println(result); + } + +} diff --git a/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/http/HttpUtilsTest.java b/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/http/HttpUtilsTest.java index 55eb6675..f238ea96 100644 --- a/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/http/HttpUtilsTest.java +++ b/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/http/HttpUtilsTest.java @@ -20,36 +20,111 @@ package cn.hippo4j.common.toolkit.http; import cn.hippo4j.common.toolkit.JSONUtil; import lombok.Getter; import lombok.Setter; +import org.apache.catalina.Context; +import org.apache.catalina.LifecycleException; +import org.apache.catalina.connector.Connector; +import org.apache.catalina.startup.Tomcat; +import org.junit.AfterClass; import org.junit.Assert; +import org.junit.BeforeClass; import org.junit.Test; +import java.io.File; +import java.io.IOException; +import java.net.ServerSocket; +import java.nio.file.FileVisitResult; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.attribute.BasicFileAttributes; import java.util.HashMap; import java.util.Map; public class HttpUtilsTest { - /** - * test post url - */ - static String postUrl = "http://console.hippo4j.cn/hippo4j/v1/cs/"; + static int PORT = 8080; + static Tomcat tomcat; + static final String PROTOCOL = "org.apache.coyote.http11.Http11NioProtocol"; + static final String HOME_PAGE_URL = "/home"; + static final String HOME_PAGE_NAME = "homeServlet"; + static final String LOGIN_URL = "/login"; + static final String LOGIN_NAME = "loginServlet"; + static final String CONTEXT_PATH = "/"; + static final String PATH_NAME = "."; + static final String USER_DIR = "user.dir"; + static final String PREFIX = "\\tomcat."; + + @BeforeClass + public static void startWeb() throws IOException, LifecycleException { + tomcat = new Tomcat(); + // get a random port + ServerSocket socket = new ServerSocket(0); + PORT = socket.getLocalPort(); + socket.close(); + tomcat.setPort(PORT); + Connector connector = new Connector(PROTOCOL); + connector.setThrowOnFailure(true); + connector.setPort(PORT); + tomcat.setConnector(connector); + String absolutePath = new File(PATH_NAME).getAbsolutePath(); + Context context = tomcat.addContext(CONTEXT_PATH, absolutePath); + Tomcat.addServlet(context, HOME_PAGE_NAME, new HomeServlet()).setAsyncSupported(true); + context.addServletMappingDecoded(HOME_PAGE_URL, HOME_PAGE_NAME); + Tomcat.addServlet(context, LOGIN_NAME, new LoginServlet()).setAsyncSupported(true); + context.addServletMappingDecoded(LOGIN_URL, LOGIN_NAME); + tomcat.start(); + } + + @AfterClass + public static void stopWeb() throws LifecycleException, IOException { + // stop tomcat + tomcat.stop(); + // del dir + String userUrl = System.getProperty(USER_DIR); + File file = new File(userUrl + PREFIX + PORT); + if (!file.exists()) { + return; + } + Files.walkFileTree(file.toPath(), new SimpleFileVisitor() { + + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + Files.delete(file); + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { + Files.delete(dir); + return FileVisitResult.CONTINUE; + } + + }); + } /** - * test get url + * test url */ - static String getUrl = "https://hippo4j.cn/"; + String url = "http://localhost:"; + + String passwordValue = "hippo4jtest"; + String usernameValue = "hippo4j"; + String password = "password"; + String username = "username"; + String suffix = "?password=hippo4jtest&username=hippo4j"; @Test public void get() { - String s = HttpUtil.get(getUrl); + String s = HttpUtil.get(url + PORT + HOME_PAGE_URL); Assert.assertNotNull(s); } @Test public void restApiPost() { - String loginUrl = postUrl + "auth/login"; + String loginUrl = url + PORT + LOGIN_URL; LoginInfo loginInfo = new LoginInfo(); - loginInfo.setPassword("hippo4jtest"); - loginInfo.setUsername("hippo4j"); + loginInfo.setPassword(passwordValue); + loginInfo.setUsername(usernameValue); loginInfo.setRememberMe(1); String s = HttpUtil.post(loginUrl, loginInfo); Result result = JSONUtil.parseObject(s, Result.class); @@ -60,10 +135,10 @@ public class HttpUtilsTest { @Test public void testRestApiPost() { - String loginUrl = postUrl + "auth/login"; + String loginUrl = url + PORT + LOGIN_URL; LoginInfo loginInfo = new LoginInfo(); - loginInfo.setPassword("hippo4jtest"); - loginInfo.setUsername("hippo4j"); + loginInfo.setPassword(passwordValue); + loginInfo.setUsername(usernameValue); loginInfo.setRememberMe(1); Result result = HttpUtil.post(loginUrl, loginInfo, Result.class); Assert.assertNotNull(result); @@ -73,10 +148,10 @@ public class HttpUtilsTest { // @Test(expected = SocketTimeoutException.class) public void testRestApiPostTimeout() { - String loginUrl = postUrl + "auth/login"; + String loginUrl = url + PORT + LOGIN_URL; LoginInfo loginInfo = new LoginInfo(); - loginInfo.setPassword("hippo4jtest"); - loginInfo.setUsername("hippo4j"); + loginInfo.setPassword(passwordValue); + loginInfo.setUsername(usernameValue); loginInfo.setRememberMe(1); HttpUtil.post(loginUrl, loginInfo, 1, Result.class); } @@ -84,15 +159,15 @@ public class HttpUtilsTest { @Test public void buildUrl() { Map map = new HashMap<>(); - map.put("password", "hippo4jtest"); - map.put("username", "hippo4j"); - String s = HttpUtil.buildUrl(getUrl, map); - Assert.assertEquals(getUrl + "?password=hippo4jtest&username=hippo4j", s); + map.put(password, passwordValue); + map.put(username, usernameValue); + String s = HttpUtil.buildUrl(url + PORT, map); + Assert.assertEquals(url + PORT + suffix, s); } @Getter @Setter - private static class LoginInfo { + protected static class LoginInfo { private String username; @@ -103,7 +178,7 @@ public class HttpUtilsTest { @Getter @Setter - private static class Result { + protected static class Result { private String code; @@ -112,7 +187,7 @@ public class HttpUtilsTest { @Getter @Setter - private static class ResultData { + protected static class ResultData { private String data; diff --git a/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/http/LoginServlet.java b/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/http/LoginServlet.java new file mode 100644 index 00000000..9c085fd4 --- /dev/null +++ b/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/http/LoginServlet.java @@ -0,0 +1,50 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cn.hippo4j.common.toolkit.http; + +import cn.hippo4j.common.toolkit.JSONUtil; + +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.PrintWriter; + +/** + * his HttpServlet represents the login request + */ +public class LoginServlet extends HttpServlet { + + String passwordAttr = "password"; + String usernameAttr = "username"; + String status = "200"; + + @Override + protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { + String password = (String) req.getAttribute(passwordAttr); + String username = (String) req.getAttribute(usernameAttr); + HttpUtilsTest.ResultData resultData = new HttpUtilsTest.ResultData(); + resultData.setData(username + password); + HttpUtilsTest.Result result = new HttpUtilsTest.Result(); + result.setCode(status); + result.setData(resultData); + String s = JSONUtil.toJSONString(result); + PrintWriter writer = resp.getWriter(); + writer.println(s); + } +} From f5126e3b686df491913e119b0b3f73da1de9c954 Mon Sep 17 00:00:00 2001 From: Xin Chen <37373516+DDreame@users.noreply.github.com> Date: Thu, 11 May 2023 10:58:01 +0800 Subject: [PATCH 3/3] Fix some module CheckStyle Errors (#1240) * fix checkType errors about module hippo4j-spring-boot-starter. * fix checkType errors about module hippo4j-adapter-dubbo. * fix checkType errors about module hippo4j-adapter-alibaba-dubbo. * fix checkType errors about module hippo4j-adapter-hystrix. * fix checkType errors about module hippo4j-spring-boot-starter. --- .../dubbo/AlibabaDubboThreadPoolAdapter.java | 10 ++--- .../adapter/dubbo/DubboThreadPoolAdapter.java | 12 +++--- .../AbstractHystrixThreadPoolAdapter.java | 3 ++ .../cn/hippo4j/common/constant/Constants.java | 18 +++++++- .../core/BaseThreadDetailStateHandler.java | 8 ++-- .../springboot/starter/core/CacheData.java | 15 ++++--- .../starter/core/ClientShutdown.java | 2 +- .../springboot/starter/core/ClientWorker.java | 43 +++++++++++-------- .../starter/core/DiscoveryClient.java | 7 ++- .../DynamicThreadPoolSubscribeConfig.java | 4 +- .../starter/remote/AbstractHealthCheck.java | 12 +++--- .../starter/remote/ServerListManager.java | 10 ++++- .../starter/security/SecurityProxy.java | 4 +- .../DynamicThreadPoolPostProcessor.java | 24 +++++++---- 14 files changed, 111 insertions(+), 61 deletions(-) diff --git a/hippo4j-adapter/hippo4j-adapter-alibaba-dubbo/src/main/java/cn/hippo4j/adapter/alibaba/dubbo/AlibabaDubboThreadPoolAdapter.java b/hippo4j-adapter/hippo4j-adapter-alibaba-dubbo/src/main/java/cn/hippo4j/adapter/alibaba/dubbo/AlibabaDubboThreadPoolAdapter.java index 2eb12e3d..2209089e 100644 --- a/hippo4j-adapter/hippo4j-adapter-alibaba-dubbo/src/main/java/cn/hippo4j/adapter/alibaba/dubbo/AlibabaDubboThreadPoolAdapter.java +++ b/hippo4j-adapter/hippo4j-adapter-alibaba-dubbo/src/main/java/cn/hippo4j/adapter/alibaba/dubbo/AlibabaDubboThreadPoolAdapter.java @@ -42,7 +42,7 @@ import static cn.hippo4j.common.constant.ChangeThreadPoolConstants.CHANGE_DELIMI @Slf4j public class AlibabaDubboThreadPoolAdapter implements ThreadPoolAdapter, ApplicationListener { - private final Map DUBBO_PROTOCOL_EXECUTOR = new HashMap<>(); + private final Map dubboProtocolExecutor = new HashMap<>(); @Override public String mark() { @@ -52,7 +52,7 @@ public class AlibabaDubboThreadPoolAdapter implements ThreadPoolAdapter, Applica @Override public ThreadPoolAdapterState getThreadPoolState(String identify) { ThreadPoolAdapterState threadPoolAdapterState = new ThreadPoolAdapterState(); - ThreadPoolExecutor executor = DUBBO_PROTOCOL_EXECUTOR.get(identify); + ThreadPoolExecutor executor = dubboProtocolExecutor.get(identify); if (executor == null) { log.warn("[{}] Alibaba Dubbo consuming thread pool not found.", identify); return threadPoolAdapterState; @@ -66,14 +66,14 @@ public class AlibabaDubboThreadPoolAdapter implements ThreadPoolAdapter, Applica @Override public List getThreadPoolStates() { List threadPoolAdapterStates = new ArrayList<>(); - DUBBO_PROTOCOL_EXECUTOR.forEach((key, val) -> threadPoolAdapterStates.add(getThreadPoolState(String.valueOf(key)))); + dubboProtocolExecutor.forEach((key, val) -> threadPoolAdapterStates.add(getThreadPoolState(String.valueOf(key)))); return threadPoolAdapterStates; } @Override public boolean updateThreadPool(ThreadPoolAdapterParameter threadPoolAdapterParameter) { String threadPoolKey = threadPoolAdapterParameter.getThreadPoolKey(); - ThreadPoolExecutor executor = DUBBO_PROTOCOL_EXECUTOR.get(threadPoolAdapterParameter.getThreadPoolKey()); + ThreadPoolExecutor executor = dubboProtocolExecutor.get(threadPoolAdapterParameter.getThreadPoolKey()); if (executor == null) { log.warn("[{}] Alibaba Dubbo consuming thread pool not found.", threadPoolKey); return false; @@ -94,7 +94,7 @@ public class AlibabaDubboThreadPoolAdapter implements ThreadPoolAdapter, Applica try { DataStore dataStore = ExtensionLoader.getExtensionLoader(DataStore.class).getDefaultExtension(); Map executors = dataStore.get(poolKey); - executors.forEach((key, value) -> DUBBO_PROTOCOL_EXECUTOR.put(key, (ThreadPoolExecutor) value)); + executors.forEach((key, value) -> dubboProtocolExecutor.put(key, (ThreadPoolExecutor) value)); } catch (Exception ex) { log.error("Failed to get Alibaba Dubbo protocol thread pool", ex); } diff --git a/hippo4j-adapter/hippo4j-adapter-dubbo/src/main/java/cn/hippo4j/adapter/dubbo/DubboThreadPoolAdapter.java b/hippo4j-adapter/hippo4j-adapter-dubbo/src/main/java/cn/hippo4j/adapter/dubbo/DubboThreadPoolAdapter.java index a3257f19..ffc61831 100644 --- a/hippo4j-adapter/hippo4j-adapter-dubbo/src/main/java/cn/hippo4j/adapter/dubbo/DubboThreadPoolAdapter.java +++ b/hippo4j-adapter/hippo4j-adapter-dubbo/src/main/java/cn/hippo4j/adapter/dubbo/DubboThreadPoolAdapter.java @@ -46,7 +46,7 @@ import static cn.hippo4j.common.constant.ChangeThreadPoolConstants.CHANGE_DELIMI @Slf4j public class DubboThreadPoolAdapter implements ThreadPoolAdapter, ApplicationListener { - private final Map DUBBO_PROTOCOL_EXECUTOR = new HashMap<>(); + private final Map dubboProtocolExecutor = new HashMap<>(); @Override public String mark() { @@ -56,7 +56,7 @@ public class DubboThreadPoolAdapter implements ThreadPoolAdapter, ApplicationLis @Override public ThreadPoolAdapterState getThreadPoolState(String identify) { ThreadPoolAdapterState threadPoolAdapterState = new ThreadPoolAdapterState(); - ThreadPoolExecutor executor = DUBBO_PROTOCOL_EXECUTOR.get(identify); + ThreadPoolExecutor executor = dubboProtocolExecutor.get(identify); if (executor == null) { log.warn("[{}] Dubbo consuming thread pool not found.", identify); return threadPoolAdapterState; @@ -70,14 +70,14 @@ public class DubboThreadPoolAdapter implements ThreadPoolAdapter, ApplicationLis @Override public List getThreadPoolStates() { List threadPoolAdapterStates = new ArrayList<>(); - DUBBO_PROTOCOL_EXECUTOR.forEach((key, val) -> threadPoolAdapterStates.add(getThreadPoolState(String.valueOf(key)))); + dubboProtocolExecutor.forEach((key, val) -> threadPoolAdapterStates.add(getThreadPoolState(String.valueOf(key)))); return threadPoolAdapterStates; } @Override public boolean updateThreadPool(ThreadPoolAdapterParameter threadPoolAdapterParameter) { String threadPoolKey = threadPoolAdapterParameter.getThreadPoolKey(); - ThreadPoolExecutor executor = DUBBO_PROTOCOL_EXECUTOR.get(threadPoolAdapterParameter.getThreadPoolKey()); + ThreadPoolExecutor executor = dubboProtocolExecutor.get(threadPoolAdapterParameter.getThreadPoolKey()); if (executor == null) { log.warn("[{}] Dubbo consuming thread pool not found.", threadPoolKey); return false; @@ -105,14 +105,14 @@ public class DubboThreadPoolAdapter implements ThreadPoolAdapter, ApplicationLis if (isLegacyVersion) { DataStore dataStore = ExtensionLoader.getExtensionLoader(DataStore.class).getDefaultExtension(); Map executors = dataStore.get(poolKey); - executors.forEach((key, value) -> DUBBO_PROTOCOL_EXECUTOR.put(key, (ThreadPoolExecutor) value)); + executors.forEach((key, value) -> dubboProtocolExecutor.put(key, (ThreadPoolExecutor) value)); return; } ExecutorRepository executorRepository = ExtensionLoader.getExtensionLoader(ExecutorRepository.class).getDefaultExtension(); ConcurrentMap> data = (ConcurrentMap>) ReflectUtil.getFieldValue(executorRepository, "data"); ConcurrentMap executorServiceMap = data.get(poolKey); - executorServiceMap.forEach((key, value) -> DUBBO_PROTOCOL_EXECUTOR.put(String.valueOf(key), (ThreadPoolExecutor) value)); + executorServiceMap.forEach((key, value) -> dubboProtocolExecutor.put(String.valueOf(key), (ThreadPoolExecutor) value)); } catch (Exception ex) { log.error("Failed to get Dubbo {} protocol thread pool", Version.getVersion(), ex); } diff --git a/hippo4j-adapter/hippo4j-adapter-hystrix/src/main/java/cn/hippo4j/adapter/hystrix/AbstractHystrixThreadPoolAdapter.java b/hippo4j-adapter/hippo4j-adapter-hystrix/src/main/java/cn/hippo4j/adapter/hystrix/AbstractHystrixThreadPoolAdapter.java index 441a1efb..36771408 100644 --- a/hippo4j-adapter/hippo4j-adapter-hystrix/src/main/java/cn/hippo4j/adapter/hystrix/AbstractHystrixThreadPoolAdapter.java +++ b/hippo4j-adapter/hippo4j-adapter-hystrix/src/main/java/cn/hippo4j/adapter/hystrix/AbstractHystrixThreadPoolAdapter.java @@ -113,6 +113,9 @@ public abstract class AbstractHystrixThreadPoolAdapter implements ThreadPoolAdap scheduler.schedule(hystrixThreadPoolRefreshTask, taskIntervalSeconds, TimeUnit.SECONDS); } + /** + * hystrix thread-pool refresh task + */ class HystrixThreadPoolRefreshTask implements Runnable { private final ScheduledExecutorService scheduler; diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/constant/Constants.java b/hippo4j-common/src/main/java/cn/hippo4j/common/constant/Constants.java index 2b651ffc..80e7951d 100644 --- a/hippo4j-common/src/main/java/cn/hippo4j/common/constant/Constants.java +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/constant/Constants.java @@ -102,6 +102,22 @@ public class Constants { public static final int HEALTH_CHECK_INTERVAL = 5; + public static final int MAX_CHECK_FAILURE_COUNT = 4; + + public static final int INITIAL_CAPACITY = 3; + + public static final int DATA_GROUP_TENANT_SIZE = 3; + + public static final int ACTIVE_ALARM = 80; + + public static final int CAPACITY_ALARM = 80; + + public static final long EXECUTE_TIME_OUT = 10000L; + + public static final int SECONDS_IN_MILLISECONDS = 1000; + + public static final long FAILURE_SLEEP_INTERVAL = 25000L; + public static final int AVAILABLE_PROCESSORS = Runtime.getRuntime().availableProcessors(); public static final String DEFAULT_GROUP = "default group"; @@ -110,7 +126,7 @@ public class Constants { public static final String EXECUTE_TIMEOUT_TRACE = "executeTimeoutTrace"; - public static final int HTTP_EXECUTE_TIMEOUT = 5000; + public static final long HTTP_EXECUTE_TIMEOUT = 5000L; public static final String CLIENT_VERSION = "Client-Version"; diff --git a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/core/BaseThreadDetailStateHandler.java b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/core/BaseThreadDetailStateHandler.java index 2e3f1051..72772f8b 100644 --- a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/core/BaseThreadDetailStateHandler.java +++ b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/core/BaseThreadDetailStateHandler.java @@ -38,9 +38,9 @@ import java.util.concurrent.ThreadPoolExecutor; @Slf4j public class BaseThreadDetailStateHandler implements ThreadDetailState { - private final String WORKERS = "workers"; + private final String workersName = "workers"; - private final String THREAD = "thread"; + private final String threadName = "thread"; @Override public List getThreadDetailStateInfo(String threadPoolId) { @@ -53,14 +53,14 @@ public class BaseThreadDetailStateHandler implements ThreadDetailState { public List getThreadDetailStateInfo(ThreadPoolExecutor threadPoolExecutor) { List resultThreadStates = new ArrayList(); try { - HashSet workers = (HashSet) ReflectUtil.getFieldValue(threadPoolExecutor, WORKERS); + HashSet workers = (HashSet) ReflectUtil.getFieldValue(threadPoolExecutor, workersName); if (CollectionUtil.isEmpty(workers)) { return resultThreadStates; } for (Object worker : workers) { Thread thread; try { - thread = (Thread) ReflectUtil.getFieldValue(worker, THREAD); + thread = (Thread) ReflectUtil.getFieldValue(worker, threadName); if (thread == null) { log.warn("Reflection get worker thread is null. Worker: {}", worker); continue; diff --git a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/core/CacheData.java b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/core/CacheData.java index acd88ef2..19813c49 100644 --- a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/core/CacheData.java +++ b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/core/CacheData.java @@ -35,15 +35,18 @@ import java.util.concurrent.CopyOnWriteArrayList; public class CacheData { @Getter - public volatile String md5; + private volatile String md5; - public volatile String content; + private volatile String content; - public final String tenantId; + @Getter + private final String tenantId; - public final String itemId; + @Getter + private final String itemId; - public final String threadPoolId; + @Getter + private final String threadPoolId; @Setter private volatile boolean isInitializing = true; @@ -56,7 +59,7 @@ public class CacheData { this.threadPoolId = threadPoolId; this.content = ContentUtil.getPoolContent(GlobalThreadPoolManage.getPoolParameter(threadPoolId)); this.md5 = getMd5String(content); - this.listeners = new CopyOnWriteArrayList(); + this.listeners = new CopyOnWriteArrayList<>(); } public void addListener(Listener listener) { diff --git a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/core/ClientShutdown.java b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/core/ClientShutdown.java index bd12c789..1434d4b2 100644 --- a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/core/ClientShutdown.java +++ b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/core/ClientShutdown.java @@ -33,7 +33,7 @@ public class ClientShutdown { @Getter private volatile boolean prepareClose = false; - private final static Long TIME_OUT_SECOND = 1L; + private static final Long TIME_OUT_SECOND = 1L; private static final int DEFAULT_COUNT = 1; private final CountDownLatch countDownLatch = new CountDownLatch(DEFAULT_COUNT); diff --git a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/core/ClientWorker.java b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/core/ClientWorker.java index 1e5af1a7..8656c5ce 100644 --- a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/core/ClientWorker.java +++ b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/core/ClientWorker.java @@ -30,7 +30,6 @@ import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.DisposableBean; import org.springframework.util.StringUtils; - import java.net.URLDecoder; import java.util.ArrayList; import java.util.Collections; @@ -43,20 +42,21 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; - -import static cn.hippo4j.common.constant.Constants.CLIENT_VERSION; -import static cn.hippo4j.common.constant.Constants.CONFIG_CONTROLLER_PATH; import static cn.hippo4j.common.constant.Constants.CONFIG_LONG_POLL_TIMEOUT; import static cn.hippo4j.common.constant.Constants.GROUP_KEY_DELIMITER_TRANSLATION; +import static cn.hippo4j.common.constant.Constants.WORD_SEPARATOR; import static cn.hippo4j.common.constant.Constants.LINE_SEPARATOR; -import static cn.hippo4j.common.constant.Constants.LISTENER_PATH; -import static cn.hippo4j.common.constant.Constants.LONG_PULLING_CLIENT_IDENTIFICATION; +import static cn.hippo4j.common.constant.Constants.PROBE_MODIFY_REQUEST; +import static cn.hippo4j.common.constant.Constants.WEIGHT_CONFIGS; import static cn.hippo4j.common.constant.Constants.LONG_PULLING_TIMEOUT; +import static cn.hippo4j.common.constant.Constants.LONG_PULLING_CLIENT_IDENTIFICATION; import static cn.hippo4j.common.constant.Constants.LONG_PULLING_TIMEOUT_NO_HANGUP; +import static cn.hippo4j.common.constant.Constants.CLIENT_VERSION; +import static cn.hippo4j.common.constant.Constants.LISTENER_PATH; +import static cn.hippo4j.common.constant.Constants.INITIAL_CAPACITY; +import static cn.hippo4j.common.constant.Constants.DATA_GROUP_TENANT_SIZE; +import static cn.hippo4j.common.constant.Constants.CONFIG_CONTROLLER_PATH; import static cn.hippo4j.common.constant.Constants.NULL; -import static cn.hippo4j.common.constant.Constants.PROBE_MODIFY_REQUEST; -import static cn.hippo4j.common.constant.Constants.WEIGHT_CONFIGS; -import static cn.hippo4j.common.constant.Constants.WORD_SEPARATOR; /** * Client worker. @@ -77,6 +77,8 @@ public class ClientWorker implements DisposableBean { private final CountDownLatch cacheCondition = new CountDownLatch(1); private final ConcurrentHashMap cacheMap = new ConcurrentHashMap<>(16); + private final long defaultTimedOut = 3000L; + @SuppressWarnings("all") public ClientWorker(HttpAgent httpAgent, String identify, @@ -113,13 +115,16 @@ public class ClientWorker implements DisposableBean { executorService.shutdownNow(); } + /** + * LongPollingRunnable + */ class LongPollingRunnable implements Runnable { private boolean cacheMapInitEmptyFlag; private final CountDownLatch cacheCondition; - public LongPollingRunnable(boolean cacheMapInitEmptyFlag, CountDownLatch cacheCondition) { + LongPollingRunnable(boolean cacheMapInitEmptyFlag, CountDownLatch cacheCondition) { this.cacheMapInitEmptyFlag = cacheMapInitEmptyFlag; this.cacheCondition = cacheCondition; } @@ -147,7 +152,7 @@ public class ClientWorker implements DisposableBean { String itemId = keys[1]; String namespace = keys[2]; try { - String content = getServerConfig(namespace, itemId, tpId, 3000L); + String content = getServerConfig(namespace, itemId, tpId, defaultTimedOut); CacheData cacheData = cacheMap.get(tpId); String poolContent = ContentUtil.getPoolContent(JSONUtil.parseObject(content, ThreadPoolParameterInfo.class)); cacheData.setContent(poolContent); @@ -157,7 +162,7 @@ public class ClientWorker implements DisposableBean { } for (CacheData cacheData : cacheDataList) { if (!cacheData.isInitializing() || inInitializingCacheList - .contains(GroupKey.getKeyTenant(cacheData.threadPoolId, cacheData.itemId, cacheData.tenantId))) { + .contains(GroupKey.getKeyTenant(cacheData.getThreadPoolId(), cacheData.getItemId(), cacheData.getTenantId()))) { cacheData.checkListenerMd5(); cacheData.setInitializing(false); } @@ -170,13 +175,13 @@ public class ClientWorker implements DisposableBean { private List checkUpdateDataIds(List cacheDataList, List inInitializingCacheList) { StringBuilder sb = new StringBuilder(); for (CacheData cacheData : cacheDataList) { - sb.append(cacheData.threadPoolId).append(WORD_SEPARATOR); - sb.append(cacheData.itemId).append(WORD_SEPARATOR); - sb.append(cacheData.tenantId).append(WORD_SEPARATOR); + sb.append(cacheData.getThreadPoolId()).append(WORD_SEPARATOR); + sb.append(cacheData.getItemId()).append(WORD_SEPARATOR); + sb.append(cacheData.getTenantId()).append(WORD_SEPARATOR); sb.append(identify).append(WORD_SEPARATOR); sb.append(cacheData.getMd5()).append(LINE_SEPARATOR); if (cacheData.isInitializing()) { - inInitializingCacheList.add(GroupKey.getKeyTenant(cacheData.threadPoolId, cacheData.itemId, cacheData.tenantId)); + inInitializingCacheList.add(GroupKey.getKeyTenant(cacheData.getThreadPoolId(), cacheData.getItemId(), cacheData.getTenantId())); } } boolean isInitializingCacheList = !inInitializingCacheList.isEmpty(); @@ -213,7 +218,7 @@ public class ClientWorker implements DisposableBean { } public String getServerConfig(String namespace, String itemId, String threadPoolId, long readTimeout) { - Map params = new HashMap<>(3); + Map params = new HashMap<>(INITIAL_CAPACITY); params.put("namespace", namespace); params.put("itemId", itemId); params.put("tpId", threadPoolId); @@ -241,7 +246,7 @@ public class ClientWorker implements DisposableBean { String[] keyArr = dataIdAndGroup.split(WORD_SEPARATOR); String dataId = keyArr[0]; String group = keyArr[1]; - if (keyArr.length == 3) { + if (keyArr.length == DATA_GROUP_TENANT_SIZE) { String tenant = keyArr[2]; updateList.add(GroupKey.getKeyTenant(dataId, group, tenant)); log.info("[{}] Refresh thread pool changed.", dataId); @@ -274,7 +279,7 @@ public class ClientWorker implements DisposableBean { if (lastCacheData == null) { String serverConfig; try { - serverConfig = getServerConfig(namespace, itemId, threadPoolId, 3000L); + serverConfig = getServerConfig(namespace, itemId, threadPoolId, defaultTimedOut); ThreadPoolParameterInfo poolInfo = JSONUtil.parseObject(serverConfig, ThreadPoolParameterInfo.class); cacheData.setContent(ContentUtil.getPoolContent(poolInfo)); } catch (Exception ex) { diff --git a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/core/DiscoveryClient.java b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/core/DiscoveryClient.java index 38a22368..ce01cbcd 100644 --- a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/core/DiscoveryClient.java +++ b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/core/DiscoveryClient.java @@ -51,6 +51,8 @@ public class DiscoveryClient implements DisposableBean { private static final String PREFIX = "DiscoveryClient_"; private final String appPathIdentifier; + private final int delayTime = 30; + public DiscoveryClient(HttpAgent httpAgent, InstanceInfo instanceInfo, ClientShutdown hippo4jClientShutdown) { this.httpAgent = httpAgent; this.instanceInfo = instanceInfo; @@ -65,7 +67,7 @@ public class DiscoveryClient implements DisposableBean { } private void initScheduledTasks() { - scheduler.scheduleWithFixedDelay(new HeartbeatThread(), 30, 30, TimeUnit.SECONDS); + scheduler.scheduleWithFixedDelay(new HeartbeatThread(), delayTime, delayTime, TimeUnit.SECONDS); } boolean register() { @@ -118,6 +120,9 @@ public class DiscoveryClient implements DisposableBean { hippo4jClientShutdown.prepareDestroy(); } + /** + * HeartbeatThread + */ public class HeartbeatThread implements Runnable { @Override diff --git a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/core/DynamicThreadPoolSubscribeConfig.java b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/core/DynamicThreadPoolSubscribeConfig.java index 804c0864..db646ff8 100644 --- a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/core/DynamicThreadPoolSubscribeConfig.java +++ b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/core/DynamicThreadPoolSubscribeConfig.java @@ -41,10 +41,12 @@ public class DynamicThreadPoolSubscribeConfig { private final BootstrapProperties properties; + private final int defaultAliveTime = 2000; + private final ExecutorService configRefreshExecutorService = ThreadPoolBuilder.builder() .corePoolSize(1) .maximumPoolSize(2) - .keepAliveTime(2000) + .keepAliveTime(defaultAliveTime) .timeUnit(TimeUnit.MILLISECONDS) .workQueue(BlockingQueueTypeEnum.SYNCHRONOUS_QUEUE) .allowCoreThreadTimeOut(true) diff --git a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/remote/AbstractHealthCheck.java b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/remote/AbstractHealthCheck.java index 1fd78118..246f80ad 100644 --- a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/remote/AbstractHealthCheck.java +++ b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/remote/AbstractHealthCheck.java @@ -31,8 +31,10 @@ import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; - +import static cn.hippo4j.common.constant.Constants.MAX_CHECK_FAILURE_COUNT; +import static cn.hippo4j.common.constant.Constants.SECONDS_IN_MILLISECONDS; import static cn.hippo4j.common.constant.Constants.HEALTH_CHECK_INTERVAL; +import static cn.hippo4j.common.constant.Constants.FAILURE_SLEEP_INTERVAL; /** * Abstract health check. @@ -99,10 +101,10 @@ public abstract class AbstractHealthCheck implements ServerHealthCheck, Initiali } else { healthStatus = false; checkFailureCount++; - if (checkFailureCount > 1 && checkFailureCount < 4) { - ThreadUtil.sleep(HEALTH_CHECK_INTERVAL * 1000 * (checkFailureCount - 1)); - } else if (checkFailureCount >= 4) { - ThreadUtil.sleep(25000L); + if (checkFailureCount > 1 && checkFailureCount < MAX_CHECK_FAILURE_COUNT) { + ThreadUtil.sleep((long) HEALTH_CHECK_INTERVAL * SECONDS_IN_MILLISECONDS * (checkFailureCount - 1)); + } else if (checkFailureCount >= MAX_CHECK_FAILURE_COUNT) { + ThreadUtil.sleep(FAILURE_SLEEP_INTERVAL); } } } diff --git a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/remote/ServerListManager.java b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/remote/ServerListManager.java index cc5abd36..3202869c 100644 --- a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/remote/ServerListManager.java +++ b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/remote/ServerListManager.java @@ -88,13 +88,16 @@ public class ServerListManager { return new ServerAddressIterator(serverUrls); } + /** + * Server Address Iterator + */ private static class ServerAddressIterator implements Iterator { final List sorted; final Iterator iter; - public ServerAddressIterator(List source) { + ServerAddressIterator(List source) { sorted = new ArrayList(); for (String address : source) { sorted.add(new RandomizedServerAddress(address)); @@ -113,6 +116,9 @@ public class ServerListManager { return null; } + /** + * Randomized Server Address + */ static class RandomizedServerAddress implements Comparable { static Random random = new Random(); @@ -123,7 +129,7 @@ public class ServerListManager { int seed; - public RandomizedServerAddress(String ip) { + RandomizedServerAddress(String ip) { try { this.serverIp = ip; /* diff --git a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/security/SecurityProxy.java b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/security/SecurityProxy.java index 72c5bd07..c03d518a 100644 --- a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/security/SecurityProxy.java +++ b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/security/SecurityProxy.java @@ -39,6 +39,8 @@ public class SecurityProxy { private static final String APPLY_TOKEN_URL = Constants.BASE_PATH + "/auth/users/apply/token"; + private final int refreshWindowDuration = 10; + private final String username; private final String password; @@ -88,7 +90,7 @@ public class SecurityProxy { TokenInfo tokenInfo = JSONUtil.parseObject(tokenJsonStr, TokenInfo.class); accessToken = tokenInfo.getAccessToken(); tokenTtl = tokenInfo.getTokenTtl(); - tokenRefreshWindow = tokenTtl / 10; + tokenRefreshWindow = tokenTtl / refreshWindowDuration; } catch (Throwable ex) { log.error("Failed to apply for token. message: {}", ex.getMessage()); return false; diff --git a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/support/DynamicThreadPoolPostProcessor.java b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/support/DynamicThreadPoolPostProcessor.java index 3d94628c..c3bd82e1 100644 --- a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/support/DynamicThreadPoolPostProcessor.java +++ b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/support/DynamicThreadPoolPostProcessor.java @@ -53,10 +53,14 @@ import java.util.Optional; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; - +import static cn.hippo4j.common.constant.Constants.INITIAL_CAPACITY; +import static cn.hippo4j.common.constant.Constants.TP_ID; import static cn.hippo4j.common.constant.Constants.ITEM_ID; import static cn.hippo4j.common.constant.Constants.NAMESPACE; -import static cn.hippo4j.common.constant.Constants.TP_ID; +import static cn.hippo4j.common.constant.Constants.ACTIVE_ALARM; +import static cn.hippo4j.common.constant.Constants.CAPACITY_ALARM; +import static cn.hippo4j.common.constant.Constants.EXECUTE_TIME_OUT; +import static cn.hippo4j.common.constant.Constants.HTTP_EXECUTE_TIMEOUT; /** * Dynamic thread-pool post processor. @@ -94,7 +98,8 @@ public final class DynamicThreadPoolPostProcessor implements BeanPostProcessor { return bean; } DynamicThreadPoolExecutor dynamicThreadPoolExecutor; - if ((dynamicThreadPoolExecutor = DynamicThreadPoolAdapterChoose.unwrap(bean)) == null) { + dynamicThreadPoolExecutor = DynamicThreadPoolAdapterChoose.unwrap(bean); + if ((dynamicThreadPoolExecutor) == null) { dynamicThreadPoolExecutor = (DynamicThreadPoolExecutor) bean; } DynamicThreadPoolWrapper dynamicThreadPoolWrapper = new DynamicThreadPoolWrapper(dynamicThreadPoolExecutor.getThreadPoolId(), dynamicThreadPoolExecutor); @@ -128,16 +133,17 @@ public final class DynamicThreadPoolPostProcessor implements BeanPostProcessor { protected ThreadPoolExecutor fillPoolAndRegister(DynamicThreadPoolWrapper dynamicThreadPoolWrapper) { String threadPoolId = dynamicThreadPoolWrapper.getThreadPoolId(); ThreadPoolExecutor executor = dynamicThreadPoolWrapper.getExecutor(); - Map queryStrMap = new HashMap(3); + Map queryStrMap = new HashMap<>(INITIAL_CAPACITY); queryStrMap.put(TP_ID, threadPoolId); queryStrMap.put(ITEM_ID, properties.getItemId()); queryStrMap.put(NAMESPACE, properties.getNamespace()); ThreadPoolParameterInfo threadPoolParameterInfo = new ThreadPoolParameterInfo(); try { - Result result = httpAgent.httpGetByConfig(Constants.CONFIG_CONTROLLER_PATH, null, queryStrMap, 5000L); + Result result = httpAgent.httpGetByConfig(Constants.CONFIG_CONTROLLER_PATH, null, queryStrMap, HTTP_EXECUTE_TIMEOUT); if (result.isSuccess() && result.getData() != null) { String resultJsonStr = JSONUtil.toJSONString(result.getData()); - if ((threadPoolParameterInfo = JSONUtil.parseObject(resultJsonStr, ThreadPoolParameterInfo.class)) != null) { + threadPoolParameterInfo = JSONUtil.parseObject(resultJsonStr, ThreadPoolParameterInfo.class); + if (threadPoolParameterInfo != null) { threadPoolParamReplace(executor, threadPoolParameterInfo); registerNotifyAlarm(threadPoolParameterInfo); } @@ -153,9 +159,9 @@ public final class DynamicThreadPoolPostProcessor implements BeanPostProcessor { .allowCoreThreadTimeOut(executor.allowsCoreThreadTimeOut()) .keepAliveTime(executor.getKeepAliveTime(TimeUnit.MILLISECONDS)) .isAlarm(false) - .activeAlarm(80) - .capacityAlarm(80) - .executeTimeOut(10000L) + .activeAlarm(ACTIVE_ALARM) + .capacityAlarm(CAPACITY_ALARM) + .executeTimeOut(EXECUTE_TIME_OUT) .rejectedPolicyType(RejectedPolicyTypeEnum.getRejectedPolicyTypeEnumByName(executor.getRejectedExecutionHandler().getClass().getSimpleName())) .build(); DynamicThreadPoolRegisterWrapper registerWrapper = DynamicThreadPoolRegisterWrapper.builder()