diff --git a/polaris-agent-examples/spring-cloud-plugins-examples/spring-cloud-2023-examples/quickstart-examples/consumer/pom.xml b/polaris-agent-examples/spring-cloud-plugins-examples/spring-cloud-2023-examples/quickstart-examples/consumer/pom.xml index b721aefc..aa01d756 100644 --- a/polaris-agent-examples/spring-cloud-plugins-examples/spring-cloud-2023-examples/quickstart-examples/consumer/pom.xml +++ b/polaris-agent-examples/spring-cloud-plugins-examples/spring-cloud-2023-examples/quickstart-examples/consumer/pom.xml @@ -38,6 +38,10 @@ + + org.springframework.cloud + spring-cloud-starter-bootstrap + org.springframework.boot spring-boot-starter-web diff --git a/polaris-agent-examples/spring-cloud-plugins-examples/spring-cloud-2023-examples/quickstart-examples/consumer/src/main/java/cn/polarismesh/agent/examples/alibaba/cloud/cloud/ConsumerApplication.java b/polaris-agent-examples/spring-cloud-plugins-examples/spring-cloud-2023-examples/quickstart-examples/consumer/src/main/java/cn/polarismesh/agent/examples/alibaba/cloud/cloud/ConsumerApplication.java index 50057e02..9621da17 100644 --- a/polaris-agent-examples/spring-cloud-plugins-examples/spring-cloud-2023-examples/quickstart-examples/consumer/src/main/java/cn/polarismesh/agent/examples/alibaba/cloud/cloud/ConsumerApplication.java +++ b/polaris-agent-examples/spring-cloud-plugins-examples/spring-cloud-2023-examples/quickstart-examples/consumer/src/main/java/cn/polarismesh/agent/examples/alibaba/cloud/cloud/ConsumerApplication.java @@ -66,13 +66,20 @@ public EchoController(RestTemplate restTemplate, Registration registration) { this.registration = registration; } +// @GetMapping("/echo/{str}") +// public ResponseEntity rest(@PathVariable String str) { +// String content = String.format("%s[%d] -> ", registration.getServiceId(), port); +// ResponseEntity response = template.getForEntity("http://service-provider-2023/echo/" + str +"123", +// String.class); +// content += response.getBody(); +// return new ResponseEntity<>(content, HttpStatus.OK); +// } + @GetMapping("/echo/{str}") public ResponseEntity rest(@PathVariable String str) { - String content = String.format("%s[%d] -> ", registration.getServiceId(), port); - ResponseEntity response = template.getForEntity("http://service-provider-2023/echo/" + str +"123", + ResponseEntity response = template.getForEntity("http://service-provider-2023/echo/" + str, String.class); - content += response.getBody(); - return new ResponseEntity<>(content, HttpStatus.OK); + return response; } @GetMapping("/custom/config") diff --git a/polaris-agent-examples/spring-cloud-plugins-examples/spring-cloud-2023-examples/quickstart-examples/consumer/src/main/resources/application.yaml b/polaris-agent-examples/spring-cloud-plugins-examples/spring-cloud-2023-examples/quickstart-examples/consumer/src/main/resources/bootstrap.yaml similarity index 73% rename from polaris-agent-examples/spring-cloud-plugins-examples/spring-cloud-2023-examples/quickstart-examples/consumer/src/main/resources/application.yaml rename to polaris-agent-examples/spring-cloud-plugins-examples/spring-cloud-2023-examples/quickstart-examples/consumer/src/main/resources/bootstrap.yaml index f9e0d222..ea29f285 100644 --- a/polaris-agent-examples/spring-cloud-plugins-examples/spring-cloud-2023-examples/quickstart-examples/consumer/src/main/resources/application.yaml +++ b/polaris-agent-examples/spring-cloud-plugins-examples/spring-cloud-2023-examples/quickstart-examples/consumer/src/main/resources/bootstrap.yaml @@ -10,13 +10,15 @@ spring: enabled: false server-addr: 127.0.0.1:8848 config: - enabled: true + enabled: false serverAddr: 127.0.0.1:8848 username: 'nacos' password: 'nacos' - config: - import: - - nacos:service-consumer-2023.properties?refreshEnabled=true + main: + allow-bean-definition-overriding: true +# config: +# import: +# - nacos:service-consumer-2023.properties?refreshEnabled=true management: endpoint: health: diff --git a/polaris-agent-examples/spring-cloud-plugins-examples/spring-cloud-2023-examples/quickstart-examples/consumer/src/main/resources/polaris.yml b/polaris-agent-examples/spring-cloud-plugins-examples/spring-cloud-2023-examples/quickstart-examples/consumer/src/main/resources/polaris.yml new file mode 100644 index 00000000..58dd214d --- /dev/null +++ b/polaris-agent-examples/spring-cloud-plugins-examples/spring-cloud-2023-examples/quickstart-examples/consumer/src/main/resources/polaris.yml @@ -0,0 +1,8 @@ +consumer: + serviceRouter: + plugin: + # 设置就近路由插件配置 + nearbyBasedRouter: + # 描述:就近路由的最小匹配级别,需要显示设置 + # 范围: zone(腾讯云地域信息,eg: ap-guangzhou)、campus(腾讯云可用区, eg: ap-guangzhou-3) + matchLevel: campus diff --git a/polaris-agent-examples/spring-cloud-plugins-examples/spring-cloud-2023-examples/quickstart-examples/provider/pom.xml b/polaris-agent-examples/spring-cloud-plugins-examples/spring-cloud-2023-examples/quickstart-examples/provider/pom.xml index d4fe43bd..eaeeb519 100644 --- a/polaris-agent-examples/spring-cloud-plugins-examples/spring-cloud-2023-examples/quickstart-examples/provider/pom.xml +++ b/polaris-agent-examples/spring-cloud-plugins-examples/spring-cloud-2023-examples/quickstart-examples/provider/pom.xml @@ -38,6 +38,10 @@ + + org.springframework.cloud + spring-cloud-starter-bootstrap + org.springframework.boot spring-boot-starter-web diff --git a/polaris-agent-examples/spring-cloud-plugins-examples/spring-cloud-2023-examples/quickstart-examples/provider/src/main/resources/application.yaml b/polaris-agent-examples/spring-cloud-plugins-examples/spring-cloud-2023-examples/quickstart-examples/provider/src/main/resources/bootstrap.yaml similarity index 81% rename from polaris-agent-examples/spring-cloud-plugins-examples/spring-cloud-2023-examples/quickstart-examples/provider/src/main/resources/application.yaml rename to polaris-agent-examples/spring-cloud-plugins-examples/spring-cloud-2023-examples/quickstart-examples/provider/src/main/resources/bootstrap.yaml index 88ba3011..649a698f 100644 --- a/polaris-agent-examples/spring-cloud-plugins-examples/spring-cloud-2023-examples/quickstart-examples/provider/src/main/resources/application.yaml +++ b/polaris-agent-examples/spring-cloud-plugins-examples/spring-cloud-2023-examples/quickstart-examples/provider/src/main/resources/bootstrap.yaml @@ -12,13 +12,13 @@ spring: enabled: false server-addr: 127.0.0.1:8848 config: - enabled: true + enabled: false serverAddr: 127.0.0.1:8848 username: 'nacos' password: 'nacos' - config: - import: - - nacos:service-provider-2023.properties?refreshEnabled=true +# config: +# import: +# - nacos:service-provider-2023.properties?refreshEnabled=true management: endpoint: health: diff --git a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/pom.xml b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/pom.xml index 2dfb5c5c..2ca445b6 100644 --- a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/pom.xml +++ b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> spring-cloud-plugins com.tencent.polaris @@ -34,13 +34,6 @@ pom import - - jakarta.servlet - jakarta.servlet-api - 6.0.0 - provided - - org.springframework.cloud spring-cloud-starter-bootstrap @@ -63,6 +56,16 @@ + + + + + + + com.tencent.polaris + spring-cloud-plugin-common + ${project.version} + org.springframework.cloud spring-cloud-starter-openfeign @@ -84,12 +87,6 @@ provided - - org.apache.commons - commons-lang3 - 3.10 - - org.springframework.cloud @@ -125,10 +122,10 @@ polaris-all + com.google.guava guava - 32.0.1-jre @@ -158,10 +155,10 @@ polaris-plugin-api - - com.tencent.polaris - connector-polaris-grpc - + + + + com.tencent.polaris @@ -257,6 +254,11 @@ + + com.tencent.cloud + spring-cloud-starter-tencent-polaris-contract + + com.tencent.cloud spring-cloud-starter-tencent-polaris-router @@ -367,6 +369,56 @@ + + com.tencent.cloud + spring-cloud-starter-tencent-polaris-circuitbreaker + ${spring.cloud.tencent.version} + + + com.tencent.cloud + spring-cloud-tencent-rpc-enhancement + + + com.tencent.polaris + polaris-circuitbreaker-factory + + + com.tencent.polaris + healthchecker-http + + + com.tencent.polaris + healthchecker-udp + + + com.tencent.polaris + healthchecker-tcp + + + + + + com.tencent.cloud + spring-cloud-starter-tencent-polaris-ratelimit + ${spring.cloud.tencent.version} + + + com.tencent.cloud + spring-cloud-tencent-rpc-enhancement + + + com.tencent.polaris + polaris-ratelimit-factory + + + + + com.tencent.polaris + spring-cloud-plugin-2023-common + 1.7.0-RC2 + compile + + diff --git a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/conf/plugin/spring-cloud-2023/application.properties b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/conf/plugin/spring-cloud-2023/application.properties index 2aa0c330..21b9c358 100644 --- a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/conf/plugin/spring-cloud-2023/application.properties +++ b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/conf/plugin/spring-cloud-2023/application.properties @@ -1,5 +1,5 @@ # the application name for spring cloud, register as the service name in registry center -spring.application.name=application-name +spring.application.name=service-provider-2023 # polaris server address spring.cloud.polaris.address=grpc\://127.0.0.1\:8091 # switch for spring cloud polaris all features @@ -26,6 +26,8 @@ spring.cloud.polaris.router.nearby-router.enabled=true spring.cloud.polaris.ratelimit.enabled=false # rejectHttpCode for polaris ratelimit, will be returned as limited spring.cloud.polaris.ratelimit.rejectHttpCode=429 +# switch for circuitbreaker +spring.cloud.polaris.circuitbreaker.enabled=false # maxQueuingTime for polaris ratelimit spring.cloud.polaris.ratelimit.maxQueuingTime=1000 # switch for rpc-enhancement feature @@ -38,3 +40,5 @@ spring.cloud.polaris.stat.enabled=false spring.cloud.polaris.stat.port=0 # path for polaris stat spring.cloud.polaris.stat.path=/metrics + +logging.level.root=INFO \ No newline at end of file diff --git a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/MainPlugin.java b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/MainPlugin.java index bc86a5bd..3eb1c820 100644 --- a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/MainPlugin.java +++ b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/MainPlugin.java @@ -27,17 +27,16 @@ import cn.polarismesh.agent.core.extension.instrument.exception.InstrumentException; import cn.polarismesh.agent.core.extension.transform.TransformCallback; import cn.polarismesh.agent.core.extension.transform.TransformOperations; -import cn.polarismesh.agent.plugin.spring.cloud.common.ClassNames; import cn.polarismesh.agent.plugin.spring.cloud.common.Constant; -import cn.polarismesh.agent.plugin.spring.cloud.interceptor.ApplicationContextAwareInterceptor; -import cn.polarismesh.agent.plugin.spring.cloud.interceptor.ConfigurationInjectInterceptor; - -import org.springframework.context.ApplicationContext; +import cn.polarismesh.agent.plugin.spring.cloud.interceptor.ConfigurationParserInterceptor; +import cn.polarismesh.agent.plugin.spring.cloud.interceptor.ConfigurationPostProcessorInterceptor; +import cn.polarismesh.agent.plugin.spring.cloud.interceptor.RegisterBeanInterceptor; +import cn.polarismesh.agent.plugin.spring.cloud.interceptor.SpringFactoriesLoaderInterceptor; /** - * Polaris Spring Cloud 2021 Plugin + * Polaris Spring Cloud hoxton Plugin * - * @author zhuyuhan + * @author shuhanliu */ public class MainPlugin implements AgentPlugin { @@ -52,42 +51,69 @@ public void init(PluginContext context) { */ private void addPolarisTransformers(TransformOperations operations) { - // 在 agent 中注入 Spring 的 ApplicationContext - operations.transform(ClassNames.APPLICATION_CONTEXT_AWARE, ApplicationContextAwareTransform.class); + // 注入默认配置 + operations.transform(Constant.CONFIGURATION_CLAZZ_POST_PROCESSOR, ConfigurationPostProcessorTransform.class); + + // 注入bootstrap的bean定义 + operations.transform(Constant.CONFIGURATION_CLAZZ_PARSER, ConfigurationParserTransform.class); - // EnvironmentPostProcessor 处理 - // operations.transform(ClassNames.ENVIRONMENT_POST_PROCESSOR, ConfigurationInjectTransform.class); + // 注入bean定义的调整设置 + operations.transform(Constant.BEAN_DEFINITION_REGISTRY, RegisterBeanDefinitionTransform.class); + // 注入JNI定义 + operations.transform(Constant.SPRING_FACTORIES_LOADER, SpringFactoriesLoaderTransform.class); } - /** - * 注入 spring 的 {@link ApplicationContext} - */ - public static class ApplicationContextAwareTransform implements TransformCallback { + public static class ConfigurationParserTransform implements TransformCallback { @Override - public byte[] doInTransform(Instrumentor instrumentor, ClassLoader classLoader, String className, - Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classFileBuffer) throws InstrumentException { + public byte[] doInTransform(Instrumentor instrumentor, ClassLoader classLoader, String className, Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classFileBuffer) throws InstrumentException { + InstrumentClass target = instrumentor.getInstrumentClass(classLoader, className, classFileBuffer); + InstrumentMethod constructMethod = target.getDeclaredMethod("parse", "java.util.Set"); + if (constructMethod != null) { + constructMethod.addInterceptor(ConfigurationParserInterceptor.class); + } + + return target.toBytecode(); + } + } + + public static class ConfigurationPostProcessorTransform implements TransformCallback { + @Override + public byte[] doInTransform(Instrumentor instrumentor, ClassLoader classLoader, String className, Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classFileBuffer) throws InstrumentException { + InstrumentClass target = instrumentor.getInstrumentClass(classLoader, className, classFileBuffer); + InstrumentMethod constructMethod = target.getDeclaredMethod("processConfigBeanDefinitions", "org.springframework.beans.factory.support.BeanDefinitionRegistry"); + if (constructMethod != null) { + constructMethod.addInterceptor(ConfigurationPostProcessorInterceptor.class); + } + + return target.toBytecode(); + } + } + + public static class RegisterBeanDefinitionTransform implements TransformCallback { + + @Override + public byte[] doInTransform(Instrumentor instrumentor, ClassLoader classLoader, String className, Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classFileBuffer) throws InstrumentException { InstrumentClass target = instrumentor.getInstrumentClass(classLoader, className, classFileBuffer); - InstrumentMethod constructMethod = target.getConstructor("org.springframework.context.ConfigurableApplicationContext"); + InstrumentMethod constructMethod = target.getDeclaredMethod("registerBeanDefinition", "java.lang.String", "org.springframework.beans.factory.config.BeanDefinition"); if (constructMethod != null) { - constructMethod.addInterceptor(ApplicationContextAwareInterceptor.class); + constructMethod.addInterceptor(RegisterBeanInterceptor.class); } return target.toBytecode(); } } - public static class ConfigurationInjectTransform implements TransformCallback { + public static class SpringFactoriesLoaderTransform implements TransformCallback { @Override - public byte[] doInTransform(Instrumentor instrumentor, ClassLoader classLoader, String className, - Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classFileBuffer) throws InstrumentException { + public byte[] doInTransform(Instrumentor instrumentor, ClassLoader classLoader, String className, Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classFileBuffer) throws InstrumentException { InstrumentClass target = instrumentor.getInstrumentClass(classLoader, className, classFileBuffer); - InstrumentMethod constructMethod = target.getDeclaredMethod("onApplicationEnvironmentPreparedEvent", "org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent"); + InstrumentMethod constructMethod = target.getDeclaredMethod("loadSpringFactories", "java.lang.ClassLoader"); if (constructMethod != null) { - constructMethod.addInterceptor(ConfigurationInjectInterceptor.class); + constructMethod.addInterceptor(SpringFactoriesLoaderInterceptor.class); } return target.toBytecode(); diff --git a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/base/AbstractContextHandler.java b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/base/AbstractContextHandler.java deleted file mode 100644 index 400790d6..00000000 --- a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/base/AbstractContextHandler.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Tencent is pleased to support the open source community by making Polaris available. - * - * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * 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.polarismesh.agent.plugin.spring.cloud.base; - -import java.util.function.BiConsumer; - -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; - -public abstract class AbstractContextHandler implements ApplicationContextAware { - - public static boolean hasBeanDefinition(ApplicationContext context, String name) { - if (context.containsBeanDefinition(name)) { - return true; - } - ApplicationContext parent = context.getParent(); - if (null != parent) { - return hasBeanDefinition(parent, name); - } - return false; - } - - protected void registerBean(ApplicationContext context, String name, BiConsumer callback) { - if (hasBeanDefinition(context, name)) { - return; - } - callback.accept(context, name); - } -} diff --git a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/base/BaseBeanHandler.java b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/base/BaseBeanHandler.java deleted file mode 100644 index 38974ef9..00000000 --- a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/base/BaseBeanHandler.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Tencent is pleased to support the open source community by making Polaris available. - * - * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * 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.polarismesh.agent.plugin.spring.cloud.base; - -import java.util.function.Supplier; - -import cn.polarismesh.agent.plugin.spring.cloud.common.Holder; -import com.tencent.cloud.common.metadata.StaticMetadataManager; -import com.tencent.cloud.polaris.context.PolarisSDKContextManager; -import com.tencent.cloud.polaris.context.ServiceRuleManager; -import com.tencent.cloud.polaris.context.config.PolarisContextPostConfiguration; -import com.tencent.cloud.polaris.context.config.PolarisContextProperties; -import com.tencent.cloud.polaris.loadbalancer.PolarisLoadBalancerAutoConfiguration; - -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.support.BeanDefinitionBuilder; -import org.springframework.beans.factory.support.DefaultListableBeanFactory; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ConfigurableApplicationContext; - -public class BaseBeanHandler extends AbstractContextHandler { - - @Override - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - registerPolarisSDKContextManager(applicationContext); - registerBean(applicationContext, "staticMetadataManager", (ctx, name) -> { - ConfigurableApplicationContext cfgCtx = (ConfigurableApplicationContext) ctx; - DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) cfgCtx.getBeanFactory(); - beanFactory.registerBeanDefinition(name, - BeanDefinitionBuilder.genericBeanDefinition(StaticMetadataManager.class, new Supplier() { - @Override - public StaticMetadataManager get() { - return Holder.getStaticMetadataManager(); - } - }).getBeanDefinition()); - }); - registerBean(applicationContext, "polarisContextPostConfiguration", (ctx, name) -> { - ConfigurableApplicationContext cfgCtx = (ConfigurableApplicationContext) ctx; - DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) cfgCtx.getBeanFactory(); - beanFactory.registerBeanDefinition(name, BeanDefinitionBuilder.genericBeanDefinition( - PolarisContextPostConfiguration.class).getBeanDefinition()); - }); - registerBean(applicationContext, "serviceRuleManager", (ctx, name) -> { - ConfigurableApplicationContext cfgCtx = (ConfigurableApplicationContext) ctx; - DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) cfgCtx.getBeanFactory(); - beanFactory.registerBeanDefinition(name, - BeanDefinitionBuilder.genericBeanDefinition(ServiceRuleManager.class, new Supplier() { - @Override - public ServiceRuleManager get() { - return Holder.newServiceRuleManager(); - } - }).getBeanDefinition()); - }); - registerBean(applicationContext, "polarisContextProperties", (ctx, name) -> { - ConfigurableApplicationContext cfgCtx = (ConfigurableApplicationContext) ctx; - DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) cfgCtx.getBeanFactory(); - beanFactory.registerBeanDefinition(name, - BeanDefinitionBuilder.genericBeanDefinition(PolarisContextProperties.class, new Supplier() { - @Override - public PolarisContextProperties get() { - return Holder.getPolarisContextProperties(); - } - }).getBeanDefinition()); - }); - registerBean(applicationContext, "polarisLoadBalancerAutoConfiguration", (ctx, name) -> { - ConfigurableApplicationContext cfgCtx = (ConfigurableApplicationContext) ctx; - DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) cfgCtx.getBeanFactory(); - beanFactory.registerBeanDefinition(name, BeanDefinitionBuilder.genericBeanDefinition( - PolarisLoadBalancerAutoConfiguration.class).getBeanDefinition()); - }); - } - - private void registerPolarisSDKContextManager(ApplicationContext context) { - registerBean(context, "polarisSDKContextManager", (ctx, name) -> { - ConfigurableApplicationContext cfgCtx = (ConfigurableApplicationContext) ctx; - DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) cfgCtx.getBeanFactory(); - beanFactory.registerBeanDefinition(name, - BeanDefinitionBuilder.genericBeanDefinition(PolarisSDKContextManager.class, new Supplier() { - @Override - public PolarisSDKContextManager get() { - return Holder.getContextManager(); - } - }).getBeanDefinition()); - }); - } -} diff --git a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/common/ClassNames.java b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/common/ClassNames.java deleted file mode 100644 index a52693bb..00000000 --- a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/common/ClassNames.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Tencent is pleased to support the open source community by making Polaris available. - * - * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * 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.polarismesh.agent.plugin.spring.cloud.common; - -import java.util.List; -import java.util.stream.Stream; - -import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent; -import org.springframework.cloud.openfeign.EnableFeignClients; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ConfigurableApplicationContext; - -/** - * @author liaochuntao - */ -public class ClassNames { - - - /** - * {@link org.springframework.cloud.client.serviceregistry.AbstractAutoServiceRegistration#start()} - */ - public static final String SERVICE_REGISTRATION = "org.springframework.cloud.client.serviceregistry.AbstractAutoServiceRegistration"; - - /** - * {@link org.springframework.cloud.client.discovery.composite.CompositeDiscoveryClient#CompositeDiscoveryClient(List)} - */ - public static final String DISCOVERY_CLIENT = "org.springframework.cloud.client.discovery.composite.CompositeDiscoveryClient"; - - /** - * {@link org.springframework.cloud.client.discovery.composite.reactive.ReactiveCompositeDiscoveryClient#ReactiveCompositeDiscoveryClient(List)} - */ - public static final String REACTIVE_DISCOVERY_CLIENT = "org.springframework.cloud.client.discovery.composite.reactive.ReactiveCompositeDiscoveryClient"; - - /** - * {@link org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplierBuilder#withDiscoveryClient()} - * {@link org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplierBuilder#withBlockingDiscoveryClient()} - * {@link org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplierBuilder#withCaching()} - */ - public static final String ROUTER = "org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplierBuilder"; - - /** - * {@link org.springframework.web.server.handler.FilteringWebHandler#FilteringWebHandler(org.springframework.web.server.WebHandler, List)} - */ - public static final String REACTIVE_WEB_FILTER = "org.springframework.web.server.handler.FilteringWebHandler"; - - /** - * {@link org.springframework.web.servlet.DispatcherServlet#initStrategies(ApplicationContext)} - */ - public static final String SERVLET_WEB_FILTER = "org.springframework.web.servlet.DispatcherServlet"; - - /** - * {@link org.springframework.http.client.support.InterceptingHttpAccessor#getInterceptors()} - */ - public static final String REST_TEMPLATE = "org.springframework.http.client.support.InterceptingHttpAccessor"; - - /** - * {@link org.springframework.cloud.openfeign.FeignClientFactoryBean#getInheritedAwareInstances(FeignContext, Class)} - */ - public static final String FEIGN_TEMPLATE = "org.springframework.cloud.openfeign.FeignClientFactoryBean"; - - /** - * {@link org.springframework.context.support.ApplicationContextAwareProcessor#ApplicationContextAwareProcessor(ConfigurableApplicationContext)} - */ - public static final String APPLICATION_CONTEXT_AWARE = "org.springframework.context.support.ApplicationContextAwareProcessor"; - - /** - * {@link org.springframework.boot.env.EnvironmentPostProcessorApplicationListener#onApplicationEnvironmentPreparedEvent(ApplicationEnvironmentPreparedEvent)} - */ - public static final String ENVIRONMENT_POST_PROCESSOR = "org.springframework.boot.env.EnvironmentPostProcessorApplicationListener"; - - /** - * {@link org.springframework.cloud.loadbalancer.blocking.client.BlockingLoadBalancerClient} - */ - public static final String BLOCKING_LOADBALANCER_CLIENT = "org.springframework.cloud.loadbalancer.blocking.client.BlockingLoadBalancerClient"; - - - public static final String INTERCEPTING_HTTP_ACCESSOR = "org.springframework.http.client.support.InterceptingHttpAccessor"; -} diff --git a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/common/Constant.java b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/common/Constant.java deleted file mode 100644 index 2e34941d..00000000 --- a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/common/Constant.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Tencent is pleased to support the open source community by making Polaris available. - * - * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * 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.polarismesh.agent.plugin.spring.cloud.common; - -public interface Constant { - - String POLARIS_CONF_FILE = "polaris.yml"; - - int POLARIS_DEFAULT_WEIGHT = 100; - - String AGENT_CONF_PATH = "__agent_conf_path__"; - -} \ No newline at end of file diff --git a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/common/Holder.java b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/common/Holder.java deleted file mode 100644 index 78290a72..00000000 --- a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/common/Holder.java +++ /dev/null @@ -1,360 +0,0 @@ -/* - * Tencent is pleased to support the open source community by making Polaris available. - * - * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * 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.polarismesh.agent.plugin.spring.cloud.common; - -import java.io.IOException; -import java.io.InputStream; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Objects; -import java.util.Properties; - -import cn.polarismesh.agent.core.common.exception.PolarisAgentException; -import com.tencent.cloud.common.metadata.StaticMetadataManager; -import com.tencent.cloud.common.metadata.config.MetadataLocalProperties; -import com.tencent.cloud.plugin.lossless.config.LosslessConfigModifier; -import com.tencent.cloud.plugin.lossless.config.LosslessProperties; -import com.tencent.cloud.polaris.DiscoveryConfigModifier; -import com.tencent.cloud.polaris.PolarisDiscoveryConfigModifier; -import com.tencent.cloud.polaris.PolarisDiscoveryProperties; -import com.tencent.cloud.polaris.config.ConfigurationModifier; -import com.tencent.cloud.polaris.config.adapter.PolarisPropertySourceManager; -import com.tencent.cloud.polaris.config.config.PolarisConfigProperties; -import com.tencent.cloud.polaris.config.config.PolarisCryptoConfigProperties; -import com.tencent.cloud.polaris.context.ModifyAddress; -import com.tencent.cloud.polaris.context.PolarisConfigModifier; -import com.tencent.cloud.polaris.context.PolarisSDKContextManager; -import com.tencent.cloud.polaris.context.ServiceRuleManager; -import com.tencent.cloud.polaris.context.config.PolarisContextProperties; -import com.tencent.cloud.polaris.extend.consul.ConsulConfigModifier; -import com.tencent.cloud.polaris.extend.consul.ConsulContextProperties; -import com.tencent.cloud.polaris.extend.nacos.NacosConfigModifier; -import com.tencent.cloud.polaris.extend.nacos.NacosContextProperties; -import com.tencent.cloud.polaris.router.RouterConfigModifier; -import com.tencent.cloud.polaris.router.config.properties.PolarisMetadataRouterProperties; -import com.tencent.cloud.polaris.router.config.properties.PolarisNearByRouterProperties; -import com.tencent.cloud.polaris.router.config.properties.PolarisRuleBasedRouterProperties; -import com.tencent.cloud.rpc.enhancement.config.RpcEnhancementReporterProperties; -import com.tencent.cloud.rpc.enhancement.stat.config.PolarisStatProperties; -import com.tencent.cloud.rpc.enhancement.stat.config.StatConfigModifier; -import com.tencent.polaris.api.utils.StringUtils; -import com.tencent.polaris.logging.LoggingConsts; -import com.tencent.polaris.logging.PolarisLogging; - -import org.springframework.boot.context.properties.bind.Bindable; -import org.springframework.boot.context.properties.bind.Binder; -import org.springframework.cloud.client.HostInfoEnvironmentPostProcessor; -import org.springframework.cloud.commons.util.InetUtils; -import org.springframework.cloud.commons.util.InetUtilsProperties; -import org.springframework.core.ResolvableType; -import org.springframework.core.env.Environment; -import org.springframework.core.env.PropertiesPropertySource; -import org.springframework.core.env.StandardEnvironment; - -import static com.tencent.cloud.polaris.extend.nacos.NacosContextProperties.DEFAULT_GROUP; - -/** - * @author liaochuntao - */ -public class Holder { - - private static final String GROUP_SERVER_ID_FORMAT = "%s__%s"; - private static final String NACOS_CLUSTER = "nacos.cluster"; - - private static PolarisDiscoveryProperties discoveryProperties; - - private static ConsulContextProperties consulContextProperties; - - private static NacosContextProperties nacosContextProperties; - - private static MetadataLocalProperties localProperties; - - private static StaticMetadataManager staticMetadataManager; - - private static PolarisContextProperties polarisContextProperties; - - private static PolarisCryptoConfigProperties polarisCryptoConfigProperties; - - private static PolarisRuleBasedRouterProperties routerProperties; - - private static PolarisNearByRouterProperties nearByRouterProperties; - - private static LosslessProperties losslessProperties; - - private static PolarisMetadataRouterProperties metadataRouterProperties; - - private static PolarisConfigProperties polarisConfigProperties; - - private static PolarisStatProperties polarisStatProperties; - - private static RpcEnhancementReporterProperties rpcEnhancementReporterProperties; - - private static String CONF_FILE_PATH; - - private static boolean allowDiscovery = true; - - private static PolarisSDKContextManager contextManager; - - private static Environment environment; - - private static PolarisPropertySourceManager polarisPropertySourceManager; - - private static void initProperties() { - polarisContextProperties = new PolarisContextProperties(); - discoveryProperties = new PolarisDiscoveryProperties(); - consulContextProperties = new ConsulContextProperties(); - nacosContextProperties = new NacosContextProperties(); - localProperties = new MetadataLocalProperties(); - routerProperties = new PolarisRuleBasedRouterProperties(); - nearByRouterProperties = new PolarisNearByRouterProperties(); - metadataRouterProperties = new PolarisMetadataRouterProperties(); - polarisConfigProperties = new PolarisConfigProperties(); - polarisStatProperties = new PolarisStatProperties(); - losslessProperties = new LosslessProperties(); - rpcEnhancementReporterProperties = new RpcEnhancementReporterProperties(); - polarisCryptoConfigProperties = new PolarisCryptoConfigProperties(); - discoveryProperties.setService(Holder.getLocalService()); - polarisPropertySourceManager = new PolarisPropertySourceManager(); - } - - public static void init() { - CONF_FILE_PATH = Paths.get(System.getProperty(Constant.AGENT_CONF_PATH), "conf").toString(); - initProperties(); - try (InetUtils utils = new InetUtils(new InetUtilsProperties())) { - polarisContextProperties.setLocalIpAddress(utils.findFirstNonLoopbackHostInfo().getIpAddress()); - // 读取 application.yaml - environment = buildEnv(); - - // sct 本身的额外的配饰信息 - bindObject("spring.cloud.tencent.metadata", localProperties, environment); - bindObject("spring.cloud.polaris", polarisContextProperties, environment); - staticMetadataManager = new StaticMetadataManager(localProperties, null); - - allowDiscovery = environment.getProperty("spring.cloud.discovery.enabled", Boolean.class, true); - // 服务发现配置 - discoveryProperties.setRegisterEnabled(environment.getProperty("spring.cloud.polaris.discovery.register", Boolean.class, true)); - discoveryProperties.setProtocol(environment.getProperty("spring.cloud.polaris.discovery.protocol", String.class, "http")); - discoveryProperties.setService(environment.getProperty("spring.application.name", String.class)); - discoveryProperties.setWeight(environment.getProperty("spring.cloud.polaris.discovery.weight", Integer.class, 100)); - String namespace = environment.getProperty("spring.cloud.polaris.namespace", String.class); - if (StringUtils.isBlank(namespace)) { - namespace = environment.getProperty("spring.cloud.polaris.discovery.namespace", String.class, "default"); - } - discoveryProperties.setNamespace(namespace); - - polarisContextProperties.setNamespace(namespace); - polarisContextProperties.setService(discoveryProperties.getService()); - bindObject("spring.cloud.consul", consulContextProperties, environment); - bindObject("spring.cloud.nacos.discovery", nacosContextProperties, environment); - - // 路由规则配置 - bindObject("spring.cloud.polaris.router.rule-router", routerProperties, environment); - bindObject("spring.cloud.polaris.router.nearby-router", nearByRouterProperties, environment); - bindObject("spring.cloud.polaris.router.metadata-router", metadataRouterProperties, environment); - - bindObject("spring.cloud.polaris.config.crypto", polarisCryptoConfigProperties, environment); - // 配置中心 - bindObject("spring.cloud.polaris.config", polarisConfigProperties, environment); - - // 监控 - bindObject("spring.cloud.polaris.stat", polarisStatProperties, environment); - - bindObject("spring.cloud.polaris.lossless", losslessProperties, environment); - - // rpc 调用增强 - bindObject("spring.cloud.tencent.rpc-enhancement.reporter", rpcEnhancementReporterProperties, environment); - - runConfigModifiers(environment); - } catch (Throwable ex) { - throw new PolarisAgentException(ex); - } - } - - private static Environment buildEnv() throws Exception { - StandardEnvironment environment = new StandardEnvironment(); - HostInfoEnvironmentPostProcessor processor = new HostInfoEnvironmentPostProcessor(); - processor.postProcessEnvironment(environment, null); - - InputStream stream = Holder.class.getClassLoader().getResourceAsStream("default-plugin.conf"); - Properties defaultProperties = new Properties(); - defaultProperties.load(stream); - environment.getPropertySources() - .addFirst(new PropertiesPropertySource("__default_polaris_agent_spring_cloud_tencent__", defaultProperties)); - - Properties properties = new Properties(); - - String confPath = Paths.get(CONF_FILE_PATH, "plugin", "spring-cloud-2023", "application.properties").toString(); - String cmdVal = System.getProperty("polaris.agent.user.application.conf"); - if (StringUtils.isNotBlank(cmdVal)) { - confPath = cmdVal; - } - - properties.load(Files.newInputStream(Paths.get(confPath).toFile().toPath())); - environment.getPropertySources() - .addFirst(new PropertiesPropertySource("__polaris_agent_spring_cloud_tencent__", properties)); - - return environment; - } - - private static void bindObject(String prefix, Object bean, Environment environment) { - Binder binder = Binder.get(environment); - ResolvableType type = ResolvableType.forClass(bean.getClass()); - Bindable target = Bindable.of(type).withExistingValue(bean); - binder.bind(prefix, target); - } - - private static void runConfigModifiers(Environment environment) throws IOException { - - String logConfig = ""; - try { - Class.forName(PolarisLogging.LOGBACK_CLASSIC_LOGGER); - logConfig = Holder.class.getClassLoader().getResource("polaris-logback.xml").getFile(); - } catch (ClassNotFoundException e) { - try { - Class.forName(PolarisLogging.LOG4J2_CLASSIC_LOGGER); - logConfig = Holder.class.getClassLoader().getResource("polaris-log4j2.xml").getFile(); - } catch (ClassNotFoundException e1) { - logConfig = Holder.class.getClassLoader().getResource("polaris-log4j.xml").getFile(); - } - } - System.setProperty(LoggingConsts.LOGGING_CONFIG_PROPERTY, "jar:" + logConfig); - - if (StringUtils.isBlank(polarisContextProperties.getLocalIpAddress())) { - polarisContextProperties.setLocalIpAddress(environment.getProperty("spring.cloud.client.ip-address")); - } - - List modifiers = new ArrayList<>(Arrays.asList( - new ModifyAddress(polarisContextProperties), - new DiscoveryConfigModifier(discoveryProperties), - new PolarisDiscoveryConfigModifier(discoveryProperties), - new RouterConfigModifier(nearByRouterProperties), - //new RateLimitConfigModifier(rateLimitProperties), - new StatConfigModifier(polarisStatProperties, environment) - //new CircuitBreakerConfigModifier(rpcEnhancementReporterProperties), - )); - if (consulContextProperties.isEnabled()) { - modifiers.add(new ConsulConfigModifier(consulContextProperties)); - } - if (nacosContextProperties.isEnabled()) { - modifiers.add(new NacosConfigModifier(nacosContextProperties)); - } - if (losslessProperties.isEnabled()) { - modifiers.add(new LosslessConfigModifier(losslessProperties)); - } - if (polarisConfigProperties.isEnabled()) { - modifiers.add(new ConfigurationModifier(polarisConfigProperties, polarisCryptoConfigProperties, polarisContextProperties)); - } - - contextManager = new PolarisSDKContextManager(polarisContextProperties, environment, modifiers); - contextManager.init(); - } - - private static String getLocalService() { - String serviceId = ""; - if (Objects.isNull(nacosContextProperties)) { - serviceId = discoveryProperties.getService(); - } else { - String group = nacosContextProperties.getGroup(); - if (org.apache.commons.lang.StringUtils.isNotBlank(group) && !DEFAULT_GROUP.equals(group)) { - serviceId = String.format(GROUP_SERVER_ID_FORMAT, group, discoveryProperties.getService()); - } else { - serviceId = discoveryProperties.getService(); - } - } - return serviceId; - } - - public static Environment getEnvironment() { - return environment; - } - - public static PolarisStatProperties getPolarisStatProperties() { - return polarisStatProperties; - } - - public static PolarisSDKContextManager getContextManager() { - return contextManager; - } - - public static MetadataLocalProperties getLocalProperties() { - return localProperties; - } - - public static StaticMetadataManager getStaticMetadataManager() { - return staticMetadataManager; - } - - public static PolarisContextProperties getPolarisContextProperties() { - return polarisContextProperties; - } - - public static PolarisDiscoveryProperties getDiscoveryProperties() { - return discoveryProperties; - } - - public static PolarisRuleBasedRouterProperties getRouterProperties() { - return routerProperties; - } - - public static PolarisNearByRouterProperties getNearByRouterProperties() { - return nearByRouterProperties; - } - - public static PolarisMetadataRouterProperties getMetadataRouterProperties() { - return metadataRouterProperties; - } - - public static ConsulContextProperties getConsulContextProperties() { - return consulContextProperties; - } - - public static NacosContextProperties getNacosContextProperties() { - return nacosContextProperties; - } - - public static RpcEnhancementReporterProperties getRpcEnhancementReporterProperties() { - return rpcEnhancementReporterProperties; - } - - public static PolarisConfigProperties getPolarisConfigProperties() { - return polarisConfigProperties; - } - - public static PolarisCryptoConfigProperties getPolarisCryptoConfigProperties() { - return polarisCryptoConfigProperties; - } - - public static ServiceRuleManager newServiceRuleManager() { - return new ServiceRuleManager(getContextManager().getSDKContext(), getContextManager().getConsumerAPI()); - } - - public static boolean isAllowDiscovery() { - return allowDiscovery; - } - - public static LosslessProperties getLosslessProperties() { - return losslessProperties; - } - - public static PolarisPropertySourceManager getPolarisPropertySourceManager() { - return polarisPropertySourceManager; - } -} diff --git a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/config/ConfigHandler.java b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/config/ConfigHandler.java deleted file mode 100644 index 9f5a7212..00000000 --- a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/config/ConfigHandler.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Tencent is pleased to support the open source community by making Polaris available. - * - * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * 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.polarismesh.agent.plugin.spring.cloud.config; - -import java.util.function.Supplier; - -import cn.polarismesh.agent.plugin.spring.cloud.common.Holder; -import cn.polarismesh.agent.plugin.spring.cloud.base.AbstractContextHandler; -import com.tencent.cloud.polaris.config.PolarisConfigAutoConfiguration; -import com.tencent.cloud.polaris.config.adapter.PolarisConfigFileLocator; -import com.tencent.cloud.polaris.config.adapter.PolarisPropertySourceManager; -import com.tencent.cloud.polaris.config.config.PolarisConfigProperties; -import com.tencent.cloud.polaris.config.config.PolarisCryptoConfigProperties; -import com.tencent.polaris.configuration.api.core.ConfigFileService; -import com.tencent.polaris.configuration.factory.ConfigFileServiceFactory; - -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.support.BeanDefinitionBuilder; -import org.springframework.beans.factory.support.DefaultListableBeanFactory; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.core.env.Environment; - -public class ConfigHandler extends AbstractContextHandler { - - @Override - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - if (!Holder.getPolarisConfigProperties().isEnabled()) { - return; - } - registerBean(applicationContext, "polarisProperties", (ctx, name) -> { - ConfigurableApplicationContext cfgCtx = (ConfigurableApplicationContext) ctx; - DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) cfgCtx.getBeanFactory(); - beanFactory.registerBeanDefinition(name, - BeanDefinitionBuilder.genericBeanDefinition(PolarisConfigProperties.class, new Supplier() { - @Override - public PolarisConfigProperties get() { - return Holder.getPolarisConfigProperties(); - } - }).getBeanDefinition()); - }); - registerBean(applicationContext, "polarisCryptoConfigProperties", (ctx, name) -> { - ConfigurableApplicationContext cfgCtx = (ConfigurableApplicationContext) ctx; - DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) cfgCtx.getBeanFactory(); - beanFactory.registerBeanDefinition(name, - BeanDefinitionBuilder.genericBeanDefinition(PolarisCryptoConfigProperties.class, new Supplier() { - @Override - public PolarisCryptoConfigProperties get() { - return Holder.getPolarisCryptoConfigProperties(); - } - }).getBeanDefinition()); - }); - registerBean(applicationContext, "polarisPropertySourceManager", (ctx, name) -> { - ConfigurableApplicationContext cfgCtx = (ConfigurableApplicationContext) ctx; - DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) cfgCtx.getBeanFactory(); - beanFactory.registerBeanDefinition(name, - BeanDefinitionBuilder.genericBeanDefinition(PolarisPropertySourceManager.class, new Supplier() { - @Override - public PolarisPropertySourceManager get() { - return new PolarisPropertySourceManager(); - } - }).getBeanDefinition()); - }); - registerBean(applicationContext, "configFileService", (ctx, name) -> { - ConfigurableApplicationContext cfgCtx = (ConfigurableApplicationContext) ctx; - DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) cfgCtx.getBeanFactory(); - beanFactory.registerBeanDefinition(name, - BeanDefinitionBuilder.genericBeanDefinition(ConfigFileService.class, new Supplier() { - @Override - public ConfigFileService get() { - return ConfigFileServiceFactory.createConfigFileService(Holder.getContextManager().getSDKContext()); - } - }).getBeanDefinition()); - }); - registerBean(applicationContext, "polarisConfigFileLocator", (ctx, name) -> { - ConfigurableApplicationContext cfgCtx = (ConfigurableApplicationContext) ctx; - DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) cfgCtx.getBeanFactory(); - beanFactory.registerBeanDefinition(name, - BeanDefinitionBuilder.genericBeanDefinition(PolarisConfigFileLocator.class, new Supplier() { - @Override - public PolarisConfigFileLocator get() { - ConfigFileService configFileService = cfgCtx.getBean("configFileService", ConfigFileService.class); - PolarisPropertySourceManager polarisPropertySourceManager = cfgCtx.getBean("polarisPropertySourceManager", PolarisPropertySourceManager.class); - Environment environment = cfgCtx.getBean("environment", Environment.class); - return new PolarisConfigFileLocator(Holder.getPolarisConfigProperties(), - Holder.getPolarisContextProperties(), configFileService, - polarisPropertySourceManager, environment); - } - }).getBeanDefinition()); - }); - registerBean(applicationContext, "polarisConfigAutoConfiguration", (ctx, name) -> { - ConfigurableApplicationContext cfgCtx = (ConfigurableApplicationContext) ctx; - DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) cfgCtx.getBeanFactory(); - beanFactory.registerBeanDefinition(name, - BeanDefinitionBuilder.genericBeanDefinition(PolarisConfigAutoConfiguration.class).getBeanDefinition()); - }); - } - -} diff --git a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/discovery/DiscoveryHandler.java b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/discovery/DiscoveryHandler.java deleted file mode 100644 index d949f594..00000000 --- a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/discovery/DiscoveryHandler.java +++ /dev/null @@ -1,122 +0,0 @@ -package cn.polarismesh.agent.plugin.spring.cloud.discovery; - -import java.util.function.Supplier; - -import cn.polarismesh.agent.plugin.spring.cloud.common.Holder; -import cn.polarismesh.agent.plugin.spring.cloud.base.AbstractContextHandler; -import com.tencent.cloud.plugin.lossless.config.LosslessAutoConfiguration; -import com.tencent.cloud.polaris.PolarisDiscoveryProperties; -import com.tencent.cloud.polaris.context.PolarisSDKContextManager; -import com.tencent.cloud.polaris.discovery.PolarisDiscoveryAutoConfiguration; -import com.tencent.cloud.polaris.discovery.PolarisDiscoveryHandler; -import com.tencent.cloud.polaris.registry.PolarisAutoServiceRegistration; -import com.tencent.cloud.polaris.registry.PolarisRegistration; -import com.tencent.cloud.polaris.registry.PolarisServiceRegistry; -import com.tencent.cloud.rpc.enhancement.stat.config.PolarisStatProperties; -import com.tencent.polaris.assembly.api.AssemblyAPI; -import com.tencent.polaris.client.api.SDKContext; - -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.support.BeanDefinitionBuilder; -import org.springframework.beans.factory.support.DefaultListableBeanFactory; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ConfigurableApplicationContext; - -public class DiscoveryHandler extends AbstractContextHandler { - - - @Override - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - String discoveryEnable = applicationContext.getEnvironment().getProperty("spring.cloud.discovery.enabled"); - if (null == discoveryEnable || Boolean.parseBoolean(discoveryEnable)) { - registerBean(applicationContext, "polarisDiscoveryProperties", (ctx, name) -> { - ConfigurableApplicationContext cfgCtx = (ConfigurableApplicationContext) ctx; - DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) cfgCtx.getBeanFactory(); - beanFactory.registerBeanDefinition(name, - BeanDefinitionBuilder.genericBeanDefinition(PolarisDiscoveryProperties.class, new Supplier() { - @Override - public PolarisDiscoveryProperties get() { - return Holder.getDiscoveryProperties(); - } - }).getBeanDefinition()); - }); - registerBean(applicationContext, "polarisDiscoveryHandler", (ctx, name) -> { - ConfigurableApplicationContext cfgCtx = (ConfigurableApplicationContext) ctx; - DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) cfgCtx.getBeanFactory(); - beanFactory.registerBeanDefinition(name, - BeanDefinitionBuilder.genericBeanDefinition(PolarisDiscoveryHandler.class, new Supplier() { - @Override - public PolarisDiscoveryHandler get() { - PolarisDiscoveryProperties polarisDiscoveryProperties = (PolarisDiscoveryProperties) ctx.getBean("polarisDiscoveryProperties"); - PolarisSDKContextManager polarisSDKContextManager = (PolarisSDKContextManager) ctx.getBean("polarisSDKContextManager"); - return new PolarisDiscoveryHandler(polarisDiscoveryProperties, polarisSDKContextManager); - } - }).getBeanDefinition()); - }); - registerBean(applicationContext, "polarisStatProperties", (ctx, name) -> { - ConfigurableApplicationContext cfgCtx = (ConfigurableApplicationContext) ctx; - DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) cfgCtx.getBeanFactory(); - beanFactory.registerBeanDefinition(name, - BeanDefinitionBuilder.genericBeanDefinition(PolarisStatProperties.class, new Supplier() { - @Override - public PolarisStatProperties get() { - return Holder.getPolarisStatProperties(); - } - }).getBeanDefinition()); - }); - registerBean(applicationContext, "polarisDiscoveryAutoConfiguration", (ctx, name) -> { - ConfigurableApplicationContext cfgCtx = (ConfigurableApplicationContext) ctx; - DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) cfgCtx.getBeanFactory(); - beanFactory.registerBeanDefinition(name, BeanDefinitionBuilder.genericBeanDefinition( - PolarisDiscoveryAutoConfiguration.class).getBeanDefinition()); - }); - registerBean(applicationContext, "sdkContext", (ctx, name) -> { - ConfigurableApplicationContext cfgCtx = (ConfigurableApplicationContext) ctx; - DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) cfgCtx.getBeanFactory(); - beanFactory.registerBeanDefinition(name, - BeanDefinitionBuilder.genericBeanDefinition(SDKContext.class, new Supplier() { - @Override - public SDKContext get() { - return Holder.getContextManager().getSDKContext(); - } - }).getBeanDefinition()); - }); - registerBean(applicationContext, "assemblyAPI", (ctx, name) -> { - ConfigurableApplicationContext cfgCtx = (ConfigurableApplicationContext) ctx; - DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) cfgCtx.getBeanFactory(); - beanFactory.registerBeanDefinition(name, - BeanDefinitionBuilder.genericBeanDefinition(AssemblyAPI.class, new Supplier() { - @Override - public AssemblyAPI get() { - return Holder.getContextManager().getAssemblyAPI(); - } - }).getBeanDefinition()); - }); - registerBean(applicationContext, "polarisRegistration", (ctx, name) -> { - ConfigurableApplicationContext cfgCtx = (ConfigurableApplicationContext) ctx; - DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) cfgCtx.getBeanFactory(); - beanFactory.registerBeanDefinition(name, BeanDefinitionBuilder.genericBeanDefinition( - PolarisRegistration.class).setPrimary(true).getBeanDefinition()); - }); - registerBean(applicationContext, "polarisServiceRegistry", (ctx, name) -> { - ConfigurableApplicationContext cfgCtx = (ConfigurableApplicationContext) ctx; - DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) cfgCtx.getBeanFactory(); - beanFactory.registerBeanDefinition(name, BeanDefinitionBuilder.genericBeanDefinition( - PolarisServiceRegistry.class).setPrimary(true).getBeanDefinition()); - }); - registerBean(applicationContext, "polarisAutoServiceRegistration", (ctx, name) -> { - ConfigurableApplicationContext cfgCtx = (ConfigurableApplicationContext) ctx; - DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) cfgCtx.getBeanFactory(); - beanFactory.registerBeanDefinition(name, BeanDefinitionBuilder.genericBeanDefinition( - PolarisAutoServiceRegistration.class).setPrimary(true).getBeanDefinition()); - }); - registerBean(applicationContext, "losslessAutoConfiguration", (ctx, name) -> { - ConfigurableApplicationContext cfgCtx = (ConfigurableApplicationContext) ctx; - DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) cfgCtx.getBeanFactory(); - beanFactory.registerBeanDefinition(name, BeanDefinitionBuilder.genericBeanDefinition( - LosslessAutoConfiguration.class).setPrimary(true).getBeanDefinition()); - }); - - } - } -} diff --git a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/inject/CommonBeanInjector.java b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/inject/CommonBeanInjector.java new file mode 100644 index 00000000..5d020040 --- /dev/null +++ b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/inject/CommonBeanInjector.java @@ -0,0 +1,87 @@ +/* + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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.polarismesh.agent.plugin.spring.cloud.inject; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.util.concurrent.atomic.AtomicBoolean; + +import cn.polarismesh.agent.core.common.utils.ClassUtils; +import cn.polarismesh.agent.core.common.utils.ReflectionUtils; +import cn.polarismesh.agent.plugin.spring.cloud.common.BeanInjector; +import cn.polarismesh.agent.plugin.spring.cloud.common.Utils; +import cn.polarismesh.agent.plugin.spring.cloud.con.Constant; +import com.tencent.cloud.common.metadata.config.MetadataAutoConfiguration; +import com.tencent.cloud.common.metadata.endpoint.PolarisMetadataEndpointAutoConfiguration; +import com.tencent.cloud.common.util.ApplicationContextAwareUtils; +import com.tencent.cloud.polaris.config.PolarisConfigBootstrapAutoConfiguration; +import com.tencent.cloud.polaris.router.config.FeignAutoConfiguration; +import com.tencent.cloud.polaris.router.config.RouterAutoConfiguration; +import com.tencent.cloud.polaris.router.endpoint.PolarisRouterEndpointAutoConfiguration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.beans.factory.support.BeanDefinitionBuilder; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; +import org.springframework.core.env.Environment; + +public class CommonBeanInjector implements BeanInjector { + + private static final Logger LOGGER = LoggerFactory.getLogger(CommonBeanInjector.class); + + private final AtomicBoolean bootstrapLoaded = new AtomicBoolean(false); + + @Override + public String getModule() { + return "spring-cloud-tencent-commons"; + } + + @Override + public void onApplicationStartup(Object configurationParser, Constructor configClassCreator, Method processConfigurationClass, BeanDefinitionRegistry registry, Environment environment) { + Object metadataAutoConfiguration = ReflectionUtils.invokeConstructor(configClassCreator, MetadataAutoConfiguration.class, "metadataAutoConfiguration"); + ReflectionUtils.invokeMethod(processConfigurationClass, configurationParser, metadataAutoConfiguration, cn.polarismesh.agent.plugin.spring.cloud.con.Constant.DEFAULT_EXCLUSION_FILTER); + registry.registerBeanDefinition("metadataAutoConfiguration", BeanDefinitionBuilder.genericBeanDefinition( + MetadataAutoConfiguration.class).getBeanDefinition()); + Object polarisMetadataEndpointAutoConfiguration = ReflectionUtils.invokeConstructor(configClassCreator, PolarisMetadataEndpointAutoConfiguration.class, "polarisMetadataEndpointAutoConfiguration"); + ReflectionUtils.invokeMethod(processConfigurationClass, configurationParser, polarisMetadataEndpointAutoConfiguration, cn.polarismesh.agent.plugin.spring.cloud.con.Constant.DEFAULT_EXCLUSION_FILTER); + registry.registerBeanDefinition("polarisMetadataEndpointAutoConfiguration", BeanDefinitionBuilder.genericBeanDefinition( + PolarisMetadataEndpointAutoConfiguration.class).getBeanDefinition()); + Object applicationContextAwareUtils = ReflectionUtils.invokeConstructor(configClassCreator, ApplicationContextAwareUtils.class, "applicationContextAwareUtils"); + ReflectionUtils.invokeMethod(processConfigurationClass, configurationParser, applicationContextAwareUtils, cn.polarismesh.agent.plugin.spring.cloud.con.Constant.DEFAULT_EXCLUSION_FILTER); + registry.registerBeanDefinition("applicationContextAwareUtils", BeanDefinitionBuilder.genericBeanDefinition( + ApplicationContextAwareUtils.class).getBeanDefinition()); + if (null != ClassUtils.getClazz("feign.RequestInterceptor", + Thread.currentThread().getContextClassLoader())) { + Object feignAutoConfiguration = ReflectionUtils.invokeConstructor(configClassCreator, FeignAutoConfiguration.class, "feignAutoConfiguration"); + ReflectionUtils.invokeMethod(processConfigurationClass, configurationParser, feignAutoConfiguration, cn.polarismesh.agent.plugin.spring.cloud.con.Constant.DEFAULT_EXCLUSION_FILTER); + registry.registerBeanDefinition("feignAutoConfiguration", BeanDefinitionBuilder.genericBeanDefinition( + FeignAutoConfiguration.class).getBeanDefinition()); + } + Object routerAutoConfiguration = ReflectionUtils.invokeConstructor(configClassCreator, RouterAutoConfiguration.class, "routerAutoConfiguration"); + ReflectionUtils.invokeMethod(processConfigurationClass, configurationParser, routerAutoConfiguration, Constant.DEFAULT_EXCLUSION_FILTER); + registry.registerBeanDefinition("routerAutoConfiguration", BeanDefinitionBuilder.genericBeanDefinition( + RouterAutoConfiguration.class).getBeanDefinition()); + LOGGER.info("[PolarisJavaAgent] success to inject application bean definitions for module {}", getModule()); + } + + + @Override + public void onBootstrapStartup(Object configurationParser, Constructor configClassCreator, Method processConfigurationClass, BeanDefinitionRegistry registry, Environment environment) { + LOGGER.info("[PolarisJavaAgent] success to inject bootstrap bean definitions for module {}", getModule()); + } +} diff --git a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/inject/ConfigBeanInjector.java b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/inject/ConfigBeanInjector.java new file mode 100644 index 00000000..e3c13d81 --- /dev/null +++ b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/inject/ConfigBeanInjector.java @@ -0,0 +1,78 @@ +/* + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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.polarismesh.agent.plugin.spring.cloud.inject; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.util.concurrent.atomic.AtomicBoolean; + +import cn.polarismesh.agent.core.common.utils.ReflectionUtils; +import cn.polarismesh.agent.plugin.spring.cloud.common.BeanInjector; +import cn.polarismesh.agent.plugin.spring.cloud.common.Constant; +import cn.polarismesh.agent.plugin.spring.cloud.common.Utils; +import com.tencent.cloud.polaris.config.PolarisConfigAutoConfiguration; +import com.tencent.cloud.polaris.config.PolarisConfigBootstrapAutoConfiguration; +import com.tencent.cloud.polaris.config.endpoint.PolarisConfigEndpointAutoConfiguration; +import com.tencent.cloud.polaris.contract.config.PolarisContractPropertiesAutoConfiguration; +import com.tencent.cloud.polaris.contract.config.PolarisContractProperties; +import com.tencent.cloud.polaris.contract.config.PolarisSwaggerAutoConfiguration; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.beans.factory.support.BeanDefinitionBuilder; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; +import org.springframework.core.env.Environment; + +public class ConfigBeanInjector implements BeanInjector { + + private static final Logger LOGGER = LoggerFactory.getLogger(ConfigBeanInjector.class); + + private final AtomicBoolean bootstrapLoaded = new AtomicBoolean(false); + + @Override + public String getModule() { + return "spring-cloud-starter-tencent-polaris-config"; + } + + @Override + public void onBootstrapStartup(Object configurationParser, Constructor configClassCreator, Method processConfigurationClass, BeanDefinitionRegistry registry, Environment environment) { + LOGGER.info("[PolarisJavaAgent] success to inject bootstrap bean definitions for module {}", getModule()); + } + + @Override + public void onApplicationStartup(Object configurationParser, Constructor configClassCreator, Method processConfigurationClass, BeanDefinitionRegistry registry, Environment environment) { + Object polarisConfigAutoConfiguration = ReflectionUtils.invokeConstructor(configClassCreator, PolarisConfigAutoConfiguration.class, "polarisConfigAutoConfiguration"); + ReflectionUtils.invokeMethod(processConfigurationClass, configurationParser, polarisConfigAutoConfiguration, Constant.DEFAULT_EXCLUSION_FILTER); + registry.registerBeanDefinition("polarisConfigAutoConfiguration", BeanDefinitionBuilder.genericBeanDefinition( + PolarisConfigAutoConfiguration.class).getBeanDefinition()); + Object polarisConfigEndpointAutoConfiguration = ReflectionUtils.invokeConstructor(configClassCreator, PolarisConfigEndpointAutoConfiguration.class, "polarisConfigEndpointAutoConfiguration"); + ReflectionUtils.invokeMethod(processConfigurationClass, configurationParser, polarisConfigEndpointAutoConfiguration, Constant.DEFAULT_EXCLUSION_FILTER); + registry.registerBeanDefinition("polarisConfigEndpointAutoConfiguration", BeanDefinitionBuilder.genericBeanDefinition( + PolarisConfigEndpointAutoConfiguration.class).getBeanDefinition()); + Object polarisContractProperties = ReflectionUtils.invokeConstructor(configClassCreator, PolarisContractProperties.class, "polarisContractProperties"); + ReflectionUtils.invokeMethod(processConfigurationClass, configurationParser, polarisContractProperties, Constant.DEFAULT_EXCLUSION_FILTER); + registry.registerBeanDefinition("polarisContractProperties", BeanDefinitionBuilder.genericBeanDefinition( + PolarisContractProperties.class).getBeanDefinition()); + Object polarisConfigBootstrapAutoConfiguration = ReflectionUtils.invokeConstructor(configClassCreator, PolarisConfigBootstrapAutoConfiguration.class, "polarisConfigBootstrapAutoConfiguration"); + ReflectionUtils.invokeMethod(processConfigurationClass, configurationParser, polarisConfigBootstrapAutoConfiguration, Constant.DEFAULT_EXCLUSION_FILTER); + registry.registerBeanDefinition("polarisConfigBootstrapAutoConfiguration", BeanDefinitionBuilder.genericBeanDefinition( + PolarisConfigBootstrapAutoConfiguration.class).getBeanDefinition()); + LOGGER.info("[PolarisJavaAgent] success to inject application bean definitions for module {}", getModule()); + } +} diff --git a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/inject/LoadbalancerBeanInjector.java b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/inject/LoadbalancerBeanInjector.java new file mode 100644 index 00000000..2ed6ea6d --- /dev/null +++ b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/inject/LoadbalancerBeanInjector.java @@ -0,0 +1,54 @@ +/* + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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.polarismesh.agent.plugin.spring.cloud.inject; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.util.Map; + +import cn.polarismesh.agent.core.common.utils.ReflectionUtils; +import cn.polarismesh.agent.plugin.spring.cloud.common.BeanInjector; +import cn.polarismesh.agent.plugin.spring.cloud.common.Constant; +import cn.polarismesh.agent.plugin.spring.cloud.common.Utils; +import com.tencent.cloud.polaris.loadbalancer.PolarisLoadBalancerAutoConfiguration; +import org.springframework.cloud.loadbalancer.config.LoadBalancerAutoConfiguration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.beans.factory.support.BeanDefinitionBuilder; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; +import org.springframework.core.env.Environment; +import org.springframework.core.io.ClassPathResource; + +public class LoadbalancerBeanInjector implements BeanInjector { + + private static final Logger LOGGER = LoggerFactory.getLogger(LoadbalancerBeanInjector.class); + @Override + public String getModule() { + return "spring-cloud-tencent-polaris-loadbalancer"; + } + + @Override + public void onApplicationStartup(Object configurationParser, Constructor configClassCreator, Method processConfigurationClass, BeanDefinitionRegistry registry, Environment environment) { + Object polarisLoadBalancerAutoConfiguration = ReflectionUtils.invokeConstructor(configClassCreator, PolarisLoadBalancerAutoConfiguration.class, "polarisLoadBalancerAutoConfiguration"); + ReflectionUtils.invokeMethod(processConfigurationClass, configurationParser, polarisLoadBalancerAutoConfiguration, Constant.DEFAULT_EXCLUSION_FILTER); + registry.registerBeanDefinition("polarisLoadBalancerAutoConfiguration", BeanDefinitionBuilder.genericBeanDefinition( + PolarisLoadBalancerAutoConfiguration.class).getBeanDefinition()); + LOGGER.info("[PolarisJavaAgent] success to inject application bean definitions for module {}", getModule()); + } +} diff --git a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/inject/LosslessBeanInjector.java b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/inject/LosslessBeanInjector.java new file mode 100644 index 00000000..2d487518 --- /dev/null +++ b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/inject/LosslessBeanInjector.java @@ -0,0 +1,70 @@ +/* + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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.polarismesh.agent.plugin.spring.cloud.inject; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.util.concurrent.atomic.AtomicBoolean; + +import cn.polarismesh.agent.core.common.utils.ReflectionUtils; +import cn.polarismesh.agent.plugin.spring.cloud.common.BeanInjector; +import cn.polarismesh.agent.plugin.spring.cloud.common.Constant; +import cn.polarismesh.agent.plugin.spring.cloud.common.Utils; +import com.tencent.cloud.plugin.lossless.config.LosslessAutoConfiguration; +import com.tencent.cloud.plugin.lossless.config.LosslessPropertiesAutoConfiguration; +import com.tencent.cloud.plugin.lossless.config.LosslessPropertiesBootstrapConfiguration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.beans.factory.support.BeanDefinitionBuilder; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; +import org.springframework.core.env.Environment; + +public class LosslessBeanInjector implements BeanInjector { + + private static final Logger LOGGER = LoggerFactory.getLogger(LosslessBeanInjector.class); + + private final AtomicBoolean bootstrapLoaded = new AtomicBoolean(false); + + @Override + public String getModule() { + return "spring-cloud-tencent-lossless-plugin"; + } + + @Override + public void onBootstrapStartup(Object configurationParser, Constructor configClassCreator, Method processConfigurationClass, BeanDefinitionRegistry registry, Environment environment) { + Object losslessPropertiesBootstrapConfiguration = ReflectionUtils.invokeConstructor(configClassCreator, LosslessPropertiesBootstrapConfiguration.class, "losslessPropertiesBootstrapConfiguration"); + ReflectionUtils.invokeMethod(processConfigurationClass, configurationParser, losslessPropertiesBootstrapConfiguration, Constant.DEFAULT_EXCLUSION_FILTER); + registry.registerBeanDefinition("losslessPropertiesBootstrapConfiguration", BeanDefinitionBuilder.genericBeanDefinition( + LosslessPropertiesBootstrapConfiguration.class).getBeanDefinition()); + LOGGER.info("[PolarisJavaAgent] success to inject bootstrap bean definitions for module {}", getModule()); + } + + @Override + public void onApplicationStartup(Object configurationParser, Constructor configClassCreator, Method processConfigurationClass, BeanDefinitionRegistry registry, Environment environment) { + Object losslessPropertiesAutoConfiguration = ReflectionUtils.invokeConstructor(configClassCreator, LosslessPropertiesAutoConfiguration.class, "losslessPropertiesAutoConfiguration"); + ReflectionUtils.invokeMethod(processConfigurationClass, configurationParser, losslessPropertiesAutoConfiguration, Constant.DEFAULT_EXCLUSION_FILTER); + registry.registerBeanDefinition("losslessPropertiesAutoConfiguration", BeanDefinitionBuilder.genericBeanDefinition( + LosslessPropertiesAutoConfiguration.class).getBeanDefinition()); + Object losslessAutoConfiguration = ReflectionUtils.invokeConstructor(configClassCreator, LosslessAutoConfiguration.class, "losslessAutoConfiguration"); + ReflectionUtils.invokeMethod(processConfigurationClass, configurationParser, losslessAutoConfiguration, Constant.DEFAULT_EXCLUSION_FILTER); + registry.registerBeanDefinition("losslessAutoConfiguration", BeanDefinitionBuilder.genericBeanDefinition( + LosslessAutoConfiguration.class).getBeanDefinition()); + LOGGER.info("[PolarisJavaAgent] success to inject application bean definitions for module {}", getModule()); + } +} diff --git a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/inject/MetadataTransferBeanInjector.java b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/inject/MetadataTransferBeanInjector.java new file mode 100644 index 00000000..3717e0e3 --- /dev/null +++ b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/inject/MetadataTransferBeanInjector.java @@ -0,0 +1,64 @@ +/* + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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.polarismesh.agent.plugin.spring.cloud.inject; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.util.concurrent.atomic.AtomicBoolean; + +import cn.polarismesh.agent.core.common.utils.ReflectionUtils; +import cn.polarismesh.agent.plugin.spring.cloud.common.BeanInjector; +import cn.polarismesh.agent.plugin.spring.cloud.common.Constant; +import cn.polarismesh.agent.plugin.spring.cloud.common.Utils; +import com.tencent.cloud.metadata.config.MetadataTransferAutoConfiguration; +import com.tencent.cloud.polaris.config.PolarisConfigBootstrapAutoConfiguration; +import com.tencent.cloud.common.metadata.config.MetadataAutoConfiguration; +import com.tencent.cloud.common.metadata.endpoint.PolarisMetadataEndpointAutoConfiguration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.beans.factory.support.BeanDefinitionBuilder; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; +import org.springframework.core.env.Environment; + +public class MetadataTransferBeanInjector implements BeanInjector { + + private static final Logger LOGGER = LoggerFactory.getLogger(MetadataTransferBeanInjector.class); + + private final AtomicBoolean bootstrapLoaded = new AtomicBoolean(false); + + @Override + public String getModule() { + return "spring-cloud-starter-tencent-metadata-transfer"; + } + + @Override + public void onApplicationStartup(Object configurationParser, Constructor configClassCreator, Method processConfigurationClass, BeanDefinitionRegistry registry, Environment environment) { + LOGGER.info("[PolarisJavaAgent] success to inject application bean definitions for module {}", getModule()); + } + + @Override + public void onBootstrapStartup(Object configurationParser, Constructor configClassCreator, Method processConfigurationClass, BeanDefinitionRegistry registry, Environment environment) { + Object metadataTransferAutoConfiguration = ReflectionUtils.invokeConstructor(configClassCreator, MetadataTransferAutoConfiguration.class, "metadataTransferAutoConfiguration"); + ReflectionUtils.invokeMethod(processConfigurationClass, configurationParser, metadataTransferAutoConfiguration, Constant.DEFAULT_EXCLUSION_FILTER); + registry.registerBeanDefinition("metadataTransferAutoConfiguration", BeanDefinitionBuilder.genericBeanDefinition( + MetadataTransferAutoConfiguration.class).getBeanDefinition()); + LOGGER.info("[PolarisJavaAgent] success to inject bootstrap bean definitions for module {}", getModule()); + } + +} diff --git a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/inject/PolarisContextBeanInjector.java b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/inject/PolarisContextBeanInjector.java new file mode 100644 index 00000000..81b69fd7 --- /dev/null +++ b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/inject/PolarisContextBeanInjector.java @@ -0,0 +1,86 @@ +/* + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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.polarismesh.agent.plugin.spring.cloud.inject; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicBoolean; + +import cn.polarismesh.agent.core.common.utils.ReflectionUtils; +import cn.polarismesh.agent.plugin.spring.cloud.common.BeanInjector; +import cn.polarismesh.agent.plugin.spring.cloud.common.Constant; +import cn.polarismesh.agent.plugin.spring.cloud.common.Utils; +import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration; +import com.tencent.cloud.polaris.context.config.PolarisContextBootstrapAutoConfiguration; +import com.tencent.cloud.polaris.context.config.PolarisContextPostConfiguration; +import com.tencent.cloud.polaris.context.logging.PolarisLoggingApplicationListener; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.beans.factory.support.BeanDefinitionBuilder; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; +import org.springframework.core.env.Environment; + +public class PolarisContextBeanInjector implements BeanInjector { + + private static final Logger LOGGER = LoggerFactory.getLogger(PolarisContextBeanInjector.class); + + private final AtomicBoolean bootstrapLoaded = new AtomicBoolean(false); + + @Override + public String getModule() { + return "spring-cloud-tencent-polaris-context"; + } + + @Override + public Map> getClassNameForType() { + Map> values = new HashMap<>(); + values.put("org.springframework.context.ApplicationListener", Collections.singletonList("com.tencent.cloud.polaris.context.logging.PolarisLoggingApplicationListener")); + return values; + } + + @Override + public void onBootstrapStartup(Object configurationParser, + Constructor configClassCreator, Method processConfigurationClass, BeanDefinitionRegistry registry, Environment environment) { + Object polarisContextAutoConfiguration = ReflectionUtils.invokeConstructor(configClassCreator, PolarisContextAutoConfiguration.class, "polarisContextAutoConfiguration"); + ReflectionUtils.invokeMethod(processConfigurationClass, configurationParser, polarisContextAutoConfiguration, Constant.DEFAULT_EXCLUSION_FILTER); + registry.registerBeanDefinition("polarisContextAutoConfiguration", BeanDefinitionBuilder.genericBeanDefinition( + PolarisContextAutoConfiguration.class).getBeanDefinition()); + Object polarisContextBootstrapAutoConfiguration = ReflectionUtils.invokeConstructor(configClassCreator, PolarisContextBootstrapAutoConfiguration.class, "polarisContextBootstrapAutoConfiguration"); + ReflectionUtils.invokeMethod(processConfigurationClass, configurationParser, polarisContextBootstrapAutoConfiguration, Constant.DEFAULT_EXCLUSION_FILTER); + registry.registerBeanDefinition("polarisContextBootstrapAutoConfiguration", BeanDefinitionBuilder.genericBeanDefinition( + PolarisContextBootstrapAutoConfiguration.class).getBeanDefinition()); + + LOGGER.info("[PolarisJavaAgent] success to inject bootstrap bean definitions for module {}", getModule()); + } + + @Override + public void onApplicationStartup(Object configurationParser, + Constructor configClassCreator, Method processConfigurationClass, BeanDefinitionRegistry registry, Environment environment) { + + Object polarisContextPostConfiguration = ReflectionUtils.invokeConstructor(configClassCreator, PolarisContextPostConfiguration.class, "polarisContextPostConfiguration"); + ReflectionUtils.invokeMethod(processConfigurationClass, configurationParser, polarisContextPostConfiguration, Constant.DEFAULT_EXCLUSION_FILTER); + registry.registerBeanDefinition("polarisContextPostConfiguration", BeanDefinitionBuilder.genericBeanDefinition( + PolarisContextPostConfiguration.class).getBeanDefinition()); + LOGGER.info("[PolarisJavaAgent] success to inject application bean definitions for module {}", getModule()); + } +} diff --git a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/inject/RegistryBeanInjector.java b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/inject/RegistryBeanInjector.java new file mode 100644 index 00000000..877997cd --- /dev/null +++ b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/inject/RegistryBeanInjector.java @@ -0,0 +1,106 @@ +/* + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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.polarismesh.agent.plugin.spring.cloud.inject; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.util.concurrent.atomic.AtomicBoolean; + +import cn.polarismesh.agent.core.common.utils.ReflectionUtils; +import cn.polarismesh.agent.plugin.spring.cloud.common.BeanInjector; +import cn.polarismesh.agent.plugin.spring.cloud.common.Constant; +import cn.polarismesh.agent.plugin.spring.cloud.common.Utils; +import com.tencent.cloud.common.metadata.config.MetadataLocalProperties; +import com.tencent.cloud.polaris.DiscoveryPropertiesAutoConfiguration; +import com.tencent.cloud.polaris.DiscoveryPropertiesBootstrapAutoConfiguration; +import com.tencent.cloud.polaris.discovery.PolarisDiscoveryAutoConfiguration; +import com.tencent.cloud.polaris.discovery.PolarisDiscoveryClientConfiguration; +import com.tencent.cloud.polaris.discovery.reactive.PolarisReactiveDiscoveryClientConfiguration; +import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationProperties; +import com.tencent.polaris.api.config.Configuration; +import com.tencent.cloud.polaris.endpoint.PolarisDiscoveryEndpointAutoConfiguration; +import com.tencent.cloud.polaris.loadbalancer.PolarisLoadBalancerAutoConfiguration; +import com.tencent.cloud.polaris.registry.PolarisServiceRegistryAutoConfiguration; +import com.tencent.cloud.common.metadata.StaticMetadataManager; +import com.tencent.cloud.rpc.enhancement.stat.config.PolarisStatProperties; +import com.tencent.cloud.polaris.registry.PolarisAutoServiceRegistration; +import com.tencent.cloud.polaris.registry.PolarisRegistration; +import com.tencent.cloud.polaris.registry.PolarisServiceRegistry; +import com.tencent.polaris.client.api.SDKContext; +import com.tencent.cloud.polaris.discovery.refresh.PolarisRefreshConfiguration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.beans.factory.support.BeanDefinitionBuilder; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; +import org.springframework.cloud.loadbalancer.config.LoadBalancerAutoConfiguration; +import org.springframework.core.env.Environment; + +public class RegistryBeanInjector implements BeanInjector { + + private static final Logger LOGGER = LoggerFactory.getLogger(RegistryBeanInjector.class); + + private final AtomicBoolean bootstrapLoaded = new AtomicBoolean(false); + + @Override + public String getModule() { + return "spring-cloud-starter-tencent-polaris-discovery"; + } + + @Override + public void onBootstrapStartup(Object configurationParser, Constructor configClassCreator, Method processConfigurationClass, BeanDefinitionRegistry registry, Environment environment) { + LOGGER.info("[PolarisJavaAgent] success to inject bootstrap bean definitions for module {}", getModule()); + } + + @Override + public void onApplicationStartup(Object configurationParser, Constructor configClassCreator, Method processConfigurationClass, BeanDefinitionRegistry registry, Environment environment) { + Object polarisDiscoveryAutoConfiguration = ReflectionUtils.invokeConstructor(configClassCreator, PolarisDiscoveryAutoConfiguration.class, "polarisDiscoveryAutoConfiguration"); + ReflectionUtils.invokeMethod(processConfigurationClass, configurationParser, polarisDiscoveryAutoConfiguration, cn.polarismesh.agent.plugin.spring.cloud.con.Constant.DEFAULT_EXCLUSION_FILTER); + registry.registerBeanDefinition("polarisDiscoveryAutoConfiguration", BeanDefinitionBuilder.genericBeanDefinition( + PolarisDiscoveryAutoConfiguration.class).getBeanDefinition()); + Object polarisDiscoveryClientConfiguration = ReflectionUtils.invokeConstructor(configClassCreator, PolarisDiscoveryClientConfiguration.class, "polarisDiscoveryClientConfiguration"); + ReflectionUtils.invokeMethod(processConfigurationClass, configurationParser, polarisDiscoveryClientConfiguration, cn.polarismesh.agent.plugin.spring.cloud.con.Constant.DEFAULT_EXCLUSION_FILTER); + registry.registerBeanDefinition("polarisDiscoveryClientConfiguration", BeanDefinitionBuilder.genericBeanDefinition( + PolarisDiscoveryClientConfiguration.class).getBeanDefinition()); + Object polarisReactiveDiscoveryClientConfiguration = ReflectionUtils.invokeConstructor(configClassCreator, PolarisReactiveDiscoveryClientConfiguration.class, "polarisReactiveDiscoveryClientConfiguration"); + ReflectionUtils.invokeMethod(processConfigurationClass, configurationParser, polarisReactiveDiscoveryClientConfiguration, cn.polarismesh.agent.plugin.spring.cloud.con.Constant.DEFAULT_EXCLUSION_FILTER); + registry.registerBeanDefinition("polarisReactiveDiscoveryClientConfiguration", BeanDefinitionBuilder.genericBeanDefinition( + PolarisReactiveDiscoveryClientConfiguration.class).getBeanDefinition()); + Object polarisRefreshConfiguration = ReflectionUtils.invokeConstructor(configClassCreator, PolarisRefreshConfiguration.class, "polarisRefreshConfiguration"); + ReflectionUtils.invokeMethod(processConfigurationClass, configurationParser, polarisRefreshConfiguration, cn.polarismesh.agent.plugin.spring.cloud.con.Constant.DEFAULT_EXCLUSION_FILTER); + registry.registerBeanDefinition("polarisRefreshConfiguration", BeanDefinitionBuilder.genericBeanDefinition( + PolarisRefreshConfiguration.class).getBeanDefinition()); + Object polarisServiceRegistryAutoConfiguration = ReflectionUtils.invokeConstructor(configClassCreator, PolarisServiceRegistryAutoConfiguration.class, "polarisServiceRegistryAutoConfiguration"); + ReflectionUtils.invokeMethod(processConfigurationClass, configurationParser, polarisServiceRegistryAutoConfiguration, cn.polarismesh.agent.plugin.spring.cloud.con.Constant.DEFAULT_EXCLUSION_FILTER); + registry.registerBeanDefinition("polarisServiceRegistryAutoConfiguration", BeanDefinitionBuilder.genericBeanDefinition( + PolarisServiceRegistryAutoConfiguration.class).getBeanDefinition()); + Object polarisDiscoveryEndpointAutoConfiguration = ReflectionUtils.invokeConstructor(configClassCreator, PolarisDiscoveryEndpointAutoConfiguration.class, "polarisDiscoveryEndpointAutoConfiguration"); + ReflectionUtils.invokeMethod(processConfigurationClass, configurationParser, polarisDiscoveryEndpointAutoConfiguration, cn.polarismesh.agent.plugin.spring.cloud.con.Constant.DEFAULT_EXCLUSION_FILTER); + registry.registerBeanDefinition("polarisDiscoveryEndpointAutoConfiguration", BeanDefinitionBuilder.genericBeanDefinition( + PolarisDiscoveryEndpointAutoConfiguration.class).getBeanDefinition()); + Object discoveryPropertiesAutoConfiguration = ReflectionUtils.invokeConstructor(configClassCreator, DiscoveryPropertiesAutoConfiguration.class, "discoveryPropertiesAutoConfiguration"); + ReflectionUtils.invokeMethod(processConfigurationClass, configurationParser, discoveryPropertiesAutoConfiguration, cn.polarismesh.agent.plugin.spring.cloud.con.Constant.DEFAULT_EXCLUSION_FILTER); + registry.registerBeanDefinition("discoveryPropertiesAutoConfiguration", BeanDefinitionBuilder.genericBeanDefinition( + DiscoveryPropertiesAutoConfiguration.class).getBeanDefinition()); + Object discoveryPropertiesBootstrapAutoConfiguration = ReflectionUtils.invokeConstructor(configClassCreator, DiscoveryPropertiesBootstrapAutoConfiguration.class, "discoveryPropertiesBootstrapAutoConfiguration"); + ReflectionUtils.invokeMethod(processConfigurationClass, configurationParser, discoveryPropertiesBootstrapAutoConfiguration, cn.polarismesh.agent.plugin.spring.cloud.con.Constant.DEFAULT_EXCLUSION_FILTER); + registry.registerBeanDefinition("discoveryPropertiesBootstrapAutoConfiguration", BeanDefinitionBuilder.genericBeanDefinition( + DiscoveryPropertiesBootstrapAutoConfiguration.class).getBeanDefinition()); + LOGGER.info("[PolarisJavaAgent] success to inject application bean definitions for module {}", getModule()); + } +} \ No newline at end of file diff --git a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/inject/RouterBeanInjector.java b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/inject/RouterBeanInjector.java new file mode 100644 index 00000000..758cebce --- /dev/null +++ b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/inject/RouterBeanInjector.java @@ -0,0 +1,90 @@ +/* + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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.polarismesh.agent.plugin.spring.cloud.inject; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.util.Map; +import java.util.concurrent.atomic.AtomicBoolean; + +import cn.polarismesh.agent.core.common.utils.ClassUtils; +import cn.polarismesh.agent.core.common.utils.ReflectionUtils; +import cn.polarismesh.agent.plugin.spring.cloud.common.BeanInjector; +import cn.polarismesh.agent.plugin.spring.cloud.common.Constant; +import cn.polarismesh.agent.plugin.spring.cloud.common.Utils; +import com.tencent.cloud.polaris.DiscoveryPropertiesAutoConfiguration; +import com.tencent.cloud.polaris.contract.config.PolarisContractPropertiesAutoConfiguration; +import com.tencent.cloud.polaris.router.config.properties.PolarisNearByRouterProperties; +import com.tencent.cloud.polaris.DiscoveryPropertiesBootstrapAutoConfiguration; +import com.tencent.cloud.polaris.router.config.properties.PolarisRuleBasedRouterProperties; +import com.tencent.cloud.polaris.router.config.FeignAutoConfiguration; +import com.tencent.cloud.polaris.router.config.RouterAutoConfiguration; +import com.tencent.cloud.polaris.router.endpoint.PolarisRouterEndpointAutoConfiguration; +import com.tencent.cloud.polaris.router.config.properties.PolarisMetadataRouterProperties; +import com.tencent.cloud.polaris.router.config.RouterConfigModifierAutoConfiguration; +import com.tencent.cloud.rpc.enhancement.webclient.PolarisLoadBalancerClientRequestTransformer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.beans.factory.support.BeanDefinitionBuilder; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; +import org.springframework.core.env.Environment; +import org.springframework.core.io.ClassPathResource; + +public class RouterBeanInjector implements BeanInjector { + + private static final Logger LOGGER = LoggerFactory.getLogger(RouterBeanInjector.class); + @Override + public String getModule() { + return "spring-cloud-starter-tencent-polaris-router"; + } + + private final AtomicBoolean bootstrapLoaded = new AtomicBoolean(false); + + @Override + public void onBootstrapStartup(Object configurationParser, Constructor configClassCreator, Method processConfigurationClass, BeanDefinitionRegistry registry, Environment environment) { + Object polarisNearByRouterProperties = ReflectionUtils.invokeConstructor(configClassCreator, PolarisNearByRouterProperties.class, "polarisNearByRouterProperties"); + ReflectionUtils.invokeMethod(processConfigurationClass, configurationParser, polarisNearByRouterProperties, Constant.DEFAULT_EXCLUSION_FILTER); + registry.registerBeanDefinition("polarisNearByRouterProperties", BeanDefinitionBuilder.genericBeanDefinition( + PolarisNearByRouterProperties.class).getBeanDefinition()); + Object polarisMetadataRouterProperties = ReflectionUtils.invokeConstructor(configClassCreator, PolarisMetadataRouterProperties.class, "polarisMetadataRouterProperties"); + ReflectionUtils.invokeMethod(processConfigurationClass, configurationParser, polarisMetadataRouterProperties, Constant.DEFAULT_EXCLUSION_FILTER); + registry.registerBeanDefinition("polarisMetadataRouterProperties", BeanDefinitionBuilder.genericBeanDefinition( + PolarisMetadataRouterProperties.class).getBeanDefinition()); + Object polarisRuleBasedRouterProperties = ReflectionUtils.invokeConstructor(configClassCreator, PolarisRuleBasedRouterProperties.class, "polarisRuleBasedRouterProperties"); + ReflectionUtils.invokeMethod(processConfigurationClass, configurationParser, polarisRuleBasedRouterProperties, Constant.DEFAULT_EXCLUSION_FILTER); + registry.registerBeanDefinition("polarisRuleBasedRouterProperties", BeanDefinitionBuilder.genericBeanDefinition( + PolarisRuleBasedRouterProperties.class).getBeanDefinition()); + Object routerConfigModifierAutoConfiguration = ReflectionUtils.invokeConstructor(configClassCreator, RouterConfigModifierAutoConfiguration.class, "routerConfigModifierAutoConfiguration"); + ReflectionUtils.invokeMethod(processConfigurationClass, configurationParser, routerConfigModifierAutoConfiguration, Constant.DEFAULT_EXCLUSION_FILTER); + registry.registerBeanDefinition("routerConfigModifierAutoConfiguration", BeanDefinitionBuilder.genericBeanDefinition( + RouterConfigModifierAutoConfiguration.class).getBeanDefinition()); + Object polarisContractPropertiesAutoConfiguration = ReflectionUtils.invokeConstructor(configClassCreator, PolarisContractPropertiesAutoConfiguration.class, "polarisContractPropertiesAutoConfiguration"); + ReflectionUtils.invokeMethod(processConfigurationClass, configurationParser, polarisContractPropertiesAutoConfiguration, Constant.DEFAULT_EXCLUSION_FILTER); + registry.registerBeanDefinition("polarisContractPropertiesAutoConfiguration", BeanDefinitionBuilder.genericBeanDefinition( + PolarisContractPropertiesAutoConfiguration.class).getBeanDefinition()); + LOGGER.info("[PolarisJavaAgent] success to inject bootstrap bean definitions for module {}", getModule()); + } + + + @Override + @SuppressWarnings("unchecked") + public void onApplicationStartup(Object configurationParser, Constructor configClassCreator, Method processConfigurationClass, BeanDefinitionRegistry registry, Environment environment) { + LOGGER.info("[PolarisJavaAgent] success to inject application bean definitions for module {}", getModule()); + } +} diff --git a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/inject/RpcEnhancementBeanInjector.java b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/inject/RpcEnhancementBeanInjector.java new file mode 100644 index 00000000..73a487d1 --- /dev/null +++ b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/inject/RpcEnhancementBeanInjector.java @@ -0,0 +1,76 @@ +/* + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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.polarismesh.agent.plugin.spring.cloud.inject; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.util.concurrent.atomic.AtomicBoolean; + +import cn.polarismesh.agent.core.common.utils.ClassUtils; +import cn.polarismesh.agent.core.common.utils.ReflectionUtils; +import cn.polarismesh.agent.plugin.spring.cloud.common.BeanInjector; +import cn.polarismesh.agent.plugin.spring.cloud.common.Constant; +import cn.polarismesh.agent.plugin.spring.cloud.common.Utils; +import com.tencent.cloud.rpc.enhancement.config.RpcEnhancementAutoConfiguration; +import com.tencent.cloud.rpc.enhancement.config.RpcEnhancementBootstrapConfiguration; +import com.tencent.cloud.rpc.enhancement.stat.config.PolarisStatPropertiesAutoConfiguration; +import com.tencent.cloud.rpc.enhancement.stat.config.PolarisStatPropertiesBootstrapConfiguration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.beans.factory.support.BeanDefinitionBuilder; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; +import org.springframework.core.env.Environment; + +public class RpcEnhancementBeanInjector implements BeanInjector { + + private static final Logger LOGGER = LoggerFactory.getLogger(RpcEnhancementBeanInjector.class); + + private final AtomicBoolean bootstrapLoaded = new AtomicBoolean(false); + + @Override + public String getModule() { + return "spring-cloud-tencent-rpc-enhancement"; + } + + @Override + public void onBootstrapStartup(Object configurationParser, Constructor configClassCreator, Method processConfigurationClass, BeanDefinitionRegistry registry, Environment environment) { + LOGGER.info("[PolarisJavaAgent] success to inject bootstrap bean definitions for module {}", getModule()); + } + + @Override + public void onApplicationStartup(Object configurationParser, Constructor configClassCreator, Method processConfigurationClass, BeanDefinitionRegistry registry, Environment environment) { + Object polarisStatPropertiesAutoConfiguration = ReflectionUtils.invokeConstructor(configClassCreator, PolarisStatPropertiesAutoConfiguration.class, "polarisStatPropertiesAutoConfiguration"); + ReflectionUtils.invokeMethod(processConfigurationClass, configurationParser, polarisStatPropertiesAutoConfiguration, Constant.DEFAULT_EXCLUSION_FILTER); + registry.registerBeanDefinition("polarisStatPropertiesAutoConfiguration", BeanDefinitionBuilder.genericBeanDefinition( + PolarisStatPropertiesAutoConfiguration.class).getBeanDefinition()); + Object polarisStatPropertiesBootstrapConfiguration = ReflectionUtils.invokeConstructor(configClassCreator, PolarisStatPropertiesBootstrapConfiguration.class, "polarisStatPropertiesBootstrapConfiguration"); + ReflectionUtils.invokeMethod(processConfigurationClass, configurationParser, polarisStatPropertiesBootstrapConfiguration, Constant.DEFAULT_EXCLUSION_FILTER); + registry.registerBeanDefinition("polarisStatPropertiesBootstrapConfiguration", BeanDefinitionBuilder.genericBeanDefinition( + PolarisStatPropertiesBootstrapConfiguration.class).getBeanDefinition()); + Object rpcEnhancementAutoConfiguration = ReflectionUtils.invokeConstructor(configClassCreator, RpcEnhancementAutoConfiguration.class, "rpcEnhancementAutoConfiguration"); + ReflectionUtils.invokeMethod(processConfigurationClass, configurationParser, rpcEnhancementAutoConfiguration, Constant.DEFAULT_EXCLUSION_FILTER); + registry.registerBeanDefinition("rpcEnhancementAutoConfiguration", BeanDefinitionBuilder.genericBeanDefinition( + RpcEnhancementAutoConfiguration.class).getBeanDefinition()); + Object rpcEnhancementBootstrapConfiguration = ReflectionUtils.invokeConstructor(configClassCreator, RpcEnhancementBootstrapConfiguration.class, "rpcEnhancementBootstrapConfiguration"); + ReflectionUtils.invokeMethod(processConfigurationClass, configurationParser, rpcEnhancementBootstrapConfiguration, Constant.DEFAULT_EXCLUSION_FILTER); + registry.registerBeanDefinition("rpcEnhancementBootstrapConfiguration", BeanDefinitionBuilder.genericBeanDefinition( + RpcEnhancementBootstrapConfiguration.class).getBeanDefinition()); + LOGGER.info("[PolarisJavaAgent] success to inject application bean definitions for module {}", getModule()); + } +} diff --git a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/interceptor/ApplicationContextAwareInterceptor.java b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/interceptor/ApplicationContextAwareInterceptor.java deleted file mode 100644 index 2b0e79d4..00000000 --- a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/interceptor/ApplicationContextAwareInterceptor.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Tencent is pleased to support the open source community by making Polaris available. - * - * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * 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.polarismesh.agent.plugin.spring.cloud.interceptor; - -import java.util.Arrays; -import java.util.List; - -import cn.polarismesh.agent.core.common.logger.CommonLogger; -import cn.polarismesh.agent.core.common.logger.StdoutCommonLoggerFactory; -import cn.polarismesh.agent.plugin.spring.cloud.common.Holder; -import cn.polarismesh.agent.plugin.spring.cloud.base.BaseBeanHandler; -import cn.polarismesh.agent.plugin.spring.cloud.discovery.DiscoveryHandler; -import cn.polarismesh.agent.plugin.spring.cloud.metadata.MetadataHandler; -import cn.polarismesh.agent.plugin.spring.cloud.router.RouterHandler; -import cn.polarismesh.agent.plugin.spring.cloud.rpc.RpcEnhancementHandler; -import com.tencent.cloud.common.metadata.MetadataContext; -import com.tencent.cloud.common.util.ApplicationContextAwareUtils; - -import org.springframework.beans.factory.support.DefaultListableBeanFactory; -import org.springframework.context.ApplicationContextAware; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.core.env.ConfigurableEnvironment; - -public class ApplicationContextAwareInterceptor extends BaseInterceptor { - - private static final CommonLogger logger = StdoutCommonLoggerFactory.INSTANCE - .getLogger(ApplicationContextAwareInterceptor.class.getCanonicalName()); - - @Override - public void onAfter(Object target, Object[] args, Object result, Throwable throwable) { - ConfigurableApplicationContext context = (ConfigurableApplicationContext) args[0]; - String enable = context.getEnvironment().getProperty("spring.cloud.polaris.enabled"); - if (null != enable && !Boolean.parseBoolean(enable)) { - logger.warn("polaris is disabled, no polaris inject actions will be taken"); - return; - } - ApplicationContextAwareUtils utils = new ApplicationContextAwareUtils(); - - // MetadataContext 需要读取到 agent 配置的内容 - AnnotationConfigApplicationContext tmpCtx = new AnnotationConfigApplicationContext((DefaultListableBeanFactory) context.getBeanFactory()); - tmpCtx.setEnvironment((ConfigurableEnvironment) Holder.getEnvironment()); - utils.setApplicationContext(tmpCtx); - // 触发 MetadataContext 的加载机制 - MetadataContext metadataContext = new MetadataContext(); - // 重写 SCT 中错误的 LOCAL_SERVICE 信息 - MetadataContext.LOCAL_SERVICE = Holder.getDiscoveryProperties().getService(); - - // 设置为真正的 ApplicationContext - utils.setApplicationContext(context); - buildAwares().forEach(aware -> aware.setApplicationContext(context)); - } - - private List buildAwares() { - return Arrays.asList( - new BaseBeanHandler(), - new DiscoveryHandler(), - new RpcEnhancementHandler(), - new MetadataHandler(), - new RouterHandler() - ); - } -} diff --git a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/interceptor/BaseInterceptor.java b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/interceptor/BaseInterceptor.java deleted file mode 100644 index ba620402..00000000 --- a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/interceptor/BaseInterceptor.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Tencent is pleased to support the open source community by making Polaris available. - * - * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * 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.polarismesh.agent.plugin.spring.cloud.interceptor; - -import java.lang.reflect.Field; -import java.util.concurrent.atomic.AtomicBoolean; - -import cn.polarismesh.agent.core.common.exception.PolarisAgentException; -import cn.polarismesh.agent.core.extension.interceptor.Interceptor; -import cn.polarismesh.agent.plugin.spring.cloud.common.Holder; -import com.tencent.cloud.common.metadata.MetadataContextHolder; - -import org.springframework.util.ReflectionUtils; - -/** - * @author liaochuntao - */ -public abstract class BaseInterceptor implements Interceptor { - - private static final AtomicBoolean initialize = new AtomicBoolean(false); - - @Override - public final void before(Object target, Object[] args) { - init(); - onBefore(target, args); - } - - @Override - public final void after(Object target, Object[] args, Object result, Throwable throwable) { - init(); - onAfter(target, args, result, throwable); - } - - public void onBefore(Object target, Object[] args) { - - } - - public void onAfter(Object target, Object[] args, Object result, Throwable throwable) { - - } - - private void init() { - if (initialize.compareAndSet(false, true)) { - try { - Holder.init(); - - Field field = MetadataContextHolder.class.getDeclaredField("metadataLocalProperties"); - field.setAccessible(true); - ReflectionUtils.setField(field, null, Holder.getLocalProperties()); - - field = MetadataContextHolder.class.getDeclaredField("staticMetadataManager"); - field.setAccessible(true); - ReflectionUtils.setField(field, null, Holder.getStaticMetadataManager()); - } - catch (Exception e) { - throw new PolarisAgentException("setValueByFieldName", e); - } - } - } -} diff --git a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/interceptor/ConfigurationInjectInterceptor.java b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/interceptor/ConfigurationInjectInterceptor.java deleted file mode 100644 index 526f75e8..00000000 --- a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/interceptor/ConfigurationInjectInterceptor.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Tencent is pleased to support the open source community by making Polaris available. - * - * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * 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.polarismesh.agent.plugin.spring.cloud.interceptor; - -import cn.polarismesh.agent.plugin.spring.cloud.common.Holder; -import com.tencent.cloud.polaris.config.adapter.PolarisConfigFileLocator; -import com.tencent.polaris.configuration.api.core.ConfigFileService; -import com.tencent.polaris.configuration.factory.ConfigFileServiceFactory; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent; -import org.springframework.boot.env.EnvironmentPostProcessor; -import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.core.env.PropertiesPropertySource; - -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -/** - * {@link org.springframework.boot.util.Instantiator#instantiate(Stream)} - * - * @author liaochuntao - */ -public class ConfigurationInjectInterceptor extends BaseInterceptor { - - private static final Logger LOGGER = LoggerFactory.getLogger(ConfigurationInjectInterceptor.class); - - @Override - public void onBefore(Object target, Object[] args) { - ApplicationEnvironmentPreparedEvent event = (ApplicationEnvironmentPreparedEvent) args[0]; - - List external = new ArrayList<>(); - // 插入禁止 spring cloud alibaba 的一切能力 - external.add(new DisableSpringCloudAlibabaAbility()); - - for (EnvironmentPostProcessor processor : external) { - processor.postProcessEnvironment(event.getEnvironment(), event.getSpringApplication()); - } - } - - private static class DisableSpringCloudAlibabaAbility implements EnvironmentPostProcessor { - - @Override - public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { - disableSpringCloudAlibabaAbility(environment); - } - - private void disableSpringCloudAlibabaAbility(ConfigurableEnvironment environment) { -// String disableSCA = "__disable__sca__"; -// -// Properties properties = new Properties(); -// properties.setProperty("spring.cloud.sentinel.enabled", "false"); -// properties.setProperty("spring.cloud.nacos.discovery.watch.enabled", "false"); -// properties.setProperty("spring.cloud.loadbalancer.cache.enabled", "false"); -// properties.setProperty("spring.cloud.nacos.config.enabled", "false"); - - String disableCheck = "__disable__check__"; - Properties properties = new Properties(); - properties.setProperty("spring.cloud.polaris.config.import-check.enabled", "false"); - environment.getPropertySources().addFirst(new PropertiesPropertySource(disableCheck, properties)); - - LOGGER.info("[PolarisAgent] disable spring cloud alibaba all ability"); - } - } - -} \ No newline at end of file diff --git a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/interceptor/ConfigurationParserInterceptor.java b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/interceptor/ConfigurationParserInterceptor.java new file mode 100644 index 00000000..afa31b0a --- /dev/null +++ b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/interceptor/ConfigurationParserInterceptor.java @@ -0,0 +1,157 @@ +/* + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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.polarismesh.agent.plugin.spring.cloud.interceptor; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.function.Predicate; + +import cn.polarismesh.agent.core.common.utils.ClassUtils; +import cn.polarismesh.agent.core.common.utils.ReflectionUtils; +import cn.polarismesh.agent.core.extension.interceptor.Interceptor; +import cn.polarismesh.agent.plugin.spring.cloud.common.BeanInjector; +import cn.polarismesh.agent.plugin.spring.cloud.common.PropertiesProvider; +import cn.polarismesh.agent.plugin.spring.cloud.common.Utils; +import cn.polarismesh.agent.plugin.spring.cloud.inject.CommonBeanInjector; +import cn.polarismesh.agent.plugin.spring.cloud.inject.ConfigBeanInjector; +import cn.polarismesh.agent.plugin.spring.cloud.inject.LoadbalancerBeanInjector; +import cn.polarismesh.agent.plugin.spring.cloud.inject.LosslessBeanInjector; +import cn.polarismesh.agent.plugin.spring.cloud.inject.MetadataTransferBeanInjector; +import cn.polarismesh.agent.plugin.spring.cloud.inject.PolarisContextBeanInjector; +import cn.polarismesh.agent.plugin.spring.cloud.inject.RegistryBeanInjector; +import cn.polarismesh.agent.plugin.spring.cloud.inject.RouterBeanInjector; +import cn.polarismesh.agent.plugin.spring.cloud.inject.RpcEnhancementBeanInjector; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.beans.factory.annotation.AnnotatedGenericBeanDefinition; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.BeanDefinitionHolder; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.env.Environment; +import org.springframework.core.env.MutablePropertySources; +import org.springframework.core.env.PropertiesPropertySource; + +public class ConfigurationParserInterceptor implements Interceptor { + + private static final Logger LOGGER = LoggerFactory.getLogger(ConfigurationParserInterceptor.class); + + private final List beanInjectors = new ArrayList<>(); + + private boolean judge = false; + + public ConfigurationParserInterceptor() { + beanInjectors.add(new CommonBeanInjector()); + beanInjectors.add(new MetadataTransferBeanInjector()); + beanInjectors.add(new RegistryBeanInjector()); + beanInjectors.add(new RpcEnhancementBeanInjector()); + beanInjectors.add(new PolarisContextBeanInjector()); + beanInjectors.add(new RouterBeanInjector()); + beanInjectors.add(new LoadbalancerBeanInjector()); + beanInjectors.add(new ConfigBeanInjector()); + } + + + private static boolean isMainBeanDefinition(BeanDefinitionHolder beanDefinitionHolder) { + BeanDefinition beanDefinition = beanDefinitionHolder.getBeanDefinition(); + if (beanDefinition instanceof AnnotatedGenericBeanDefinition) { + AnnotatedGenericBeanDefinition annotatedBeanDefinition = (AnnotatedGenericBeanDefinition)beanDefinition; + Class beanClass = annotatedBeanDefinition.getBeanClass(); + Annotation[] annotations = beanClass.getAnnotations(); + for (Annotation annotation : annotations) { + Class aClass = annotation.annotationType(); + if ("org.springframework.boot.autoconfigure.SpringBootApplication".equals(aClass.getCanonicalName())) { + return true; + } + } + } + return false; + } + + @Override + public void after(Object target, Object[] args, Object result, Throwable throwable) { + Set candidates = (Set) args[0]; + BeanDefinitionHolder beanDefinitionHolder = (BeanDefinitionHolder) candidates.iterator().next(); + if ("bootstrapImportSelectorConfiguration".equals(beanDefinitionHolder.getBeanName())) { + // bootstrap + Class clazz = ClassUtils.getClazz("org.springframework.context.annotation.ConfigurationClass", null); + Constructor constructor = ReflectionUtils.accessibleConstructor(clazz, Class.class, String.class); + Method processConfigurationClass = ReflectionUtils.findMethod(target.getClass(), "processConfigurationClass", clazz, Predicate.class); + ReflectionUtils.makeAccessible(processConfigurationClass); + + BeanDefinitionRegistry registry = (BeanDefinitionRegistry) ReflectionUtils.getObjectByFieldName(target, "registry"); + Environment environment = (Environment) ReflectionUtils.getObjectByFieldName(target, "environment"); + for (BeanInjector beanInjector : beanInjectors) { + LOGGER.info("[PolarisJavaAgent] start to inject bootstrap bean definitions in module {}", beanInjector.getModule()); + beanInjector.onBootstrapStartup(target, constructor, processConfigurationClass, registry, environment); + } + LOGGER.info("[PolarisJavaAgent] successfully injected spring cloud tencent bootstrap bean definitions"); + + } else if (isMainBeanDefinition(beanDefinitionHolder)) { + Class clazz = ClassUtils.getClazz("org.springframework.context.annotation.ConfigurationClass", null); + Constructor constructor = ReflectionUtils.accessibleConstructor(clazz, Class.class, String.class); + Method processConfigurationClass = ReflectionUtils.findMethod(target.getClass(), "processConfigurationClass", clazz, Predicate.class); + ReflectionUtils.makeAccessible(processConfigurationClass); + + BeanDefinitionRegistry registry = (BeanDefinitionRegistry) ReflectionUtils.getObjectByFieldName(target, "registry"); + Environment environment = (Environment) ReflectionUtils.getObjectByFieldName(target, "environment"); + for (BeanInjector beanInjector : beanInjectors) { + if (!(beanInjector instanceof CommonBeanInjector)) { + LOGGER.info("[PolarisJavaAgent] start to inject application bean definitions in module {}", beanInjector.getModule()); + beanInjector.onApplicationStartup(target, constructor, processConfigurationClass, registry, environment); + } + } + LOGGER.info("[PolarisJavaAgent] successfully injected spring cloud tencent application bean definitions"); + + } + } + + @Override + public void before(Object target, Object[] args) { + Set candidates = (Set) args[0]; + BeanDefinitionHolder beanDefinitionHolder = (BeanDefinitionHolder) candidates.iterator().next(); + if (isMainBeanDefinition(beanDefinitionHolder)) { + Class clazz = ClassUtils.getClazz("org.springframework.context.annotation.ConfigurationClass", null); + Constructor constructor = ReflectionUtils.accessibleConstructor(clazz, Class.class, String.class); + Method processConfigurationClass = ReflectionUtils.findMethod(target.getClass(), "processConfigurationClass", clazz, Predicate.class); + ReflectionUtils.makeAccessible(processConfigurationClass); + + BeanDefinitionRegistry registry = (BeanDefinitionRegistry) ReflectionUtils.getObjectByFieldName(target, "registry"); + Environment environment = (Environment) ReflectionUtils.getObjectByFieldName(target, "environment"); + for (BeanInjector beanInjector : beanInjectors) { + if (beanInjector instanceof CommonBeanInjector) { + LOGGER.info("[PolarisJavaAgent] start to inject application bean definitions in module {}", beanInjector.getModule()); + beanInjector.onApplicationStartup(target, constructor, processConfigurationClass, registry, environment); + } + } + LOGGER.info("[PolarisJavaAgent] successfully injected spring cloud tencent application bean definitions"); + + } + } + + + + +} + + diff --git a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/interceptor/ConfigurationPostProcessorInterceptor.java b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/interceptor/ConfigurationPostProcessorInterceptor.java new file mode 100644 index 00000000..b444ed27 --- /dev/null +++ b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/interceptor/ConfigurationPostProcessorInterceptor.java @@ -0,0 +1,55 @@ +/* + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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.polarismesh.agent.plugin.spring.cloud.interceptor; + +import java.util.List; + +import cn.polarismesh.agent.core.common.utils.ReflectionUtils; +import cn.polarismesh.agent.core.extension.interceptor.Interceptor; +import cn.polarismesh.agent.plugin.spring.cloud.common.PropertiesProvider; +import cn.polarismesh.agent.plugin.spring.cloud.common.Utils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.env.MutablePropertySources; +import org.springframework.core.env.PropertiesPropertySource; + +public class ConfigurationPostProcessorInterceptor implements Interceptor { + private static final Logger LOGGER = LoggerFactory.getLogger(ConfigurationPostProcessorInterceptor.class); + + @Override + public void before(Object target, Object[] args) { + ConfigurableEnvironment environment = (ConfigurableEnvironment) ReflectionUtils.getObjectByFieldName(target, "environment"); + if (!Utils.checkSpringApplicationNameExists(environment)) { + LOGGER.warn("[PolarisJavaAgent] skip inject polaris java agent configuration for no spring application name"); + return; + } + List propertySources = PropertiesProvider.loadPropertiesSource(); + MutablePropertySources mutablePropertySources = environment.getPropertySources(); + if (mutablePropertySources.contains(propertySources.get(0).getName())) { + return; + } + for (PropertiesPropertySource propertiesPropertySource : propertySources) { + LOGGER.info("[PolarisJavaAgent] start to add propertiesPropertySource {}", propertiesPropertySource.getName()); + environment.getPropertySources().addLast(propertiesPropertySource); + } + LOGGER.info("[PolarisJavaAgent] successfully injected agent properties into environment, size is " + propertySources.size()); + } + +} diff --git a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/interceptor/RegisterBeanInterceptor.java b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/interceptor/RegisterBeanInterceptor.java new file mode 100644 index 00000000..e5a5b2b5 --- /dev/null +++ b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/interceptor/RegisterBeanInterceptor.java @@ -0,0 +1,48 @@ +/* + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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.polarismesh.agent.plugin.spring.cloud.interceptor; + +import java.util.HashSet; +import java.util.Set; + +import cn.polarismesh.agent.core.extension.interceptor.Interceptor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.beans.factory.config.BeanDefinition; + +public class RegisterBeanInterceptor implements Interceptor { + + private static final Logger LOGGER = LoggerFactory.getLogger(RegisterBeanInterceptor.class); + + private final Set primaryBeanNames = new HashSet<>(); + + public RegisterBeanInterceptor() { + } + + @Override + public void before(Object target, Object[] args) { + String beanName = (String) args[0]; + if (!primaryBeanNames.contains(beanName)) { + return; + } + BeanDefinition beanDefinition = (BeanDefinition) args[1]; + beanDefinition.setPrimary(true); + LOGGER.info("[PolarisJavaAgent] bean {} has been made primary", beanName); + } +} diff --git a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/interceptor/SpringFactoriesLoaderInterceptor.java b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/interceptor/SpringFactoriesLoaderInterceptor.java new file mode 100644 index 00000000..20741f09 --- /dev/null +++ b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/interceptor/SpringFactoriesLoaderInterceptor.java @@ -0,0 +1,97 @@ +/* + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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.polarismesh.agent.plugin.spring.cloud.interceptor; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; + +import cn.polarismesh.agent.core.extension.interceptor.Interceptor; +import cn.polarismesh.agent.plugin.spring.cloud.common.BeanInjector; +import cn.polarismesh.agent.plugin.spring.cloud.inject.CommonBeanInjector; +import cn.polarismesh.agent.plugin.spring.cloud.inject.ConfigBeanInjector; +import cn.polarismesh.agent.plugin.spring.cloud.inject.LoadbalancerBeanInjector; +import cn.polarismesh.agent.plugin.spring.cloud.inject.LosslessBeanInjector; +import cn.polarismesh.agent.plugin.spring.cloud.inject.MetadataTransferBeanInjector; +import cn.polarismesh.agent.plugin.spring.cloud.inject.PolarisContextBeanInjector; +import cn.polarismesh.agent.plugin.spring.cloud.inject.RegistryBeanInjector; +import cn.polarismesh.agent.plugin.spring.cloud.inject.RouterBeanInjector; +import cn.polarismesh.agent.plugin.spring.cloud.inject.RpcEnhancementBeanInjector; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SpringFactoriesLoaderInterceptor implements Interceptor { + + private static final Logger LOGGER = LoggerFactory.getLogger(SpringFactoriesLoaderInterceptor.class); + + private final List beanInjectors = new ArrayList<>(); + + private final Map parsedClasses = new ConcurrentHashMap<>(); + + public SpringFactoriesLoaderInterceptor() { + beanInjectors.add(new RegistryBeanInjector()); + beanInjectors.add(new RpcEnhancementBeanInjector()); + beanInjectors.add(new PolarisContextBeanInjector()); + beanInjectors.add(new ConfigBeanInjector()); + beanInjectors.add(new RouterBeanInjector()); + beanInjectors.add(new CommonBeanInjector()); + beanInjectors.add(new MetadataTransferBeanInjector()); + beanInjectors.add(new LoadbalancerBeanInjector()); + } + + + @SuppressWarnings("unchecked") + @Override + public void after(Object target, Object[] args, Object result, Throwable throwable) { + if (args[0] == null) { + return; + } + ClassLoader classLoader = (ClassLoader)args[0]; + parsedClasses.computeIfAbsent(classLoader, new Function() { + @Override + public Boolean apply(ClassLoader classLoader) { + Map> loadedClasses = (Map>) result; + + for (BeanInjector beanInjector : beanInjectors) { + LOGGER.info("[PolarisJavaAgent] start to inject JNI definition in module {}", beanInjector.getModule()); + Map> classNames = beanInjector.getClassNameForType(); + if (classNames.isEmpty()) { + continue; + } + for (Map.Entry> entry : classNames.entrySet()) { + List existsValues = loadedClasses.get(entry.getKey()); + List toAddValues = entry.getValue(); + if (null != existsValues) { + for (String toAddValue : toAddValues) { + if (existsValues.contains(toAddValue)) { + continue; + } + existsValues.add(toAddValue); + } + } else { + classNames.put(entry.getKey(), toAddValues); + } + } + } + return true; + } + }); + } +} diff --git a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/metadata/MetadataHandler.java b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/metadata/MetadataHandler.java deleted file mode 100644 index b248ec4b..00000000 --- a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/metadata/MetadataHandler.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Tencent is pleased to support the open source community by making Polaris available. - * - * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * 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.polarismesh.agent.plugin.spring.cloud.metadata; - -import cn.polarismesh.agent.plugin.spring.cloud.base.AbstractContextHandler; -import com.tencent.cloud.metadata.config.MetadataTransferAutoConfiguration; - -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.support.BeanDefinitionBuilder; -import org.springframework.beans.factory.support.DefaultListableBeanFactory; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ConfigurableApplicationContext; - -public class MetadataHandler extends AbstractContextHandler { - - @Override - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - registerBean(applicationContext, "metadataTransferAutoConfiguration", (ctx, name) -> { - ConfigurableApplicationContext cfgCtx = (ConfigurableApplicationContext) ctx; - DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) cfgCtx.getBeanFactory(); - beanFactory.registerBeanDefinition(name, - BeanDefinitionBuilder.genericBeanDefinition(MetadataTransferAutoConfiguration.class).getBeanDefinition()); - }); - } - -} diff --git a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/router/RouterHandler.java b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/router/RouterHandler.java deleted file mode 100644 index bebe86c5..00000000 --- a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/router/RouterHandler.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Tencent is pleased to support the open source community by making Polaris available. - * - * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * 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.polarismesh.agent.plugin.spring.cloud.router; - -import java.util.ArrayList; -import java.util.Map; -import java.util.function.Supplier; - -import cn.polarismesh.agent.core.common.utils.ClassUtils; -import cn.polarismesh.agent.plugin.spring.cloud.common.Holder; -import cn.polarismesh.agent.plugin.spring.cloud.base.AbstractContextHandler; -import com.tencent.cloud.polaris.context.PolarisSDKContextManager; -import com.tencent.cloud.polaris.router.PolarisRouterServiceInstanceListSupplier; -import com.tencent.cloud.polaris.router.config.FeignAutoConfiguration; -import com.tencent.cloud.polaris.router.config.RouterAutoConfiguration; -import com.tencent.cloud.polaris.router.config.properties.PolarisMetadataRouterProperties; -import com.tencent.cloud.polaris.router.config.properties.PolarisNearByRouterProperties; -import com.tencent.cloud.polaris.router.config.properties.PolarisRuleBasedRouterProperties; -import com.tencent.cloud.polaris.router.spi.RouterRequestInterceptor; -import com.tencent.cloud.polaris.router.spi.RouterResponseInterceptor; -import com.tencent.cloud.rpc.enhancement.transformer.InstanceTransformer; - -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.support.BeanDefinitionBuilder; -import org.springframework.beans.factory.support.DefaultListableBeanFactory; -import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ConfigurableApplicationContext; - -public class RouterHandler extends AbstractContextHandler { - - @Override - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - registerBean(applicationContext, "polarisMetadataRouterProperties", (ctx, name) -> { - ConfigurableApplicationContext cfgCtx = (ConfigurableApplicationContext) ctx; - DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) cfgCtx.getBeanFactory(); - beanFactory.registerBeanDefinition(name, - BeanDefinitionBuilder.genericBeanDefinition(PolarisMetadataRouterProperties.class, new Supplier() { - @Override - public PolarisMetadataRouterProperties get() { - return Holder.getMetadataRouterProperties(); - } - }).getBeanDefinition()); - }); - registerBean(applicationContext, "polarisNearByRouterProperties", (ctx, name) -> { - ConfigurableApplicationContext cfgCtx = (ConfigurableApplicationContext) ctx; - DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) cfgCtx.getBeanFactory(); - beanFactory.registerBeanDefinition(name, - BeanDefinitionBuilder.genericBeanDefinition(PolarisNearByRouterProperties.class, new Supplier() { - @Override - public PolarisNearByRouterProperties get() { - return Holder.getNearByRouterProperties(); - } - }).getBeanDefinition()); - }); - registerBean(applicationContext, "polarisRuleBasedRouterProperties", (ctx, name) -> { - ConfigurableApplicationContext cfgCtx = (ConfigurableApplicationContext) ctx; - DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) cfgCtx.getBeanFactory(); - beanFactory.registerBeanDefinition(name, - BeanDefinitionBuilder.genericBeanDefinition(PolarisRuleBasedRouterProperties.class, new Supplier() { - @Override - public PolarisRuleBasedRouterProperties get() { - return Holder.getRouterProperties(); - } - }).getBeanDefinition()); - }); - registerBean(applicationContext, "routerAutoConfiguration", (ctx, name) -> { - ConfigurableApplicationContext cfgCtx = (ConfigurableApplicationContext) ctx; - DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) cfgCtx.getBeanFactory(); - beanFactory.registerBeanDefinition(name, - BeanDefinitionBuilder.genericBeanDefinition(RouterAutoConfiguration.class).getBeanDefinition()); - }); - if (null != ClassUtils.getClazz("feign.RequestInterceptor", - Thread.currentThread().getContextClassLoader())) { - registerBean(applicationContext, "feignAutoConfiguration", (ctx, name) -> { - ConfigurableApplicationContext cfgCtx = (ConfigurableApplicationContext) ctx; - DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) cfgCtx.getBeanFactory(); - beanFactory.registerBeanDefinition(name, - BeanDefinitionBuilder.genericBeanDefinition(FeignAutoConfiguration.class).getBeanDefinition()); - }); - } - if (null != ClassUtils.getClazz("org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier", - Thread.currentThread().getContextClassLoader())) { - if (null != ClassUtils.getClazz("org.springframework.web.reactive.function.client.WebClient", Thread.currentThread() - .getContextClassLoader())) { - String reactiveEnableStr = applicationContext.getEnvironment() - .getProperty("spring.cloud.discovery.reactive.enabled"); - if (null == reactiveEnableStr || Boolean.parseBoolean(reactiveEnableStr)) { - registerBean(applicationContext, "polarisRouterDiscoveryClientServiceInstanceListSupplier", (ctx, name) -> { - ConfigurableApplicationContext cfgCtx = (ConfigurableApplicationContext) ctx; - DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) cfgCtx.getBeanFactory(); - beanFactory.registerBeanDefinition(name, BeanDefinitionBuilder.genericBeanDefinition(ServiceInstanceListSupplier.class, new Supplier() { - @Override - public ServiceInstanceListSupplier get() { - PolarisSDKContextManager polarisSDKContextManager = (PolarisSDKContextManager) applicationContext.getBean("polarisSDKContextManager"); - Map requestInterceptors = applicationContext.getBeansOfType(RouterRequestInterceptor.class); - Map responseInterceptors = applicationContext.getBeansOfType(RouterResponseInterceptor.class); - InstanceTransformer instanceTransformer = applicationContext.getBean("instanceTransformer", InstanceTransformer.class); - return new PolarisRouterServiceInstanceListSupplier( - ServiceInstanceListSupplier.builder().withDiscoveryClient() - .build((ConfigurableApplicationContext) applicationContext), - polarisSDKContextManager.getRouterAPI(), - new ArrayList<>(requestInterceptors.values()), - new ArrayList<>(responseInterceptors.values()), - instanceTransformer); - } - }).getBeanDefinition()); - }); - } - } - String blockingEnable = applicationContext.getEnvironment() - .getProperty("spring.cloud.discovery.blocking.enabled"); - if (null == blockingEnable || Boolean.parseBoolean(blockingEnable)) { - registerBean(applicationContext, "polarisRouterDiscoveryClientServiceInstanceListSupplier", (ctx, name) -> { - ConfigurableApplicationContext cfgCtx = (ConfigurableApplicationContext) ctx; - DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) cfgCtx.getBeanFactory(); - beanFactory.registerBeanDefinition(name, BeanDefinitionBuilder.genericBeanDefinition(ServiceInstanceListSupplier.class, new Supplier() { - @Override - public ServiceInstanceListSupplier get() { - PolarisSDKContextManager polarisSDKContextManager = (PolarisSDKContextManager) applicationContext.getBean("polarisSDKContextManager"); - Map requestInterceptors = applicationContext.getBeansOfType(RouterRequestInterceptor.class); - Map responseInterceptors = applicationContext.getBeansOfType(RouterResponseInterceptor.class); - InstanceTransformer instanceTransformer = applicationContext.getBean("instanceTransformer", InstanceTransformer.class); - return new PolarisRouterServiceInstanceListSupplier( - ServiceInstanceListSupplier.builder().withBlockingDiscoveryClient() - .build((ConfigurableApplicationContext) applicationContext), - polarisSDKContextManager.getRouterAPI(), - new ArrayList<>(requestInterceptors.values()), - new ArrayList<>(responseInterceptors.values()), - instanceTransformer); - } - }).getBeanDefinition()); - }); - - } -// registerBean(applicationContext, "loadBalancerConfiguration", (ctx, name) -> { -// ConfigurableApplicationContext cfgCtx = (ConfigurableApplicationContext) ctx; -// DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) cfgCtx.getBeanFactory(); -// beanFactory.registerBeanDefinition(name, -// BeanDefinitionBuilder.genericBeanDefinition(LoadBalancerConfiguration.class) -// .getBeanDefinition()); -// }); - } - } - -} diff --git a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/rpc/RpcEnhancementHandler.java b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/rpc/RpcEnhancementHandler.java deleted file mode 100644 index da1c979e..00000000 --- a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/rpc/RpcEnhancementHandler.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Tencent is pleased to support the open source community by making Polaris available. - * - * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * 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.polarismesh.agent.plugin.spring.cloud.rpc; - -import cn.polarismesh.agent.plugin.spring.cloud.base.AbstractContextHandler; -import com.tencent.cloud.plugin.discovery.adapter.config.NacosDiscoveryAdapterAutoConfiguration; -import com.tencent.cloud.rpc.enhancement.config.RpcEnhancementAutoConfiguration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.support.BeanDefinitionBuilder; -import org.springframework.beans.factory.support.DefaultListableBeanFactory; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ConfigurableApplicationContext; - -/** - * @author liaochuntao - */ -public class RpcEnhancementHandler extends AbstractContextHandler { - - private static final Logger LOGGER = LoggerFactory.getLogger(RpcEnhancementHandler.class); - - @Override - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - registerRpcEnhancementAutoConfiguration(applicationContext); - } - - private void registerRpcEnhancementAutoConfiguration(ApplicationContext context) { - registerBean(context, "rpcEnhancementAutoConfiguration", (ctx, name) -> { - ConfigurableApplicationContext cfgCtx = (ConfigurableApplicationContext) ctx; - DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) cfgCtx.getBeanFactory(); - beanFactory.registerBeanDefinition(name, - BeanDefinitionBuilder.genericBeanDefinition(RpcEnhancementAutoConfiguration.class).getBeanDefinition()); - }); - registerBean(context, "nacosDiscoveryAdapterAutoConfiguration", (ctx, name) -> { - ConfigurableApplicationContext cfgCtx = (ConfigurableApplicationContext) ctx; - DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) cfgCtx.getBeanFactory(); - beanFactory.registerBeanDefinition(name, - BeanDefinitionBuilder.genericBeanDefinition(NacosDiscoveryAdapterAutoConfiguration.class).getBeanDefinition()); - }); - } - -} diff --git a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/resources/default-plugin.conf b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/resources/default-plugin.conf index 81bb213f..f37d0470 100644 --- a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/resources/default-plugin.conf +++ b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-2023-plugin/src/main/resources/default-plugin.conf @@ -1,5 +1,4 @@ # 配置北极星服务端地址 -spring.cloud.polaris.address=grpc\://127.0.0.1\:8091 spring.cloud.polaris.enabled=true # 启用 Java Agent 的 Spring Cloud Tencent 注册发现能力 @@ -10,12 +9,10 @@ spring.cloud.polaris.discovery.namespace=default spring.cloud.polaris.discovery.enabled=true spring.cloud.polaris.discovery.register=true -## 是否启用北极星的 LoadBalancer -spring.cloud.polaris.loadbalancer.enabled=true -#spring.cloud.polaris.loadbalancer.discoveryType=POLARIS -#spring.cloud.polaris.loadbalancer.strategy=random +# 是否启用北极星的 LoadBalancer +spring.cloud.polaris.loadbalancer.enabled=false -## 是否启用北极星服务路由能力 +# 是否启用北极星服务路由能力 spring.cloud.polaris.router.enabled=false # 是否启用北极星的自定义路由能力 spring.cloud.polaris.router.rule-router.enabled=false @@ -24,8 +21,8 @@ spring.cloud.polaris.router.metadata-router.enabled=false # 是否启用北极星的就近路由能力 spring.cloud.polaris.router.nearby-router.enabled=false -## 是否启用北极星的服务限流能力 -spring.cloud.polaris.ratelimit.enabled=true +# 是否启用北极星的服务限流能力 +spring.cloud.polaris.ratelimit.enabled=false # 设置触发限流时的提示信息 # spring.cloud.polaris.ratelimit.rejectRequestTips="" # 设置触发限流时的响应码 @@ -33,23 +30,30 @@ spring.cloud.polaris.ratelimit.rejectHttpCode=429 # 设置限流匀速排队最大排队时间 spring.cloud.polaris.ratelimit.maxQueuingTime=1000 +# 是否启用北极星的服务熔断能力 +spring.cloud.polaris.circuitbreaker.enabled=false ## RPC 调用增强 -spring.cloud.tencent.rpc-enhancement.enabled=true +spring.cloud.tencent.rpc-enhancement.enabled=false + # 开启 RPC 调用结果上报 -spring.cloud.tencent.rpc-enhancement.reporter.enabled=true +spring.cloud.tencent.rpc-enhancement.reporter.enabled=false # 配置北极星监控指标上报 -spring.cloud.polaris.stat.enabled=true +spring.cloud.polaris.stat.enabled=false # 指标上报监听端口 spring.cloud.polaris.stat.port=0 # 指标上报暴露的 http path spring.cloud.polaris.stat.path=/metrics -## 启用北极星配置中心能力 -spring.cloud.polaris.config.enabled=false +# 启用北极星配置中心能力 +spring.cloud.polaris.config.enabled=true # 是否开启配置监听刷新 spring.cloud.polaris.config.auto-refresh=true -# Spring Cloud Tencent 配置刷新机制 -spring.cloud.polaris.config.refresh-type=refresh_context +# 启用优雅上下线功能 +spring.cloud.polaris.lossless.enabled=false +spring.cloud.polaris.lossless.port=28080 + +# 日志级别 +logging.level.root=INFO \ No newline at end of file diff --git a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-plugin-common/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/common/PropertiesProvider.java b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-plugin-common/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/common/PropertiesProvider.java index 1b0745e5..f07b9abc 100644 --- a/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-plugin-common/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/common/PropertiesProvider.java +++ b/polaris-agent-plugins/spring-cloud-plugins/spring-cloud-plugin-common/src/main/java/cn/polarismesh/agent/plugin/spring/cloud/common/PropertiesProvider.java @@ -57,7 +57,7 @@ public static List loadPropertiesSource() { String configPath = Paths.get(System.getProperty(Constant.AGENT_CONF_PATH), "conf").toString(); LOGGER.info("load property sources from config path " + configPath); Properties properties = new Properties(); - String confPath = Paths.get(configPath, "plugin", "spring-cloud-hoxton", "application.properties").toString(); + String confPath = Paths.get(configPath, "plugin", "spring-cloud-2023", "application.properties").toString(); String cmdVal = System.getProperty("polaris.agent.user.application.conf"); if (null != cmdVal && !cmdVal.isEmpty()) { confPath = cmdVal;