diff --git a/spring-cloud-alicloud-acm/pom.xml b/spring-cloud-alicloud-acm/pom.xml index 6f431517..8d407636 100644 --- a/spring-cloud-alicloud-acm/pom.xml +++ b/spring-cloud-alicloud-acm/pom.xml @@ -73,7 +73,6 @@ 1.7.1 test - org.powermock powermock-api-mockito diff --git a/spring-cloud-alicloud-ans/pom.xml b/spring-cloud-alicloud-ans/pom.xml index 239386b4..d6532f94 100644 --- a/spring-cloud-alicloud-ans/pom.xml +++ b/spring-cloud-alicloud-ans/pom.xml @@ -81,6 +81,18 @@ spring-boot-starter-test test + + org.powermock + powermock-module-junit4 + 1.7.1 + test + + + org.powermock + powermock-api-mockito + 1.7.1 + test + diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/AnsAutoConfiguration.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/AnsAutoConfiguration.java index 4a39ded0..08f79c62 100644 --- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/AnsAutoConfiguration.java +++ b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/AnsAutoConfiguration.java @@ -17,12 +17,10 @@ package org.springframework.cloud.alicloud.ans; import org.springframework.boot.autoconfigure.AutoConfigureAfter; -import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.cloud.alicloud.ans.migrate.MigrateOnConditionMissingClass; import org.springframework.cloud.alicloud.ans.registry.AnsAutoServiceRegistration; import org.springframework.cloud.alicloud.ans.registry.AnsRegistration; import org.springframework.cloud.alicloud.ans.registry.AnsServiceRegistry; @@ -31,7 +29,6 @@ import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationC import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationProperties; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; /** @@ -39,11 +36,9 @@ import org.springframework.context.annotation.Configuration; */ @Configuration @EnableConfigurationProperties -@Conditional(MigrateOnConditionMissingClass.class) @ConditionalOnClass(name = "org.springframework.boot.context.embedded.EmbeddedServletContainerInitializedEvent") @ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true) @ConditionalOnAnsEnabled -@AutoConfigureBefore(AnsDiscoveryClientAutoConfiguration.class) @AutoConfigureAfter(AutoServiceRegistrationConfiguration.class) public class AnsAutoConfiguration { diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/AnsDiscoveryClientAutoConfiguration.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/AnsDiscoveryClientAutoConfiguration.java index 99118791..0862ee1f 100644 --- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/AnsDiscoveryClientAutoConfiguration.java +++ b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/AnsDiscoveryClientAutoConfiguration.java @@ -19,12 +19,10 @@ package org.springframework.cloud.alicloud.ans; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.cloud.alicloud.ans.migrate.MigrateOnConditionMissingClass; import org.springframework.cloud.alicloud.ans.registry.AnsRegistration; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.cloud.client.discovery.simple.SimpleDiscoveryClientAutoConfiguration; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; /** @@ -32,7 +30,6 @@ import org.springframework.context.annotation.Configuration; * @author pbting */ @Configuration -@Conditional(MigrateOnConditionMissingClass.class) @ConditionalOnMissingBean(DiscoveryClient.class) @EnableConfigurationProperties @AutoConfigureBefore(SimpleDiscoveryClientAutoConfiguration.class) diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateEndpoint.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateEndpoint.java deleted file mode 100644 index e8609648..00000000 --- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateEndpoint.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.springframework.cloud.alicloud.ans.migrate; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.boot.actuate.endpoint.AbstractEndpoint; - -import java.util.Map; -import java.util.concurrent.ConcurrentMap; - -/** - * @author pbting - */ -public class MigrateEndpoint - extends AbstractEndpoint>> { - - private static final Logger log = LoggerFactory.getLogger(MigrateEndpoint.class); - - public MigrateEndpoint() { - super("migrate"); - } - - /** - * @return ans endpoint - */ - @Override - public Map> invoke() { - - Map> result = ServerListInvocationHandler - .getServerRegistry(); - - log.info("migrate server list :" + result); - return result; - } -} \ No newline at end of file diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateEndpointAutoConfiguration.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateEndpointAutoConfiguration.java deleted file mode 100644 index 3f3b1e72..00000000 --- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateEndpointAutoConfiguration.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.springframework.cloud.alicloud.ans.migrate; - -import org.springframework.boot.actuate.endpoint.Endpoint; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Conditional; - -/** - * @author pbting - */ -@ConditionalOnWebApplication -@ConditionalOnClass(value = Endpoint.class) -@Conditional(MigrateOnConditionClass.class) -public class MigrateEndpointAutoConfiguration { - - @Bean - public MigrateEndpoint ansEndpoint() { - return new MigrateEndpoint(); - } -} \ No newline at end of file diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateOnCondition.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateOnCondition.java deleted file mode 100644 index 86816587..00000000 --- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateOnCondition.java +++ /dev/null @@ -1,48 +0,0 @@ -package org.springframework.cloud.alicloud.ans.migrate; - -import org.springframework.beans.factory.BeanClassLoaderAware; -import org.springframework.context.annotation.Condition; -import org.springframework.context.annotation.ConditionContext; -import org.springframework.core.type.AnnotatedTypeMetadata; -import org.springframework.util.ClassUtils; - -/** - * @author pbting - */ -public abstract class MigrateOnCondition implements Condition, BeanClassLoaderAware { - - final String[] conditionOnClass = new String[] { - "org.springframework.cloud.consul.serviceregistry.ConsulAutoServiceRegistration", - "org.springframework.cloud.netflix.eureka.serviceregistry.EurekaAutoServiceRegistration" }; - - ClassLoader classLoader; - - @Override - public void setBeanClassLoader(ClassLoader classLoader) { - this.classLoader = classLoader; - } - - @Override - public abstract boolean matches(ConditionContext context, - AnnotatedTypeMetadata metadata); - - boolean isPresent(String className, ClassLoader classLoader) { - if (classLoader == null) { - classLoader = ClassUtils.getDefaultClassLoader(); - } - - try { - forName(className, classLoader); - return true; - } - catch (Throwable throwable) { - return false; - } - } - - Class forName(String className, ClassLoader classLoader) - throws ClassNotFoundException { - return classLoader != null ? classLoader.loadClass(className) - : Class.forName(className); - } -} \ No newline at end of file diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateOnConditionClass.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateOnConditionClass.java deleted file mode 100644 index 9e99c9f8..00000000 --- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateOnConditionClass.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.springframework.cloud.alicloud.ans.migrate; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.annotation.ConditionContext; -import org.springframework.core.type.AnnotatedTypeMetadata; - -/** - * @author pbting - */ -public class MigrateOnConditionClass extends MigrateOnCondition { - - private static final Logger log = LoggerFactory - .getLogger(MigrateOnConditionClass.class); - - @Override - public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { - boolean result = isPresent(conditionOnClass[0], classLoader) - || isPresent(conditionOnClass[1], classLoader); - log.info("the result of matcher is " + result); - return result; - } -} \ No newline at end of file diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateOnConditionMissingClass.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateOnConditionMissingClass.java deleted file mode 100644 index b5653bb7..00000000 --- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateOnConditionMissingClass.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.springframework.cloud.alicloud.ans.migrate; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.annotation.ConditionContext; -import org.springframework.core.type.AnnotatedTypeMetadata; - -/** - * @author pbting - */ -public class MigrateOnConditionMissingClass extends MigrateOnConditionClass { - private static final Logger log = LoggerFactory - .getLogger(MigrateOnConditionMissingClass.class); - - @Override - public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { - boolean result = !super.matches(context, metadata); - log.info(" the result of matcher is " + result); - return result; - } - -} \ No newline at end of file diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateProxyManager.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateProxyManager.java deleted file mode 100644 index 8b62c22e..00000000 --- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateProxyManager.java +++ /dev/null @@ -1,102 +0,0 @@ -package org.springframework.cloud.alicloud.ans.migrate; - -import com.netflix.client.config.IClientConfig; -import com.netflix.loadbalancer.ILoadBalancer; -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ServerList; -import org.aopalliance.aop.Advice; -import org.aopalliance.intercept.MethodInterceptor; -import org.aopalliance.intercept.MethodInvocation; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.aop.framework.ProxyFactory; - -import java.util.*; -import java.util.concurrent.ConcurrentSkipListSet; -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * @author pbting - */ -final class MigrateProxyManager { - - private static final Logger log = LoggerFactory.getLogger(MigrateProxyManager.class); - - private final static AtomicBoolean IS_PROXY = new AtomicBoolean(true); - - private final static Set SERVICES_ID = new ConcurrentSkipListSet<>(); - - private static Object springProxyFactory(Object target, ClassLoader classLoader, - List adviceList, Class... interfaces) { - final ProxyFactory proxyFactory = new ProxyFactory(interfaces); - proxyFactory.setTarget(target); - for (Iterator iterator = adviceList.iterator(); iterator.hasNext();) { - proxyFactory.addAdvice(iterator.next()); - } - return proxyFactory.getProxy(classLoader); - } - - static Object newServerListProxy(Object bean, ClassLoader classLoader, - IClientConfig clientConfig) { - List adviceLists = new LinkedList<>(); - adviceLists.add(new ServerListInvocationHandler(clientConfig)); - bean = springProxyFactory(bean, classLoader, adviceLists, - new Class[] { ServerList.class }); - log.info("[service id]" + clientConfig.getClientName() - + " new a ServerList proxy instance for spring cloud netflix to spring cloud alibaba "); - collectServiceId(clientConfig.getClientName()); - return bean; - } - - static Object newLoadBalancerProxy(Object bean, ClassLoader classLoader, - final IClientConfig clientConfig) { - // step 1: initializer a advice for after returning advice - final List adviceLists = new LinkedList<>(); - adviceLists.add(new MethodInterceptor() { - private final IClientConfig iclientConfig = clientConfig; - - @Override - public Object invoke(MethodInvocation methodInvocation) throws Throwable { - Object returnValue = methodInvocation.proceed(); - String methodName = methodInvocation.getMethod().getName(); - if (!"chooseServer".equals(methodName)) { - return returnValue; - } - - String serviceId = iclientConfig.getClientName(); - Server server = ServerListInvocationHandler - .checkAndGetServiceServer(serviceId, (Server) returnValue); - ServerListInvocationHandler.incrementCallService(serviceId, server); - return server; - } - }); - // step 2: new proxy instance by spring factory - bean = springProxyFactory(bean, classLoader, adviceLists, - new Class[] { ILoadBalancer.class }); - log.info("[service id]" + clientConfig.getClientName() - + " new a ILoadBalancer proxy instance for spring cloud netflix to spring cloud alibaba "); - return bean; - } - - static void migrateProxyClose() { - IS_PROXY.set(false); - } - - static void migrateProxyUp() { - IS_PROXY.set(true); - } - - static boolean isMigrateProxy() { - - return IS_PROXY.get(); - } - - static void collectServiceId(String serviceId) { - SERVICES_ID.add(serviceId); - } - - static Set getServicesId() { - - return Collections.unmodifiableSet(SERVICES_ID); - } -} \ No newline at end of file diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateRefreshEventListener.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateRefreshEventListener.java deleted file mode 100644 index db941c84..00000000 --- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateRefreshEventListener.java +++ /dev/null @@ -1,100 +0,0 @@ -package org.springframework.cloud.alicloud.ans.migrate; - -import java.util.Iterator; -import java.util.Set; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - -import javax.annotation.PostConstruct; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.cloud.context.named.NamedContextFactory; -import org.springframework.cloud.endpoint.event.RefreshEvent; -import org.springframework.context.ApplicationListener; -import org.springframework.core.env.Environment; -import org.springframework.stereotype.Component; - -import com.netflix.loadbalancer.ILoadBalancer; - -/** - * @author pbting - */ -@Component -public class MigrateRefreshEventListener implements ApplicationListener { - private static final Logger log = LoggerFactory - .getLogger(MigrateRefreshEventListener.class); - - private final static int CHECK_INTERVAL = 1; - - private final static String MIGRATE_SWITCH = "spring.cloud.alicloud.migarte.ans.switch"; - - private volatile String lastScaMigrateAnsSwitchValue = "true"; - - private Environment environment; - - private NamedContextFactory namedContextFactory; - - public MigrateRefreshEventListener(Environment environment, - NamedContextFactory namedContextFactory) { - this.environment = environment; - this.namedContextFactory = namedContextFactory; - } - - @PostConstruct - public void initTimerCheck() { - Executors.newSingleThreadScheduledExecutor() - .scheduleWithFixedDelay(new Runnable() { - @Override - public void run() { - try { - onApplicationEvent(null); - } - catch (Exception e) { - log.error( - "check the value of 'sca.migrate.ans.switch' in environment whether changed or not cause an Exeption", - e); - } - } - }, CHECK_INTERVAL, CHECK_INTERVAL, TimeUnit.SECONDS); - } - - @Override - public void onApplicationEvent(RefreshEvent event) { - String value = environment.getProperty(MIGRATE_SWITCH, "true"); - - // check 1: check the value - if (value.equals(lastScaMigrateAnsSwitchValue)) { - return; - } - - updateLastScaMigrateAnsResetValue(value); - - // step 1: migrate up - if ("true".equals(value)) { - MigrateProxyManager.migrateProxyUp(); - serviceIdContextInit(); - return; - } - - // step 2: migrate close - if ("false".equals(value)) { - MigrateProxyManager.migrateProxyClose(); - serviceIdContextInit(); - return; - } - } - - private void serviceIdContextInit() { - namedContextFactory.destroy(); - // initializer each spring context for service id - Set serviceIds = MigrateProxyManager.getServicesId(); - for (Iterator iterator = serviceIds.iterator(); iterator.hasNext();) { - namedContextFactory.getInstance(iterator.next(), ILoadBalancer.class); - } - } - - private synchronized void updateLastScaMigrateAnsResetValue(String value) { - this.lastScaMigrateAnsSwitchValue = value; - } -} \ No newline at end of file diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateRibbonBeanPostProcessor.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateRibbonBeanPostProcessor.java deleted file mode 100644 index 74fa658a..00000000 --- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateRibbonBeanPostProcessor.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.springframework.cloud.alicloud.ans.migrate; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.BeanClassLoaderAware; -import org.springframework.beans.factory.config.BeanPostProcessor; - -import com.netflix.client.config.IClientConfig; -import com.netflix.loadbalancer.ILoadBalancer; -import com.netflix.loadbalancer.ServerList; - -/** - * @author pbting - */ -public class MigrateRibbonBeanPostProcessor - implements BeanPostProcessor, BeanClassLoaderAware { - - private static final Logger log = LoggerFactory.getLogger(MigrateOnCondition.class); - - private ClassLoader classLoader; - private IClientConfig clientConfig; - - public MigrateRibbonBeanPostProcessor(IClientConfig clientConfig) { - this.clientConfig = clientConfig; - } - - @Override - public Object postProcessAfterInitialization(Object bean, String beanName) - throws BeansException { - - // step 1 : check the bean whether proxy or not - if (!MigrateProxyManager.isMigrateProxy()) { - log.info("Migrate proxy is Close."); - return bean; - } - - // step 2 : proxy the designated bean - if (bean instanceof ServerList) { - bean = MigrateProxyManager.newServerListProxy(bean, classLoader, - clientConfig); - } - - if (bean instanceof ILoadBalancer) { - bean = MigrateProxyManager.newLoadBalancerProxy(bean, classLoader, - clientConfig); - } - return bean; - } - - @Override - public Object postProcessBeforeInitialization(Object o, String s) - throws BeansException { - return o; - } - - @Override - public void setBeanClassLoader(ClassLoader classLoader) { - this.classLoader = classLoader; - } - -} \ No newline at end of file diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateServiceRegistry.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateServiceRegistry.java deleted file mode 100644 index 8220d377..00000000 --- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrateServiceRegistry.java +++ /dev/null @@ -1,69 +0,0 @@ -package org.springframework.cloud.alicloud.ans.migrate; - -import java.util.concurrent.atomic.AtomicBoolean; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.boot.context.event.ApplicationReadyEvent; -import org.springframework.cloud.alicloud.ans.registry.AnsRegistration; -import org.springframework.cloud.alicloud.ans.registry.AnsServiceRegistry; -import org.springframework.cloud.alicloud.context.ans.AnsProperties; -import org.springframework.cloud.client.serviceregistry.ServiceRegistry; -import org.springframework.context.ApplicationContext; -import org.springframework.context.event.EventListener; -import org.springframework.stereotype.Component; - -/** - * @author pbting - */ -@Component -public class MigrateServiceRegistry { - - private static final Logger log = LoggerFactory - .getLogger(MigrateServiceRegistry.class); - - private AtomicBoolean running = new AtomicBoolean(false); - - private ServiceRegistry serviceRegistry; - private AnsRegistration ansRegistration; - - public MigrateServiceRegistry(AnsProperties ansProperties, - ApplicationContext context) { - this.ansRegistration = new AnsRegistration(ansProperties, context); - this.ansRegistration.init(); - this.serviceRegistry = new AnsServiceRegistry(); - } - - @EventListener(ApplicationReadyEvent.class) - public void onApplicationEvent(ApplicationReadyEvent event) { - String serverPort = event.getApplicationContext().getEnvironment() - .getProperty("server.port"); - if (null != serverPort && serverPort.trim().length() > 0) { - try { - this.ansRegistration.setPort(Integer.parseInt(serverPort)); - } - catch (NumberFormatException e) { - // nothing to do - } - } - log.info("[ Migrate ] change the port to " + serverPort); - - if (this.running.get()) { - return; - } - - if (this.ansRegistration.getPort() > 0) { - long s = System.currentTimeMillis(); - log.info("[Migrate] start to registry server to ANS"); - this.serviceRegistry.register(this.ansRegistration); - log.info("[migrate] end to registry server to ANS cost time with " - + (System.currentTimeMillis() - s) + " ms."); - } - else { - log.warn("the server port is smaller than zero. " - + this.ansRegistration.getPort()); - } - this.running.set(true); - } - -} \ No newline at end of file diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrationAutoconfiguration.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrationAutoconfiguration.java deleted file mode 100644 index 8f632bf1..00000000 --- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/MigrationAutoconfiguration.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.springframework.cloud.alicloud.ans.migrate; - -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.cloud.alicloud.ans.ConditionalOnAnsEnabled; -import org.springframework.cloud.alicloud.context.ans.AnsProperties; -import org.springframework.cloud.context.named.NamedContextFactory; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Conditional; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.Environment; - -/** - * @author pbting - */ -@Configuration -@EnableConfigurationProperties -@Conditional(MigrateOnConditionClass.class) -@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true) -@ConditionalOnAnsEnabled -public class MigrationAutoconfiguration { - - @Bean - public MigrateServiceRegistry migrationManger(AnsProperties ansProperties, - ApplicationContext applicationContext) { - - return new MigrateServiceRegistry(ansProperties, applicationContext); - } - - @Bean - public MigrateRefreshEventListener migrateRefreshEventListener( - Environment environment, - @Qualifier(value = "springClientFactory") NamedContextFactory namedContextFactory) { - - return new MigrateRefreshEventListener(environment, namedContextFactory); - } -} \ No newline at end of file diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/ServerListInvocationHandler.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/ServerListInvocationHandler.java deleted file mode 100644 index 85ca5c3c..00000000 --- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/ServerListInvocationHandler.java +++ /dev/null @@ -1,177 +0,0 @@ -package org.springframework.cloud.alicloud.ans.migrate; - -import com.netflix.client.config.IClientConfig; -import com.netflix.loadbalancer.Server; -import org.aopalliance.intercept.MethodInterceptor; -import org.aopalliance.intercept.MethodInvocation; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.cloud.alicloud.ans.ribbon.AnsServer; -import org.springframework.cloud.alicloud.ans.ribbon.AnsServerList; - -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.ConcurrentSkipListSet; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicLong; - -/** - * @author pbting - */ -class ServerListInvocationHandler implements MethodInterceptor { - - private static final Logger log = LoggerFactory - .getLogger(ServerListInvocationHandler.class); - - private final static ConcurrentMap SERVER_LIST_CONCURRENT_MAP = new ConcurrentHashMap<>(); - - private final static ConcurrentMap> CALL_SERVICE_COUNT = new ConcurrentHashMap<>(); - private final static Set INTERCEPTOR_METHOD_NAME = new ConcurrentSkipListSet(); - - private IClientConfig clientConfig; - private AnsServerList ansServerList; - private AtomicBoolean isFirst = new AtomicBoolean(false); - - static { - INTERCEPTOR_METHOD_NAME.add("getInitialListOfServers"); - INTERCEPTOR_METHOD_NAME.add("getUpdatedListOfServers"); - } - - ServerListInvocationHandler(IClientConfig clientConfig) { - this.clientConfig = clientConfig; - this.ansServerList = new AnsServerList(clientConfig.getClientName()); - SERVER_LIST_CONCURRENT_MAP.put(ansServerList.getDom(), ansServerList); - } - - @Override - public Object invoke(MethodInvocation invocation) throws Throwable { - String methodName = invocation.getMethod().getName(); - // step 1: check the method is not interceptor - if (!INTERCEPTOR_METHOD_NAME.contains(methodName)) { - return invocation.proceed(); - } - - // step 2: interceptor the method - List serverList = (List) invocation.proceed(); - long s = System.currentTimeMillis(); - log.info("[ START ] merage server list for " + clientConfig.getClientName()); - serverList = mergeAnsServerList(serverList); - log.info("[ END ] merage server list for " + clientConfig.getClientName() - + ", cost time " + (System.currentTimeMillis() - s) + " ms ."); - return serverList; - } - - /** - * 后台线程 和 Eureka 两个注册中心进行 Merage 的时候,List 表中始终保持是有效的 Server. 即不考虑 ANS 客户端本地容灾的情况 - */ - private List mergeAnsServerList(final List source) { - if (source.size() > 0 && isFirst.compareAndSet(false, true)) { - return source; - } - - // step 1: get all of server list and filter the alive - List ansServerList = filterAliveAnsServer( - this.ansServerList.getInitialListOfServers()); - - if (ansServerList.isEmpty()) { - return source; - } - - log.info("[" + this.clientConfig.getClientName() + "] Get Server List from ANS:" - + ansServerList + "; loadbalancer server list override before:" + source); - - // step 2:remove servers of that have in load balancer list - final Iterator serverIterator = source.iterator(); - while (serverIterator.hasNext()) { - final Server server = serverIterator.next(); - for (Iterator iterator = ansServerList.iterator(); iterator - .hasNext();) { - AnsServer ansServer = iterator.next(); - if (server.getHostPort() - .equals(ansServer.getHealthService().toInetAddr())) { - // fix bug: mast be set the zone, update server list,will filter - // by: ZoneAffinityPredicate - serverIterator.remove(); - log.info("Source Server is remove " + server.getHostPort() - + ", and from ANS Server is override:" - + ansServer.toString()); - } - ansServer.setZone(server.getZone()); - ansServer.setSchemea(server.getScheme()); - ansServer.setId(ansServer.getHealthService().toInetAddr()); - ansServer.setReadyToServe(true); - } - } - - for (Iterator iterator = ansServerList.iterator(); iterator - .hasNext();) { - source.add(iterator.next()); - } - log.info("[" + this.clientConfig.getClientName() + "] " - + "; loadbalancer server list override after:" + source); - // override - return source; - } - - private List filterAliveAnsServer(List sourceServerList) { - final List resultServerList = new LinkedList<>(); - for (Iterator iterator = sourceServerList.iterator(); iterator - .hasNext();) { - AnsServer ansServer = iterator.next(); - boolean isAlive = ansServer.isAlive(3); - if (isAlive) { - resultServerList.add(ansServer); - } - log.warn(ansServer.toString() + " isAlive :" + isAlive); - } - return resultServerList; - } - - static Map> getServerRegistry() { - - return Collections.unmodifiableMap(CALL_SERVICE_COUNT); - } - - static Server checkAndGetServiceServer(String serviceId, Server server) { - if (server != null) { - return server; - } - - log.warn(String.format("[%s] refers the server is null", server)); - - List ansServerList = SERVER_LIST_CONCURRENT_MAP.get(serviceId) - .getInitialListOfServers(); - - if (!ansServerList.isEmpty()) { - return ansServerList.get(0); - } - - return server; - } - - /** - * - * @param serviceId - * @param server - * @return - */ - static long incrementCallService(String serviceId, Server server) { - ConcurrentMap concurrentHashMap = CALL_SERVICE_COUNT - .putIfAbsent(serviceId, new ConcurrentHashMap()); - - if (concurrentHashMap == null) { - concurrentHashMap = CALL_SERVICE_COUNT.get(serviceId); - } - - String ipPort = server.getHostPort(); - ServerWrapper serverWraper = concurrentHashMap.putIfAbsent(ipPort, - new ServerWrapper(server, new AtomicLong())); - - if (serverWraper == null) { - serverWraper = concurrentHashMap.get(ipPort); - } - serverWraper.setServer(server); - return serverWraper.getCallCount().incrementAndGet(); - } -} \ No newline at end of file diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/ServerWrapper.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/ServerWrapper.java deleted file mode 100644 index 4fbccfdf..00000000 --- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/migrate/ServerWrapper.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.springframework.cloud.alicloud.ans.migrate; - -import com.netflix.loadbalancer.Server; - -import java.util.concurrent.atomic.AtomicLong; - -/** - * @author pbting - */ -public class ServerWrapper { - - private Server server; - private AtomicLong callCount; - - public ServerWrapper() { - } - - public ServerWrapper(Server server, AtomicLong callCount) { - this.server = server; - this.callCount = callCount; - } - - public Server getServer() { - return server; - } - - public void setServer(Server server) { - this.server = server; - } - - public AtomicLong getCallCount() { - return callCount; - } - - public void setCallCount(AtomicLong callCount) { - this.callCount = callCount; - } -} \ No newline at end of file diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistration.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistration.java index 084f85a8..9f324600 100644 --- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistration.java +++ b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistration.java @@ -18,12 +18,9 @@ package org.springframework.cloud.alicloud.ans.registry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.boot.context.embedded.EmbeddedServletContainerInitializedEvent; import org.springframework.cloud.client.serviceregistry.AbstractAutoServiceRegistration; import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationProperties; import org.springframework.cloud.client.serviceregistry.ServiceRegistry; -import org.springframework.context.event.EventListener; -import org.springframework.stereotype.Component; import org.springframework.util.Assert; import org.springframework.util.StringUtils; @@ -31,7 +28,6 @@ import org.springframework.util.StringUtils; * @author xiaolongzuo * @author pbting */ -@Component public class AnsAutoServiceRegistration extends AbstractAutoServiceRegistration { @@ -66,16 +62,6 @@ public class AnsAutoServiceRegistration return null; } - @Override - public void start() { - // nothing to do - } - - @EventListener(EmbeddedServletContainerInitializedEvent.class) - public void doStart() { - super.start(); - } - @Override protected void register() { if (!this.registration.getAnsProperties().isRegisterEnabled()) { diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/registry/AnsRegistration.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/registry/AnsRegistration.java index 3e72273c..75bce182 100644 --- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/registry/AnsRegistration.java +++ b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/registry/AnsRegistration.java @@ -16,11 +16,6 @@ package org.springframework.cloud.alicloud.ans.registry; -import java.net.URI; -import java.util.Map; - -import javax.annotation.PostConstruct; - import org.springframework.cloud.alicloud.context.ans.AnsProperties; import org.springframework.cloud.client.DefaultServiceInstance; import org.springframework.cloud.client.ServiceInstance; @@ -30,14 +25,18 @@ import org.springframework.context.ApplicationContext; import org.springframework.core.env.Environment; import org.springframework.util.StringUtils; +import javax.annotation.PostConstruct; +import java.net.URI; +import java.util.Map; + /** * @author xiaolongzuo */ public class AnsRegistration implements Registration, ServiceInstance { - private static final String MANAGEMENT_PORT = "management.port"; - private static final String MANAGEMENT_CONTEXT_PATH = "management.context-path"; - private static final String MANAGEMENT_ADDRESS = "management.address"; + static final String MANAGEMENT_PORT = "management.port"; + static final String MANAGEMENT_CONTEXT_PATH = "management.context-path"; + static final String MANAGEMENT_ADDRESS = "management.address"; private AnsProperties ansProperties; private ApplicationContext context; diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/registry/AnsServiceRegistry.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/registry/AnsServiceRegistry.java index 924d2976..05b43639 100644 --- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/registry/AnsServiceRegistry.java +++ b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/registry/AnsServiceRegistry.java @@ -18,6 +18,7 @@ package org.springframework.cloud.alicloud.ans.registry; import com.alibaba.ans.core.NamingService; import com.alibaba.ans.shaded.com.taobao.vipserver.client.ipms.NodeReactor; + import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -40,11 +41,11 @@ public class AnsServiceRegistry implements ServiceRegistry { public void register(AnsRegistration registration) { if (!registration.isRegisterEnabled()) { - log.info("Registration is disabled..."); + log.warn("Registration is disabled..."); return; } if (StringUtils.isEmpty(registration.getServiceId())) { - log.info("No service to register for client..."); + log.warn("No service to register for client..."); return; } @@ -62,14 +63,13 @@ public class AnsServiceRegistry implements ServiceRegistry { NamingService.regDom(dom, registration.getHost(), registration.getPort(), registration.getRegisterWeight(dom), registration.getCluster(), tags); - log.info("INFO_ANS_REGISTER, " + dom + " " - + registration.getAnsProperties().getClientIp() + ":" - + registration.getAnsProperties().getClientPort() - + " register finished"); + log.info("INFO_ANS_REGISTER, {} {}:{} register finished", dom, + registration.getAnsProperties().getClientIp(), + registration.getAnsProperties().getClientPort()); } catch (Exception e) { - log.error("ERR_ANS_REGISTER, " + dom + " register failed..." - + registration.toString() + ",", e); + log.error("ERR_ANS_REGISTER, {} register failed...{},", dom, + registration.toString(), e); } } } @@ -80,7 +80,7 @@ public class AnsServiceRegistry implements ServiceRegistry { log.info("De-registering from ANSServer now..."); if (StringUtils.isEmpty(registration.getServiceId())) { - log.info("No dom to de-register for client..."); + log.warn("No dom to de-register for client..."); return; } @@ -89,8 +89,8 @@ public class AnsServiceRegistry implements ServiceRegistry { registration.getPort(), registration.getCluster()); } catch (Exception e) { - log.error("ERR_ANS_DEREGISTER, de-register failed..." - + registration.toString() + ",", e); + log.error("ERR_ANS_DEREGISTER, de-register failed...{},", + registration.toString(), e); } log.info("De-registration finished."); diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/ribbon/AnsRibbonClientConfiguration.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/ribbon/AnsRibbonClientConfiguration.java index 7b6d229b..d189a4da 100644 --- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/ribbon/AnsRibbonClientConfiguration.java +++ b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/ribbon/AnsRibbonClientConfiguration.java @@ -16,21 +16,17 @@ package org.springframework.cloud.alicloud.ans.ribbon; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.cloud.alicloud.ans.migrate.MigrateOnConditionMissingClass; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Conditional; -import org.springframework.context.annotation.Configuration; - import com.netflix.client.config.IClientConfig; import com.netflix.loadbalancer.ServerList; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; /** * @author xiaolongzuo * @author pbting */ @Configuration -@Conditional(MigrateOnConditionMissingClass.class) public class AnsRibbonClientConfiguration { @Bean diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/ribbon/AnsServer.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/ribbon/AnsServer.java index d874e2d9..55684a64 100644 --- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/ribbon/AnsServer.java +++ b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/ribbon/AnsServer.java @@ -16,19 +16,14 @@ package org.springframework.cloud.alicloud.ans.ribbon; -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.Socket; -import java.util.HashMap; +import java.util.Collections; import java.util.Map; -import java.util.concurrent.TimeUnit; import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host; import com.netflix.loadbalancer.Server; /** * @author xiaolongzuo - * @author pbting */ public class AnsServer extends Server { @@ -39,8 +34,7 @@ public class AnsServer extends Server { public AnsServer(final Host host, final String dom) { super(host.getIp(), host.getPort()); this.host = host; - this.metadata = new HashMap(); - this.metadata.put("source", "ANS"); + this.metadata = Collections.emptyMap(); metaInfo = new MetaInfo() { @Override public String getAppName() { @@ -65,33 +59,6 @@ public class AnsServer extends Server { }; } - @Override - public boolean isAlive() { - - return true; - } - - /** - * - * @param timeOut Unit: Seconds - * @return - */ - public boolean isAlive(long timeOut) { - try { - String hostName = this.host.getHostname(); - hostName = hostName != null && hostName.trim().length() > 0 ? hostName - : this.host.getIp(); - Socket socket = new Socket(); - socket.connect(new InetSocketAddress(hostName, this.host.getPort()), - (int) TimeUnit.SECONDS.toMillis(timeOut)); - socket.close(); - return true; - } - catch (IOException e) { - return false; - } - } - @Override public MetaInfo getMetaInfo() { return metaInfo; diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/ribbon/AnsServerList.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/ribbon/AnsServerList.java index c44d6241..f34f19ff 100644 --- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/ribbon/AnsServerList.java +++ b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/ribbon/AnsServerList.java @@ -16,22 +16,19 @@ package org.springframework.cloud.alicloud.ans.ribbon; +import java.util.ArrayList; +import java.util.List; + import com.alibaba.ans.core.NamingService; import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host; import com.netflix.client.config.IClientConfig; import com.netflix.loadbalancer.AbstractServerList; -import java.util.ArrayList; -import java.util.List; - /** * @author xiaolongzuo - * @author pbting */ public class AnsServerList extends AbstractServerList { - private final static int CONNECT_TIME_OUT = 3; - private String dom; public AnsServerList(String dom) { @@ -63,12 +60,10 @@ public class AnsServerList extends AbstractServerList { List result = new ArrayList(hosts.size()); for (Host host : hosts) { if (host.isValid()) { - AnsServer ansServer = hostToServer(host); - if (ansServer.isAlive(CONNECT_TIME_OUT)) { - result.add(ansServer); - } + result.add(hostToServer(host)); } } + return result; } diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/ribbon/MigrateRibbonCofiguration.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/ribbon/MigrateRibbonCofiguration.java deleted file mode 100644 index 5bda207c..00000000 --- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/ribbon/MigrateRibbonCofiguration.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.springframework.cloud.alicloud.ans.ribbon; - -import org.springframework.cloud.alicloud.ans.migrate.MigrateRibbonBeanPostProcessor; -import org.springframework.cloud.alicloud.ans.migrate.MigrateOnConditionClass; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Conditional; -import org.springframework.context.annotation.Configuration; - -import com.netflix.client.config.IClientConfig; - -@Configuration -@Conditional(MigrateOnConditionClass.class) -public class MigrateRibbonCofiguration { - - @Bean - public MigrateRibbonBeanPostProcessor migrateBeanPostProcessor(IClientConfig clientConfig) { - - return new MigrateRibbonBeanPostProcessor(clientConfig); - } -} \ No newline at end of file diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/ribbon/RibbonAnsAutoConfiguration.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/ribbon/RibbonAnsAutoConfiguration.java index cf7d52ff..4333cb53 100644 --- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/ribbon/RibbonAnsAutoConfiguration.java +++ b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/ribbon/RibbonAnsAutoConfiguration.java @@ -34,7 +34,6 @@ import org.springframework.context.annotation.Configuration; @ConditionalOnBean(SpringClientFactory.class) @ConditionalOnRibbonAns @AutoConfigureAfter(RibbonAutoConfiguration.class) -@RibbonClients(defaultConfiguration = { AnsRibbonClientConfiguration.class, - MigrateRibbonCofiguration.class }) +@RibbonClients(defaultConfiguration = AnsRibbonClientConfiguration.class) public class RibbonAnsAutoConfiguration { } diff --git a/spring-cloud-alicloud-ans/src/main/resources/META-INF/spring.factories b/spring-cloud-alicloud-ans/src/main/resources/META-INF/spring.factories index f733a74e..02177b93 100644 --- a/spring-cloud-alicloud-ans/src/main/resources/META-INF/spring.factories +++ b/spring-cloud-alicloud-ans/src/main/resources/META-INF/spring.factories @@ -2,7 +2,4 @@ org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ org.springframework.cloud.alicloud.ans.endpoint.AnsEndpointAutoConfiguration,\ org.springframework.cloud.alicloud.ans.ribbon.RibbonAnsAutoConfiguration,\ org.springframework.cloud.alicloud.ans.AnsAutoConfiguration,\ - org.springframework.cloud.alicloud.ans.migrate.MigrateEndpointAutoConfiguration,\ - org.springframework.cloud.alicloud.ans.migrate.MigrationAutoconfiguration -org.springframework.cloud.client.discovery.EnableDiscoveryClient=\ org.springframework.cloud.alicloud.ans.AnsDiscoveryClientAutoConfiguration \ No newline at end of file diff --git a/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alibaba/ans/ribbon/AnsServiceListTests.java b/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alibaba/ans/ribbon/AnsServiceListTests.java deleted file mode 100644 index 5cb38532..00000000 --- a/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alibaba/ans/ribbon/AnsServiceListTests.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.alibaba.ans.ribbon; - -import static org.junit.Assert.*; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; - -import java.util.Arrays; -import java.util.List; - -import org.junit.Test; -import org.springframework.cloud.alicloud.ans.ribbon.AnsServer; -import org.springframework.cloud.alicloud.ans.ribbon.AnsServerList; - -import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host; -import com.netflix.loadbalancer.Server; - -/** - * @author xiaolongzuo - */ -public class AnsServiceListTests { - - static final String IP_ADDR = "10.0.0.2"; - - static final int PORT = 8080; - - @Test - public void testAnsServer() { - AnsServerList serverList = getAnsServerList(); - List servers = serverList.getInitialListOfServers(); - assertNotNull("servers was null", servers); - assertEquals("servers was not size 1", 1, servers.size()); - Server des = assertAnsServer(servers); - assertEquals("hostPort was wrong", IP_ADDR + ":" + PORT, des.getHostPort()); - } - - protected Server assertAnsServer(List servers) { - Server actualServer = servers.get(0); - assertTrue("server was not a DomainExtractingServer", - actualServer instanceof AnsServer); - AnsServer des = AnsServer.class.cast(actualServer); - assertNotNull("host is null", des.getHealthService()); - assertEquals("unit was wrong", "DEFAULT", des.getHealthService().getUnit()); - return des; - } - - protected AnsServerList getAnsServerList() { - Host host = mock(Host.class); - given(host.getIp()).willReturn(IP_ADDR); - given(host.getDoubleWeight()).willReturn(1.0); - given(host.getPort()).willReturn(PORT); - given(host.getWeight()).willReturn(1); - given(host.getUnit()).willReturn("DEFAULT"); - - AnsServer server = new AnsServer(host, "testDom"); - @SuppressWarnings("unchecked") - AnsServerList originalServerList = mock(AnsServerList.class); - given(originalServerList.getInitialListOfServers()) - .willReturn(Arrays.asList(server)); - return originalServerList; - } - -} diff --git a/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/AnsDiscoveryClientTests.java b/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/AnsDiscoveryClientTests.java new file mode 100644 index 00000000..40222903 --- /dev/null +++ b/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/AnsDiscoveryClientTests.java @@ -0,0 +1,120 @@ +/* + * Copyright (C) 2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.cloud.alicloud.ans; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.springframework.cloud.alicloud.ans.test.AnsMockTest.hostInstance; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.cloud.alicloud.ans.registry.AnsRegistration; +import org.springframework.cloud.client.ServiceInstance; + +import com.alibaba.ans.core.NamingService; +import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host; + +/** + * @author xiaojing + */ +@RunWith(PowerMockRunner.class) +@PrepareForTest(NamingService.class) +public class AnsDiscoveryClientTests { + + private String host = "123.123.123.123"; + private int port = 8888; + private String serviceName = "test-service"; + + @Test + public void testGetServers() throws Exception { + + ArrayList hosts = new ArrayList<>(); + + HashMap map = new HashMap<>(); + map.put("test-key", "test-value"); + map.put("secure", "true"); + + hosts.add(hostInstance(serviceName, false, host, port, map)); + + PowerMockito.mockStatic(NamingService.class); + when(NamingService.getHosts(eq(serviceName))).thenReturn(hosts); + + AnsRegistration ansRegistration = mock(AnsRegistration.class); + AnsDiscoveryClient discoveryClient = new AnsDiscoveryClient(ansRegistration); + + List serviceInstances = discoveryClient + .getInstances(serviceName); + + assertThat(serviceInstances.size()).isEqualTo(1); + + ServiceInstance serviceInstance = serviceInstances.get(0); + + assertThat(serviceInstance.getServiceId()).isEqualTo(serviceName); + assertThat(serviceInstance.getHost()).isEqualTo(host); + assertThat(serviceInstance.getPort()).isEqualTo(port); + // assertThat(serviceInstance.isSecure()).isEqualTo(true); + // ans doesn't support metadata + assertThat(serviceInstance.getUri().toString()) + .isEqualTo(getUri(serviceInstance)); + // assertThat(serviceInstance.getMetadata().get("test-key")).isEqualTo("test-value"); + // ans doesn't support metadata + + } + + @Test + public void testGetAllService() throws Exception { + + Set subscribedServices = new HashSet<>(); + + subscribedServices.add(serviceName + "1"); + subscribedServices.add(serviceName + "2"); + subscribedServices.add(serviceName + "3"); + + PowerMockito.mockStatic(NamingService.class); + when(NamingService.getDomsSubscribed()).thenReturn(subscribedServices); + + AnsRegistration ansRegistration = mock(AnsRegistration.class); + AnsDiscoveryClient discoveryClient = new AnsDiscoveryClient(ansRegistration); + List services = discoveryClient.getServices(); + + assertThat(services.size()).isEqualTo(3); + assertThat(services.contains(serviceName + "1")); + assertThat(services.contains(serviceName + "2")); + assertThat(services.contains(serviceName + "3")); + + } + + private String getUri(ServiceInstance instance) { + + if (instance.isSecure()) { + return "https://" + host + ":" + port; + } + + return "http://" + host + ":" + port; + } +} diff --git a/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistrationEnabledTests.java b/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistrationEnabledTests.java new file mode 100644 index 00000000..28c465f7 --- /dev/null +++ b/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistrationEnabledTests.java @@ -0,0 +1,80 @@ +/* + * Copyright (C) 2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.cloud.alicloud.ans.registry; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.ImportAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.cloud.alicloud.ans.AnsAutoConfiguration; +import org.springframework.cloud.alicloud.ans.AnsDiscoveryClientAutoConfiguration; +import org.springframework.cloud.alicloud.context.ans.AnsProperties; +import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.junit4.SpringRunner; + +/** + * @author xiaojing + */ + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = AnsAutoServiceRegistrationEnabledTests.TestConfig.class, properties = { + "spring.application.name=myTestService1", + "spring.cloud.alicloud.ans.server-list=127.0.0.1", + "spring.cloud.alicloud.ans.server-port=8080", + "spring.cloud.alicloud.ans.register-enabled=false" }, webEnvironment = RANDOM_PORT) +public class AnsAutoServiceRegistrationEnabledTests { + + @Autowired + private AnsRegistration registration; + + @Autowired + private AnsAutoServiceRegistration ansAutoServiceRegistration; + + @Autowired + private AnsProperties properties; + + @Test + public void contextLoads() throws Exception { + + assertNotNull("AnsRegistration was not created", registration); + assertNotNull("AnsProperties was not created", properties); + assertNotNull("AnsAutoServiceRegistration was not created", + ansAutoServiceRegistration); + + checkEnabled(); + + } + + private void checkEnabled() { + assertFalse("Ans Auto Registration should not start", + ansAutoServiceRegistration.isEnabled()); + } + + @Configuration + @EnableAutoConfiguration + @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, + AnsDiscoveryClientAutoConfiguration.class, AnsAutoConfiguration.class }) + public static class TestConfig { + } +} diff --git a/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistrationIpNetworkInterfaceTests.java b/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistrationIpNetworkInterfaceTests.java new file mode 100644 index 00000000..6f855a20 --- /dev/null +++ b/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistrationIpNetworkInterfaceTests.java @@ -0,0 +1,147 @@ +/* + * Copyright (C) 2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.cloud.alicloud.ans.registry; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertEquals; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; + +import java.net.Inet4Address; +import java.net.InetAddress; +import java.net.NetworkInterface; +import java.util.Enumeration; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.ImportAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.cloud.alicloud.ans.AnsAutoConfiguration; +import org.springframework.cloud.alicloud.ans.AnsDiscoveryClientAutoConfiguration; +import org.springframework.cloud.alicloud.context.ans.AnsProperties; +import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration; +import org.springframework.cloud.commons.util.InetUtils; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.junit4.SpringRunner; + +/** + * @author xiaojing + */ + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = AnsAutoServiceRegistrationIpNetworkInterfaceTests.TestConfig.class, properties = { + "spring.application.name=myTestService1", + "spring.cloud.alicloud.ans.server-list=127.0.0.1", + "spring.cloud.alicloud.ans.server-port=8080" }, webEnvironment = RANDOM_PORT) +public class AnsAutoServiceRegistrationIpNetworkInterfaceTests { + + @Autowired + private AnsRegistration registration; + + @Autowired + private AnsAutoServiceRegistration ansAutoServiceRegistration; + + @Autowired + private AnsProperties properties; + + @Autowired + private InetUtils inetUtils; + + @Test + public void contextLoads() throws Exception { + + assertNotNull("AnsRegistration was not created", registration); + assertNotNull("AnsProperties was not created", properties); + assertNotNull("AnsAutoServiceRegistration was not created", + ansAutoServiceRegistration); + + checkoutAnsDiscoveryServiceIP(); + + } + + private void checkoutAnsDiscoveryServiceIP() { + assertEquals("AnsProperties service IP was wrong", + getIPFromNetworkInterface(TestConfig.netWorkInterfaceName), + registration.getHost()); + + } + + private String getIPFromNetworkInterface(String networkInterface) { + + if (!TestConfig.hasValidNetworkInterface) { + return inetUtils.findFirstNonLoopbackHostInfo().getIpAddress(); + } + + try { + NetworkInterface netInterface = NetworkInterface.getByName(networkInterface); + + Enumeration inetAddress = netInterface.getInetAddresses(); + while (inetAddress.hasMoreElements()) { + InetAddress currentAddress = inetAddress.nextElement(); + if (currentAddress instanceof Inet4Address + && !currentAddress.isLoopbackAddress()) { + return currentAddress.getHostAddress(); + } + } + return networkInterface; + } + catch (Exception e) { + return networkInterface; + } + } + + @Configuration + @EnableAutoConfiguration + @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, + AnsDiscoveryClientAutoConfiguration.class, AnsAutoConfiguration.class }) + public static class TestConfig { + + static boolean hasValidNetworkInterface = false; + static String netWorkInterfaceName; + + static { + + try { + Enumeration enumeration = NetworkInterface + .getNetworkInterfaces(); + while (enumeration.hasMoreElements() && !hasValidNetworkInterface) { + NetworkInterface networkInterface = enumeration.nextElement(); + Enumeration inetAddress = networkInterface + .getInetAddresses(); + while (inetAddress.hasMoreElements()) { + InetAddress currentAddress = inetAddress.nextElement(); + if (currentAddress instanceof Inet4Address + && !currentAddress.isLoopbackAddress()) { + hasValidNetworkInterface = true; + netWorkInterfaceName = networkInterface.getName(); + System.setProperty( + "spring.cloud.alicloud.ans.client-interface-name", + networkInterface.getName()); + break; + } + } + } + + } + catch (Exception e) { + + } + } + } + +} diff --git a/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistrationIpTests.java b/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistrationIpTests.java new file mode 100644 index 00000000..7bf76b25 --- /dev/null +++ b/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistrationIpTests.java @@ -0,0 +1,92 @@ +/* + * Copyright (C) 2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.cloud.alicloud.ans.registry; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.ImportAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.cloud.alicloud.ans.AnsAutoConfiguration; +import org.springframework.cloud.alicloud.ans.AnsDiscoveryClientAutoConfiguration; +import org.springframework.cloud.alicloud.context.ans.AnsProperties; +import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.junit4.SpringRunner; + +/** + * @author xiaojing + */ + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = AnsAutoServiceRegistrationIpTests.TestConfig.class, properties = { + "spring.application.name=myTestService1", + "spring.cloud.alicloud.ans.client-domains=myTestService2", + "spring.cloud.alicloud.ans.server-list=127.0.0.1", + "spring.cloud.alicloud.ans.client-weight=2", + "spring.cloud.alicloud.ans.server-port=8080", + "spring.cloud.alicloud.ans.client-ip=123.123.123.123" }, webEnvironment = RANDOM_PORT) +public class AnsAutoServiceRegistrationIpTests { + + @Autowired + private AnsRegistration registration; + + @Autowired + private AnsAutoServiceRegistration ansAutoServiceRegistration; + + @Autowired + private AnsProperties properties; + + @Test + public void contextLoads() throws Exception { + + assertNotNull("AnsRegistration was not created", registration); + assertNotNull("AnsProperties was not created", properties); + assertNotNull("AnsAutoServiceRegistration was not created", + ansAutoServiceRegistration); + + checkoutAnsDiscoveryServiceIP(); + checkoutAnsDiscoveryServiceName(); + checkoutAnsDiscoveryWeight(); + } + + private void checkoutAnsDiscoveryServiceIP() { + assertEquals("AnsProperties service IP was wrong", "123.123.123.123", + registration.getHost()); + } + + private void checkoutAnsDiscoveryServiceName() { + assertEquals("AnsDiscoveryProperties service name was wrong", "myTestService2", + properties.getClientDomains()); + } + + private void checkoutAnsDiscoveryWeight() { + assertEquals(2L, properties.getClientWeight(), 0); + } + + @Configuration + @EnableAutoConfiguration + @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, + AnsDiscoveryClientAutoConfiguration.class, AnsAutoConfiguration.class }) + public static class TestConfig { + } +} diff --git a/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistrationManagementPortTests.java b/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistrationManagementPortTests.java new file mode 100644 index 00000000..aa346518 --- /dev/null +++ b/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistrationManagementPortTests.java @@ -0,0 +1,87 @@ +/* + * Copyright (C) 2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.cloud.alicloud.ans.registry; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; +import static org.springframework.cloud.alicloud.ans.registry.AnsRegistration.MANAGEMENT_CONTEXT_PATH; +import static org.springframework.cloud.alicloud.ans.registry.AnsRegistration.MANAGEMENT_PORT; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.ImportAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.cloud.alicloud.ans.AnsAutoConfiguration; +import org.springframework.cloud.alicloud.ans.AnsDiscoveryClientAutoConfiguration; +import org.springframework.cloud.alicloud.context.ans.AnsProperties; +import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.junit4.SpringRunner; + +/** + * @author xiaojing + */ + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = AnsAutoServiceRegistrationManagementPortTests.TestConfig.class, properties = { + "spring.application.name=myTestService1", "management.port=8888", + "management.context-path=/test-context-path", + "spring.cloud.alicloud.ans.server-list=127.0.0.1", + "spring.cloud.alicloud.ans.server-port=8080" }, webEnvironment = RANDOM_PORT) +public class AnsAutoServiceRegistrationManagementPortTests { + + @Autowired + private AnsRegistration registration; + + @Autowired + private AnsAutoServiceRegistration ansAutoServiceRegistration; + + @Autowired + private AnsProperties properties; + + @Test + public void contextLoads() throws Exception { + + assertNotNull("AnsRegistration was not created", registration); + assertNotNull("AnsProperties was not created", properties); + assertNotNull("AnsAutoServiceRegistration was not created", + ansAutoServiceRegistration); + + checkoutNacosDiscoveryManagementData(); + + } + + private void checkoutNacosDiscoveryManagementData() { + assertEquals("AnsProperties management port was wrong", "8888", + properties.getClientMetadata().get(MANAGEMENT_PORT)); + + assertEquals("AnsProperties management context path was wrong", + "/test-context-path", + properties.getClientMetadata().get(MANAGEMENT_CONTEXT_PATH)); + + } + + @Configuration + @EnableAutoConfiguration + @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, + AnsDiscoveryClientAutoConfiguration.class, AnsAutoConfiguration.class }) + public static class TestConfig { + } +} diff --git a/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistrationPortTests.java b/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistrationPortTests.java new file mode 100644 index 00000000..20e03eb4 --- /dev/null +++ b/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistrationPortTests.java @@ -0,0 +1,81 @@ +/* + * Copyright (C) 2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.cloud.alicloud.ans.registry; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.ImportAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.cloud.alicloud.ans.AnsAutoConfiguration; +import org.springframework.cloud.alicloud.ans.AnsDiscoveryClientAutoConfiguration; +import org.springframework.cloud.alicloud.context.ans.AnsProperties; +import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.junit4.SpringRunner; + +/** + * @author xiaojing + */ + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = AnsAutoServiceRegistrationPortTests.TestConfig.class, properties = { + "spring.application.name=myTestService1", + "spring.cloud.alicloud.ans.server-list=127.0.0.1", + "spring.cloud.alicloud.ans.server-port=8080", + "spring.cloud.alicloud.ans.client-port=8888" }, webEnvironment = RANDOM_PORT) +public class AnsAutoServiceRegistrationPortTests { + + @Autowired + private AnsRegistration registration; + + @Autowired + private AnsAutoServiceRegistration ansAutoServiceRegistration; + + @Autowired + private AnsProperties properties; + + @Test + public void contextLoads() throws Exception { + + assertNotNull("AnsRegistration was not created", registration); + assertNotNull("AnsDiscoveryProperties was not created", properties); + assertNotNull("AnsAutoServiceRegistration was not created", + ansAutoServiceRegistration); + + checkoutAnsDiscoveryServicePort(); + + } + + private void checkoutAnsDiscoveryServicePort() { + assertEquals("AnsDiscoveryProperties service Port was wrong", 8888, + registration.getPort()); + + } + + @Configuration + @EnableAutoConfiguration + @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, + AnsDiscoveryClientAutoConfiguration.class, AnsAutoConfiguration.class }) + public static class TestConfig { + } +} diff --git a/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistrationTests.java b/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistrationTests.java new file mode 100644 index 00000000..ad66e1aa --- /dev/null +++ b/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistrationTests.java @@ -0,0 +1,160 @@ +/* + * Copyright (C) 2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.cloud.alicloud.ans.registry; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.alibaba.ans.core.NamingService; +import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.ImportAutoConfiguration; +import org.springframework.boot.context.embedded.LocalServerPort; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.cloud.alicloud.ans.AnsAutoConfiguration; +import org.springframework.cloud.alicloud.ans.AnsDiscoveryClientAutoConfiguration; +import org.springframework.cloud.alicloud.ans.endpoint.AnsEndpoint; +import org.springframework.cloud.alicloud.context.ans.AnsProperties; +import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration; +import org.springframework.cloud.commons.util.InetUtils; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.junit4.SpringRunner; + +/** + * @author xiaojing + */ + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = AnsAutoServiceRegistrationTests.TestConfig.class, properties = { + "spring.application.name=myTestService1", + "spring.cloud.alicloud.ans.server-list=127.0.0.1", + "spring.cloud.alicloud.ans.server-port=8080", + "spring.cloud.alicloud.ans.secure=true", + "spring.cloud.alicloud.ans.endpoint=test-endpoint" }, webEnvironment = RANDOM_PORT) +public class AnsAutoServiceRegistrationTests { + + @Autowired + private AnsRegistration registration; + + @Autowired + private AnsAutoServiceRegistration ansAutoServiceRegistration; + + @LocalServerPort + private int port; + + @Autowired + private AnsProperties properties; + + @Autowired + private InetUtils inetUtils; + + @Test + public void contextLoads() throws Exception { + + assertNotNull("AnsRegistration was not created", registration); + assertNotNull("AnsProperties was not created", properties); + assertNotNull("AnsAutoServiceRegistration was not created", + ansAutoServiceRegistration); + + checkoutAnsDiscoveryServerList(); + checkoutAnsDiscoveryServerPort(); + + checkoutAnsDiscoveryServiceName(); + checkoutAnsDiscoveryServiceIP(); + checkoutAnsDiscoveryServicePort(); + checkoutAnsDiscoverySecure(); + + checkAutoRegister(); + + checkoutEndpoint(); + + } + + private void checkAutoRegister() { + assertTrue("Ans Auto Registration was not start", + ansAutoServiceRegistration.isRunning()); + } + + private void checkoutAnsDiscoveryServerList() { + assertEquals("AnsDiscoveryProperties server list was wrong", "127.0.0.1", + properties.getServerList()); + } + + private void checkoutAnsDiscoveryServerPort() { + assertEquals("AnsDiscoveryProperties server port was wrong", "8080", + properties.getServerPort()); + } + + private void checkoutAnsDiscoveryServiceName() { + assertEquals("AnsDiscoveryProperties service name was wrong", "myTestService1", + properties.getClientDomains()); + } + + private void checkoutAnsDiscoveryServiceIP() { + assertEquals("AnsDiscoveryProperties service IP was wrong", + inetUtils.findFirstNonLoopbackHostInfo().getIpAddress(), + registration.getHost()); + } + + private void checkoutAnsDiscoveryServicePort() { + assertEquals("AnsDiscoveryProperties service Port was wrong", port, + registration.getPort()); + } + + private void checkoutAnsDiscoverySecure() { + assertTrue("AnsDiscoveryProperties secure should be true", properties.isSecure()); + + } + + private void checkoutEndpoint() throws Exception { + AnsEndpoint ansEndpoint = new AnsEndpoint(properties); + Map map = ansEndpoint.invoke(); + assertEquals(map.get("ansProperties"), properties); + + Map subscribes = new HashMap<>(); + Set subscribeServices = NamingService.getDomsSubscribed(); + for (String service : subscribeServices) { + try { + List hosts = NamingService.getHosts(service); + subscribes.put(service, hosts); + } + catch (Exception ignoreException) { + + } + } + + assertEquals(map.get("subscribes"), subscribes); + } + + @Configuration + @EnableAutoConfiguration + @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, + AnsDiscoveryClientAutoConfiguration.class, AnsAutoConfiguration.class }) + public static class TestConfig { + } +} diff --git a/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/ribbon/AnsRibbonClientConfigurationTests.java b/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/ribbon/AnsRibbonClientConfigurationTests.java new file mode 100644 index 00000000..beb825c7 --- /dev/null +++ b/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/ribbon/AnsRibbonClientConfigurationTests.java @@ -0,0 +1,86 @@ +/* + * Copyright (C) 2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.cloud.alicloud.ans.ribbon; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.ImportAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.cloud.alicloud.ans.AnsAutoConfiguration; +import org.springframework.cloud.alicloud.ans.AnsDiscoveryClientAutoConfiguration; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; +import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.web.client.RestTemplate; + +import com.netflix.client.config.DefaultClientConfigImpl; +import com.netflix.client.config.IClientConfig; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; + +/** + * @author xiaojing + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = AnsRibbonClientConfigurationTests.TestConfig.class, properties = { + "spring.application.name=myTestService1", + "spring.cloud.alicloud.ans.server-list=127.0.0.1", + "spring.cloud.alicloud.ans.server-port=8080", + "spring.cloud.alicloud.ans.endpoint=test-endpoint" }, webEnvironment = RANDOM_PORT) +public class AnsRibbonClientConfigurationTests { + + @Autowired + private AnsServerList serverList; + + @Test + public void contextLoads() throws Exception { + assertThat(serverList.getDom()).isEqualTo("myapp"); + } + + @Configuration + public static class AnsRibbonTestConfiguration { + + @Bean + IClientConfig iClientConfig() { + DefaultClientConfigImpl config = new DefaultClientConfigImpl(); + config.setClientName("myapp"); + return config; + } + + @Bean + @LoadBalanced + RestTemplate restTemplate() { + return new RestTemplate(); + } + + } + + @Configuration + @EnableAutoConfiguration + @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, + AnsDiscoveryClientAutoConfiguration.class, AnsAutoConfiguration.class, + AnsRibbonTestConfiguration.class, RibbonAnsAutoConfiguration.class, + AnsRibbonClientConfiguration.class }) + public static class TestConfig { + } + +} diff --git a/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/ribbon/AnsServerListTests.java b/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/ribbon/AnsServerListTests.java new file mode 100644 index 00000000..78f88790 --- /dev/null +++ b/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/ribbon/AnsServerListTests.java @@ -0,0 +1,157 @@ +/* + * Copyright (C) 2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.cloud.alicloud.ans.ribbon; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.springframework.cloud.alicloud.ans.test.AnsMockTest.hostInstance; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import com.alibaba.ans.core.NamingService; +import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host; + +import com.netflix.client.config.IClientConfig; + +/** + * @author xiaojing + */ +@RunWith(PowerMockRunner.class) +@PrepareForTest({ NamingService.class, AnsServer.class }) +public class AnsServerListTests { + + @Test + @SuppressWarnings("unchecked") + public void testEmptyInstancesReturnsEmptyList() throws Exception { + + PowerMockito.mockStatic(NamingService.class); + when(NamingService.getHosts(anyString())).thenReturn(Collections.EMPTY_LIST); + + IClientConfig clientConfig = mock(IClientConfig.class); + when(clientConfig.getClientName()).thenReturn("test-service"); + AnsServerList serverList = new AnsServerList("test-service"); + serverList.initWithNiwsConfig(clientConfig); + List servers = serverList.getInitialListOfServers(); + assertThat(servers).isEmpty(); + } + + @Test + @SuppressWarnings("unchecked") + public void testGetServers() throws Exception { + + ArrayList hosts = new ArrayList<>(); + hosts.add(hostInstance("test-service", true, + Collections. emptyMap())); + + PowerMockito.mockStatic(NamingService.class); + when(NamingService.getHosts(anyString())).thenReturn(hosts); + + IClientConfig clientConfig = mock(IClientConfig.class); + when(clientConfig.getClientName()).thenReturn("test-service"); + AnsServerList serverList = new AnsServerList("test-service"); + serverList.initWithNiwsConfig(clientConfig); + List servers = serverList.getInitialListOfServers(); + assertThat(servers).hasSize(1); + + servers = serverList.getUpdatedListOfServers(); + assertThat(servers).hasSize(1); + } + + @Test + @SuppressWarnings("unchecked") + public void testGetServersWithInstanceStatus() throws Exception { + ArrayList hosts = new ArrayList<>(); + + HashMap map1 = new HashMap<>(); + map1.put("instanceNum", "1"); + HashMap map2 = new HashMap<>(); + map2.put("instanceNum", "2"); + hosts.add(hostInstance("test-service", false, map1)); + hosts.add(hostInstance("test-service", true, map2)); + + PowerMockito.mockStatic(NamingService.class); + + List returnInstances = new LinkedList<>(); + + for (Host host : hosts) { + if (host.isValid()) { + returnInstances.add(host); + } + } + when(NamingService.getHosts(eq("test-service"))).thenReturn(returnInstances); + + IClientConfig clientConfig = mock(IClientConfig.class); + when(clientConfig.getClientName()).thenReturn("test-service"); + AnsServerList serverList = new AnsServerList("test-service"); + serverList.initWithNiwsConfig(clientConfig); + List servers = serverList.getInitialListOfServers(); + assertThat(servers).hasSize(1); + + AnsServer ansServer = servers.get(0); + Host host = ansServer.getHealthService(); + + assertThat(ansServer.getMetaInfo().getInstanceId()).isEqualTo( + host.getIp() + ":" + host.getHostname() + ":" + host.getPort()); + assertThat(ansServer.getHealthService().isValid()).isEqualTo(true); + assertThat(ansServer.getHealthService().getHostname()).isEqualTo("test-service"); + + } + + @Test + public void testUpdateServers() throws Exception { + ArrayList hosts = new ArrayList<>(); + + HashMap map = new HashMap<>(); + map.put("instanceNum", "1"); + hosts.add(hostInstance("test-service", true, map)); + + PowerMockito.mockStatic(NamingService.class); + + List returnInstances = new LinkedList<>(); + for (Host host : hosts) { + if (host.isValid()) { + returnInstances.add(host); + } + } + when(NamingService.getHosts(eq("test-service"))).thenReturn(returnInstances); + + when(NamingService.getHosts(eq("test-service"))).thenReturn(returnInstances); + + IClientConfig clientConfig = mock(IClientConfig.class); + when(clientConfig.getClientName()).thenReturn("test-service"); + AnsServerList serverList = new AnsServerList("test-service"); + serverList.initWithNiwsConfig(clientConfig); + + List servers = serverList.getUpdatedListOfServers(); + assertThat(servers).hasSize(1); + + assertThat(servers.get(0).getHealthService().isValid()).isEqualTo(true); + } +} \ No newline at end of file diff --git a/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/test/AnsMockTest.java b/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/test/AnsMockTest.java new file mode 100644 index 00000000..795f2b49 --- /dev/null +++ b/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/test/AnsMockTest.java @@ -0,0 +1,45 @@ +/* + * Copyright (C) 2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.cloud.alicloud.ans.test; + +import java.util.Map; + +import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host; + +/** + * @author xiaojing + */ +public class AnsMockTest { + + public static Host hostInstance(String serviceName, boolean valid, + Map metadata) { + Host host = new Host(); + host.setHostname(serviceName); + host.setValid(valid); + return host; + } + + public static Host hostInstance(String serviceName, boolean valid, String ip, + int port, Map metadata) { + Host host = new Host(); + host.setIp(ip); + host.setPort(port); + host.setValid(valid); + host.setHostname(serviceName); + return host; + } +}