index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/context
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/context/event/DubboConfigBeanDefinitionConflictApplicationListener.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.spring.boot.context.event; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.spring.context.annotation.EnableDubboConfig; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.Stream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.beans.factory.config.AutowireCapableBeanFactory; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.core.Ordered; import org.springframework.core.env.Environment; import static org.springframework.beans.factory.BeanFactoryUtils.beanNamesForTypeIncludingAncestors; import static org.springframework.context.ConfigurableApplicationContext.ENVIRONMENT_BEAN_NAME; /** * The {@link ApplicationListener} class for Dubbo Config {@link BeanDefinition Bean Definition} to resolve conflict * * @see BeanDefinition * @see ApplicationListener * @since 2.7.5 */ public class DubboConfigBeanDefinitionConflictApplicationListener implements ApplicationListener<ContextRefreshedEvent>, Ordered { private final Logger logger = LoggerFactory.getLogger(getClass()); @Override public void onApplicationEvent(ContextRefreshedEvent event) { ApplicationContext applicationContext = event.getApplicationContext(); BeanDefinitionRegistry registry = getBeanDefinitionRegistry(applicationContext); resolveUniqueApplicationConfigBean(registry, applicationContext); } private BeanDefinitionRegistry getBeanDefinitionRegistry(ApplicationContext applicationContext) { AutowireCapableBeanFactory beanFactory = applicationContext.getAutowireCapableBeanFactory(); if (beanFactory instanceof BeanDefinitionRegistry) { return (BeanDefinitionRegistry) beanFactory; } throw new IllegalStateException( "The BeanFactory in the ApplicationContext must bea subclass of BeanDefinitionRegistry"); } /** * Resolve the unique {@link ApplicationConfig} Bean * * @param registry {@link BeanDefinitionRegistry} instance * @param beanFactory {@link ConfigurableListableBeanFactory} instance * @see EnableDubboConfig */ private void resolveUniqueApplicationConfigBean(BeanDefinitionRegistry registry, ListableBeanFactory beanFactory) { String[] beansNames = beanNamesForTypeIncludingAncestors(beanFactory, ApplicationConfig.class); if (beansNames.length < 2) { // If the number of ApplicationConfig beans is less than two, return immediately. return; } Environment environment = beanFactory.getBean(ENVIRONMENT_BEAN_NAME, Environment.class); // Remove ApplicationConfig Beans that are configured by "dubbo.application.*" Stream.of(beansNames) .filter(beansName -> isConfiguredApplicationConfigBeanName(environment, beansName)) .forEach(registry::removeBeanDefinition); beansNames = beanNamesForTypeIncludingAncestors(beanFactory, ApplicationConfig.class); if (beansNames.length > 1) { throw new IllegalStateException(String.format( "There are more than one instances of %s, whose bean definitions : %s", ApplicationConfig.class.getSimpleName(), Stream.of(beansNames).map(registry::getBeanDefinition).collect(Collectors.toList()))); } } private boolean isConfiguredApplicationConfigBeanName(Environment environment, String beanName) { boolean removed = BeanFactoryUtils.isGeneratedBeanName(beanName) // Dubbo ApplicationConfig id as bean name || Objects.equals(beanName, environment.getProperty("dubbo.application.id")); if (removed && logger.isDebugEnabled()) { logger.debug( "The {} bean [ name : {} ] has been removed!", ApplicationConfig.class.getSimpleName(), beanName); } return removed; } @Override public int getOrder() { return LOWEST_PRECEDENCE; } }
7,700
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/util/DubboUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.spring.boot.util; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.spring.beans.factory.annotation.ServiceAnnotationPostProcessor; import org.apache.dubbo.config.spring.context.annotation.EnableDubboConfig; import org.apache.dubbo.config.spring.context.properties.DubboConfigBinder; import java.util.Set; import org.springframework.boot.context.ContextIdApplicationContextInitializer; import org.springframework.core.env.PropertyResolver; /** * The utilities class for Dubbo * * @since 2.7.0 */ public abstract class DubboUtils { /** * line separator */ public static final String LINE_SEPARATOR = System.getProperty("line.separator"); /** * The separator of property name */ public static final String PROPERTY_NAME_SEPARATOR = "."; /** * The prefix of property name of Dubbo */ public static final String DUBBO_PREFIX = "dubbo"; /** * The prefix of property name for Dubbo scan */ public static final String DUBBO_SCAN_PREFIX = DUBBO_PREFIX + PROPERTY_NAME_SEPARATOR + "scan" + PROPERTY_NAME_SEPARATOR; /** * The prefix of property name for Dubbo Config */ public static final String DUBBO_CONFIG_PREFIX = DUBBO_PREFIX + PROPERTY_NAME_SEPARATOR + "config" + PROPERTY_NAME_SEPARATOR; /** * The property name of base packages to scan * <p> * The default value is empty set. */ public static final String BASE_PACKAGES_PROPERTY_NAME = "base-packages"; /** * The property name of multiple properties binding from externalized configuration * <p> * The default value is {@link #DEFAULT_MULTIPLE_CONFIG_PROPERTY_VALUE} * * @deprecated 2.7.8 It will be remove in the future, {@link EnableDubboConfig} instead */ @Deprecated public static final String MULTIPLE_CONFIG_PROPERTY_NAME = "multiple"; /** * The default value of multiple properties binding from externalized configuration * * @deprecated 2.7.8 It will be remove in the future */ @Deprecated public static final boolean DEFAULT_MULTIPLE_CONFIG_PROPERTY_VALUE = true; /** * The property name of override Dubbo config * <p> * The default value is {@link #DEFAULT_OVERRIDE_CONFIG_PROPERTY_VALUE} */ public static final String OVERRIDE_CONFIG_FULL_PROPERTY_NAME = DUBBO_CONFIG_PREFIX + "override"; /** * The default property value of override Dubbo config */ public static final boolean DEFAULT_OVERRIDE_CONFIG_PROPERTY_VALUE = true; /** * The github URL of Dubbo Spring Boot */ public static final String DUBBO_SPRING_BOOT_GITHUB_URL = "https://github.com/apache/dubbo/tree/3.0/dubbo-spring-boot"; /** * The git URL of Dubbo Spring Boot */ public static final String DUBBO_SPRING_BOOT_GIT_URL = "https://github.com/apache/dubbo.git"; /** * The issues of Dubbo Spring Boot */ public static final String DUBBO_SPRING_BOOT_ISSUES_URL = "https://github.com/apache/dubbo/issues"; /** * The github URL of Dubbo */ public static final String DUBBO_GITHUB_URL = "https://github.com/apache/dubbo"; /** * The google group URL of Dubbo */ public static final String DUBBO_MAILING_LIST = "[email protected]"; /** * The bean name of Relaxed-binding {@link DubboConfigBinder} */ public static final String RELAXED_DUBBO_CONFIG_BINDER_BEAN_NAME = "relaxedDubboConfigBinder"; /** * The bean name of {@link PropertyResolver} for {@link ServiceAnnotationPostProcessor}'s base-packages * * @deprecated 2.7.8 It will be remove in the future, please use {@link #BASE_PACKAGES_BEAN_NAME} */ @Deprecated public static final String BASE_PACKAGES_PROPERTY_RESOLVER_BEAN_NAME = "dubboScanBasePackagesPropertyResolver"; /** * The bean name of {@link Set} presenting {@link ServiceAnnotationPostProcessor}'s base-packages * * @since 2.7.8 */ public static final String BASE_PACKAGES_BEAN_NAME = "dubbo-service-class-base-packages"; /** * The property name of Spring Application * * @see ContextIdApplicationContextInitializer * @since 2.7.1 */ public static final String SPRING_APPLICATION_NAME_PROPERTY = "spring.application.name"; /** * The property id of {@link ApplicationConfig} Bean * * @see EnableDubboConfig * @since 2.7.1 */ public static final String DUBBO_APPLICATION_ID_PROPERTY = "dubbo.application.id"; /** * The property name of {@link ApplicationConfig} * * @see EnableDubboConfig * @since 2.7.1 */ public static final String DUBBO_APPLICATION_NAME_PROPERTY = "dubbo.application.name"; /** * The property name of {@link ApplicationConfig#getQosEnable() application's QOS enable} * * @since 2.7.1 */ public static final String DUBBO_APPLICATION_QOS_ENABLE_PROPERTY = "dubbo.application.qos-enable"; /** * The property name of {@link EnableDubboConfig#multiple() @EnableDubboConfig.multiple()} * * @since 2.7.1 */ public static final String DUBBO_CONFIG_MULTIPLE_PROPERTY = "dubbo.config.multiple"; }
7,701
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/env/DubboDefaultPropertiesEnvironmentPostProcessor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.spring.boot.env; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.springframework.boot.SpringApplication; import org.springframework.boot.env.EnvironmentPostProcessor; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.core.Ordered; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.Environment; import org.springframework.core.env.MapPropertySource; import org.springframework.core.env.MutablePropertySources; import org.springframework.core.env.PropertySource; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_APPLICATION_NAME_PROPERTY; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_CONFIG_MULTIPLE_PROPERTY; import static org.apache.dubbo.spring.boot.util.DubboUtils.SPRING_APPLICATION_NAME_PROPERTY; /** * The lowest precedence {@link EnvironmentPostProcessor} processes * {@link SpringApplication#setDefaultProperties(Properties) Spring Boot default properties} for Dubbo * as late as possible before {@link ConfigurableApplicationContext#refresh() application context refresh}. */ public class DubboDefaultPropertiesEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered { /** * The name of default {@link PropertySource} defined in SpringApplication#configurePropertySources method. */ public static final String PROPERTY_SOURCE_NAME = "defaultProperties"; /** * The property name of "spring.main.allow-bean-definition-overriding". * Please refer to: https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.1-Release-Notes#bean-overriding */ public static final String ALLOW_BEAN_DEFINITION_OVERRIDING_PROPERTY = "spring.main.allow-bean-definition-overriding"; @Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { MutablePropertySources propertySources = environment.getPropertySources(); Map<String, Object> defaultProperties = createDefaultProperties(environment); if (!CollectionUtils.isEmpty(defaultProperties)) { addOrReplace(propertySources, defaultProperties); } } @Override public int getOrder() { return LOWEST_PRECEDENCE; } private Map<String, Object> createDefaultProperties(ConfigurableEnvironment environment) { Map<String, Object> defaultProperties = new HashMap<>(); setDubboApplicationNameProperty(environment, defaultProperties); setDubboConfigMultipleProperty(defaultProperties); return defaultProperties; } private void setDubboApplicationNameProperty(Environment environment, Map<String, Object> defaultProperties) { String springApplicationName = environment.getProperty(SPRING_APPLICATION_NAME_PROPERTY); if (StringUtils.hasLength(springApplicationName) && !environment.containsProperty(DUBBO_APPLICATION_NAME_PROPERTY)) { defaultProperties.put(DUBBO_APPLICATION_NAME_PROPERTY, springApplicationName); } } private void setDubboConfigMultipleProperty(Map<String, Object> defaultProperties) { defaultProperties.put(DUBBO_CONFIG_MULTIPLE_PROPERTY, Boolean.TRUE.toString()); } /** * Set {@link #ALLOW_BEAN_DEFINITION_OVERRIDING_PROPERTY "spring.main.allow-bean-definition-overriding"} to be * <code>true</code> as default. * * @param defaultProperties the default {@link Properties properties} * @see #ALLOW_BEAN_DEFINITION_OVERRIDING_PROPERTY * @since 2.7.1 */ private void setAllowBeanDefinitionOverriding(Map<String, Object> defaultProperties) { defaultProperties.put(ALLOW_BEAN_DEFINITION_OVERRIDING_PROPERTY, Boolean.TRUE.toString()); } /** * Copy from BusEnvironmentPostProcessor#addOrReplace(MutablePropertySources, Map) * * @param propertySources {@link MutablePropertySources} * @param map Default Dubbo Properties */ private void addOrReplace(MutablePropertySources propertySources, Map<String, Object> map) { MapPropertySource target = null; if (propertySources.contains(PROPERTY_SOURCE_NAME)) { PropertySource<?> source = propertySources.get(PROPERTY_SOURCE_NAME); if (source instanceof MapPropertySource) { target = (MapPropertySource) source; for (Map.Entry<String, Object> entry : map.entrySet()) { String key = entry.getKey(); if (!target.containsProperty(key)) { target.getSource().put(key, entry.getValue()); } } } } if (target == null) { target = new MapPropertySource(PROPERTY_SOURCE_NAME, map); } if (!propertySources.contains(PROPERTY_SOURCE_NAME)) { propertySources.addLast(target); } } }
7,702
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/beans/factory
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/beans/factory/config/ServiceBeanIdConflictProcessor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.spring.boot.beans.factory.config; import org.apache.dubbo.config.ServiceConfig; import org.apache.dubbo.config.spring.ServiceBean; import org.apache.dubbo.config.spring.reference.ReferenceAttributes; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Set; import org.springframework.beans.BeansException; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.context.annotation.CommonAnnotationBeanPostProcessor; import org.springframework.core.Ordered; import org.springframework.core.PriorityOrdered; import static org.apache.dubbo.config.spring.util.SpringCompatUtils.getPropertyValue; import static org.springframework.util.ClassUtils.getUserClass; import static org.springframework.util.ClassUtils.isAssignable; /** * The post-processor for resolving the id conflict of {@link ServiceBean} when an interface is * implemented by multiple services with different groups or versions that are exported on one provider * <p> * Current implementation is a temporary resolution, and will be removed in the future. * * @see CommonAnnotationBeanPostProcessor * @since 2.7.7 * @deprecated */ public class ServiceBeanIdConflictProcessor implements MergedBeanDefinitionPostProcessor, DisposableBean, PriorityOrdered { /** * The key is the class names of interfaces that were exported by {@link ServiceBean} * The value is bean names of {@link ServiceBean} or {@link ServiceConfig}. */ private Map<String, String> interfaceNamesToBeanNames = new HashMap<>(); /** * Holds the bean names of {@link ServiceBean} or {@link ServiceConfig}. */ private Set<String> conflictedBeanNames = new HashSet<>(); @Override public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) { // Get raw bean type Class<?> rawBeanType = getUserClass(beanType); if (isAssignable(ServiceConfig.class, rawBeanType)) { // ServiceConfig type or sub-type String interfaceName = getPropertyValue(beanDefinition.getPropertyValues(), ReferenceAttributes.INTERFACE); String mappedBeanName = interfaceNamesToBeanNames.putIfAbsent(interfaceName, beanName); // If mapped bean name exists and does not equal current bean name if (mappedBeanName != null && !mappedBeanName.equals(beanName)) { // conflictedBeanNames will record current bean name. conflictedBeanNames.add(beanName); } } } @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (conflictedBeanNames.contains(beanName) && bean instanceof ServiceConfig) { ServiceConfig serviceConfig = (ServiceConfig) bean; if (isConflictedServiceConfig(serviceConfig)) { // Set id as the bean name serviceConfig.setId(beanName); } } return bean; } private boolean isConflictedServiceConfig(ServiceConfig serviceConfig) { return Objects.equals(serviceConfig.getId(), serviceConfig.getInterface()); } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; } /** * Keep the order being higher than {@link CommonAnnotationBeanPostProcessor#getOrder()} that is * {@link Ordered#LOWEST_PRECEDENCE} * * @return {@link Ordered#LOWEST_PRECEDENCE} +1 */ @Override public int getOrder() { return LOWEST_PRECEDENCE + 1; } @Override public void destroy() throws Exception { interfaceNamesToBeanNames.clear(); conflictedBeanNames.clear(); } }
7,703
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/DubboRelaxedBindingAutoConfiguration.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.spring.boot.autoconfigure; import java.util.Set; import com.alibaba.spring.context.config.ConfigurationBeanBinder; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.bind.RelaxedPropertyResolver; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; import org.springframework.core.env.Environment; import org.springframework.core.env.PropertyResolver; import static java.util.Collections.emptySet; import static org.apache.dubbo.spring.boot.util.DubboUtils.BASE_PACKAGES_BEAN_NAME; import static org.apache.dubbo.spring.boot.util.DubboUtils.BASE_PACKAGES_PROPERTY_NAME; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_PREFIX; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_SCAN_PREFIX; import static org.apache.dubbo.spring.boot.util.DubboUtils.RELAXED_DUBBO_CONFIG_BINDER_BEAN_NAME; import static org.springframework.beans.factory.config.ConfigurableBeanFactory.SCOPE_PROTOTYPE; /** * Dubbo Relaxed Binding Auto-{@link Configuration} for Spring Boot 1.x */ @ConditionalOnProperty(prefix = DUBBO_PREFIX, name = "enabled", matchIfMissing = true) @ConditionalOnClass(name = "org.springframework.boot.bind.RelaxedPropertyResolver") @Configuration public class DubboRelaxedBindingAutoConfiguration { public PropertyResolver dubboScanBasePackagesPropertyResolver(Environment environment) { return new RelaxedPropertyResolver(environment, DUBBO_SCAN_PREFIX); } /** * The bean is used to scan the packages of Dubbo Service classes * * @param environment {@link Environment} instance * @return non-null {@link Set} * @since 2.7.8 */ @ConditionalOnMissingBean(name = BASE_PACKAGES_BEAN_NAME) @Bean(name = BASE_PACKAGES_BEAN_NAME) public Set<String> dubboBasePackages(Environment environment) { PropertyResolver propertyResolver = dubboScanBasePackagesPropertyResolver(environment); return propertyResolver.getProperty(BASE_PACKAGES_PROPERTY_NAME, Set.class, emptySet()); } @ConditionalOnMissingBean(name = RELAXED_DUBBO_CONFIG_BINDER_BEAN_NAME, value = ConfigurationBeanBinder.class) @Bean(RELAXED_DUBBO_CONFIG_BINDER_BEAN_NAME) @Scope(scopeName = SCOPE_PROTOTYPE) public ConfigurationBeanBinder relaxedDubboConfigBinder() { return new RelaxedDubboConfigBinder(); } }
7,704
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/DubboListenerAutoConfiguration.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.spring.boot.autoconfigure; import org.apache.dubbo.spring.boot.context.event.AwaitingNonWebApplicationListener; import org.apache.dubbo.spring.boot.context.event.DubboConfigBeanDefinitionConflictApplicationListener; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_PREFIX; /** * Dubbo Listener Auto-{@link Configuration} * * @since 3.0.4 */ @ConditionalOnProperty(prefix = DUBBO_PREFIX, name = "enabled", matchIfMissing = true) @Configuration public class DubboListenerAutoConfiguration { @ConditionalOnMissingBean @Bean public DubboConfigBeanDefinitionConflictApplicationListener dubboConfigBeanDefinitionConflictApplicationListener() { return new DubboConfigBeanDefinitionConflictApplicationListener(); } @ConditionalOnMissingBean @Bean public AwaitingNonWebApplicationListener awaitingNonWebApplicationListener() { return new AwaitingNonWebApplicationListener(); } }
7,705
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/DubboConfigurationProperties.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.spring.boot.autoconfigure; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ConfigKeys; import org.apache.dubbo.config.ConsumerConfig; import org.apache.dubbo.config.MetadataReportConfig; import org.apache.dubbo.config.MetricsConfig; import org.apache.dubbo.config.ModuleConfig; import org.apache.dubbo.config.MonitorConfig; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.ProviderConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.TracingConfig; import org.apache.dubbo.config.context.ConfigMode; import org.apache.dubbo.config.spring.ConfigCenterBean; import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.NestedConfigurationProperty; import static org.apache.dubbo.spring.boot.util.DubboUtils.DEFAULT_MULTIPLE_CONFIG_PROPERTY_VALUE; import static org.apache.dubbo.spring.boot.util.DubboUtils.DEFAULT_OVERRIDE_CONFIG_PROPERTY_VALUE; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_PREFIX; /** * Dubbo {@link ConfigurationProperties Config Properties} only used to generate JSON metadata(non-public class) * * @see ConfigKeys * @since 2.7.1 */ @ConfigurationProperties(DUBBO_PREFIX) public class DubboConfigurationProperties { @NestedConfigurationProperty private Config config = new Config(); @NestedConfigurationProperty private Scan scan = new Scan(); // Single Config Bindings @NestedConfigurationProperty private ApplicationConfig application = new ApplicationConfig(); @NestedConfigurationProperty private ModuleConfig module = new ModuleConfig(); @NestedConfigurationProperty private RegistryConfig registry = new RegistryConfig(); @NestedConfigurationProperty private ProtocolConfig protocol = new ProtocolConfig(); @NestedConfigurationProperty private MonitorConfig monitor = new MonitorConfig(); @NestedConfigurationProperty private ProviderConfig provider = new ProviderConfig(); @NestedConfigurationProperty private ConsumerConfig consumer = new ConsumerConfig(); @NestedConfigurationProperty private ConfigCenterBean configCenter = new ConfigCenterBean(); @NestedConfigurationProperty private MetadataReportConfig metadataReport = new MetadataReportConfig(); @NestedConfigurationProperty private MetricsConfig metrics = new MetricsConfig(); @NestedConfigurationProperty private TracingConfig tracing = new TracingConfig(); // Multiple Config Bindings private Map<String, ModuleConfig> modules = new LinkedHashMap<>(); private Map<String, RegistryConfig> registries = new LinkedHashMap<>(); private Map<String, ProtocolConfig> protocols = new LinkedHashMap<>(); private Map<String, MonitorConfig> monitors = new LinkedHashMap<>(); private Map<String, ProviderConfig> providers = new LinkedHashMap<>(); private Map<String, ConsumerConfig> consumers = new LinkedHashMap<>(); private Map<String, ConfigCenterBean> configCenters = new LinkedHashMap<>(); private Map<String, MetadataReportConfig> metadataReports = new LinkedHashMap<>(); private Map<String, MetricsConfig> metricses = new LinkedHashMap<>(); private Map<String, TracingConfig> tracings = new LinkedHashMap<>(); public Config getConfig() { return config; } public void setConfig(Config config) { this.config = config; } public Scan getScan() { return scan; } public void setScan(Scan scan) { this.scan = scan; } public ApplicationConfig getApplication() { return application; } public void setApplication(ApplicationConfig application) { this.application = application; } public ModuleConfig getModule() { return module; } public void setModule(ModuleConfig module) { this.module = module; } public RegistryConfig getRegistry() { return registry; } public void setRegistry(RegistryConfig registry) { this.registry = registry; } public ProtocolConfig getProtocol() { return protocol; } public void setProtocol(ProtocolConfig protocol) { this.protocol = protocol; } public MonitorConfig getMonitor() { return monitor; } public void setMonitor(MonitorConfig monitor) { this.monitor = monitor; } public ProviderConfig getProvider() { return provider; } public void setProvider(ProviderConfig provider) { this.provider = provider; } public ConsumerConfig getConsumer() { return consumer; } public void setConsumer(ConsumerConfig consumer) { this.consumer = consumer; } public ConfigCenterBean getConfigCenter() { return configCenter; } public void setConfigCenter(ConfigCenterBean configCenter) { this.configCenter = configCenter; } public MetadataReportConfig getMetadataReport() { return metadataReport; } public void setMetadataReport(MetadataReportConfig metadataReport) { this.metadataReport = metadataReport; } public MetricsConfig getMetrics() { return metrics; } public void setMetrics(MetricsConfig metrics) { this.metrics = metrics; } public TracingConfig getTracing() { return tracing; } public void setTracing(TracingConfig tracing) { this.tracing = tracing; } public Map<String, ModuleConfig> getModules() { return modules; } public void setModules(Map<String, ModuleConfig> modules) { this.modules = modules; } public Map<String, RegistryConfig> getRegistries() { return registries; } public void setRegistries(Map<String, RegistryConfig> registries) { this.registries = registries; } public Map<String, ProtocolConfig> getProtocols() { return protocols; } public void setProtocols(Map<String, ProtocolConfig> protocols) { this.protocols = protocols; } public Map<String, MonitorConfig> getMonitors() { return monitors; } public void setMonitors(Map<String, MonitorConfig> monitors) { this.monitors = monitors; } public Map<String, ProviderConfig> getProviders() { return providers; } public void setProviders(Map<String, ProviderConfig> providers) { this.providers = providers; } public Map<String, ConsumerConfig> getConsumers() { return consumers; } public void setConsumers(Map<String, ConsumerConfig> consumers) { this.consumers = consumers; } public Map<String, ConfigCenterBean> getConfigCenters() { return configCenters; } public void setConfigCenters(Map<String, ConfigCenterBean> configCenters) { this.configCenters = configCenters; } public Map<String, MetadataReportConfig> getMetadataReports() { return metadataReports; } public void setMetadataReports(Map<String, MetadataReportConfig> metadataReports) { this.metadataReports = metadataReports; } public Map<String, MetricsConfig> getMetricses() { return metricses; } public void setMetricses(Map<String, MetricsConfig> metricses) { this.metricses = metricses; } public Map<String, TracingConfig> getTracings() { return tracings; } public void setTracings(Map<String, TracingConfig> tracings) { this.tracings = tracings; } static class Config { /** * Config processing mode * @see ConfigMode */ private ConfigMode mode = ConfigMode.STRICT; /** * Indicates multiple properties binding from externalized configuration or not. */ private boolean multiple = DEFAULT_MULTIPLE_CONFIG_PROPERTY_VALUE; /** * The property name of override Dubbo config */ private boolean override = DEFAULT_OVERRIDE_CONFIG_PROPERTY_VALUE; public boolean isOverride() { return override; } public void setOverride(boolean override) { this.override = override; } public boolean isMultiple() { return multiple; } public void setMultiple(boolean multiple) { this.multiple = multiple; } public ConfigMode getMode() { return mode; } public void setMode(ConfigMode mode) { this.mode = mode; } } static class Scan { /** * The basePackages to scan , the multiple-value is delimited by comma * * @see EnableDubbo#scanBasePackages() */ private Set<String> basePackages = new LinkedHashSet<>(); public Set<String> getBasePackages() { return basePackages; } public void setBasePackages(Set<String> basePackages) { this.basePackages = basePackages; } } }
7,706
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/DubboAutoConfiguration.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.spring.boot.autoconfigure; import org.apache.dubbo.config.annotation.DubboReference; import org.apache.dubbo.config.annotation.DubboService; import org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessor; import org.apache.dubbo.config.spring.beans.factory.annotation.ServiceAnnotationPostProcessor; import org.apache.dubbo.config.spring.context.annotation.EnableDubboConfig; import java.util.Set; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import static org.apache.dubbo.spring.boot.util.DubboUtils.BASE_PACKAGES_BEAN_NAME; import static org.apache.dubbo.spring.boot.util.DubboUtils.BASE_PACKAGES_PROPERTY_NAME; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_PREFIX; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_SCAN_PREFIX; /** * Dubbo Auto {@link Configuration} * * @see DubboReference * @see DubboService * @see ServiceAnnotationPostProcessor * @see ReferenceAnnotationBeanPostProcessor * @since 2.7.0 */ @ConditionalOnProperty(prefix = DUBBO_PREFIX, name = "enabled", matchIfMissing = true) @Configuration @AutoConfigureAfter(DubboRelaxedBindingAutoConfiguration.class) @EnableConfigurationProperties(DubboConfigurationProperties.class) @EnableDubboConfig public class DubboAutoConfiguration { /** * Creates {@link ServiceAnnotationPostProcessor} Bean * * @param packagesToScan the packages to scan * @return {@link ServiceAnnotationPostProcessor} */ @ConditionalOnProperty(prefix = DUBBO_SCAN_PREFIX, name = BASE_PACKAGES_PROPERTY_NAME) @ConditionalOnBean(name = BASE_PACKAGES_BEAN_NAME) @Bean public ServiceAnnotationPostProcessor serviceAnnotationBeanProcessor( @Qualifier(BASE_PACKAGES_BEAN_NAME) Set<String> packagesToScan) { return new ServiceAnnotationPostProcessor(packagesToScan); } }
7,707
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/RelaxedDubboConfigBinder.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.spring.boot.autoconfigure; import org.apache.dubbo.config.spring.context.properties.DubboConfigBinder; import java.util.Map; import com.alibaba.spring.context.config.ConfigurationBeanBinder; import org.springframework.beans.MutablePropertyValues; import org.springframework.boot.bind.RelaxedDataBinder; /** * Spring Boot Relaxed {@link DubboConfigBinder} implementation * * @since 2.7.0 */ class RelaxedDubboConfigBinder implements ConfigurationBeanBinder { @Override public void bind( Map<String, Object> configurationProperties, boolean ignoreUnknownFields, boolean ignoreInvalidFields, Object configurationBean) { RelaxedDataBinder relaxedDataBinder = new RelaxedDataBinder(configurationBean); // Set ignored* relaxedDataBinder.setIgnoreInvalidFields(ignoreInvalidFields); relaxedDataBinder.setIgnoreUnknownFields(ignoreUnknownFields); // Get properties under specified prefix from PropertySources // Convert Map to MutablePropertyValues MutablePropertyValues propertyValues = new MutablePropertyValues(configurationProperties); // Bind relaxedDataBinder.bind(propertyValues); } }
7,708
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-autoconfigure/src/test/java/org/apache/dubbo/spring/boot
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-autoconfigure/src/test/java/org/apache/dubbo/spring/boot/env/DubboDefaultPropertiesEnvironmentPostProcessorTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.spring.boot.env; import java.util.HashMap; import org.junit.Assert; import org.junit.Test; import org.springframework.boot.SpringApplication; import org.springframework.core.Ordered; import org.springframework.core.env.MapPropertySource; import org.springframework.core.env.MutablePropertySources; import org.springframework.core.env.PropertySource; import org.springframework.mock.env.MockEnvironment; /** * {@link DubboDefaultPropertiesEnvironmentPostProcessor} Test */ class DubboDefaultPropertiesEnvironmentPostProcessorTest { private DubboDefaultPropertiesEnvironmentPostProcessor instance = new DubboDefaultPropertiesEnvironmentPostProcessor(); private SpringApplication springApplication = new SpringApplication(); @Test void testOrder() { Assert.assertEquals(Ordered.LOWEST_PRECEDENCE, instance.getOrder()); } @Test void testPostProcessEnvironment() { MockEnvironment environment = new MockEnvironment(); // Case 1 : Not Any property instance.postProcessEnvironment(environment, springApplication); // Get PropertySources MutablePropertySources propertySources = environment.getPropertySources(); // Nothing to change PropertySource defaultPropertySource = propertySources.get("defaultProperties"); Assert.assertNotNull(defaultPropertySource); Assert.assertEquals("true", defaultPropertySource.getProperty("dubbo.config.multiple")); Assert.assertEquals("true", defaultPropertySource.getProperty("dubbo.application.qos-enable")); // Case 2 : Only set property "spring.application.name" environment.setProperty("spring.application.name", "demo-dubbo-application"); instance.postProcessEnvironment(environment, springApplication); defaultPropertySource = propertySources.get("defaultProperties"); Object dubboApplicationName = defaultPropertySource.getProperty("dubbo.application.name"); Assert.assertEquals("demo-dubbo-application", dubboApplicationName); // Case 3 : Only set property "dubbo.application.name" // Reset environment environment = new MockEnvironment(); propertySources = environment.getPropertySources(); environment.setProperty("dubbo.application.name", "demo-dubbo-application"); instance.postProcessEnvironment(environment, springApplication); defaultPropertySource = propertySources.get("defaultProperties"); Assert.assertNotNull(defaultPropertySource); dubboApplicationName = environment.getProperty("dubbo.application.name"); Assert.assertEquals("demo-dubbo-application", dubboApplicationName); // Case 4 : If "defaultProperties" PropertySource is present in PropertySources // Reset environment environment = new MockEnvironment(); propertySources = environment.getPropertySources(); propertySources.addLast(new MapPropertySource("defaultProperties", new HashMap<String, Object>())); environment.setProperty("spring.application.name", "demo-dubbo-application"); instance.postProcessEnvironment(environment, springApplication); defaultPropertySource = propertySources.get("defaultProperties"); dubboApplicationName = defaultPropertySource.getProperty("dubbo.application.name"); Assert.assertEquals("demo-dubbo-application", dubboApplicationName); // Case 5 : Reset dubbo.config.multiple and dubbo.application.qos-enable environment = new MockEnvironment(); propertySources = environment.getPropertySources(); propertySources.addLast(new MapPropertySource("defaultProperties", new HashMap<String, Object>())); environment.setProperty("dubbo.config.multiple", "false"); environment.setProperty("dubbo.application.qos-enable", "false"); instance.postProcessEnvironment(environment, springApplication); Assert.assertEquals("false", environment.getProperty("dubbo.config.multiple")); Assert.assertEquals("false", environment.getProperty("dubbo.application.qos-enable")); } }
7,709
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-autoconfigure/src/test/java/org/apache/dubbo/spring/boot
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/DubboRelaxedBinding2AutoConfigurationTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.spring.boot.autoconfigure; import org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessor; import org.apache.dubbo.config.spring.beans.factory.annotation.ServiceAnnotationPostProcessor; import org.apache.dubbo.config.spring.util.DubboBeanUtils; import java.util.Map; import java.util.Set; import com.alibaba.spring.context.config.ConfigurationBeanBinder; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.util.ClassUtils; import static org.apache.dubbo.spring.boot.util.DubboUtils.BASE_PACKAGES_BEAN_NAME; import static org.apache.dubbo.spring.boot.util.DubboUtils.RELAXED_DUBBO_CONFIG_BINDER_BEAN_NAME; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; /** * {@link DubboRelaxedBinding2AutoConfiguration} Test */ @RunWith(SpringRunner.class) @SpringBootTest( classes = DubboRelaxedBinding2AutoConfigurationTest.class, properties = {"dubbo.scan.basePackages = org.apache.dubbo.spring.boot.autoconfigure"}) @EnableAutoConfiguration @PropertySource(value = "classpath:/dubbo.properties") class DubboRelaxedBinding2AutoConfigurationTest { @Autowired @Qualifier(BASE_PACKAGES_BEAN_NAME) private Set<String> packagesToScan; @Autowired @Qualifier(RELAXED_DUBBO_CONFIG_BINDER_BEAN_NAME) private ConfigurationBeanBinder dubboConfigBinder; @Autowired private ObjectProvider<ServiceAnnotationPostProcessor> serviceAnnotationPostProcessor; @Autowired private Environment environment; @Autowired private Map<String, Environment> environments; @Autowired private ApplicationContext applicationContext; @Test void testBeans() { assertTrue(ClassUtils.isAssignableValue(BinderDubboConfigBinder.class, dubboConfigBinder)); assertNotNull(serviceAnnotationPostProcessor); assertNotNull(serviceAnnotationPostProcessor.getIfAvailable()); ReferenceAnnotationBeanPostProcessor referenceAnnotationBeanPostProcessor = DubboBeanUtils.getReferenceAnnotationBeanPostProcessor(applicationContext); assertNotNull(referenceAnnotationBeanPostProcessor); assertNotNull(environment); assertNotNull(environments); assertEquals(1, environments.size()); assertTrue(environments.containsValue(environment)); } }
7,710
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-autoconfigure/src/test/java/org/apache/dubbo/spring/boot
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/BinderDubboConfigBinderTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.spring.boot.autoconfigure; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.RegistryConfig; import java.util.Map; import com.alibaba.spring.context.config.ConfigurationBeanBinder; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import static com.alibaba.spring.util.PropertySourcesUtils.getSubProperties; /** * {@link BinderDubboConfigBinder} Test * * @since 2.7.0 */ @RunWith(SpringRunner.class) @TestPropertySource(locations = "classpath:/dubbo.properties") @ContextConfiguration(classes = BinderDubboConfigBinder.class) class BinderDubboConfigBinderTest { @Autowired private ConfigurationBeanBinder dubboConfigBinder; @Autowired private ConfigurableEnvironment environment; @Test void testBinder() { ApplicationConfig applicationConfig = new ApplicationConfig(); Map<String, Object> properties = getSubProperties(environment.getPropertySources(), "dubbo.application"); dubboConfigBinder.bind(properties, true, true, applicationConfig); Assert.assertEquals("hello", applicationConfig.getName()); Assert.assertEquals("world", applicationConfig.getOwner()); RegistryConfig registryConfig = new RegistryConfig(); properties = getSubProperties(environment.getPropertySources(), "dubbo.registry"); dubboConfigBinder.bind(properties, true, true, registryConfig); Assert.assertEquals("10.20.153.17", registryConfig.getAddress()); ProtocolConfig protocolConfig = new ProtocolConfig(); properties = getSubProperties(environment.getPropertySources(), "dubbo.protocol"); dubboConfigBinder.bind(properties, true, true, protocolConfig); Assert.assertEquals(Integer.valueOf(20881), protocolConfig.getPort()); } }
7,711
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/DubboRelaxedBinding2AutoConfiguration.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.spring.boot.autoconfigure; import org.apache.dubbo.config.spring.util.PropertySourcesUtils; import java.util.Map; import java.util.Set; import com.alibaba.spring.context.config.ConfigurationBeanBinder; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.source.ConfigurationPropertySources; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; import org.springframework.core.env.AbstractEnvironment; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.Environment; import org.springframework.core.env.MapPropertySource; import org.springframework.core.env.MutablePropertySources; import org.springframework.core.env.PropertyResolver; import static java.util.Collections.emptySet; import static org.apache.dubbo.spring.boot.util.DubboUtils.BASE_PACKAGES_BEAN_NAME; import static org.apache.dubbo.spring.boot.util.DubboUtils.BASE_PACKAGES_PROPERTY_NAME; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_PREFIX; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_SCAN_PREFIX; import static org.apache.dubbo.spring.boot.util.DubboUtils.RELAXED_DUBBO_CONFIG_BINDER_BEAN_NAME; import static org.springframework.beans.factory.config.ConfigurableBeanFactory.SCOPE_PROTOTYPE; /** * Dubbo Relaxed Binding Auto-{@link Configuration} for Spring Boot 2.0 * * @see DubboRelaxedBindingAutoConfiguration * @since 2.7.0 */ @Configuration @ConditionalOnProperty(prefix = DUBBO_PREFIX, name = "enabled", matchIfMissing = true) @ConditionalOnClass(name = "org.springframework.boot.context.properties.bind.Binder") @AutoConfigureBefore(DubboRelaxedBindingAutoConfiguration.class) public class DubboRelaxedBinding2AutoConfiguration { public PropertyResolver dubboScanBasePackagesPropertyResolver(ConfigurableEnvironment environment) { ConfigurableEnvironment propertyResolver = new AbstractEnvironment() { @Override protected void customizePropertySources(MutablePropertySources propertySources) { Map<String, Object> dubboScanProperties = PropertySourcesUtils.getSubProperties(environment.getPropertySources(), DUBBO_SCAN_PREFIX); propertySources.addLast(new MapPropertySource("dubboScanProperties", dubboScanProperties)); } }; ConfigurationPropertySources.attach(propertyResolver); return propertyResolver; } /** * The bean is used to scan the packages of Dubbo Service classes * * @param environment {@link Environment} instance * @return non-null {@link Set} * @since 2.7.8 */ @ConditionalOnMissingBean(name = BASE_PACKAGES_BEAN_NAME) @Bean(name = BASE_PACKAGES_BEAN_NAME) public Set<String> dubboBasePackages(ConfigurableEnvironment environment) { PropertyResolver propertyResolver = dubboScanBasePackagesPropertyResolver(environment); return propertyResolver.getProperty(BASE_PACKAGES_PROPERTY_NAME, Set.class, emptySet()); } @ConditionalOnMissingBean(name = RELAXED_DUBBO_CONFIG_BINDER_BEAN_NAME, value = ConfigurationBeanBinder.class) @Bean(RELAXED_DUBBO_CONFIG_BINDER_BEAN_NAME) @Scope(scopeName = SCOPE_PROTOTYPE) public ConfigurationBeanBinder relaxedDubboConfigBinder() { return new BinderDubboConfigBinder(); } }
7,712
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/BinderDubboConfigBinder.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.spring.boot.autoconfigure; import org.apache.dubbo.config.spring.context.properties.DubboConfigBinder; import java.util.Map; import com.alibaba.spring.context.config.ConfigurationBeanBinder; import org.springframework.boot.context.properties.bind.BindHandler; import org.springframework.boot.context.properties.bind.Bindable; import org.springframework.boot.context.properties.bind.Binder; import org.springframework.boot.context.properties.bind.PropertySourcesPlaceholdersResolver; import org.springframework.boot.context.properties.bind.handler.IgnoreErrorsBindHandler; import org.springframework.boot.context.properties.bind.handler.NoUnboundElementsBindHandler; import org.springframework.boot.context.properties.source.ConfigurationPropertySource; import org.springframework.boot.context.properties.source.UnboundElementsSourceFilter; import org.springframework.core.env.MapPropertySource; import org.springframework.core.env.PropertySource; import static java.util.Arrays.asList; import static org.springframework.boot.context.properties.source.ConfigurationPropertySources.from; /** * Spring Boot Relaxed {@link DubboConfigBinder} implementation * see org.springframework.boot.context.properties.ConfigurationPropertiesBinder * * @since 2.7.0 */ class BinderDubboConfigBinder implements ConfigurationBeanBinder { @Override public void bind( Map<String, Object> configurationProperties, boolean ignoreUnknownFields, boolean ignoreInvalidFields, Object configurationBean) { Iterable<PropertySource<?>> propertySources = asList(new MapPropertySource("internal", configurationProperties)); // Converts ConfigurationPropertySources Iterable<ConfigurationPropertySource> configurationPropertySources = from(propertySources); // Wrap Bindable from DubboConfig instance Bindable bindable = Bindable.ofInstance(configurationBean); Binder binder = new Binder(configurationPropertySources, new PropertySourcesPlaceholdersResolver(propertySources)); // Get BindHandler BindHandler bindHandler = getBindHandler(ignoreUnknownFields, ignoreInvalidFields); // Bind binder.bind("", bindable, bindHandler); } private BindHandler getBindHandler(boolean ignoreUnknownFields, boolean ignoreInvalidFields) { BindHandler handler = BindHandler.DEFAULT; if (ignoreInvalidFields) { handler = new IgnoreErrorsBindHandler(handler); } if (!ignoreUnknownFields) { UnboundElementsSourceFilter filter = new UnboundElementsSourceFilter(); handler = new NoUnboundElementsBindHandler(handler, filter); } return handler; } }
7,713
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/observability/autoconfigure
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/observability/autoconfigure/observability/DubboMicrometerTracingAutoConfigurationTests.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.spring.boot.observability.autoconfigure.observability; import org.apache.dubbo.spring.boot.observability.autoconfigure.DubboMicrometerTracingAutoConfiguration; import java.util.List; import java.util.stream.Collectors; import io.micrometer.tracing.Tracer; import io.micrometer.tracing.handler.DefaultTracingObservationHandler; import io.micrometer.tracing.handler.PropagatingReceiverTracingObservationHandler; import io.micrometer.tracing.handler.PropagatingSenderTracingObservationHandler; import io.micrometer.tracing.handler.TracingObservationHandler; import io.micrometer.tracing.propagation.Propagator; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.FilteredClassLoader; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** * Tests for {@link DubboMicrometerTracingAutoConfiguration} */ class DubboMicrometerTracingAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(DubboMicrometerTracingAutoConfiguration.class)) .withPropertyValues("dubbo.tracing.enabled=true"); @Test void shouldSupplyBeans() { this.contextRunner .withUserConfiguration(TracerConfiguration.class, PropagatorConfiguration.class) .run((context) -> { assertThat(context).hasSingleBean(DefaultTracingObservationHandler.class); assertThat(context).hasSingleBean(PropagatingReceiverTracingObservationHandler.class); assertThat(context).hasSingleBean(PropagatingSenderTracingObservationHandler.class); }); } @Test @SuppressWarnings("rawtypes") void shouldSupplyBeansInCorrectOrder() { this.contextRunner .withUserConfiguration(TracerConfiguration.class, PropagatorConfiguration.class) .run((context) -> { List<TracingObservationHandler> tracingObservationHandlers = context.getBeanProvider( TracingObservationHandler.class) .orderedStream() .collect(Collectors.toList()); assertThat(tracingObservationHandlers).hasSize(3); assertThat(tracingObservationHandlers.get(0)) .isInstanceOf(PropagatingReceiverTracingObservationHandler.class); assertThat(tracingObservationHandlers.get(1)) .isInstanceOf(PropagatingSenderTracingObservationHandler.class); assertThat(tracingObservationHandlers.get(2)).isInstanceOf(DefaultTracingObservationHandler.class); }); } @Test void shouldBackOffOnCustomBeans() { this.contextRunner.withUserConfiguration(CustomConfiguration.class).run((context) -> { assertThat(context).hasBean("customDefaultTracingObservationHandler"); assertThat(context).hasSingleBean(DefaultTracingObservationHandler.class); assertThat(context).hasBean("customPropagatingReceiverTracingObservationHandler"); assertThat(context).hasSingleBean(PropagatingReceiverTracingObservationHandler.class); assertThat(context).hasBean("customPropagatingSenderTracingObservationHandler"); assertThat(context).hasSingleBean(PropagatingSenderTracingObservationHandler.class); }); } @Test void shouldNotSupplyBeansIfMicrometerIsMissing() { this.contextRunner .withClassLoader(new FilteredClassLoader("io.micrometer")) .run((context) -> { assertThat(context).doesNotHaveBean(DefaultTracingObservationHandler.class); assertThat(context).doesNotHaveBean(PropagatingReceiverTracingObservationHandler.class); assertThat(context).doesNotHaveBean(PropagatingSenderTracingObservationHandler.class); }); } @Test void shouldNotSupplyBeansIfTracerIsMissing() { this.contextRunner.withUserConfiguration(PropagatorConfiguration.class).run((context) -> { assertThat(context).doesNotHaveBean(DefaultTracingObservationHandler.class); assertThat(context).doesNotHaveBean(PropagatingReceiverTracingObservationHandler.class); assertThat(context).doesNotHaveBean(PropagatingSenderTracingObservationHandler.class); }); } @Test void shouldNotSupplyBeansIfPropagatorIsMissing() { this.contextRunner.withUserConfiguration(TracerConfiguration.class).run((context) -> { assertThat(context).doesNotHaveBean(PropagatingSenderTracingObservationHandler.class); assertThat(context).doesNotHaveBean(PropagatingReceiverTracingObservationHandler.class); }); } @Test void shouldNotSupplyBeansIfTracingIsDisabled() { this.contextRunner .withUserConfiguration(TracerConfiguration.class, PropagatorConfiguration.class) .withPropertyValues("dubbo.tracing.enabled=false") .run((context) -> { assertThat(context).doesNotHaveBean(DefaultTracingObservationHandler.class); assertThat(context).doesNotHaveBean(PropagatingReceiverTracingObservationHandler.class); assertThat(context).doesNotHaveBean(PropagatingSenderTracingObservationHandler.class); }); } @Configuration(proxyBeanMethods = false) private static class TracerConfiguration { @Bean Tracer tracer() { return mock(Tracer.class); } } @Configuration(proxyBeanMethods = false) private static class PropagatorConfiguration { @Bean Propagator propagator() { return mock(Propagator.class); } } @Configuration(proxyBeanMethods = false) private static class CustomConfiguration { @Bean DefaultTracingObservationHandler customDefaultTracingObservationHandler() { return mock(DefaultTracingObservationHandler.class); } @Bean PropagatingReceiverTracingObservationHandler<?> customPropagatingReceiverTracingObservationHandler() { return mock(PropagatingReceiverTracingObservationHandler.class); } @Bean PropagatingSenderTracingObservationHandler<?> customPropagatingSenderTracingObservationHandler() { return mock(PropagatingSenderTracingObservationHandler.class); } } }
7,714
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/DubboObservationAutoConfiguration.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.spring.boot.observability.autoconfigure; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.qos.protocol.QosProtocolWrapper; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.spring.boot.observability.autoconfigure.annotation.ConditionalOnDubboTracingEnable; import java.util.Arrays; import io.micrometer.core.instrument.MeterRegistry; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.SmartInitializingSingleton; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_PREFIX; /** * Register observationRegistry to ApplicationModel. * Create observationRegistry when you are using Boot <3.0 or you are not using spring-boot-starter-actuator */ @ConditionalOnProperty(prefix = DUBBO_PREFIX, name = "enabled", matchIfMissing = true) @AutoConfiguration( after = DubboMicrometerTracingAutoConfiguration.class, afterName = "org.springframework.boot.actuate.autoconfigure.observation.ObservationAutoConfiguration") @ConditionalOnDubboTracingEnable @ConditionalOnClass(name = {"io.micrometer.observation.Observation", "io.micrometer.tracing.Tracer"}) public class DubboObservationAutoConfiguration implements BeanFactoryAware, SmartInitializingSingleton { private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(QosProtocolWrapper.class); public DubboObservationAutoConfiguration(ApplicationModel applicationModel) { this.applicationModel = applicationModel; } private final ApplicationModel applicationModel; private BeanFactory beanFactory; @Bean @ConditionalOnMissingBean @ConditionalOnClass(name = "io.micrometer.observation.ObservationRegistry") io.micrometer.observation.ObservationRegistry observationRegistry() { return io.micrometer.observation.ObservationRegistry.create(); } @Bean @ConditionalOnMissingBean( type = "org.springframework.boot.actuate.autoconfigure.observation.ObservationRegistryPostProcessor") @ConditionalOnClass(name = "io.micrometer.observation.ObservationHandler") public ObservationRegistryPostProcessor dubboObservationRegistryPostProcessor( ObjectProvider<ObservationHandlerGrouping> observationHandlerGrouping, ObjectProvider<io.micrometer.observation.ObservationHandler<?>> observationHandlers) { return new ObservationRegistryPostProcessor(observationHandlerGrouping, observationHandlers); } @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = beanFactory; } @Override public void afterSingletonsInstantiated() { try { applicationModel .getBeanFactory() .registerBean(beanFactory.getBean(io.micrometer.observation.ObservationRegistry.class)); io.micrometer.tracing.Tracer bean = beanFactory.getBean(io.micrometer.tracing.Tracer.class); applicationModel.getBeanFactory().registerBean(bean); } catch (NoSuchBeanDefinitionException e) { logger.info("Please use a version of micrometer higher than 1.10.0 :{}" + e.getMessage()); } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(MeterRegistry.class) @ConditionalOnMissingClass("io.micrometer.tracing.Tracer") @ConditionalOnMissingBean( type = "org.springframework.boot.actuate.autoconfigure.observation.ObservationRegistryPostProcessor") static class OnlyMetricsConfiguration { @Bean @ConditionalOnClass(name = "io.micrometer.core.instrument.observation.MeterObservationHandler") ObservationHandlerGrouping metricsObservationHandlerGrouping() { return new ObservationHandlerGrouping( io.micrometer.core.instrument.observation.MeterObservationHandler.class); } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(io.micrometer.tracing.Tracer.class) @ConditionalOnMissingClass("io.micrometer.core.instrument.MeterRegistry") @ConditionalOnMissingBean( type = "org.springframework.boot.actuate.autoconfigure.observation.ObservationRegistryPostProcessor") static class OnlyTracingConfiguration { @Bean @ConditionalOnClass(name = "io.micrometer.tracing.handler.TracingObservationHandler") ObservationHandlerGrouping tracingObservationHandlerGrouping() { return new ObservationHandlerGrouping(io.micrometer.tracing.handler.TracingObservationHandler.class); } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass({MeterRegistry.class, io.micrometer.tracing.Tracer.class}) @ConditionalOnMissingBean( type = "org.springframework.boot.actuate.autoconfigure.observation.ObservationRegistryPostProcessor") static class MetricsWithTracingConfiguration { @Bean @ConditionalOnClass( name = { "io.micrometer.tracing.handler.TracingObservationHandler", "io.micrometer.core.instrument.observation.MeterObservationHandler" }) ObservationHandlerGrouping metricsAndTracingObservationHandlerGrouping() { return new ObservationHandlerGrouping(Arrays.asList( io.micrometer.tracing.handler.TracingObservationHandler.class, io.micrometer.core.instrument.observation.MeterObservationHandler.class)); } } @Configuration(proxyBeanMethods = false) @ConditionalOnBean(MeterRegistry.class) @ConditionalOnMissingBean(io.micrometer.core.instrument.observation.MeterObservationHandler.class) static class MeterObservationHandlerConfiguration { @ConditionalOnMissingBean(type = "io.micrometer.tracing.Tracer") @Configuration(proxyBeanMethods = false) static class OnlyMetricsMeterObservationHandlerConfiguration { @Bean @ConditionalOnClass(name = {"io.micrometer.core.instrument.observation.DefaultMeterObservationHandler"}) io.micrometer.core.instrument.observation.DefaultMeterObservationHandler defaultMeterObservationHandler( MeterRegistry meterRegistry) { return new io.micrometer.core.instrument.observation.DefaultMeterObservationHandler(meterRegistry); } } @ConditionalOnBean(io.micrometer.tracing.Tracer.class) @Configuration(proxyBeanMethods = false) static class TracingAndMetricsObservationHandlerConfiguration { @Bean @ConditionalOnClass( name = { "io.micrometer.tracing.handler.TracingAwareMeterObservationHandler", "io.micrometer.tracing.Tracer" }) io.micrometer.tracing.handler.TracingAwareMeterObservationHandler< io.micrometer.observation.Observation.Context> tracingAwareMeterObservationHandler( MeterRegistry meterRegistry, io.micrometer.tracing.Tracer tracer) { io.micrometer.core.instrument.observation.DefaultMeterObservationHandler delegate = new io.micrometer.core.instrument.observation.DefaultMeterObservationHandler(meterRegistry); return new io.micrometer.tracing.handler.TracingAwareMeterObservationHandler<>(delegate, tracer); } } } }
7,715
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/ObservationRegistryPostProcessor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.spring.boot.observability.autoconfigure; import java.util.List; import java.util.stream.Collectors; import io.micrometer.observation.ObservationHandler; import io.micrometer.observation.ObservationRegistry; import org.springframework.beans.BeansException; import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.config.BeanPostProcessor; /** * registry observationHandlers to observationConfig */ public class ObservationRegistryPostProcessor implements BeanPostProcessor { private final ObjectProvider<ObservationHandlerGrouping> observationHandlerGrouping; private final ObjectProvider<ObservationHandler<?>> observationHandlers; public ObservationRegistryPostProcessor( ObjectProvider<ObservationHandlerGrouping> observationHandlerGrouping, ObjectProvider<ObservationHandler<?>> observationHandlers) { this.observationHandlerGrouping = observationHandlerGrouping; this.observationHandlers = observationHandlers; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof ObservationRegistry) { ObservationRegistry observationRegistry = (ObservationRegistry) bean; List<ObservationHandler<?>> observationHandlerList = observationHandlers.orderedStream().collect(Collectors.toList()); observationHandlerGrouping.ifAvailable(grouping -> { grouping.apply(observationHandlerList, observationRegistry.observationConfig()); }); } return bean; } }
7,716
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/ObservationHandlerGrouping.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.spring.boot.observability.autoconfigure; import java.util.Collections; import java.util.List; import io.micrometer.observation.ObservationHandler; import io.micrometer.observation.ObservationRegistry; import org.springframework.util.CollectionUtils; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; /** * Groups {@link ObservationHandler ObservationHandlers} by type. * copy from {@link org.springframework.boot.actuate.autoconfigure.observation.ObservationHandlerGrouping} * this class is available starting from Boot 3.0. It's not available if you're using Boot < 3.0 * * @author Andy Wilkinson */ class ObservationHandlerGrouping { private final List<Class<? extends ObservationHandler>> categories; ObservationHandlerGrouping(Class<? extends ObservationHandler> category) { this(Collections.singletonList(category)); } ObservationHandlerGrouping(List<Class<? extends ObservationHandler>> categories) { this.categories = categories; } void apply(List<ObservationHandler<?>> handlers, ObservationRegistry.ObservationConfig config) { MultiValueMap<Class<? extends ObservationHandler>, ObservationHandler<?>> groupings = new LinkedMultiValueMap<>(); for (ObservationHandler<?> handler : handlers) { Class<? extends ObservationHandler> category = findCategory(handler); if (category != null) { groupings.add(category, handler); } else { config.observationHandler(handler); } } for (Class<? extends ObservationHandler> category : this.categories) { List<ObservationHandler<?>> handlerGroup = groupings.get(category); if (!CollectionUtils.isEmpty(handlerGroup)) { config.observationHandler( new ObservationHandler.FirstMatchingCompositeObservationHandler(handlerGroup)); } } } private Class<? extends ObservationHandler> findCategory(ObservationHandler<?> handler) { for (Class<? extends ObservationHandler> category : this.categories) { if (category.isInstance(handler)) { return category; } } return null; } }
7,717
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/ObservabilityUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.spring.boot.observability.autoconfigure; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_PREFIX; import static org.apache.dubbo.spring.boot.util.DubboUtils.PROPERTY_NAME_SEPARATOR; /** * The utilities class for Dubbo Observability * * @since 3.2.0 */ public class ObservabilityUtils { public static final String DUBBO_TRACING_PREFIX = DUBBO_PREFIX + PROPERTY_NAME_SEPARATOR + "tracing"; public static final String DUBBO_TRACING_PROPAGATION = DUBBO_TRACING_PREFIX + PROPERTY_NAME_SEPARATOR + "propagation"; public static final String DUBBO_TRACING_BAGGAGE = DUBBO_TRACING_PREFIX + PROPERTY_NAME_SEPARATOR + "baggage"; public static final String DUBBO_TRACING_BAGGAGE_CORRELATION = DUBBO_TRACING_BAGGAGE + PROPERTY_NAME_SEPARATOR + "correlation"; public static final String DUBBO_TRACING_BAGGAGE_ENABLED = DUBBO_TRACING_BAGGAGE + PROPERTY_NAME_SEPARATOR + "enabled"; public static final String DUBBO_TRACING_ZIPKIN_CONFIG_PREFIX = DUBBO_TRACING_PREFIX + PROPERTY_NAME_SEPARATOR + "tracing-exporter.zipkin-config"; public static final String DUBBO_TRACING_OTLP_CONFIG_PREFIX = DUBBO_TRACING_PREFIX + PROPERTY_NAME_SEPARATOR + "tracing-exporter.otlp-config"; }
7,718
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/DubboMicrometerTracingAutoConfiguration.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.spring.boot.observability.autoconfigure; import org.apache.dubbo.spring.boot.observability.autoconfigure.annotation.ConditionalOnDubboTracingEnable; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.core.annotation.Order; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_PREFIX; /** * copy from {@link org.springframework.boot.actuate.autoconfigure.tracing.MicrometerTracingAutoConfiguration} * this class is available starting from Boot 3.0. It's not available if you're using Boot < 3.0 */ @ConditionalOnProperty(prefix = DUBBO_PREFIX, name = "enabled", matchIfMissing = true) @ConditionalOnDubboTracingEnable @ConditionalOnClass( name = { "io.micrometer.observation.Observation", "io.micrometer.tracing.Tracer", "io.micrometer.tracing.propagation.Propagator" }) @AutoConfigureAfter(name = "org.springframework.boot.actuate.autoconfigure.tracing.MicrometerTracingAutoConfiguration") public class DubboMicrometerTracingAutoConfiguration { /** * {@code @Order} value of * {@link #propagatingReceiverTracingObservationHandler(io.micrometer.tracing.Tracer, io.micrometer.tracing.propagation.Propagator)}. */ public static final int RECEIVER_TRACING_OBSERVATION_HANDLER_ORDER = 1000; /** * {@code @Order} value of * {@link #propagatingSenderTracingObservationHandler(io.micrometer.tracing.Tracer, io.micrometer.tracing.propagation.Propagator)}. */ public static final int SENDER_TRACING_OBSERVATION_HANDLER_ORDER = 2000; @Bean @ConditionalOnMissingBean @ConditionalOnBean(io.micrometer.tracing.Tracer.class) public io.micrometer.tracing.handler.DefaultTracingObservationHandler defaultTracingObservationHandler( io.micrometer.tracing.Tracer tracer) { return new io.micrometer.tracing.handler.DefaultTracingObservationHandler(tracer); } @Bean @ConditionalOnMissingBean @ConditionalOnBean({io.micrometer.tracing.Tracer.class, io.micrometer.tracing.propagation.Propagator.class}) @Order(SENDER_TRACING_OBSERVATION_HANDLER_ORDER) public io.micrometer.tracing.handler.PropagatingSenderTracingObservationHandler<?> propagatingSenderTracingObservationHandler( io.micrometer.tracing.Tracer tracer, io.micrometer.tracing.propagation.Propagator propagator) { return new io.micrometer.tracing.handler.PropagatingSenderTracingObservationHandler<>(tracer, propagator); } @Bean @ConditionalOnMissingBean @ConditionalOnBean({io.micrometer.tracing.Tracer.class, io.micrometer.tracing.propagation.Propagator.class}) @Order(RECEIVER_TRACING_OBSERVATION_HANDLER_ORDER) public io.micrometer.tracing.handler.PropagatingReceiverTracingObservationHandler<?> propagatingReceiverTracingObservationHandler( io.micrometer.tracing.Tracer tracer, io.micrometer.tracing.propagation.Propagator propagator) { return new io.micrometer.tracing.handler.PropagatingReceiverTracingObservationHandler<>(tracer, propagator); } }
7,719
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/annotation/ConditionalOnDubboTracingEnable.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.spring.boot.observability.autoconfigure.annotation; import org.apache.dubbo.spring.boot.observability.autoconfigure.ObservabilityUtils; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; /** * Checks whether tracing is enabled. * It matches if the value of the {@code dubbo.tracing.enabled} property is {@code true} or if it * is not configured. * * @since 3.2.0 */ @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented @ConditionalOnProperty(prefix = ObservabilityUtils.DUBBO_TRACING_PREFIX, name = "enabled") public @interface ConditionalOnDubboTracingEnable {}
7,720
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/otel/OpenTelemetryAutoConfiguration.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.spring.boot.observability.autoconfigure.otel; import org.apache.dubbo.common.Version; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.rpc.model.ModuleModel; import org.apache.dubbo.spring.boot.autoconfigure.DubboConfigurationProperties; import org.apache.dubbo.spring.boot.observability.autoconfigure.DubboMicrometerTracingAutoConfiguration; import org.apache.dubbo.spring.boot.observability.autoconfigure.ObservabilityUtils; import org.apache.dubbo.spring.boot.observability.autoconfigure.annotation.ConditionalOnDubboTracingEnable; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_PREFIX; /** * provider OpenTelemetry when you are using Boot <3.0 or you are not using spring-boot-starter-actuator */ @ConditionalOnProperty(prefix = DUBBO_PREFIX, name = "enabled", matchIfMissing = true) @AutoConfiguration( before = DubboMicrometerTracingAutoConfiguration.class, afterName = "org.springframework.boot.actuate.autoconfigure.tracing.OpenTelemetryAutoConfiguration") @ConditionalOnDubboTracingEnable @ConditionalOnClass( name = { "io.micrometer.tracing.otel.bridge.OtelTracer", "io.opentelemetry.sdk.trace.SdkTracerProvider", "io.opentelemetry.api.OpenTelemetry", "io.micrometer.tracing.SpanCustomizer" }) @EnableConfigurationProperties(DubboConfigurationProperties.class) public class OpenTelemetryAutoConfiguration { /** * Default value for application name if {@code spring.application.name} is not set. */ private static final String DEFAULT_APPLICATION_NAME = "application"; private final DubboConfigurationProperties dubboConfigProperties; private final ModuleModel moduleModel; OpenTelemetryAutoConfiguration(DubboConfigurationProperties dubboConfigProperties, ModuleModel moduleModel) { this.dubboConfigProperties = dubboConfigProperties; this.moduleModel = moduleModel; } @Bean @ConditionalOnMissingBean io.opentelemetry.api.OpenTelemetry openTelemetry( io.opentelemetry.sdk.trace.SdkTracerProvider sdkTracerProvider, io.opentelemetry.context.propagation.ContextPropagators contextPropagators) { return io.opentelemetry.sdk.OpenTelemetrySdk.builder() .setTracerProvider(sdkTracerProvider) .setPropagators(contextPropagators) .build(); } @Bean @ConditionalOnMissingBean io.opentelemetry.sdk.trace.SdkTracerProvider otelSdkTracerProvider( ObjectProvider<io.opentelemetry.sdk.trace.SpanProcessor> spanProcessors, io.opentelemetry.sdk.trace.samplers.Sampler sampler) { String applicationName = moduleModel .getApplicationModel() .getApplicationConfigManager() .getApplication() .map(ApplicationConfig::getName) .orElse(DEFAULT_APPLICATION_NAME); io.opentelemetry.sdk.trace.SdkTracerProviderBuilder builder = io.opentelemetry.sdk.trace.SdkTracerProvider.builder() .setSampler(sampler) .setResource(io.opentelemetry.sdk.resources.Resource.create( io.opentelemetry.api.common.Attributes.of( io.opentelemetry.semconv.resource.attributes.ResourceAttributes.SERVICE_NAME, applicationName))); spanProcessors.orderedStream().forEach(builder::addSpanProcessor); return builder.build(); } @Bean @ConditionalOnMissingBean io.opentelemetry.context.propagation.ContextPropagators otelContextPropagators( ObjectProvider<io.opentelemetry.context.propagation.TextMapPropagator> textMapPropagators) { return io.opentelemetry.context.propagation.ContextPropagators.create( io.opentelemetry.context.propagation.TextMapPropagator.composite( textMapPropagators.orderedStream().collect(Collectors.toList()))); } @Bean @ConditionalOnMissingBean io.opentelemetry.sdk.trace.samplers.Sampler otelSampler() { io.opentelemetry.sdk.trace.samplers.Sampler rootSampler = io.opentelemetry.sdk.trace.samplers.Sampler.traceIdRatioBased( this.dubboConfigProperties.getTracing().getSampling().getProbability()); return io.opentelemetry.sdk.trace.samplers.Sampler.parentBased(rootSampler); } @Bean @ConditionalOnMissingBean io.opentelemetry.sdk.trace.SpanProcessor otelSpanProcessor( ObjectProvider<io.opentelemetry.sdk.trace.export.SpanExporter> spanExporters, ObjectProvider<io.micrometer.tracing.exporter.SpanExportingPredicate> spanExportingPredicates, ObjectProvider<io.micrometer.tracing.exporter.SpanReporter> spanReporters, ObjectProvider<io.micrometer.tracing.exporter.SpanFilter> spanFilters) { return io.opentelemetry.sdk.trace.export.BatchSpanProcessor.builder( new io.micrometer.tracing.otel.bridge.CompositeSpanExporter( spanExporters.orderedStream().collect(Collectors.toList()), spanExportingPredicates.orderedStream().collect(Collectors.toList()), spanReporters.orderedStream().collect(Collectors.toList()), spanFilters.orderedStream().collect(Collectors.toList()))) .build(); } @Bean @ConditionalOnMissingBean io.opentelemetry.api.trace.Tracer otelTracer(io.opentelemetry.api.OpenTelemetry openTelemetry) { return openTelemetry.getTracer("org.apache.dubbo", Version.getVersion()); } @Bean @ConditionalOnMissingBean(io.micrometer.tracing.Tracer.class) io.micrometer.tracing.otel.bridge.OtelTracer micrometerOtelTracer( io.opentelemetry.api.trace.Tracer tracer, io.micrometer.tracing.otel.bridge.OtelTracer.EventPublisher eventPublisher, io.micrometer.tracing.otel.bridge.OtelCurrentTraceContext otelCurrentTraceContext) { return new io.micrometer.tracing.otel.bridge.OtelTracer( tracer, otelCurrentTraceContext, eventPublisher, new io.micrometer.tracing.otel.bridge.OtelBaggageManager( otelCurrentTraceContext, this.dubboConfigProperties.getTracing().getBaggage().getRemoteFields(), Collections.emptyList())); } @Bean @ConditionalOnMissingBean io.micrometer.tracing.otel.bridge.OtelPropagator otelPropagator( io.opentelemetry.context.propagation.ContextPropagators contextPropagators, io.opentelemetry.api.trace.Tracer tracer) { return new io.micrometer.tracing.otel.bridge.OtelPropagator(contextPropagators, tracer); } @Bean @ConditionalOnMissingBean io.micrometer.tracing.otel.bridge.OtelTracer.EventPublisher otelTracerEventPublisher( List<io.micrometer.tracing.otel.bridge.EventListener> eventListeners) { return new OTelEventPublisher(eventListeners); } @Bean @ConditionalOnMissingBean io.micrometer.tracing.otel.bridge.OtelCurrentTraceContext otelCurrentTraceContext( io.micrometer.tracing.otel.bridge.OtelTracer.EventPublisher publisher) { io.opentelemetry.context.ContextStorage.addWrapper( new io.micrometer.tracing.otel.bridge.EventPublishingContextWrapper(publisher)); return new io.micrometer.tracing.otel.bridge.OtelCurrentTraceContext(); } @Bean @ConditionalOnMissingBean io.micrometer.tracing.otel.bridge.Slf4JEventListener otelSlf4JEventListener() { return new io.micrometer.tracing.otel.bridge.Slf4JEventListener(); } @Bean @ConditionalOnMissingBean(io.micrometer.tracing.SpanCustomizer.class) io.micrometer.tracing.otel.bridge.OtelSpanCustomizer otelSpanCustomizer() { return new io.micrometer.tracing.otel.bridge.OtelSpanCustomizer(); } @Configuration(proxyBeanMethods = false) @ConditionalOnProperty(prefix = ObservabilityUtils.DUBBO_TRACING_BAGGAGE, name = "enabled", matchIfMissing = true) static class BaggageConfiguration { private final DubboConfigurationProperties dubboConfigProperties; BaggageConfiguration(DubboConfigurationProperties dubboConfigProperties) { this.dubboConfigProperties = dubboConfigProperties; } @Bean @ConditionalOnMissingBean @ConditionalOnProperty( prefix = ObservabilityUtils.DUBBO_TRACING_PROPAGATION, name = "type", havingValue = "W3C", matchIfMissing = true) io.opentelemetry.context.propagation.TextMapPropagator w3cTextMapPropagatorWithBaggage( io.micrometer.tracing.otel.bridge.OtelCurrentTraceContext otelCurrentTraceContext) { List<String> remoteFields = this.dubboConfigProperties.getTracing().getBaggage().getRemoteFields(); return io.opentelemetry.context.propagation.TextMapPropagator.composite( io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator.getInstance(), io.opentelemetry.api.baggage.propagation.W3CBaggagePropagator.getInstance(), new io.micrometer.tracing.otel.propagation.BaggageTextMapPropagator( remoteFields, new io.micrometer.tracing.otel.bridge.OtelBaggageManager( otelCurrentTraceContext, remoteFields, Collections.emptyList()))); } @Bean @ConditionalOnMissingBean @ConditionalOnProperty(prefix = ObservabilityUtils.DUBBO_TRACING_PROPAGATION, name = "type", havingValue = "B3") io.opentelemetry.context.propagation.TextMapPropagator b3BaggageTextMapPropagator( io.micrometer.tracing.otel.bridge.OtelCurrentTraceContext otelCurrentTraceContext) { List<String> remoteFields = this.dubboConfigProperties.getTracing().getBaggage().getRemoteFields(); return io.opentelemetry.context.propagation.TextMapPropagator.composite( io.opentelemetry.extension.trace.propagation.B3Propagator.injectingSingleHeader(), new io.micrometer.tracing.otel.propagation.BaggageTextMapPropagator( remoteFields, new io.micrometer.tracing.otel.bridge.OtelBaggageManager( otelCurrentTraceContext, remoteFields, Collections.emptyList()))); } @Bean @ConditionalOnMissingBean @ConditionalOnProperty( prefix = ObservabilityUtils.DUBBO_TRACING_BAGGAGE_CORRELATION, name = "enabled", matchIfMissing = true) io.micrometer.tracing.otel.bridge.Slf4JBaggageEventListener otelSlf4JBaggageEventListener() { return new io.micrometer.tracing.otel.bridge.Slf4JBaggageEventListener(this.dubboConfigProperties .getTracing() .getBaggage() .getCorrelation() .getFields()); } } @Configuration(proxyBeanMethods = false) @ConditionalOnProperty(prefix = ObservabilityUtils.DUBBO_TRACING_BAGGAGE, name = "enabled", havingValue = "false") static class NoBaggageConfiguration { @Bean @ConditionalOnMissingBean @ConditionalOnProperty(prefix = ObservabilityUtils.DUBBO_TRACING_PROPAGATION, name = "type", havingValue = "B3") io.opentelemetry.extension.trace.propagation.B3Propagator b3TextMapPropagator() { return io.opentelemetry.extension.trace.propagation.B3Propagator.injectingSingleHeader(); } @Bean @ConditionalOnMissingBean @ConditionalOnProperty( prefix = ObservabilityUtils.DUBBO_TRACING_PROPAGATION, name = "type", havingValue = "W3C", matchIfMissing = true) io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator w3cTextMapPropagatorWithoutBaggage() { return io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator.getInstance(); } } static class OTelEventPublisher implements io.micrometer.tracing.otel.bridge.OtelTracer.EventPublisher { private final List<io.micrometer.tracing.otel.bridge.EventListener> listeners; OTelEventPublisher(List<io.micrometer.tracing.otel.bridge.EventListener> listeners) { this.listeners = listeners; } @Override public void publishEvent(Object event) { for (io.micrometer.tracing.otel.bridge.EventListener listener : this.listeners) { listener.onEvent(event); } } } }
7,721
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/brave/BraveAutoConfiguration.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.spring.boot.observability.autoconfigure.brave; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.rpc.model.ModuleModel; import org.apache.dubbo.spring.boot.autoconfigure.DubboConfigurationProperties; import org.apache.dubbo.spring.boot.observability.autoconfigure.DubboMicrometerTracingAutoConfiguration; import org.apache.dubbo.spring.boot.observability.autoconfigure.ObservabilityUtils; import org.apache.dubbo.spring.boot.observability.autoconfigure.annotation.ConditionalOnDubboTracingEnable; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_PREFIX; /** * provider Brave when you are using Boot <3.0 or you are not using spring-boot-starter-actuator */ @ConditionalOnProperty(prefix = DUBBO_PREFIX, name = "enabled", matchIfMissing = true) @AutoConfiguration( before = DubboMicrometerTracingAutoConfiguration.class, afterName = "org.springframework.boot.actuate.autoconfigure.tracing.BraveAutoConfiguration") @ConditionalOnClass( name = { "io.micrometer.tracing.Tracer", "io.micrometer.tracing.brave.bridge.BraveTracer", "io.micrometer.tracing.brave.bridge.BraveBaggageManager", "brave.Tracing" }) @EnableConfigurationProperties(DubboConfigurationProperties.class) @ConditionalOnDubboTracingEnable public class BraveAutoConfiguration { private static final io.micrometer.tracing.brave.bridge.BraveBaggageManager BRAVE_BAGGAGE_MANAGER = new io.micrometer.tracing.brave.bridge.BraveBaggageManager(); /** * Default value for application name if {@code spring.application.name} is not set. */ private static final String DEFAULT_APPLICATION_NAME = "application"; private final ModuleModel moduleModel; public BraveAutoConfiguration(ModuleModel moduleModel) { this.moduleModel = moduleModel; } @Bean @ConditionalOnMissingBean @Order(Ordered.HIGHEST_PRECEDENCE) io.micrometer.tracing.brave.bridge.CompositeSpanHandler compositeSpanHandler( ObjectProvider<io.micrometer.tracing.exporter.SpanExportingPredicate> predicates, ObjectProvider<io.micrometer.tracing.exporter.SpanReporter> reporters, ObjectProvider<io.micrometer.tracing.exporter.SpanFilter> filters) { return new io.micrometer.tracing.brave.bridge.CompositeSpanHandler( predicates.orderedStream().collect(Collectors.toList()), reporters.orderedStream().collect(Collectors.toList()), filters.orderedStream().collect(Collectors.toList())); } @Bean @ConditionalOnMissingBean public brave.Tracing braveTracing( List<brave.handler.SpanHandler> spanHandlers, List<brave.TracingCustomizer> tracingCustomizers, brave.propagation.CurrentTraceContext currentTraceContext, brave.propagation.Propagation.Factory propagationFactory, brave.sampler.Sampler sampler) { String applicationName = moduleModel .getApplicationModel() .getApplicationConfigManager() .getApplication() .map(ApplicationConfig::getName) .orElse(DEFAULT_APPLICATION_NAME); brave.Tracing.Builder builder = brave.Tracing.newBuilder() .currentTraceContext(currentTraceContext) .traceId128Bit(true) .supportsJoin(false) .propagationFactory(propagationFactory) .sampler(sampler) .localServiceName(applicationName); spanHandlers.forEach(builder::addSpanHandler); for (brave.TracingCustomizer tracingCustomizer : tracingCustomizers) { tracingCustomizer.customize(builder); } return builder.build(); } @Bean @ConditionalOnMissingBean public brave.Tracer braveTracer(brave.Tracing tracing) { return tracing.tracer(); } @Bean @ConditionalOnMissingBean public brave.propagation.CurrentTraceContext braveCurrentTraceContext( List<brave.propagation.CurrentTraceContext.ScopeDecorator> scopeDecorators, List<brave.propagation.CurrentTraceContextCustomizer> currentTraceContextCustomizers) { brave.propagation.ThreadLocalCurrentTraceContext.Builder builder = brave.propagation.ThreadLocalCurrentTraceContext.newBuilder(); scopeDecorators.forEach(builder::addScopeDecorator); for (brave.propagation.CurrentTraceContextCustomizer currentTraceContextCustomizer : currentTraceContextCustomizers) { currentTraceContextCustomizer.customize(builder); } return builder.build(); } @Bean @ConditionalOnMissingBean public brave.sampler.Sampler braveSampler(DubboConfigurationProperties properties) { return brave.sampler.Sampler.create( properties.getTracing().getSampling().getProbability()); } @Bean @ConditionalOnMissingBean(io.micrometer.tracing.Tracer.class) io.micrometer.tracing.brave.bridge.BraveTracer braveTracerBridge( brave.Tracer tracer, brave.propagation.CurrentTraceContext currentTraceContext) { return new io.micrometer.tracing.brave.bridge.BraveTracer( tracer, new io.micrometer.tracing.brave.bridge.BraveCurrentTraceContext(currentTraceContext), BRAVE_BAGGAGE_MANAGER); } @Bean @ConditionalOnMissingBean io.micrometer.tracing.brave.bridge.BravePropagator bravePropagator(brave.Tracing tracing) { return new io.micrometer.tracing.brave.bridge.BravePropagator(tracing); } @Bean @ConditionalOnMissingBean(brave.SpanCustomizer.class) brave.CurrentSpanCustomizer currentSpanCustomizer(brave.Tracing tracing) { return brave.CurrentSpanCustomizer.create(tracing); } @Bean @ConditionalOnMissingBean(io.micrometer.tracing.SpanCustomizer.class) io.micrometer.tracing.brave.bridge.BraveSpanCustomizer braveSpanCustomizer(brave.SpanCustomizer spanCustomizer) { return new io.micrometer.tracing.brave.bridge.BraveSpanCustomizer(spanCustomizer); } @Configuration(proxyBeanMethods = false) @ConditionalOnProperty(value = ObservabilityUtils.DUBBO_TRACING_BAGGAGE_ENABLED, havingValue = "false") static class BraveNoBaggageConfiguration { @Bean @ConditionalOnMissingBean brave.propagation.Propagation.Factory propagationFactory(DubboConfigurationProperties tracing) { String type = tracing.getTracing().getPropagation().getType(); switch (type) { case org.apache.dubbo.config.nested.PropagationConfig.B3: return brave.propagation.B3Propagation.newFactoryBuilder() .injectFormat(brave.propagation.B3Propagation.Format.SINGLE_NO_PARENT) .build(); case org.apache.dubbo.config.nested.PropagationConfig.W3C: return new io.micrometer.tracing.brave.bridge.W3CPropagation(); default: throw new IllegalArgumentException("UnSupport propagation type"); } } } @ConditionalOnProperty(value = ObservabilityUtils.DUBBO_TRACING_BAGGAGE_ENABLED, matchIfMissing = true) @Configuration(proxyBeanMethods = false) static class BraveBaggageConfiguration { private final DubboConfigurationProperties dubboConfigProperties; public BraveBaggageConfiguration(DubboConfigurationProperties dubboConfigProperties) { this.dubboConfigProperties = dubboConfigProperties; } @Bean @ConditionalOnMissingBean @ConditionalOnProperty( prefix = ObservabilityUtils.DUBBO_TRACING_PROPAGATION, value = "type", havingValue = "B3") brave.baggage.BaggagePropagation.FactoryBuilder b3PropagationFactoryBuilder( ObjectProvider<brave.baggage.BaggagePropagationCustomizer> baggagePropagationCustomizers) { brave.propagation.Propagation.Factory delegate = brave.propagation.B3Propagation.newFactoryBuilder() .injectFormat(brave.propagation.B3Propagation.Format.SINGLE_NO_PARENT) .build(); brave.baggage.BaggagePropagation.FactoryBuilder builder = brave.baggage.BaggagePropagation.newFactoryBuilder(delegate); baggagePropagationCustomizers.orderedStream().forEach((customizer) -> customizer.customize(builder)); return builder; } @Bean @ConditionalOnMissingBean @ConditionalOnProperty( prefix = ObservabilityUtils.DUBBO_TRACING_PROPAGATION, value = "type", havingValue = "W3C", matchIfMissing = true) brave.baggage.BaggagePropagation.FactoryBuilder w3cPropagationFactoryBuilder( ObjectProvider<brave.baggage.BaggagePropagationCustomizer> baggagePropagationCustomizers) { brave.propagation.Propagation.Factory delegate = new io.micrometer.tracing.brave.bridge.W3CPropagation( BRAVE_BAGGAGE_MANAGER, Collections.emptyList()); brave.baggage.BaggagePropagation.FactoryBuilder builder = brave.baggage.BaggagePropagation.newFactoryBuilder(delegate); baggagePropagationCustomizers.orderedStream().forEach((customizer) -> customizer.customize(builder)); return builder; } @Bean @ConditionalOnMissingBean @Order(0) brave.baggage.BaggagePropagationCustomizer remoteFieldsBaggagePropagationCustomizer() { return (builder) -> { List<String> remoteFields = dubboConfigProperties.getTracing().getBaggage().getRemoteFields(); for (String fieldName : remoteFields) { builder.add(brave.baggage.BaggagePropagationConfig.SingleBaggageField.remote( brave.baggage.BaggageField.create(fieldName))); } }; } @Bean @ConditionalOnMissingBean brave.propagation.Propagation.Factory propagationFactory( brave.baggage.BaggagePropagation.FactoryBuilder factoryBuilder) { return factoryBuilder.build(); } @Bean @ConditionalOnMissingBean brave.baggage.CorrelationScopeDecorator.Builder mdcCorrelationScopeDecoratorBuilder( ObjectProvider<brave.baggage.CorrelationScopeCustomizer> correlationScopeCustomizers) { brave.baggage.CorrelationScopeDecorator.Builder builder = brave.context.slf4j.MDCScopeDecorator.newBuilder(); correlationScopeCustomizers.orderedStream().forEach((customizer) -> customizer.customize(builder)); return builder; } @Bean @Order(0) @ConditionalOnProperty( prefix = ObservabilityUtils.DUBBO_TRACING_BAGGAGE_CORRELATION, name = "enabled", matchIfMissing = true) brave.baggage.CorrelationScopeCustomizer correlationFieldsCorrelationScopeCustomizer() { return (builder) -> { List<String> correlationFields = this.dubboConfigProperties .getTracing() .getBaggage() .getCorrelation() .getFields(); for (String field : correlationFields) { builder.add(brave.baggage.CorrelationScopeConfig.SingleCorrelationField.newBuilder( brave.baggage.BaggageField.create(field)) .flushOnUpdate() .build()); } }; } @Bean @ConditionalOnMissingBean(brave.propagation.CurrentTraceContext.ScopeDecorator.class) brave.propagation.CurrentTraceContext.ScopeDecorator correlationScopeDecorator( brave.baggage.CorrelationScopeDecorator.Builder builder) { return builder.build(); } } }
7,722
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter/otlp/OtlpAutoConfiguration.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.spring.boot.observability.autoconfigure.exporter.otlp; import org.apache.dubbo.config.nested.ExporterConfig.OtlpConfig; import org.apache.dubbo.spring.boot.autoconfigure.DubboConfigurationProperties; import org.apache.dubbo.spring.boot.observability.autoconfigure.annotation.ConditionalOnDubboTracingEnable; import java.util.Map; import io.micrometer.tracing.otel.bridge.OtelTracer; import io.opentelemetry.api.OpenTelemetry; import io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporter; import io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder; import io.opentelemetry.sdk.trace.SdkTracerProvider; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import static org.apache.dubbo.spring.boot.observability.autoconfigure.ObservabilityUtils.DUBBO_TRACING_OTLP_CONFIG_PREFIX; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_PREFIX; /** * @since 3.2.2 */ @ConditionalOnProperty(prefix = DUBBO_PREFIX, name = "enabled", matchIfMissing = true) @AutoConfiguration @ConditionalOnClass({OtelTracer.class, SdkTracerProvider.class, OpenTelemetry.class, OtlpGrpcSpanExporter.class}) @ConditionalOnDubboTracingEnable @EnableConfigurationProperties(DubboConfigurationProperties.class) public class OtlpAutoConfiguration { @Bean @ConditionalOnProperty(prefix = DUBBO_TRACING_OTLP_CONFIG_PREFIX, name = "endpoint") @ConditionalOnMissingBean( value = OtlpGrpcSpanExporter.class, type = "io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporter") OtlpGrpcSpanExporter otlpGrpcSpanExporter(DubboConfigurationProperties properties) { OtlpConfig cfg = properties.getTracing().getTracingExporter().getOtlpConfig(); OtlpGrpcSpanExporterBuilder builder = OtlpGrpcSpanExporter.builder() .setEndpoint(cfg.getEndpoint()) .setTimeout(cfg.getTimeout()) .setCompression(cfg.getCompressionMethod()); for (Map.Entry<String, String> entry : cfg.getHeaders().entrySet()) { builder.addHeader(entry.getKey(), entry.getValue()); } return builder.build(); } }
7,723
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter/zipkin/HttpSender.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.spring.boot.observability.autoconfigure.exporter.zipkin; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UncheckedIOException; import java.util.Collections; import java.util.List; import java.util.zip.GZIPOutputStream; import org.springframework.http.HttpHeaders; import org.springframework.util.unit.DataSize; import zipkin2.Call; import zipkin2.CheckResult; import zipkin2.codec.Encoding; import zipkin2.reporter.BytesMessageEncoder; import zipkin2.reporter.ClosedSenderException; import zipkin2.reporter.Sender; /** * A Zipkin {@link Sender} that uses an HTTP client to send JSON spans. Supports automatic compression with gzip. */ abstract class HttpSender extends Sender { private static final DataSize MESSAGE_MAX_SIZE = DataSize.ofKilobytes(512); private volatile boolean closed; @Override public Encoding encoding() { return Encoding.JSON; } @Override public int messageMaxBytes() { return (int) MESSAGE_MAX_SIZE.toBytes(); } @Override public int messageSizeInBytes(List<byte[]> encodedSpans) { return encoding().listSizeInBytes(encodedSpans); } @Override public int messageSizeInBytes(int encodedSizeInBytes) { return encoding().listSizeInBytes(encodedSizeInBytes); } @Override public CheckResult check() { try { sendSpans(Collections.emptyList()).execute(); return CheckResult.OK; } catch (IOException | RuntimeException ex) { return CheckResult.failed(ex); } } @Override public void close() throws IOException { this.closed = true; } /** * The returned {@link HttpPostCall} will send span(s) as a POST to a zipkin endpoint * when executed. * * @param batchedEncodedSpans list of encoded spans as a byte array * @return an instance of a Zipkin {@link Call} which can be executed */ protected abstract HttpPostCall sendSpans(byte[] batchedEncodedSpans); @Override public Call<Void> sendSpans(List<byte[]> encodedSpans) { if (this.closed) { throw new ClosedSenderException(); } return sendSpans(BytesMessageEncoder.JSON.encode(encodedSpans)); } abstract static class HttpPostCall extends Call.Base<Void> { /** * Only use gzip compression on data which is bigger than this in bytes. */ private static final DataSize COMPRESSION_THRESHOLD = DataSize.ofKilobytes(1); private final byte[] body; HttpPostCall(byte[] body) { this.body = body; } protected byte[] getBody() { if (needsCompression()) { return compress(this.body); } return this.body; } protected byte[] getUncompressedBody() { return this.body; } protected HttpHeaders getDefaultHeaders() { HttpHeaders headers = new HttpHeaders(); headers.set("b3", "0"); headers.set("Content-Type", "application/json"); if (needsCompression()) { headers.set("Content-Encoding", "gzip"); } return headers; } private boolean needsCompression() { return this.body.length > COMPRESSION_THRESHOLD.toBytes(); } private byte[] compress(byte[] input) { ByteArrayOutputStream result = new ByteArrayOutputStream(); try (GZIPOutputStream gzip = new GZIPOutputStream(result)) { gzip.write(input); } catch (IOException ex) { throw new UncheckedIOException(ex); } return result.toByteArray(); } } }
7,724
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter/zipkin/ZipkinAutoConfiguration.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.spring.boot.observability.autoconfigure.exporter.zipkin; import org.apache.dubbo.spring.boot.observability.autoconfigure.annotation.ConditionalOnDubboTracingEnable; import org.apache.dubbo.spring.boot.observability.autoconfigure.exporter.zipkin.ZipkinConfigurations.BraveConfiguration; import org.apache.dubbo.spring.boot.observability.autoconfigure.exporter.zipkin.ZipkinConfigurations.OpenTelemetryConfiguration; import org.apache.dubbo.spring.boot.observability.autoconfigure.exporter.zipkin.ZipkinConfigurations.ReporterConfiguration; import org.apache.dubbo.spring.boot.observability.autoconfigure.exporter.zipkin.ZipkinConfigurations.SenderConfiguration; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Import; import zipkin2.Span; import zipkin2.codec.BytesEncoder; import zipkin2.codec.SpanBytesEncoder; import zipkin2.reporter.Sender; import static org.apache.dubbo.spring.boot.observability.autoconfigure.ObservabilityUtils.DUBBO_TRACING_ZIPKIN_CONFIG_PREFIX; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_PREFIX; /** * {@link EnableAutoConfiguration Auto-configuration} for Zipkin. * <p> * It uses imports on {@link ZipkinConfigurations} to guarantee the correct configuration ordering. * Create Zipkin sender and exporter when you are using Boot < 3.0 or you are not using spring-boot-starter-actuator. * When you use SpringBoot 3.*, priority should be given to loading S3 related configurations. Dubbo related zipkin configurations are invalid. * * @since 3.2.1 */ @ConditionalOnProperty(prefix = DUBBO_PREFIX, name = "enabled", matchIfMissing = true) @AutoConfiguration( after = RestTemplateAutoConfiguration.class, afterName = "org.springframework.boot.actuate.autoconfigure.tracing.zipkin") @ConditionalOnClass(Sender.class) @Import({ SenderConfiguration.class, ReporterConfiguration.class, BraveConfiguration.class, OpenTelemetryConfiguration.class }) @ConditionalOnDubboTracingEnable public class ZipkinAutoConfiguration { @Bean @ConditionalOnProperty(prefix = DUBBO_TRACING_ZIPKIN_CONFIG_PREFIX, name = "endpoint") @ConditionalOnMissingBean public BytesEncoder<Span> spanBytesEncoder() { return SpanBytesEncoder.JSON_V2; } }
7,725
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter/zipkin/ZipkinRestTemplateSender.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.spring.boot.observability.autoconfigure.exporter.zipkin; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.web.client.RestTemplate; import zipkin2.Call; import zipkin2.Callback; class ZipkinRestTemplateSender extends HttpSender { private final String endpoint; private final RestTemplate restTemplate; ZipkinRestTemplateSender(String endpoint, RestTemplate restTemplate) { this.endpoint = endpoint; this.restTemplate = restTemplate; } @Override public HttpPostCall sendSpans(byte[] batchedEncodedSpans) { return new RestTemplateHttpPostCall(this.endpoint, batchedEncodedSpans, this.restTemplate); } private static class RestTemplateHttpPostCall extends HttpPostCall { private final String endpoint; private final RestTemplate restTemplate; RestTemplateHttpPostCall(String endpoint, byte[] body, RestTemplate restTemplate) { super(body); this.endpoint = endpoint; this.restTemplate = restTemplate; } @Override public Call<Void> clone() { return new RestTemplateHttpPostCall(this.endpoint, getUncompressedBody(), this.restTemplate); } @Override protected Void doExecute() { HttpEntity<byte[]> request = new HttpEntity<>(getBody(), getDefaultHeaders()); this.restTemplate.exchange(this.endpoint, HttpMethod.POST, request, Void.class); return null; } @Override protected void doEnqueue(Callback<Void> callback) { try { doExecute(); callback.onSuccess(null); } catch (Exception ex) { callback.onError(ex); } } } }
7,726
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter/zipkin/ZipkinConfigurations.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.spring.boot.observability.autoconfigure.exporter.zipkin; import org.apache.dubbo.config.nested.ExporterConfig; import org.apache.dubbo.spring.boot.autoconfigure.DubboConfigurationProperties; import org.apache.dubbo.spring.boot.observability.autoconfigure.exporter.zipkin.customizer.ZipkinRestTemplateBuilderCustomizer; import org.apache.dubbo.spring.boot.observability.autoconfigure.exporter.zipkin.customizer.ZipkinWebClientBuilderCustomizer; import java.util.concurrent.atomic.AtomicReference; import io.opentelemetry.exporter.zipkin.ZipkinSpanExporter; import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.web.client.RestTemplate; import org.springframework.web.reactive.function.client.WebClient; import zipkin2.Span; import zipkin2.codec.BytesEncoder; import zipkin2.reporter.AsyncReporter; import zipkin2.reporter.Reporter; import zipkin2.reporter.Sender; import zipkin2.reporter.brave.ZipkinSpanHandler; import zipkin2.reporter.urlconnection.URLConnectionSender; import static org.apache.dubbo.spring.boot.observability.autoconfigure.ObservabilityUtils.DUBBO_TRACING_ZIPKIN_CONFIG_PREFIX; /** * Configurations for Zipkin. Those are imported by {@link ZipkinAutoConfiguration}. */ class ZipkinConfigurations { @Configuration(proxyBeanMethods = false) @ConditionalOnProperty(prefix = DUBBO_TRACING_ZIPKIN_CONFIG_PREFIX, name = "endpoint") @Import({ UrlConnectionSenderConfiguration.class, WebClientSenderConfiguration.class, RestTemplateSenderConfiguration.class }) static class SenderConfiguration {} @Configuration(proxyBeanMethods = false) @ConditionalOnClass(URLConnectionSender.class) @EnableConfigurationProperties(DubboConfigurationProperties.class) static class UrlConnectionSenderConfiguration { @Bean @ConditionalOnMissingBean(Sender.class) URLConnectionSender urlConnectionSender(DubboConfigurationProperties properties) { URLConnectionSender.Builder builder = URLConnectionSender.newBuilder(); ExporterConfig.ZipkinConfig zipkinConfig = properties.getTracing().getTracingExporter().getZipkinConfig(); builder.connectTimeout((int) zipkinConfig.getConnectTimeout().toMillis()); builder.readTimeout((int) zipkinConfig.getReadTimeout().toMillis()); builder.endpoint(zipkinConfig.getEndpoint()); return builder.build(); } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(RestTemplate.class) @EnableConfigurationProperties(DubboConfigurationProperties.class) static class RestTemplateSenderConfiguration { @Bean @ConditionalOnMissingBean(Sender.class) ZipkinRestTemplateSender restTemplateSender( DubboConfigurationProperties properties, ObjectProvider<ZipkinRestTemplateBuilderCustomizer> customizers) { ExporterConfig.ZipkinConfig zipkinConfig = properties.getTracing().getTracingExporter().getZipkinConfig(); RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder() .setConnectTimeout(zipkinConfig.getConnectTimeout()) .setReadTimeout(zipkinConfig.getReadTimeout()); restTemplateBuilder = applyCustomizers(restTemplateBuilder, customizers); return new ZipkinRestTemplateSender(zipkinConfig.getEndpoint(), restTemplateBuilder.build()); } private RestTemplateBuilder applyCustomizers( RestTemplateBuilder restTemplateBuilder, ObjectProvider<ZipkinRestTemplateBuilderCustomizer> customizers) { Iterable<ZipkinRestTemplateBuilderCustomizer> orderedCustomizers = () -> customizers.orderedStream().iterator(); RestTemplateBuilder currentBuilder = restTemplateBuilder; for (ZipkinRestTemplateBuilderCustomizer customizer : orderedCustomizers) { currentBuilder = customizer.customize(currentBuilder); } return currentBuilder; } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(WebClient.class) @EnableConfigurationProperties(DubboConfigurationProperties.class) static class WebClientSenderConfiguration { @Bean @ConditionalOnMissingBean(Sender.class) ZipkinWebClientSender webClientSender( DubboConfigurationProperties properties, ObjectProvider<ZipkinWebClientBuilderCustomizer> customizers) { ExporterConfig.ZipkinConfig zipkinConfig = properties.getTracing().getTracingExporter().getZipkinConfig(); WebClient.Builder builder = WebClient.builder(); customizers.orderedStream().forEach((customizer) -> customizer.customize(builder)); return new ZipkinWebClientSender(zipkinConfig.getEndpoint(), builder.build()); } } @Configuration(proxyBeanMethods = false) static class ReporterConfiguration { @Bean @ConditionalOnMissingBean @ConditionalOnBean(Sender.class) AsyncReporter<Span> spanReporter(Sender sender, BytesEncoder<Span> encoder) { return AsyncReporter.builder(sender).build(encoder); } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(ZipkinSpanHandler.class) static class BraveConfiguration { @Bean @ConditionalOnMissingBean @ConditionalOnBean(Reporter.class) ZipkinSpanHandler zipkinSpanHandler(Reporter<Span> spanReporter) { return (ZipkinSpanHandler) ZipkinSpanHandler.newBuilder(spanReporter).build(); } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(ZipkinSpanExporter.class) @ConditionalOnProperty(prefix = DUBBO_TRACING_ZIPKIN_CONFIG_PREFIX, name = "endpoint") @EnableConfigurationProperties(DubboConfigurationProperties.class) static class OpenTelemetryConfiguration { @Bean @ConditionalOnMissingBean ZipkinSpanExporter zipkinSpanExporter( DubboConfigurationProperties properties, BytesEncoder<Span> encoder, ObjectProvider<Sender> senders) { AtomicReference<Sender> senderRef = new AtomicReference<>(); senders.orderedStream().findFirst().ifPresent(senderRef::set); Sender sender = senderRef.get(); if (sender == null) { ExporterConfig.ZipkinConfig zipkinConfig = properties.getTracing().getTracingExporter().getZipkinConfig(); return ZipkinSpanExporter.builder() .setEncoder(encoder) .setEndpoint(zipkinConfig.getEndpoint()) .setReadTimeout(zipkinConfig.getReadTimeout()) .build(); } return ZipkinSpanExporter.builder() .setEncoder(encoder) .setSender(sender) .build(); } } }
7,727
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter/zipkin/ZipkinWebClientSender.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.spring.boot.observability.autoconfigure.exporter.zipkin; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Mono; import zipkin2.Call; import zipkin2.Callback; class ZipkinWebClientSender extends HttpSender { private final String endpoint; private final WebClient webClient; ZipkinWebClientSender(String endpoint, WebClient webClient) { this.endpoint = endpoint; this.webClient = webClient; } @Override public HttpPostCall sendSpans(byte[] batchedEncodedSpans) { return new WebClientHttpPostCall(this.endpoint, batchedEncodedSpans, this.webClient); } private static class WebClientHttpPostCall extends HttpPostCall { private final String endpoint; private final WebClient webClient; WebClientHttpPostCall(String endpoint, byte[] body, WebClient webClient) { super(body); this.endpoint = endpoint; this.webClient = webClient; } @Override public Call<Void> clone() { return new WebClientHttpPostCall(this.endpoint, getUncompressedBody(), this.webClient); } @Override protected Void doExecute() { sendRequest().block(); return null; } @Override protected void doEnqueue(Callback<Void> callback) { sendRequest().subscribe((entity) -> callback.onSuccess(null), callback::onError); } private Mono<ResponseEntity<Void>> sendRequest() { return this.webClient .post() .uri(this.endpoint) .headers(this::addDefaultHeaders) .bodyValue(getBody()) .retrieve() .toBodilessEntity(); } private void addDefaultHeaders(HttpHeaders headers) { headers.addAll(getDefaultHeaders()); } } }
7,728
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter/zipkin
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter/zipkin/customizer/ZipkinRestTemplateBuilderCustomizer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.spring.boot.observability.autoconfigure.exporter.zipkin.customizer; import org.springframework.boot.web.client.RestTemplateBuilder; /** * Callback interface that can be implemented by beans wishing to customize the * {@link RestTemplateBuilder} used to send spans to Zipkin. * * @since 3.2.0 */ @FunctionalInterface public interface ZipkinRestTemplateBuilderCustomizer { /** * Customize the rest template builder. * * @param restTemplateBuilder the {@code RestTemplateBuilder} to customize * @return the customized {@code RestTemplateBuilder} */ RestTemplateBuilder customize(RestTemplateBuilder restTemplateBuilder); }
7,729
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter/zipkin
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter/zipkin/customizer/ZipkinWebClientBuilderCustomizer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.spring.boot.observability.autoconfigure.exporter.zipkin.customizer; import org.springframework.web.reactive.function.client.WebClient; /** * Callback interface that can be implemented by beans wishing to customize the * {@link WebClient.Builder} used to send spans to Zipkin. * * @since 3.2.0 */ @FunctionalInterface public interface ZipkinWebClientBuilderCustomizer { /** * Customize the web client builder. * * @param webClientBuilder the {@code WebClient.Builder} to customize */ void customize(WebClient.Builder webClientBuilder); }
7,730
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/ConfiguratorTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.cluster.configurator.absent.AbsentConfigurator; import org.apache.dubbo.rpc.cluster.configurator.override.OverrideConfigurator; import org.apache.dubbo.rpc.cluster.configurator.parser.ConfigParser; import java.util.Collections; import java.util.List; import java.util.Optional; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * {@link Configurator} */ class ConfiguratorTest { @Test void test() { Optional<List<Configurator>> emptyOptional = Configurator.toConfigurators(Collections.emptyList()); Assertions.assertEquals(Optional.empty(), emptyOptional); String configData = "[\"override://0.0.0.0/com.xx.Service?category=configurators&timeout=6666&disabled=true&dynamic=false&enabled=true&group=dubbo&priority=2&version=1.0\"" + ", \"absent://0.0.0.0/com.xx.Service?category=configurators&timeout=6666&disabled=true&dynamic=false&enabled=true&group=dubbo&priority=1&version=1.0\" ]"; List<URL> urls = ConfigParser.parseConfigurators(configData); Optional<List<Configurator>> optionalList = Configurator.toConfigurators(urls); Assertions.assertTrue(optionalList.isPresent()); List<Configurator> configurators = optionalList.get(); Assertions.assertEquals(configurators.size(), 2); // The hosts of AbsentConfigurator and OverrideConfigurator are equal, but the priority of OverrideConfigurator // is higher Assertions.assertTrue(configurators.get(0) instanceof AbsentConfigurator); Assertions.assertTrue(configurators.get(1) instanceof OverrideConfigurator); } }
7,731
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/RouterChainTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.configcenter.ConfigChangeType; import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent; import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.cluster.filter.DemoService; import org.apache.dubbo.rpc.cluster.router.RouterSnapshotSwitcher; import org.apache.dubbo.rpc.cluster.router.condition.config.AppStateRouter; import org.apache.dubbo.rpc.cluster.router.condition.config.ListenableStateRouter; import org.apache.dubbo.rpc.cluster.router.condition.config.ServiceStateRouter; import org.apache.dubbo.rpc.cluster.router.mesh.route.MeshAppRuleListener; import org.apache.dubbo.rpc.cluster.router.mesh.route.MeshRuleManager; import org.apache.dubbo.rpc.cluster.router.state.BitList; import org.apache.dubbo.rpc.model.FrameworkModel; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TAG_KEY; import static org.apache.dubbo.rpc.cluster.router.mesh.route.MeshRuleConstants.MESH_RULE_DATA_ID_SUFFIX; import static org.mockito.Mockito.when; class RouterChainTest { /** * verify the router and state router loaded by default */ @Test void testBuildRouterChain() { RouterChain<DemoService> routerChain = createRouterChanin(); Assertions.assertEquals(0, routerChain.getRouters().size()); Assertions.assertEquals(7, routerChain.getStateRouters().size()); } private RouterChain<DemoService> createRouterChanin() { Map<String, String> parameters = new HashMap<>(); parameters.put(INTERFACE_KEY, DemoService.class.getName()); parameters.put("registry", "zookeeper"); URL url = new ServiceConfigURL("dubbo", "127.0.0.1", 20881, DemoService.class.getName(), parameters); RouterChain<DemoService> routerChain = RouterChain.buildChain(DemoService.class, url); return routerChain; } @Test void testRoute() { RouterChain<DemoService> routerChain = createRouterChanin(); // mockInvoker will be filtered out by MockInvokersSelector Invoker<DemoService> mockInvoker = createMockInvoker(); // invoker1 will be filtered out by MeshStateRouter Map<String, String> map1 = new HashMap<>(); map1.put("env-sign", "yyyyyyy"); Invoker<DemoService> invoker1 = createNormalInvoker(map1); // invoker2 will be filtered out by TagStateRouter Map<String, String> map2 = new HashMap<>(); map2.put("env-sign", "xxx"); map2.put("tag1", "hello"); Invoker<DemoService> invoker2 = createNormalInvoker(map2); // invoker3 will be filtered out by AppStateRouter Map<String, String> map3 = new HashMap<>(); map3.put("env-sign", "xxx"); map3.put("tag1", "hello"); map3.put(TAG_KEY, "TAG_"); Invoker<DemoService> invoker3 = createNormalInvoker(map3); // invoker4 will be filtered out by ServiceStateRouter Map<String, String> map4 = new HashMap<>(); map4.put("env-sign", "xxx"); map4.put("tag1", "hello"); map4.put(TAG_KEY, "TAG_"); map4.put("timeout", "5000"); Invoker<DemoService> invoker4 = createNormalInvoker(map4); // invoker5 is the only one returned at the end that is not filtered out Map<String, String> map5 = new HashMap<>(); map5.put("env-sign", "xxx"); map5.put("tag1", "hello"); map5.put(TAG_KEY, "TAG_"); map5.put("timeout", "5000"); map5.put("serialization", "hessian2"); Invoker<DemoService> invoker5 = createNormalInvoker(map5); BitList<Invoker<DemoService>> invokers = new BitList<>(Arrays.asList(mockInvoker, invoker1, invoker2, invoker3, invoker4, invoker5)); routerChain.setInvokers(invokers, () -> {}); // mesh rule for MeshStateRouter MeshRuleManager meshRuleManager = mockInvoker.getUrl().getOrDefaultModuleModel().getBeanFactory().getBean(MeshRuleManager.class); ConcurrentHashMap<String, MeshAppRuleListener> appRuleListeners = meshRuleManager.getAppRuleListeners(); MeshAppRuleListener meshAppRuleListener = appRuleListeners.get(invoker1.getUrl().getRemoteApplication()); ConfigChangedEvent configChangedEvent = new ConfigChangedEvent( "demo-route" + MESH_RULE_DATA_ID_SUFFIX, DynamicConfiguration.DEFAULT_GROUP, MESH_RULE1 + "---\n" + MESH_RULE2, ConfigChangeType.ADDED); meshAppRuleListener.process(configChangedEvent); // condition rule for AppStateRouter&ServiceStateRouter ListenableStateRouter serviceRouter = routerChain.getStateRouters().stream() .filter(s -> s instanceof ServiceStateRouter) .map(s -> (ListenableStateRouter) s) .findAny() .orElse(null); ConfigChangedEvent serviceConditionEvent = new ConfigChangedEvent( DynamicConfiguration.getRuleKey(mockInvoker.getUrl()) + ".condition-router", DynamicConfiguration.DEFAULT_GROUP, SERVICE_CONDITION_RULE, ConfigChangeType.ADDED); serviceRouter.process(serviceConditionEvent); ListenableStateRouter appRouter = routerChain.getStateRouters().stream() .filter(s -> s instanceof AppStateRouter) .map(s -> (ListenableStateRouter) s) .findAny() .orElse(null); ConfigChangedEvent appConditionEvent = new ConfigChangedEvent( "app.condition-router", DynamicConfiguration.DEFAULT_GROUP, APP_CONDITION_RULE, ConfigChangeType.ADDED); appRouter.process(appConditionEvent); // prepare consumerUrl and RpcInvocation URL consumerUrl = URL.valueOf("consumer://localhost/DemoInterface?remote.application=app1"); RpcInvocation rpcInvocation = new RpcInvocation(); rpcInvocation.setServiceName("DemoService"); rpcInvocation.setObjectAttachment("trafficLabel", "xxx"); rpcInvocation.setObjectAttachment(TAG_KEY, "TAG_"); RpcContext.getServiceContext().setNeedPrintRouterSnapshot(true); RouterSnapshotSwitcher routerSnapshotSwitcher = FrameworkModel.defaultModel().getBeanFactory().getBean(RouterSnapshotSwitcher.class); routerSnapshotSwitcher.addEnabledService("org.apache.dubbo.demo.DemoService"); // route List<Invoker<DemoService>> result = routerChain .getSingleChain(consumerUrl, invokers, rpcInvocation) .route(consumerUrl, invokers, rpcInvocation); Assertions.assertEquals(result.size(), 1); Assertions.assertTrue(result.contains(invoker5)); String snapshotLog = "[ Parent (Input: 6) (Current Node Output: 6) (Chain Node Output: 1) ] Input: localhost:9103,localhost:9103,localhost:9103,localhost:9103,localhost:9103 -> Chain Node Output: localhost:9103...\n" + " [ MockInvokersSelector (Input: 6) (Current Node Output: 5) (Chain Node Output: 1) Router message: invocation.need.mock not set. Return normal Invokers. ] Current Node Output: localhost:9103,localhost:9103,localhost:9103,localhost:9103,localhost:9103\n" + " [ StandardMeshRuleRouter (Input: 5) (Current Node Output: 4) (Chain Node Output: 1) Router message: Match App: app Subset: isolation ] Current Node Output: localhost:9103,localhost:9103,localhost:9103,localhost:9103\n" + " [ TagStateRouter (Input: 4) (Current Node Output: 3) (Chain Node Output: 1) Router message: Disable Tag Router. Reason: tagRouterRule is invalid or disabled ] Current Node Output: localhost:9103,localhost:9103,localhost:9103\n" + " [ ServiceStateRouter (Input: 3) (Current Node Output: 3) (Chain Node Output: 1) Router message: null ] Current Node Output: localhost:9103,localhost:9103,localhost:9103\n" + " [ ConditionStateRouter (Input: 3) (Current Node Output: 2) (Chain Node Output: 2) Router message: Match return. ] Current Node Output: localhost:9103,localhost:9103\n" + " [ ProviderAppStateRouter (Input: 2) (Current Node Output: 2) (Chain Node Output: 1) Router message: Directly return. Reason: Invokers from previous router is empty or conditionRouters is empty. ] Current Node Output: localhost:9103,localhost:9103\n" + " [ AppStateRouter (Input: 2) (Current Node Output: 2) (Chain Node Output: 1) Router message: null ] Current Node Output: localhost:9103,localhost:9103\n" + " [ ConditionStateRouter (Input: 2) (Current Node Output: 1) (Chain Node Output: 1) Router message: Match return. ] Current Node Output: localhost:9103\n" + " [ AppScriptStateRouter (Input: 1) (Current Node Output: 1) (Chain Node Output: 1) Router message: Directly return from script router. Reason: Invokers from previous router is empty or script is not enabled. Script rule is: null ] Current Node Output: localhost:9103"; String[] snapshot = routerSnapshotSwitcher.cloneSnapshot(); Assertions.assertTrue(snapshot[0].contains(snapshotLog)); RpcContext.getServiceContext().setNeedPrintRouterSnapshot(false); result = routerChain .getSingleChain(consumerUrl, invokers, rpcInvocation) .route(consumerUrl, invokers, rpcInvocation); Assertions.assertEquals(result.size(), 1); Assertions.assertTrue(result.contains(invoker5)); routerChain.destroy(); Assertions.assertEquals(routerChain.getRouters().size(), 0); Assertions.assertEquals(routerChain.getStateRouters().size(), 0); } private Invoker<DemoService> createMockInvoker() { URL url = URL.valueOf("mock://localhost:9103/DemoInterface?remote.application=app"); Invoker<DemoService> invoker = Mockito.mock(Invoker.class); when(invoker.getUrl()).thenReturn(url); return invoker; } private Invoker<DemoService> createNormalInvoker(Map<String, String> parameters) { URL url = URL.valueOf("dubbo://localhost:9103/DemoInterface?remote.application=app"); if (CollectionUtils.isNotEmptyMap(parameters)) { url = url.addParameters(parameters); } Invoker<DemoService> invoker = Mockito.mock(Invoker.class); when(invoker.getUrl()).thenReturn(url); return invoker; } private static final String MESH_RULE1 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: DestinationRule\n" + "metadata: { name: demo-route }\n" + "spec:\n" + " host: demo\n" + " subsets:\n" + " - labels: { env-sign: xxx, tag1: hello }\n" + " name: isolation\n" + " - labels: { env-sign: yyy }\n" + " name: testing-trunk\n" + " - labels: { env-sign: zzz }\n" + " name: testing\n" + " trafficPolicy:\n" + " loadBalancer: { simple: ROUND_ROBIN }\n" + "\n"; private static final String MESH_RULE2 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: VirtualService\n" + "metadata: { name: demo-route }\n" + "spec:\n" + " dubbo:\n" + " - routedetail:\n" + " - match:\n" + " - attachments: \n" + " dubboContext: {trafficLabel: {regex: xxx}}\n" + " name: xxx-project\n" + " route:\n" + " - destination: {host: demo, subset: isolation}\n" + " services:\n" + " - {regex: DemoService}\n" + " hosts: [demo]\n"; private static final String APP_CONDITION_RULE = "scope: application\n" + "force: true\n" + "runtime: false\n" + "enabled: true\n" + "priority: 1\n" + "key: demo-consumer\n" + "conditions:\n" + "- => serialization=hessian2"; private static final String SERVICE_CONDITION_RULE = "scope: service\n" + "force: true\n" + "runtime: false\n" + "enabled: true\n" + "priority: 1\n" + "key: org.apache.dubbo.demo.DemoService\n" + "conditions:\n" + "- => timeout=5000"; }
7,732
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/StickyTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.cluster.support.AbstractClusterInvoker; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.rpc.cluster.Constants.CLUSTER_STICKY_KEY; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @SuppressWarnings("unchecked") class StickyTest { private List<Invoker<StickyTest>> invokers = new ArrayList<Invoker<StickyTest>>(); private Invoker<StickyTest> invoker1 = mock(Invoker.class); private Invoker<StickyTest> invoker2 = mock(Invoker.class); private RpcInvocation invocation; private Directory<StickyTest> dic; private Result result = new AppResponse(); private StickyClusterInvoker<StickyTest> clusterinvoker = null; private URL url = URL.valueOf("test://test:11/test?" + "&loadbalance=roundrobin" + "&" + CLUSTER_STICKY_KEY + "=true"); private int runs = 1; @BeforeEach public void setUp() throws Exception { dic = mock(Directory.class); invocation = new RpcInvocation(); given(dic.getUrl()).willReturn(url); given(dic.getConsumerUrl()).willReturn(url); given(dic.list(invocation)).willReturn(invokers); given(dic.getInterface()).willReturn(StickyTest.class); invokers.add(invoker1); invokers.add(invoker2); clusterinvoker = new StickyClusterInvoker<StickyTest>(dic); } @Test void testStickyNoCheck() { int count = testSticky("t1", false); System.out.println(count); Assertions.assertTrue(count > 0 && count <= runs); } @Test void testStickyForceCheck() { int count = testSticky("t2", true); Assertions.assertTrue(count == 0 || count == runs); } @Test void testMethodStickyNoCheck() { int count = testSticky("method1", false); System.out.println(count); Assertions.assertTrue(count > 0 && count <= runs); } @Test void testMethodStickyForceCheck() { int count = testSticky("method1", true); Assertions.assertTrue(count == 0 || count == runs); } @Test void testMethodsSticky() { for (int i = 0; i < 100; i++) { // Two different methods should always use the same invoker every time. int count1 = testSticky("method1", true); int count2 = testSticky("method2", true); Assertions.assertEquals(count1, count2); } } public int testSticky(String methodName, boolean check) { if (methodName == null) { url = url.addParameter(CLUSTER_STICKY_KEY, String.valueOf(check)); } else { url = url.addParameter(methodName + "." + CLUSTER_STICKY_KEY, String.valueOf(check)); } given(invoker1.invoke(invocation)).willReturn(result); given(invoker1.isAvailable()).willReturn(true); given(invoker1.getUrl()).willReturn(url.setPort(1)); given(invoker1.getInterface()).willReturn(StickyTest.class); given(invoker2.invoke(invocation)).willReturn(result); given(invoker2.isAvailable()).willReturn(true); given(invoker2.getUrl()).willReturn(url.setPort(2)); given(invoker2.getInterface()).willReturn(StickyTest.class); invocation.setMethodName(methodName); int count = 0; for (int i = 0; i < runs; i++) { Assertions.assertNull(clusterinvoker.invoke(invocation)); if (invoker1 == clusterinvoker.getSelectedInvoker()) { count++; } } return count; } static class StickyClusterInvoker<T> extends AbstractClusterInvoker<T> { private Invoker<T> selectedInvoker; public StickyClusterInvoker(Directory<T> directory) { super(directory); } public StickyClusterInvoker(Directory<T> directory, URL url) { super(directory, url); } @Override protected Result doInvoke(Invocation invocation, List<Invoker<T>> invokers, LoadBalance loadbalance) throws RpcException { Invoker<T> invoker = select(loadbalance, invocation, invokers, null); selectedInvoker = invoker; return null; } public Invoker<T> getSelectedInvoker() { return selectedInvoker; } } }
7,733
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/RandomLoadBalanceTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.loadbalance; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcStatus; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * RandomLoadBalance Test */ class RandomLoadBalanceTest extends LoadBalanceBaseTest { @Test void testRandomLoadBalanceSelect() { int runs = 1000; Map<Invoker, AtomicLong> counter = getInvokeCounter(runs, RandomLoadBalance.NAME); for (Map.Entry<Invoker, AtomicLong> entry : counter.entrySet()) { Long count = entry.getValue().get(); Assertions.assertTrue( Math.abs(count - runs / (0f + invokers.size())) < runs / (0f + invokers.size()), "abs diff should < avg"); } for (int i = 0; i < 5; i++) { for (int j = 0; j <= i; j++) { RpcStatus.beginCount(invokers.get(i).getUrl(), invocation.getMethodName()); } } counter = getInvokeCounter(runs, LeastActiveLoadBalance.NAME); for (Map.Entry<Invoker, AtomicLong> entry : counter.entrySet()) { Long count = entry.getValue().get(); } Assertions.assertEquals(runs, counter.get(invoker1).intValue()); Assertions.assertEquals(0, counter.get(invoker2).intValue()); Assertions.assertEquals(0, counter.get(invoker3).intValue()); Assertions.assertEquals(0, counter.get(invoker4).intValue()); Assertions.assertEquals(0, counter.get(invoker5).intValue()); } @Test void testSelectByWeight() { int sumInvoker1 = 0; int sumInvoker2 = 0; int sumInvoker3 = 0; int loop = 10000; RandomLoadBalance lb = new RandomLoadBalance(); for (int i = 0; i < loop; i++) { Invoker selected = lb.select(weightInvokers, null, weightTestInvocation); if (selected.getUrl().getProtocol().equals("test1")) { sumInvoker1++; } if (selected.getUrl().getProtocol().equals("test2")) { sumInvoker2++; } if (selected.getUrl().getProtocol().equals("test3")) { sumInvoker3++; } } // 1 : 9 : 6 System.out.println(sumInvoker1); System.out.println(sumInvoker2); System.out.println(sumInvoker3); Assertions.assertEquals(sumInvoker1 + sumInvoker2 + sumInvoker3, loop, "select failed!"); } }
7,734
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/AdaptiveLoadBalanceTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.loadbalance; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.AdaptiveMetrics; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; import java.util.stream.Collectors; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; @TestMethodOrder(MethodOrderer.OrderAnnotation.class) class AdaptiveLoadBalanceTest extends LoadBalanceBaseTest { private ApplicationModel scopeModel; private AdaptiveMetrics adaptiveMetrics; @Test @Order(0) void testSelectByWeight() { int sumInvoker1 = 0; int sumInvoker2 = 0; int sumInvoker3 = 0; int loop = 10000; ApplicationModel scopeModel = ApplicationModel.defaultModel(); AdaptiveLoadBalance lb = new AdaptiveLoadBalance(scopeModel); for (int i = 0; i < loop; i++) { Invoker selected = lb.select(weightInvokers, null, weightTestInvocation); if (selected.getUrl().getProtocol().equals("test1")) { sumInvoker1++; } if (selected.getUrl().getProtocol().equals("test2")) { sumInvoker2++; } if (selected.getUrl().getProtocol().equals("test3")) { sumInvoker3++; } } // 1 : 9 : 6 System.out.println(sumInvoker1); System.out.println(sumInvoker2); System.out.println(sumInvoker3); Assertions.assertEquals(sumInvoker1 + sumInvoker2 + sumInvoker3, loop, "select failed!"); } private String buildServiceKey(Invoker invoker) { URL url = invoker.getUrl(); return url.getAddress() + ":" + invocation.getProtocolServiceKey(); } private AdaptiveMetrics getAdaptiveMetricsInstance() { if (adaptiveMetrics == null) { adaptiveMetrics = scopeModel.getBeanFactory().getBean(AdaptiveMetrics.class); } return adaptiveMetrics; } @Test @Order(1) void testSelectByAdaptive() { int sumInvoker1 = 0; int sumInvoker2 = 0; int sumInvoker5 = 0; int loop = 10000; scopeModel = ApplicationModel.defaultModel(); AdaptiveLoadBalance lb = new AdaptiveLoadBalance(scopeModel); lb.select(weightInvokersSR, null, weightTestInvocation); for (int i = 0; i < loop; i++) { Invoker selected = lb.select(weightInvokersSR, null, weightTestInvocation); Map<String, String> metricsMap = new HashMap<>(); String idKey = buildServiceKey(selected); if (selected.getUrl().getProtocol().equals("test1")) { sumInvoker1++; metricsMap.put("rt", "10"); metricsMap.put("load", "10"); metricsMap.put("curTime", String.valueOf(System.currentTimeMillis() - 10)); getAdaptiveMetricsInstance().addConsumerSuccess(idKey); } if (selected.getUrl().getProtocol().equals("test2")) { sumInvoker2++; metricsMap.put("rt", "100"); metricsMap.put("load", "40"); metricsMap.put("curTime", String.valueOf(System.currentTimeMillis() - 100)); getAdaptiveMetricsInstance().addConsumerSuccess(idKey); } if (selected.getUrl().getProtocol().equals("test5")) { metricsMap.put("rt", "5000"); metricsMap.put("load", "400"); // 400% metricsMap.put("curTime", String.valueOf(System.currentTimeMillis() - 5000)); getAdaptiveMetricsInstance().addErrorReq(idKey); sumInvoker5++; } getAdaptiveMetricsInstance().setProviderMetrics(idKey, metricsMap); } Map<Invoker<LoadBalanceBaseTest>, Integer> weightMap = weightInvokersSR.stream() .collect(Collectors.toMap( Function.identity(), e -> Integer.valueOf(e.getUrl().getParameter("weight")))); Integer totalWeight = weightMap.values().stream().reduce(0, Integer::sum); // max deviation = expectWeightValue * 2 int expectWeightValue = loop / totalWeight; int maxDeviation = expectWeightValue * 2; double beta = 0.5; // this EMA is an approximate value double ewma1 = beta * 50 + (1 - beta) * 10; double ewma2 = beta * 50 + (1 - beta) * 100; double ewma5 = beta * 50 + (1 - beta) * 5000; AtomicInteger weight1 = new AtomicInteger(); AtomicInteger weight2 = new AtomicInteger(); AtomicInteger weight5 = new AtomicInteger(); weightMap.forEach((k, v) -> { if (k.getUrl().getProtocol().equals("test1")) { weight1.set(v); } else if (k.getUrl().getProtocol().equals("test2")) { weight2.set(v); } else if (k.getUrl().getProtocol().equals("test5")) { weight5.set(v); } }); Assertions.assertEquals(sumInvoker1 + sumInvoker2 + sumInvoker5, loop, "select failed!"); Assertions.assertTrue( Math.abs(sumInvoker1 / (weightMap.get(weightInvoker1) * ewma1) - expectWeightValue) < maxDeviation, "select failed!"); Assertions.assertTrue( Math.abs(sumInvoker2 / (weightMap.get(weightInvoker2) * ewma2) - expectWeightValue) < maxDeviation, "select failed!"); Assertions.assertTrue( Math.abs(sumInvoker5 / (weightMap.get(weightInvoker5) * ewma5) - expectWeightValue) < maxDeviation, "select failed!"); } }
7,735
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/AbstractLoadBalanceTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.loadbalance; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.cluster.ClusterInvoker; import java.util.HashMap; import java.util.List; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY; import static org.apache.dubbo.rpc.cluster.Constants.WEIGHT_KEY; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; class AbstractLoadBalanceTest { private AbstractLoadBalance balance = new AbstractLoadBalance() { @Override protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) { return null; } }; @Test void testGetWeight() { RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("say"); Invoker invoker1 = mock(Invoker.class, Mockito.withSettings().stubOnly()); URL url1 = new ServiceConfigURL("", "", 0, "DemoService", new HashMap<>()); url1 = url1.addParameter(TIMESTAMP_KEY, System.currentTimeMillis() - Integer.MAX_VALUE - 1); given(invoker1.getUrl()).willReturn(url1); Invoker invoker2 = mock(Invoker.class, Mockito.withSettings().stubOnly()); URL url2 = new ServiceConfigURL("", "", 0, "DemoService", new HashMap<>()); url2 = url2.addParameter(TIMESTAMP_KEY, System.currentTimeMillis() - 10 * 60 * 1000L - 1); given(invoker2.getUrl()).willReturn(url2); Assertions.assertEquals(balance.getWeight(invoker1, invocation), balance.getWeight(invoker2, invocation)); } @Test void testGetRegistryWeight() { RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("say"); Invoker invoker1 = mock(Invoker.class, Mockito.withSettings().stubOnly()); URL url1 = new ServiceConfigURL("", "", 0, "DemoService", new HashMap<>()); given(invoker1.getUrl()).willReturn(url1); ClusterInvoker invoker2 = mock(ClusterInvoker.class, Mockito.withSettings().stubOnly()); URL url2 = new ServiceConfigURL("", "", 0, "org.apache.dubbo.registry.RegistryService", new HashMap<>()); url2 = url2.addParameter(WEIGHT_KEY, 20); URL registryUrl2 = new ServiceConfigURL("", "", 0, "org.apache.dubbo.registry.RegistryService", new HashMap<>()); registryUrl2 = registryUrl2.addParameter(WEIGHT_KEY, 30); given(invoker2.getUrl()).willReturn(url2); given(invoker2.getRegistryUrl()).willReturn(registryUrl2); Assertions.assertEquals(100, balance.getWeight(invoker1, invocation)); Assertions.assertEquals(30, balance.getWeight(invoker2, invocation)); } }
7,736
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/LeastActiveBalanceTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.loadbalance; import org.apache.dubbo.rpc.Invoker; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; class LeastActiveBalanceTest extends LoadBalanceBaseTest { @Disabled @Test void testLeastActiveLoadBalance_select() { int runs = 10000; Map<Invoker, AtomicLong> counter = getInvokeCounter(runs, LeastActiveLoadBalance.NAME); for (Map.Entry<Invoker, AtomicLong> entry : counter.entrySet()) { Long count = entry.getValue().get(); // System.out.println(count); Assertions.assertTrue( Math.abs(count - runs / (0f + invokers.size())) < runs / (0f + invokers.size()), "abs diff should < avg"); } } @Test void testSelectByWeight() { int sumInvoker1 = 0; int sumInvoker2 = 0; int loop = 10000; LeastActiveLoadBalance lb = new LeastActiveLoadBalance(); for (int i = 0; i < loop; i++) { Invoker selected = lb.select(weightInvokers, null, weightTestInvocation); if (selected.getUrl().getProtocol().equals("test1")) { sumInvoker1++; } if (selected.getUrl().getProtocol().equals("test2")) { sumInvoker2++; } // never select invoker3 because it's active is more than invoker1 and invoker2 Assertions.assertTrue( !selected.getUrl().getProtocol().equals("test3"), "select is not the least active one"); } // the sumInvoker1 : sumInvoker2 approximately equal to 1: 9 System.out.println(sumInvoker1); System.out.println(sumInvoker2); Assertions.assertEquals(sumInvoker1 + sumInvoker2, loop, "select failed!"); } }
7,737
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/LoadBalanceBaseTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.loadbalance; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.JsonUtils; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.RpcStatus; import org.apache.dubbo.rpc.cluster.LoadBalance; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.apache.dubbo.rpc.cluster.Constants.DEFAULT_WARMUP; import static org.apache.dubbo.rpc.cluster.Constants.DEFAULT_WEIGHT; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * RoundRobinLoadBalanceTest */ @SuppressWarnings({"unchecked", "rawtypes"}) class LoadBalanceBaseTest { Invocation invocation; Invocation genericInvocation; List<Invoker<LoadBalanceBaseTest>> invokers = new ArrayList<Invoker<LoadBalanceBaseTest>>(); Invoker<LoadBalanceBaseTest> invoker1; Invoker<LoadBalanceBaseTest> invoker2; Invoker<LoadBalanceBaseTest> invoker3; Invoker<LoadBalanceBaseTest> invoker4; Invoker<LoadBalanceBaseTest> invoker5; RpcStatus weightTestRpcStatus1; RpcStatus weightTestRpcStatus2; RpcStatus weightTestRpcStatus3; RpcStatus weightTestRpcStatus5; RpcInvocation weightTestInvocation; /** * @throws java.lang.Exception */ @BeforeAll public static void setUpBeforeClass() throws Exception {} /** * @throws java.lang.Exception */ @BeforeEach public void setUp() throws Exception { invocation = mock(Invocation.class); given(invocation.getMethodName()).willReturn("method1"); given(invocation.getArguments()).willReturn(new Object[] {"arg1", "arg2", "arg3"}); genericInvocation = mock(Invocation.class); String methodName = "method1"; given(genericInvocation.getMethodName()).willReturn("$invoke"); String[] paraTypes = new String[] {String.class.getName(), String.class.getName(), String.class.getName()}; Object[] argsObject = new Object[] {"arg1", "arg2", "arg3"}; Object[] args = new Object[] {methodName, paraTypes, argsObject}; given(genericInvocation.getArguments()).willReturn(args); invoker1 = mock(Invoker.class); invoker2 = mock(Invoker.class); invoker3 = mock(Invoker.class); invoker4 = mock(Invoker.class); invoker5 = mock(Invoker.class); URL url1 = URL.valueOf("test://127.0.0.1:1/DemoService"); URL url2 = URL.valueOf("test://127.0.0.1:2/DemoService"); URL url3 = URL.valueOf("test://127.0.0.1:3/DemoService"); URL url4 = URL.valueOf("test://127.0.0.1:4/DemoService"); URL url5 = URL.valueOf("test://127.0.0.1:5/DemoService"); given(invoker1.isAvailable()).willReturn(true); given(invoker1.getInterface()).willReturn(LoadBalanceBaseTest.class); given(invoker1.getUrl()).willReturn(url1); given(invoker2.isAvailable()).willReturn(true); given(invoker2.getInterface()).willReturn(LoadBalanceBaseTest.class); given(invoker2.getUrl()).willReturn(url2); given(invoker3.isAvailable()).willReturn(true); given(invoker3.getInterface()).willReturn(LoadBalanceBaseTest.class); given(invoker3.getUrl()).willReturn(url3); given(invoker4.isAvailable()).willReturn(true); given(invoker4.getInterface()).willReturn(LoadBalanceBaseTest.class); given(invoker4.getUrl()).willReturn(url4); given(invoker5.isAvailable()).willReturn(true); given(invoker5.getInterface()).willReturn(LoadBalanceBaseTest.class); given(invoker5.getUrl()).willReturn(url5); invokers.add(invoker1); invokers.add(invoker2); invokers.add(invoker3); invokers.add(invoker4); invokers.add(invoker5); } public Map<Invoker, AtomicLong> getInvokeCounter(int runs, String loadbalanceName) { Map<Invoker, AtomicLong> counter = new ConcurrentHashMap<Invoker, AtomicLong>(); LoadBalance lb = getLoadBalance(loadbalanceName); for (Invoker invoker : invokers) { counter.put(invoker, new AtomicLong(0)); } URL url = invokers.get(0).getUrl(); for (int i = 0; i < runs; i++) { Invoker sinvoker = lb.select(invokers, url, invocation); counter.get(sinvoker).incrementAndGet(); } return counter; } public Map<Invoker, AtomicLong> getGenericInvokeCounter(int runs, String loadbalanceName) { Map<Invoker, AtomicLong> counter = new ConcurrentHashMap<Invoker, AtomicLong>(); LoadBalance lb = getLoadBalance(loadbalanceName); for (Invoker invoker : invokers) { counter.put(invoker, new AtomicLong(0)); } URL url = invokers.get(0).getUrl(); for (int i = 0; i < runs; i++) { Invoker sinvoker = lb.select(invokers, url, genericInvocation); counter.get(sinvoker).incrementAndGet(); } return counter; } protected AbstractLoadBalance getLoadBalance(String loadbalanceName) { return (AbstractLoadBalance) ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(loadbalanceName); } @Test void testLoadBalanceWarmup() { Assertions.assertEquals(1, calculateDefaultWarmupWeight(0)); Assertions.assertEquals(1, calculateDefaultWarmupWeight(13)); Assertions.assertEquals(1, calculateDefaultWarmupWeight(6 * 1000)); Assertions.assertEquals(2, calculateDefaultWarmupWeight(12 * 1000)); Assertions.assertEquals(10, calculateDefaultWarmupWeight(60 * 1000)); Assertions.assertEquals(50, calculateDefaultWarmupWeight(5 * 60 * 1000)); Assertions.assertEquals(50, calculateDefaultWarmupWeight(5 * 60 * 1000 + 23)); Assertions.assertEquals(50, calculateDefaultWarmupWeight(5 * 60 * 1000 + 5999)); Assertions.assertEquals(51, calculateDefaultWarmupWeight(5 * 60 * 1000 + 6000)); Assertions.assertEquals(90, calculateDefaultWarmupWeight(9 * 60 * 1000)); Assertions.assertEquals(98, calculateDefaultWarmupWeight(10 * 60 * 1000 - 12 * 1000)); Assertions.assertEquals(99, calculateDefaultWarmupWeight(10 * 60 * 1000 - 6 * 1000)); Assertions.assertEquals(100, calculateDefaultWarmupWeight(10 * 60 * 1000)); Assertions.assertEquals(100, calculateDefaultWarmupWeight(20 * 60 * 1000)); } /** * handle default data * * @return */ private static int calculateDefaultWarmupWeight(int uptime) { return AbstractLoadBalance.calculateWarmupWeight(uptime, DEFAULT_WARMUP, DEFAULT_WEIGHT); } /*------------------------------------test invokers for weight---------------------------------------*/ protected static class InvokeResult { private AtomicLong count = new AtomicLong(); private int weight = 0; private int totalWeight = 0; public InvokeResult(int weight) { this.weight = weight; } public AtomicLong getCount() { return count; } public int getWeight() { return weight; } public int getTotalWeight() { return totalWeight; } public void setTotalWeight(int totalWeight) { this.totalWeight = totalWeight; } public int getExpected(int runCount) { return getWeight() * runCount / getTotalWeight(); } public float getDeltaPercentage(int runCount) { int expected = getExpected(runCount); return Math.abs((expected - getCount().get()) * 100.0f / expected); } @Override public String toString() { return JsonUtils.toJson(this); } } protected List<Invoker<LoadBalanceBaseTest>> weightInvokers = new ArrayList<Invoker<LoadBalanceBaseTest>>(); protected List<Invoker<LoadBalanceBaseTest>> weightInvokersSR = new ArrayList<Invoker<LoadBalanceBaseTest>>(); protected Invoker<LoadBalanceBaseTest> weightInvoker1; protected Invoker<LoadBalanceBaseTest> weightInvoker2; protected Invoker<LoadBalanceBaseTest> weightInvoker3; protected Invoker<LoadBalanceBaseTest> weightInvokerTmp; protected Invoker<LoadBalanceBaseTest> weightInvoker5; @BeforeEach public void before() throws Exception { weightInvoker1 = mock(Invoker.class, Mockito.withSettings().stubOnly()); weightInvoker2 = mock(Invoker.class, Mockito.withSettings().stubOnly()); weightInvoker3 = mock(Invoker.class, Mockito.withSettings().stubOnly()); weightInvokerTmp = mock(Invoker.class, Mockito.withSettings().stubOnly()); weightInvoker5 = mock(Invoker.class, Mockito.withSettings().stubOnly()); weightTestInvocation = new RpcInvocation(); weightTestInvocation.setMethodName("test"); URL url1 = URL.valueOf("test1://127.0.0.1:11/DemoService?weight=1&active=0"); URL url2 = URL.valueOf("test2://127.0.0.1:12/DemoService?weight=9&active=0"); URL url3 = URL.valueOf("test3://127.0.0.1:13/DemoService?weight=6&active=1"); URL urlTmp = URL.valueOf("test4://127.0.0.1:9999/DemoService?weight=11&active=0"); URL url5 = URL.valueOf("test5://127.0.0.1:15/DemoService?weight=15&active=0"); given(weightInvoker1.isAvailable()).willReturn(true); given(weightInvoker1.getInterface()).willReturn(LoadBalanceBaseTest.class); given(weightInvoker1.getUrl()).willReturn(url1); given(weightInvoker2.isAvailable()).willReturn(true); given(weightInvoker2.getInterface()).willReturn(LoadBalanceBaseTest.class); given(weightInvoker2.getUrl()).willReturn(url2); given(weightInvoker3.isAvailable()).willReturn(true); given(weightInvoker3.getInterface()).willReturn(LoadBalanceBaseTest.class); given(weightInvoker3.getUrl()).willReturn(url3); given(weightInvokerTmp.isAvailable()).willReturn(true); given(weightInvokerTmp.getInterface()).willReturn(LoadBalanceBaseTest.class); given(weightInvokerTmp.getUrl()).willReturn(urlTmp); given(weightInvoker5.isAvailable()).willReturn(true); given(weightInvoker5.getInterface()).willReturn(LoadBalanceBaseTest.class); given(weightInvoker5.getUrl()).willReturn(url5); weightInvokers.add(weightInvoker1); weightInvokers.add(weightInvoker2); weightInvokers.add(weightInvoker3); weightInvokersSR.add(weightInvoker1); weightInvokersSR.add(weightInvoker2); weightInvokersSR.add(weightInvoker5); weightTestRpcStatus1 = RpcStatus.getStatus(weightInvoker1.getUrl(), weightTestInvocation.getMethodName()); weightTestRpcStatus2 = RpcStatus.getStatus(weightInvoker2.getUrl(), weightTestInvocation.getMethodName()); weightTestRpcStatus3 = RpcStatus.getStatus(weightInvoker3.getUrl(), weightTestInvocation.getMethodName()); weightTestRpcStatus5 = RpcStatus.getStatus(weightInvoker5.getUrl(), weightTestInvocation.getMethodName()); // weightTestRpcStatus3 active is 1 RpcStatus.beginCount(weightInvoker3.getUrl(), weightTestInvocation.getMethodName()); // weightTestRpcStatus5 shortest response time of success calls is bigger than 0 // weightTestRpcStatus5 active is 1 RpcStatus.beginCount(weightInvoker5.getUrl(), weightTestInvocation.getMethodName()); RpcStatus.endCount(weightInvoker5.getUrl(), weightTestInvocation.getMethodName(), 5000L, true); RpcStatus.beginCount(weightInvoker5.getUrl(), weightTestInvocation.getMethodName()); } protected Map<Invoker, InvokeResult> getWeightedInvokeResult(int runs, String loadbalanceName) { Map<Invoker, InvokeResult> counter = new ConcurrentHashMap<Invoker, InvokeResult>(); AbstractLoadBalance lb = getLoadBalance(loadbalanceName); int totalWeight = 0; for (int i = 0; i < weightInvokers.size(); i++) { InvokeResult invokeResult = new InvokeResult(lb.getWeight(weightInvokers.get(i), weightTestInvocation)); counter.put(weightInvokers.get(i), invokeResult); totalWeight += invokeResult.getWeight(); } for (InvokeResult invokeResult : counter.values()) { invokeResult.setTotalWeight(totalWeight); } URL url = weightInvokers.get(0).getUrl(); for (int i = 0; i < runs; i++) { Invoker sinvoker = lb.select(weightInvokers, url, weightTestInvocation); counter.get(sinvoker).getCount().incrementAndGet(); } return counter; } }
7,738
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/ShortestResponseLoadBalanceTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.loadbalance; import org.apache.dubbo.common.utils.ReflectUtils; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcStatus; import org.apache.dubbo.rpc.model.ApplicationModel; import java.lang.reflect.Field; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.stream.Collectors; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; @TestMethodOrder(MethodOrderer.OrderAnnotation.class) class ShortestResponseLoadBalanceTest extends LoadBalanceBaseTest { @Test @Order(0) public void testSelectByWeight() { int sumInvoker1 = 0; int sumInvoker2 = 0; int loop = 10000; ShortestResponseLoadBalance lb = new ShortestResponseLoadBalance(); lb.setApplicationModel(ApplicationModel.defaultModel()); for (int i = 0; i < loop; i++) { Invoker selected = lb.select(weightInvokersSR, null, weightTestInvocation); if (selected.getUrl().getProtocol().equals("test1")) { sumInvoker1++; } if (selected.getUrl().getProtocol().equals("test2")) { sumInvoker2++; } // never select invoker5 because it's estimated response time is more than invoker1 and invoker2 Assertions.assertTrue(!selected.getUrl().getProtocol().equals("test5"), "select is not the shortest one"); } // the sumInvoker1 : sumInvoker2 approximately equal to 1: 9 System.out.println(sumInvoker1); System.out.println(sumInvoker2); Assertions.assertEquals(sumInvoker1 + sumInvoker2, loop, "select failed!"); } @Test @Order(1) public void testSelectByResponse() throws NoSuchFieldException, IllegalAccessException { int sumInvoker1 = 0; int sumInvoker2 = 0; int sumInvoker5 = 0; int loop = 10000; // active -> 0 RpcStatus.endCount(weightInvoker5.getUrl(), weightTestInvocation.getMethodName(), 5000L, true); ShortestResponseLoadBalance lb = new ShortestResponseLoadBalance(); lb.setApplicationModel(ApplicationModel.defaultModel()); // reset slideWindow Field lastUpdateTimeField = ReflectUtils.forName(ShortestResponseLoadBalance.class.getName()) .getDeclaredField("lastUpdateTime"); lastUpdateTimeField.setAccessible(true); lastUpdateTimeField.setLong(lb, System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(31)); lb.select(weightInvokersSR, null, weightTestInvocation); for (int i = 0; i < loop; i++) { Invoker selected = lb.select(weightInvokersSR, null, weightTestInvocation); if (selected.getUrl().getProtocol().equals("test1")) { sumInvoker1++; } if (selected.getUrl().getProtocol().equals("test2")) { sumInvoker2++; } if (selected.getUrl().getProtocol().equals("test5")) { sumInvoker5++; } } Map<Invoker<LoadBalanceBaseTest>, Integer> weightMap = weightInvokersSR.stream() .collect(Collectors.toMap( Function.identity(), e -> Integer.valueOf(e.getUrl().getParameter("weight")))); Integer totalWeight = weightMap.values().stream().reduce(0, Integer::sum); // max deviation = expectWeightValue * 2 int expectWeightValue = loop / totalWeight; int maxDeviation = expectWeightValue * 2; Assertions.assertEquals(sumInvoker1 + sumInvoker2 + sumInvoker5, loop, "select failed!"); Assertions.assertTrue( Math.abs(sumInvoker2 / weightMap.get(weightInvoker2) - expectWeightValue) < maxDeviation, "select failed!"); Assertions.assertTrue( Math.abs(sumInvoker5 / weightMap.get(weightInvoker5) - expectWeightValue) < maxDeviation, "select failed!"); } }
7,739
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/RoundRobinLoadBalanceTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.loadbalance; import org.apache.dubbo.rpc.Invoker; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @Disabled class RoundRobinLoadBalanceTest extends LoadBalanceBaseTest { private void assertStrictWRRResult(int loop, Map<Invoker, InvokeResult> resultMap) { int invokeCount = 0; for (InvokeResult invokeResult : resultMap.values()) { int count = (int) invokeResult.getCount().get(); // Because it's a strictly round robin, so the abs delta should be < 10 too Assertions.assertTrue( Math.abs(invokeResult.getExpected(loop) - count) < 10, "delta with expected count should < 10"); invokeCount += count; } Assertions.assertEquals(invokeCount, loop, "select failed!"); } @Test void testRoundRobinLoadBalanceSelect() { int runs = 10000; Map<Invoker, AtomicLong> counter = getInvokeCounter(runs, RoundRobinLoadBalance.NAME); for (Map.Entry<Invoker, AtomicLong> entry : counter.entrySet()) { Long count = entry.getValue().get(); Assertions.assertTrue(Math.abs(count - runs / (0f + invokers.size())) < 1f, "abs diff should < 1"); } } @Test void testSelectByWeight() { final Map<Invoker, InvokeResult> totalMap = new HashMap<Invoker, InvokeResult>(); final AtomicBoolean shouldBegin = new AtomicBoolean(false); final int runs = 10000; List<Thread> threads = new ArrayList<Thread>(); int threadNum = 10; for (int i = 0; i < threadNum; i++) { threads.add(new Thread(() -> { while (!shouldBegin.get()) { try { Thread.sleep(5); } catch (InterruptedException e) { } } Map<Invoker, InvokeResult> resultMap = getWeightedInvokeResult(runs, RoundRobinLoadBalance.NAME); synchronized (totalMap) { for (Entry<Invoker, InvokeResult> entry : resultMap.entrySet()) { if (!totalMap.containsKey(entry.getKey())) { totalMap.put(entry.getKey(), entry.getValue()); } else { totalMap.get(entry.getKey()) .getCount() .addAndGet(entry.getValue().getCount().get()); } } } })); } for (Thread thread : threads) { thread.start(); } // let's rock it! shouldBegin.set(true); for (Thread thread : threads) { try { thread.join(); } catch (InterruptedException e) { } } assertStrictWRRResult(runs * threadNum, totalMap); } @Test void testNodeCacheShouldNotRecycle() { int loop = 10000; // tmperately add a new invoker weightInvokers.add(weightInvokerTmp); try { Map<Invoker, InvokeResult> resultMap = getWeightedInvokeResult(loop, RoundRobinLoadBalance.NAME); assertStrictWRRResult(loop, resultMap); // inner nodes cache judgement RoundRobinLoadBalance lb = (RoundRobinLoadBalance) getLoadBalance(RoundRobinLoadBalance.NAME); Assertions.assertEquals( weightInvokers.size(), lb.getInvokerAddrList(weightInvokers, weightTestInvocation).size()); weightInvokers.remove(weightInvokerTmp); resultMap = getWeightedInvokeResult(loop, RoundRobinLoadBalance.NAME); assertStrictWRRResult(loop, resultMap); Assertions.assertNotEquals( weightInvokers.size(), lb.getInvokerAddrList(weightInvokers, weightTestInvocation).size()); } finally { // prevent other UT's failure weightInvokers.remove(weightInvokerTmp); } } @Test void testNodeCacheShouldRecycle() { { Field recycleTimeField = null; try { // change recycle time to 1 ms recycleTimeField = RoundRobinLoadBalance.class.getDeclaredField("RECYCLE_PERIOD"); recycleTimeField.setAccessible(true); recycleTimeField.setInt(RoundRobinLoadBalance.class, 10); } catch (NoSuchFieldException | IllegalAccessException | IllegalArgumentException | SecurityException e) { Assertions.assertTrue(true, "getField failed"); } } int loop = 10000; // tmperately add a new invoker weightInvokers.add(weightInvokerTmp); try { Map<Invoker, InvokeResult> resultMap = getWeightedInvokeResult(loop, RoundRobinLoadBalance.NAME); assertStrictWRRResult(loop, resultMap); // inner nodes cache judgement RoundRobinLoadBalance lb = (RoundRobinLoadBalance) getLoadBalance(RoundRobinLoadBalance.NAME); Assertions.assertEquals( weightInvokers.size(), lb.getInvokerAddrList(weightInvokers, weightTestInvocation).size()); weightInvokers.remove(weightInvokerTmp); resultMap = getWeightedInvokeResult(loop, RoundRobinLoadBalance.NAME); assertStrictWRRResult(loop, resultMap); Assertions.assertEquals( weightInvokers.size(), lb.getInvokerAddrList(weightInvokers, weightTestInvocation).size()); } finally { // prevent other UT's failure weightInvokers.remove(weightInvokerTmp); } } }
7,740
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/ConsistentHashLoadBalanceTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.loadbalance; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.cluster.LoadBalance; import org.apache.dubbo.rpc.cluster.RouterChain; import org.apache.dubbo.rpc.cluster.router.state.BitList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @SuppressWarnings("rawtypes") class ConsistentHashLoadBalanceTest extends LoadBalanceBaseTest { @Test void testConsistentHashLoadBalanceInGenericCall() { int runs = 10000; Map<Invoker, AtomicLong> genericInvokeCounter = getGenericInvokeCounter(runs, ConsistentHashLoadBalance.NAME); Map<Invoker, AtomicLong> invokeCounter = getInvokeCounter(runs, ConsistentHashLoadBalance.NAME); Invoker genericHitted = findHitted(genericInvokeCounter); Invoker hitted = findHitted(invokeCounter); Assertions.assertEquals(hitted, genericHitted, "hitted should equals to genericHitted"); } private Invoker findHitted(Map<Invoker, AtomicLong> invokerCounter) { Invoker invoker = null; for (Map.Entry<Invoker, AtomicLong> entry : invokerCounter.entrySet()) { if (entry.getValue().longValue() > 0) { invoker = entry.getKey(); break; } } Assertions.assertNotNull(invoker, "invoker should be found"); return null; } @Test void testConsistentHashLoadBalance() { int runs = 10000; long unHitedInvokerCount = 0; Map<Invoker, Long> hitedInvokers = new HashMap<>(); Map<Invoker, AtomicLong> counter = getInvokeCounter(runs, ConsistentHashLoadBalance.NAME); for (Invoker minvoker : counter.keySet()) { Long count = counter.get(minvoker).get(); if (count == 0) { unHitedInvokerCount++; } else { hitedInvokers.put(minvoker, count); } } Assertions.assertEquals( counter.size() - 1, unHitedInvokerCount, "the number of unHitedInvoker should be counter.size() - 1"); Assertions.assertEquals(1, hitedInvokers.size(), "the number of hitedInvoker should be 1"); Assertions.assertEquals( runs, hitedInvokers.values().iterator().next().intValue(), "the number of hited count should be the number of runs"); } // https://github.com/apache/dubbo/issues/5429 @Test void testNormalWhenRouterEnabled() { LoadBalance lb = getLoadBalance(ConsistentHashLoadBalance.NAME); URL url = invokers.get(0).getUrl(); RouterChain<LoadBalanceBaseTest> routerChain = RouterChain.buildChain(LoadBalanceBaseTest.class, url); Invoker<LoadBalanceBaseTest> result = lb.select(invokers, url, invocation); for (int i = 0; i < 100; i++) { routerChain.setInvokers(new BitList<>(invokers), () -> {}); List<Invoker<LoadBalanceBaseTest>> routeInvokers = routerChain .getSingleChain(url, new BitList<>(invokers), invocation) .route(url, new BitList<>(invokers), invocation); Invoker<LoadBalanceBaseTest> finalInvoker = lb.select(routeInvokers, url, invocation); Assertions.assertEquals(result, finalInvoker); } } }
7,741
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/MockDirInvocation.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.directory; import org.apache.dubbo.rpc.AttachmentsAdapter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.model.ServiceModel; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Consumer; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; /** * MockInvocation.java */ class MockDirInvocation implements Invocation { private Map<String, Object> attachments; public MockDirInvocation() { attachments = new HashMap<>(); attachments.put(PATH_KEY, "dubbo"); attachments.put(GROUP_KEY, "dubbo"); attachments.put(VERSION_KEY, "1.0.0"); attachments.put(DUBBO_VERSION_KEY, "1.0.0"); attachments.put(TOKEN_KEY, "sfag"); attachments.put(TIMEOUT_KEY, "1000"); } @Override public String getTargetServiceUniqueName() { return null; } @Override public String getProtocolServiceKey() { return null; } public String getMethodName() { return "echo"; } @Override public String getServiceName() { return "DemoService"; } public Class<?>[] getParameterTypes() { return new Class[] {String.class}; } public Object[] getArguments() { return new Object[] {"aa"}; } public Map<String, String> getAttachments() { return new AttachmentsAdapter.ObjectToStringMap(attachments); } @Override public Map<String, Object> getObjectAttachments() { return attachments; } @Override public Map<String, Object> copyObjectAttachments() { return new HashMap<>(attachments); } @Override public void foreachAttachment(Consumer<Map.Entry<String, Object>> consumer) { attachments.entrySet().forEach(consumer); } @Override public void setAttachment(String key, String value) { setObjectAttachment(key, value); } @Override public void setAttachment(String key, Object value) { setObjectAttachment(key, value); } @Override public void setObjectAttachment(String key, Object value) { attachments.put(key, value); } @Override public void setAttachmentIfAbsent(String key, String value) { setObjectAttachmentIfAbsent(key, value); } @Override public void setAttachmentIfAbsent(String key, Object value) { setObjectAttachmentIfAbsent(key, value); } @Override public void setObjectAttachmentIfAbsent(String key, Object value) { attachments.putIfAbsent(key, value); } public Invoker<?> getInvoker() { return null; } @Override public Object put(Object key, Object value) { return null; } @Override public Object get(Object key) { return null; } @Override public void setServiceModel(ServiceModel serviceModel) {} @Override public ServiceModel getServiceModel() { return null; } @Override public Map<Object, Object> getAttributes() { return null; } public String getAttachment(String key) { return (String) getObjectAttachment(key); } @Override public Object getObjectAttachment(String key) { return attachments.get(key); } public String getAttachment(String key, String defaultValue) { return (String) getObjectAttachment(key, defaultValue); } @Override public void addInvokedInvoker(Invoker<?> invoker) {} @Override public List<Invoker<?>> getInvokedInvokers() { return null; } @Override public Object getObjectAttachment(String key, Object defaultValue) { Object result = attachments.get(key); if (result == null) { return defaultValue; } return result; } }
7,742
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/directory/StaticDirectoryTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.directory; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.Holder; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.metrics.event.MetricsDispatcher; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.cluster.router.MockInvoker; import org.apache.dubbo.rpc.cluster.router.condition.ConditionStateRouterFactory; import org.apache.dubbo.rpc.cluster.router.state.BitList; import org.apache.dubbo.rpc.cluster.router.state.StateRouter; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.apache.dubbo.rpc.cluster.Constants.RULE_KEY; /** * StaticDirectory Test */ class StaticDirectoryTest { private URL SCRIPT_URL = URL.valueOf("condition://0.0.0.0/com.foo.BarService"); private URL getRouteUrl(String rule) { return SCRIPT_URL.addParameterAndEncoded(RULE_KEY, rule); } @Test void testStaticDirectory() { StateRouter router = new ConditionStateRouterFactory() .getRouter(String.class, getRouteUrl(" => " + " host = " + NetUtils.getLocalHost())); List<StateRouter> routers = new ArrayList<StateRouter>(); routers.add(router); List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>(); Invoker<String> invoker1 = new MockInvoker<String>(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService"), true); Invoker<String> invoker2 = new MockInvoker<String>( URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":20880/com.foo.BarService"), true); Invoker<String> invoker3 = new MockInvoker<String>( URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":20880/com.foo.BarService"), true); originInvokers.add(invoker1); originInvokers.add(invoker2); originInvokers.add(invoker3); BitList<Invoker<String>> invokers = new BitList<>(originInvokers); List<Invoker<String>> filteredInvokers = router.route( invokers.clone(), URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/com.foo.BarService"), new RpcInvocation(), false, new Holder<>()); ApplicationModel.defaultModel().getBeanFactory().registerBean(MetricsDispatcher.class); StaticDirectory<String> staticDirectory = new StaticDirectory<>(filteredInvokers); boolean isAvailable = staticDirectory.isAvailable(); Assertions.assertTrue(isAvailable); List<Invoker<String>> newInvokers = staticDirectory.list(new MockDirInvocation()); Assertions.assertTrue(newInvokers.size() > 0); staticDirectory.destroy(); Assertions.assertEquals(0, staticDirectory.getInvokers().size()); Assertions.assertEquals(0, staticDirectory.getValidInvokers().size()); } }
7,743
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/merger/FloatSumMerger.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.merger; import org.apache.dubbo.rpc.cluster.Merger; import java.util.Arrays; import java.util.Objects; public class FloatSumMerger implements Merger<Float> { @Override public Float merge(Float... items) { return Arrays.stream(items).filter(Objects::nonNull).reduce(0.0F, (f1, f2) -> f1 + f2); } }
7,744
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/merger/LongSumMerger.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.merger; import org.apache.dubbo.rpc.cluster.Merger; import java.util.Arrays; import java.util.Objects; public class LongSumMerger implements Merger<Long> { @Override public Long merge(Long... items) { return Arrays.stream(items) .filter(Objects::nonNull) .mapToLong(Long::longValue) .sum(); } }
7,745
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/merger/IntFindAnyMerger.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.merger; import org.apache.dubbo.rpc.cluster.Merger; import java.util.Arrays; public class IntFindAnyMerger implements Merger<Integer> { @Override public Integer merge(Integer... items) { return Arrays.stream(items).findAny().orElse(null); } }
7,746
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/merger/DoubleSumMerger.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.merger; import org.apache.dubbo.rpc.cluster.Merger; import java.util.Arrays; import java.util.Objects; public class DoubleSumMerger implements Merger<Double> { @Override public Double merge(Double... items) { return Arrays.stream(items) .filter(Objects::nonNull) .mapToDouble(Double::doubleValue) .sum(); } }
7,747
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/merger/ResultMergerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.merger; import org.apache.dubbo.rpc.cluster.Merger; import org.apache.dubbo.rpc.model.ApplicationModel; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.DoubleStream; import java.util.stream.IntStream; import java.util.stream.LongStream; import java.util.stream.Stream; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class ResultMergerTest { private MergerFactory mergerFactory; @BeforeEach public void setup() { mergerFactory = new MergerFactory(); mergerFactory.setScopeModel(ApplicationModel.defaultModel()); } /** * MergerFactory test */ @Test void testMergerFactoryIllegalArgumentException() { try { mergerFactory.getMerger(null); Assertions.fail("expected IllegalArgumentException for null argument"); } catch (IllegalArgumentException exception) { Assertions.assertEquals("returnType is null", exception.getMessage()); } } /** * ArrayMerger test */ @Test void testArrayMergerIllegalArgumentException() { String[] stringArray = {"1", "2", "3"}; Integer[] integerArray = {3, 4, 5}; try { Object result = ArrayMerger.INSTANCE.merge(stringArray, null, integerArray); Assertions.fail("expected IllegalArgumentException for different arguments' types"); } catch (IllegalArgumentException exception) { Assertions.assertEquals("Arguments' types are different", exception.getMessage()); } } /** * ArrayMerger test */ @Test void testArrayMerger() { String[] stringArray1 = {"1", "2", "3"}; String[] stringArray2 = {"4", "5", "6"}; String[] stringArray3 = {}; Object result = ArrayMerger.INSTANCE.merge(stringArray1, stringArray2, stringArray3, null); Assertions.assertTrue(result.getClass().isArray()); Assertions.assertEquals(6, Array.getLength(result)); Assertions.assertTrue(String.class.isInstance(Array.get(result, 0))); for (int i = 0; i < 6; i++) { Assertions.assertEquals(String.valueOf(i + 1), Array.get(result, i)); } Integer[] intArray1 = {1, 2, 3}; Integer[] intArray2 = {4, 5, 6}; Integer[] intArray3 = {7}; // trigger ArrayMerger result = mergerFactory.getMerger(Integer[].class).merge(intArray1, intArray2, intArray3, null); Assertions.assertTrue(result.getClass().isArray()); Assertions.assertEquals(7, Array.getLength(result)); Assertions.assertSame(Integer.class, result.getClass().getComponentType()); for (int i = 0; i < 7; i++) { Assertions.assertEquals(i + 1, Array.get(result, i)); } result = ArrayMerger.INSTANCE.merge(null); Assertions.assertEquals(0, Array.getLength(result)); result = ArrayMerger.INSTANCE.merge(null, null); Assertions.assertEquals(0, Array.getLength(result)); result = ArrayMerger.INSTANCE.merge(null, new Object[0]); Assertions.assertEquals(0, Array.getLength(result)); } /** * BooleanArrayMerger test */ @Test void testBooleanArrayMerger() { boolean[] arrayOne = {true, false}; boolean[] arrayTwo = {false}; boolean[] result = mergerFactory.getMerger(boolean[].class).merge(arrayOne, arrayTwo, null); Assertions.assertEquals(3, result.length); boolean[] mergedResult = {true, false, false}; for (int i = 0; i < mergedResult.length; i++) { Assertions.assertEquals(mergedResult[i], result[i]); } result = mergerFactory.getMerger(boolean[].class).merge(null); Assertions.assertEquals(0, result.length); result = mergerFactory.getMerger(boolean[].class).merge(null, null); Assertions.assertEquals(0, result.length); } /** * ByteArrayMerger test */ @Test void testByteArrayMerger() { byte[] arrayOne = {1, 2}; byte[] arrayTwo = {1, 32}; byte[] result = mergerFactory.getMerger(byte[].class).merge(arrayOne, arrayTwo, null); Assertions.assertEquals(4, result.length); byte[] mergedResult = {1, 2, 1, 32}; for (int i = 0; i < mergedResult.length; i++) { Assertions.assertEquals(mergedResult[i], result[i]); } result = mergerFactory.getMerger(byte[].class).merge(null); Assertions.assertEquals(0, result.length); result = mergerFactory.getMerger(byte[].class).merge(null, null); Assertions.assertEquals(0, result.length); } /** * CharArrayMerger test */ @Test void testCharArrayMerger() { char[] arrayOne = "hello".toCharArray(); char[] arrayTwo = "world".toCharArray(); char[] result = mergerFactory.getMerger(char[].class).merge(arrayOne, arrayTwo, null); Assertions.assertEquals(10, result.length); char[] mergedResult = "helloworld".toCharArray(); for (int i = 0; i < mergedResult.length; i++) { Assertions.assertEquals(mergedResult[i], result[i]); } result = mergerFactory.getMerger(char[].class).merge(null); Assertions.assertEquals(0, result.length); result = mergerFactory.getMerger(char[].class).merge(null, null); Assertions.assertEquals(0, result.length); } /** * DoubleArrayMerger test */ @Test void testDoubleArrayMerger() { double[] arrayOne = {1.2d, 3.5d}; double[] arrayTwo = {2d, 34d}; double[] result = mergerFactory.getMerger(double[].class).merge(arrayOne, arrayTwo, null); Assertions.assertEquals(4, result.length); double[] mergedResult = {1.2d, 3.5d, 2d, 34d}; for (int i = 0; i < mergedResult.length; i++) { Assertions.assertEquals(mergedResult[i], result[i], 0.0); } result = mergerFactory.getMerger(double[].class).merge(null); Assertions.assertEquals(0, result.length); result = mergerFactory.getMerger(double[].class).merge(null, null); Assertions.assertEquals(0, result.length); } /** * FloatArrayMerger test */ @Test void testFloatArrayMerger() { float[] arrayOne = {1.2f, 3.5f}; float[] arrayTwo = {2f, 34f}; float[] result = mergerFactory.getMerger(float[].class).merge(arrayOne, arrayTwo, null); Assertions.assertEquals(4, result.length); double[] mergedResult = {1.2f, 3.5f, 2f, 34f}; for (int i = 0; i < mergedResult.length; i++) { Assertions.assertEquals(mergedResult[i], result[i], 0.0); } result = mergerFactory.getMerger(float[].class).merge(null); Assertions.assertEquals(0, result.length); result = mergerFactory.getMerger(float[].class).merge(null, null); Assertions.assertEquals(0, result.length); } /** * IntArrayMerger test */ @Test void testIntArrayMerger() { int[] arrayOne = {1, 2}; int[] arrayTwo = {2, 34}; int[] result = mergerFactory.getMerger(int[].class).merge(arrayOne, arrayTwo, null); Assertions.assertEquals(4, result.length); double[] mergedResult = {1, 2, 2, 34}; for (int i = 0; i < mergedResult.length; i++) { Assertions.assertEquals(mergedResult[i], result[i], 0.0); } result = mergerFactory.getMerger(int[].class).merge(null); Assertions.assertEquals(0, result.length); result = mergerFactory.getMerger(int[].class).merge(null, null); Assertions.assertEquals(0, result.length); } /** * ListMerger test */ @Test void testListMerger() { List<Object> list1 = new ArrayList<Object>() { { add(null); add("1"); add("2"); } }; List<Object> list2 = new ArrayList<Object>() { { add("3"); add("4"); } }; List result = mergerFactory.getMerger(List.class).merge(list1, list2, null); Assertions.assertEquals(5, result.size()); ArrayList<String> expected = new ArrayList<String>() { { add(null); add("1"); add("2"); add("3"); add("4"); } }; Assertions.assertEquals(expected, result); result = mergerFactory.getMerger(List.class).merge(null); Assertions.assertEquals(0, result.size()); result = mergerFactory.getMerger(List.class).merge(null, null); Assertions.assertEquals(0, result.size()); } /** * LongArrayMerger test */ @Test void testMapArrayMerger() { Map<Object, Object> mapOne = new HashMap<Object, Object>() { { put("11", 222); put("223", 11); } }; Map<Object, Object> mapTwo = new HashMap<Object, Object>() { { put("3333", 3232); put("444", 2323); } }; Map<Object, Object> result = mergerFactory.getMerger(Map.class).merge(mapOne, mapTwo, null); Assertions.assertEquals(4, result.size()); Map<String, Integer> mergedResult = new HashMap<String, Integer>() { { put("11", 222); put("223", 11); put("3333", 3232); put("444", 2323); } }; Assertions.assertEquals(mergedResult, result); result = mergerFactory.getMerger(Map.class).merge(null); Assertions.assertEquals(0, result.size()); result = mergerFactory.getMerger(Map.class).merge(null, null); Assertions.assertEquals(0, result.size()); } /** * LongArrayMerger test */ @Test void testLongArrayMerger() { long[] arrayOne = {1L, 2L}; long[] arrayTwo = {2L, 34L}; long[] result = mergerFactory.getMerger(long[].class).merge(arrayOne, arrayTwo, null); Assertions.assertEquals(4, result.length); double[] mergedResult = {1L, 2L, 2L, 34L}; for (int i = 0; i < mergedResult.length; i++) { Assertions.assertEquals(mergedResult[i], result[i], 0.0); } result = mergerFactory.getMerger(long[].class).merge(null); Assertions.assertEquals(0, result.length); result = mergerFactory.getMerger(long[].class).merge(null, null); Assertions.assertEquals(0, result.length); } /** * SetMerger test */ @Test void testSetMerger() { Set<Object> set1 = new HashSet<Object>() { { add(null); add("1"); add("2"); } }; Set<Object> set2 = new HashSet<Object>() { { add("2"); add("3"); } }; Set result = mergerFactory.getMerger(Set.class).merge(set1, set2, null); Assertions.assertEquals(4, result.size()); Assertions.assertEquals( new HashSet<String>() { { add(null); add("1"); add("2"); add("3"); } }, result); result = mergerFactory.getMerger(Set.class).merge(null); Assertions.assertEquals(0, result.size()); result = mergerFactory.getMerger(Set.class).merge(null, null); Assertions.assertEquals(0, result.size()); } /** * ShortArrayMerger test */ @Test void testShortArrayMerger() { short[] arrayOne = {1, 2}; short[] arrayTwo = {2, 34}; short[] result = mergerFactory.getMerger(short[].class).merge(arrayOne, arrayTwo, null); Assertions.assertEquals(4, result.length); double[] mergedResult = {1, 2, 2, 34}; for (int i = 0; i < mergedResult.length; i++) { Assertions.assertEquals(mergedResult[i], result[i], 0.0); } result = mergerFactory.getMerger(short[].class).merge(null); Assertions.assertEquals(0, result.length); result = mergerFactory.getMerger(short[].class).merge(null, null); Assertions.assertEquals(0, result.length); } /** * IntSumMerger test */ @Test void testIntSumMerger() { Integer[] intArr = IntStream.rangeClosed(1, 100).boxed().toArray(Integer[]::new); Merger<Integer> merger = ApplicationModel.defaultModel().getExtension(Merger.class, "intsum"); Assertions.assertEquals(5050, merger.merge(intArr)); intArr = new Integer[] {}; Assertions.assertEquals(0, merger.merge(intArr)); } /** * DoubleSumMerger test */ @Test void testDoubleSumMerger() { Double[] doubleArr = DoubleStream.iterate(1, v -> ++v).limit(100).boxed().toArray(Double[]::new); Merger<Double> merger = ApplicationModel.defaultModel().getExtension(Merger.class, "doublesum"); Assertions.assertEquals(5050, merger.merge(doubleArr)); doubleArr = new Double[] {}; Assertions.assertEquals(0, merger.merge(doubleArr)); } /** * FloatSumMerger test */ @Test void testFloatSumMerger() { Float[] floatArr = Stream.iterate(1.0F, v -> ++v).limit(100).toArray(Float[]::new); Merger<Float> merger = ApplicationModel.defaultModel().getExtension(Merger.class, "floatsum"); Assertions.assertEquals(5050, merger.merge(floatArr)); floatArr = new Float[] {}; Assertions.assertEquals(0, merger.merge(floatArr)); } /** * LongSumMerger test */ @Test void testLongSumMerger() { Long[] longArr = LongStream.rangeClosed(1, 100).boxed().toArray(Long[]::new); Merger<Long> merger = ApplicationModel.defaultModel().getExtension(Merger.class, "longsum"); Assertions.assertEquals(5050, merger.merge(longArr)); longArr = new Long[] {}; Assertions.assertEquals(0, merger.merge(longArr)); } /** * IntFindAnyMerger test */ @Test void testIntFindAnyMerger() { Integer[] intArr = {1, 2, 3, 4}; Merger<Integer> merger = ApplicationModel.defaultModel().getExtension(Merger.class, "intany"); Assertions.assertNotNull(merger.merge(intArr)); intArr = new Integer[] {}; Assertions.assertNull(merger.merge(intArr)); } /** * IntFindFirstMerger test */ @Test void testIntFindFirstMerger() { Integer[] intArr = {1, 2, 3, 4}; Merger<Integer> merger = ApplicationModel.defaultModel().getExtension(Merger.class, "intfirst"); Assertions.assertEquals(1, merger.merge(intArr)); intArr = new Integer[] {}; Assertions.assertNull(merger.merge(intArr)); } }
7,748
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/merger/IntFindFirstMerger.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.merger; import org.apache.dubbo.rpc.cluster.Merger; import java.util.Arrays; public class IntFindFirstMerger implements Merger<Integer> { @Override public Integer merge(Integer... items) { return Arrays.stream(items).findFirst().orElse(null); } }
7,749
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/merger/IntSumMerger.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.merger; import org.apache.dubbo.rpc.cluster.Merger; import java.util.Arrays; import java.util.Objects; public class IntSumMerger implements Merger<Integer> { @Override public Integer merge(Integer... items) { return Arrays.stream(items) .filter(Objects::nonNull) .mapToInt(Integer::intValue) .sum(); } }
7,750
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/MenuService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.support; import java.util.List; public interface MenuService { Menu getMenu(); void addMenu(String menu, List<String> items); }
7,751
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ClusterUtilsTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.support; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Map; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.ALIVE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.CORE_THREADS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY_PREFIX; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PROTOCOL; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PID_KEY; import static org.apache.dubbo.common.constants.CommonConstants.QUEUES_KEY; import static org.apache.dubbo.common.constants.CommonConstants.REFERENCE_FILTER_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TAG_KEY; import static org.apache.dubbo.common.constants.CommonConstants.THREADPOOL_KEY; import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; import static org.apache.dubbo.common.constants.CommonConstants.URL_MERGE_PROCESSOR_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; class ClusterUtilsTest { private ClusterUtils clusterUtils; @BeforeEach public void setup() { clusterUtils = new ClusterUtils(); clusterUtils.setApplicationModel(ApplicationModel.defaultModel()); } @Test void testMergeUrl() { URL providerURL = URL.valueOf("dubbo://localhost:55555"); providerURL = providerURL.setPath("path").setUsername("username").setPassword("password"); providerURL = URLBuilder.from(providerURL) .addParameter(GROUP_KEY, "dubbo") .addParameter(VERSION_KEY, "1.2.3") .addParameter(DUBBO_VERSION_KEY, "2.3.7") .addParameter(THREADPOOL_KEY, "fixed") .addParameter(THREADS_KEY, Integer.MAX_VALUE) .addParameter(THREAD_NAME_KEY, "test") .addParameter(CORE_THREADS_KEY, Integer.MAX_VALUE) .addParameter(QUEUES_KEY, Integer.MAX_VALUE) .addParameter(ALIVE_KEY, Integer.MAX_VALUE) .addParameter(DEFAULT_KEY_PREFIX + THREADS_KEY, Integer.MAX_VALUE) .addParameter(DEFAULT_KEY_PREFIX + THREADPOOL_KEY, "fixed") .addParameter(DEFAULT_KEY_PREFIX + CORE_THREADS_KEY, Integer.MAX_VALUE) .addParameter(DEFAULT_KEY_PREFIX + QUEUES_KEY, Integer.MAX_VALUE) .addParameter(DEFAULT_KEY_PREFIX + ALIVE_KEY, Integer.MAX_VALUE) .addParameter(DEFAULT_KEY_PREFIX + THREAD_NAME_KEY, "test") .addParameter(APPLICATION_KEY, "provider") .addParameter(REFERENCE_FILTER_KEY, "filter1,filter2") .addParameter(TAG_KEY, "TTT") .build(); // Verify default ProviderURLMergeProcessor URL consumerURL = new URLBuilder(DUBBO_PROTOCOL, "localhost", 55555) .addParameter(PID_KEY, "1234") .addParameter(THREADPOOL_KEY, "foo") .addParameter(APPLICATION_KEY, "consumer") .addParameter(REFERENCE_FILTER_KEY, "filter3") .addParameter(TAG_KEY, "UUU") .build(); URL url = clusterUtils.mergeUrl(providerURL, consumerURL.getParameters()); Assertions.assertFalse(url.hasParameter(THREADS_KEY)); Assertions.assertFalse(url.hasParameter(DEFAULT_KEY_PREFIX + THREADS_KEY)); Assertions.assertFalse(url.hasParameter(DEFAULT_KEY_PREFIX + THREADPOOL_KEY)); Assertions.assertFalse(url.hasParameter(CORE_THREADS_KEY)); Assertions.assertFalse(url.hasParameter(DEFAULT_KEY_PREFIX + CORE_THREADS_KEY)); Assertions.assertFalse(url.hasParameter(QUEUES_KEY)); Assertions.assertFalse(url.hasParameter(DEFAULT_KEY_PREFIX + QUEUES_KEY)); Assertions.assertFalse(url.hasParameter(ALIVE_KEY)); Assertions.assertFalse(url.hasParameter(DEFAULT_KEY_PREFIX + ALIVE_KEY)); Assertions.assertFalse(url.hasParameter(THREAD_NAME_KEY)); Assertions.assertFalse(url.hasParameter(DEFAULT_KEY_PREFIX + THREAD_NAME_KEY)); Assertions.assertEquals("path", url.getPath()); Assertions.assertEquals("username", url.getUsername()); Assertions.assertEquals("password", url.getPassword()); Assertions.assertEquals("1234", url.getParameter(PID_KEY)); Assertions.assertEquals("foo", url.getParameter(THREADPOOL_KEY)); Assertions.assertEquals("consumer", url.getApplication()); Assertions.assertEquals("provider", url.getRemoteApplication()); Assertions.assertEquals("filter1,filter2,filter3", url.getParameter(REFERENCE_FILTER_KEY)); Assertions.assertEquals("TTT", url.getParameter(TAG_KEY)); // Verify custom ProviderURLMergeProcessor URL consumerUrlForTag = new URLBuilder(DUBBO_PROTOCOL, "localhost", 55555) .addParameter(PID_KEY, "1234") .addParameter(THREADPOOL_KEY, "foo") .addParameter(APPLICATION_KEY, "consumer") .addParameter(REFERENCE_FILTER_KEY, "filter3") .addParameter(TAG_KEY, "UUU") .addParameter(URL_MERGE_PROCESSOR_KEY, "tag") .build(); URL urlForTag = clusterUtils.mergeUrl(providerURL, consumerUrlForTag.getParameters()); Assertions.assertEquals("UUU", urlForTag.getParameter(TAG_KEY)); } @Test void testMergeLocalParams() { // Verify default ProviderURLMergeProcessor URL consumerURL = new URLBuilder(DUBBO_PROTOCOL, "localhost", 55555) .addParameter(PID_KEY, "1234") .addParameter(THREADPOOL_KEY, "foo") .addParameter(APPLICATION_KEY, "consumer") .addParameter(REFERENCE_FILTER_KEY, "filter3") .addParameter(TAG_KEY, "UUU") .build(); Map<String, String> params = clusterUtils.mergeLocalParams(consumerURL.getParameters()); Assertions.assertEquals("1234", params.get(PID_KEY)); Assertions.assertEquals("foo", params.get(THREADPOOL_KEY)); Assertions.assertEquals("consumer", params.get(APPLICATION_KEY)); Assertions.assertEquals("filter3", params.get(REFERENCE_FILTER_KEY)); Assertions.assertEquals("UUU", params.get(TAG_KEY)); // Verify custom ProviderURLMergeProcessor URL consumerUrlForTag = new URLBuilder(DUBBO_PROTOCOL, "localhost", 55555) .addParameter(PID_KEY, "1234") .addParameter(THREADPOOL_KEY, "foo") .addParameter(APPLICATION_KEY, "consumer") .addParameter(REFERENCE_FILTER_KEY, "filter3") .addParameter(TAG_KEY, "UUU") .addParameter(URL_MERGE_PROCESSOR_KEY, "tag") .build(); Map<String, String> paramsForTag = clusterUtils.mergeLocalParams(consumerUrlForTag.getParameters()); Assertions.assertEquals("1234", paramsForTag.get(PID_KEY)); Assertions.assertEquals("foo", paramsForTag.get(THREADPOOL_KEY)); Assertions.assertEquals("consumer", paramsForTag.get(APPLICATION_KEY)); Assertions.assertEquals("filter3", paramsForTag.get(REFERENCE_FILTER_KEY)); Assertions.assertNull(paramsForTag.get(TAG_KEY)); } }
7,752
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/TagProviderURLMergeProcessor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.support; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.cluster.ProviderURLMergeProcessor; import java.util.Map; import static org.apache.dubbo.common.constants.CommonConstants.TAG_KEY; public class TagProviderURLMergeProcessor implements ProviderURLMergeProcessor { @Override public URL mergeUrl(URL remoteUrl, Map<String, String> localParametersMap) { String tag = localParametersMap.get(TAG_KEY); remoteUrl = remoteUrl.removeParameter(TAG_KEY); remoteUrl = remoteUrl.addParameter(TAG_KEY, tag); return remoteUrl; } @Override public Map<String, String> mergeLocalParams(Map<String, String> localMap) { localMap.remove(TAG_KEY); return ProviderURLMergeProcessor.super.mergeLocalParams(localMap); } }
7,753
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvokerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.support; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.cluster.Directory; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ModuleModel; import java.lang.reflect.Proxy; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.rpc.Constants.MERGER_KEY; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; class MergeableClusterInvokerTest { private Directory directory = mock(Directory.class); private Invoker firstInvoker = mock(Invoker.class); private Invoker secondInvoker = mock(Invoker.class); private Invocation invocation = mock(RpcInvocation.class); private ModuleModel moduleModel = mock(ModuleModel.class); private MergeableClusterInvoker<MenuService> mergeableClusterInvoker; private String[] list1 = {"10", "11", "12"}; private String[] list2 = {"20", "21", "22"}; private final Map<String, List<String>> firstMenuMap = new HashMap<String, List<String>>() { { put("1", Arrays.asList(list1)); put("2", Arrays.asList(list2)); } }; private final Menu firstMenu = new Menu(firstMenuMap); private String[] list3 = {"23", "24", "25"}; private String[] list4 = {"30", "31", "32"}; private final Map<String, List<String>> secondMenuMap = new HashMap<String, List<String>>() { { put("2", Arrays.asList(list3)); put("3", Arrays.asList(list4)); } }; private final Menu secondMenu = new Menu(secondMenuMap); private URL url = URL.valueOf("test://test/" + MenuService.class.getName()); static void merge(Map<String, List<String>> first, Map<String, List<String>> second) { for (Map.Entry<String, List<String>> entry : second.entrySet()) { List<String> value = first.get(entry.getKey()); if (value != null) { value.addAll(entry.getValue()); } else { first.put(entry.getKey(), new ArrayList<>(entry.getValue())); } } } @BeforeEach public void setUp() throws Exception { directory = mock(Directory.class); firstInvoker = mock(Invoker.class); secondInvoker = mock(Invoker.class); invocation = mock(RpcInvocation.class); } @Test void testGetMenuSuccessfully() { // setup url = url.addParameter(MERGER_KEY, ".merge"); given(invocation.getMethodName()).willReturn("getMenu"); given(invocation.getParameterTypes()).willReturn(new Class<?>[] {}); given(invocation.getArguments()).willReturn(new Object[] {}); given(invocation.getObjectAttachments()).willReturn(new HashMap<>()); given(invocation.getInvoker()).willReturn(firstInvoker); firstInvoker = (Invoker) Proxy.newProxyInstance( getClass().getClassLoader(), new Class<?>[] {Invoker.class}, (proxy, method, args) -> { if ("getUrl".equals(method.getName())) { return url.addParameter(GROUP_KEY, "first"); } if ("getInterface".equals(method.getName())) { return MenuService.class; } if ("invoke".equals(method.getName())) { return AsyncRpcResult.newDefaultAsyncResult(firstMenu, invocation); } return null; }); secondInvoker = (Invoker) Proxy.newProxyInstance( getClass().getClassLoader(), new Class<?>[] {Invoker.class}, (proxy, method, args) -> { if ("getUrl".equals(method.getName())) { return url.addParameter(GROUP_KEY, "second"); } if ("getInterface".equals(method.getName())) { return MenuService.class; } if ("invoke".equals(method.getName())) { return AsyncRpcResult.newDefaultAsyncResult(secondMenu, invocation); } return null; }); given(directory.list(invocation)).willReturn(new ArrayList() { { add(firstInvoker); add(secondInvoker); } }); given(directory.getUrl()).willReturn(url); given(directory.getConsumerUrl()).willReturn(url); given(directory.getConsumerUrl()).willReturn(url); given(directory.getInterface()).willReturn(MenuService.class); mergeableClusterInvoker = new MergeableClusterInvoker<MenuService>(directory); // invoke Result result = mergeableClusterInvoker.invoke(invocation); assertTrue(result.getValue() instanceof Menu); Menu menu = (Menu) result.getValue(); Map<String, List<String>> expected = new HashMap<>(); merge(expected, firstMenuMap); merge(expected, secondMenuMap); assertEquals(expected.keySet(), menu.getMenus().keySet()); for (Map.Entry<String, List<String>> entry : expected.entrySet()) { // FIXME: cannot guarantee the sequence of the merge result, check implementation in // MergeableClusterInvoker#invoke List<String> values1 = new ArrayList<>(entry.getValue()); List<String> values2 = new ArrayList<>(menu.getMenus().get(entry.getKey())); Collections.sort(values1); Collections.sort(values2); assertEquals(values1, values2); } } @Test void testAddMenu() { String menu = "first"; List<String> menuItems = new ArrayList<String>() { { add("1"); add("2"); } }; given(invocation.getMethodName()).willReturn("addMenu"); given(invocation.getParameterTypes()).willReturn(new Class<?>[] {String.class, List.class}); given(invocation.getArguments()).willReturn(new Object[] {menu, menuItems}); given(invocation.getObjectAttachments()).willReturn(new HashMap<>()); given(invocation.getInvoker()).willReturn(firstInvoker); given(firstInvoker.getUrl()).willReturn(url.addParameter(GROUP_KEY, "first")); given(firstInvoker.getInterface()).willReturn(MenuService.class); given(firstInvoker.invoke(invocation)).willReturn(new AppResponse()); given(firstInvoker.isAvailable()).willReturn(true); given(secondInvoker.getUrl()).willReturn(url.addParameter(GROUP_KEY, "second")); given(secondInvoker.getInterface()).willReturn(MenuService.class); given(secondInvoker.invoke(invocation)).willReturn(new AppResponse()); given(secondInvoker.isAvailable()).willReturn(true); given(directory.list(invocation)).willReturn(new ArrayList() { { add(firstInvoker); add(secondInvoker); } }); given(directory.getUrl()).willReturn(url); given(directory.getConsumerUrl()).willReturn(url); given(directory.getConsumerUrl()).willReturn(url); given(directory.getInterface()).willReturn(MenuService.class); mergeableClusterInvoker = new MergeableClusterInvoker<MenuService>(directory); Result result = mergeableClusterInvoker.invoke(invocation); Assertions.assertNull(result.getValue()); } @Test void testAddMenu1() { // setup url = url.addParameter(MERGER_KEY, ".merge"); String menu = "first"; List<String> menuItems = new ArrayList<String>() { { add("1"); add("2"); } }; given(invocation.getMethodName()).willReturn("addMenu"); given(invocation.getParameterTypes()).willReturn(new Class<?>[] {String.class, List.class}); given(invocation.getArguments()).willReturn(new Object[] {menu, menuItems}); given(invocation.getObjectAttachments()).willReturn(new HashMap<>()); given(invocation.getInvoker()).willReturn(firstInvoker); firstInvoker = (Invoker) Proxy.newProxyInstance( getClass().getClassLoader(), new Class<?>[] {Invoker.class}, (proxy, method, args) -> { if ("getUrl".equals(method.getName())) { return url.addParameter(GROUP_KEY, "first"); } if ("getInterface".equals(method.getName())) { return MenuService.class; } if ("invoke".equals(method.getName())) { return AsyncRpcResult.newDefaultAsyncResult(firstMenu, invocation); } return null; }); secondInvoker = (Invoker) Proxy.newProxyInstance( getClass().getClassLoader(), new Class<?>[] {Invoker.class}, (proxy, method, args) -> { if ("getUrl".equals(method.getName())) { return url.addParameter(GROUP_KEY, "second"); } if ("getInterface".equals(method.getName())) { return MenuService.class; } if ("invoke".equals(method.getName())) { return AsyncRpcResult.newDefaultAsyncResult(secondMenu, invocation); } return null; }); given(directory.list(invocation)).willReturn(new ArrayList() { { add(firstInvoker); add(secondInvoker); } }); given(directory.getUrl()).willReturn(url); given(directory.getConsumerUrl()).willReturn(url); given(directory.getConsumerUrl()).willReturn(url); given(directory.getInterface()).willReturn(MenuService.class); mergeableClusterInvoker = new MergeableClusterInvoker<MenuService>(directory); Result result = mergeableClusterInvoker.invoke(invocation); Assertions.assertNull(result.getValue()); } @Test void testInvokerToNoInvokerAvailableException() { String menu = "first"; List<String> menuItems = new ArrayList<String>() { { add("1"); add("2"); } }; given(invocation.getMethodName()).willReturn("addMenu"); given(invocation.getParameterTypes()).willReturn(new Class<?>[] {String.class, List.class}); given(invocation.getArguments()).willReturn(new Object[] {menu, menuItems}); given(invocation.getObjectAttachments()).willReturn(new HashMap<>()); given(invocation.getInvoker()).willReturn(firstInvoker); given(firstInvoker.getUrl()).willReturn(url.addParameter(GROUP_KEY, "first")); given(firstInvoker.getInterface()).willReturn(MenuService.class); given(firstInvoker.invoke(invocation)).willReturn(new AppResponse()); given(firstInvoker.isAvailable()).willReturn(true); given(firstInvoker.invoke(invocation)) .willThrow(new RpcException(RpcException.NO_INVOKER_AVAILABLE_AFTER_FILTER)); given(secondInvoker.getUrl()).willReturn(url.addParameter(GROUP_KEY, "second")); given(secondInvoker.getInterface()).willReturn(MenuService.class); given(secondInvoker.invoke(invocation)).willReturn(new AppResponse()); given(secondInvoker.isAvailable()).willReturn(true); given(secondInvoker.invoke(invocation)) .willThrow(new RpcException(RpcException.NO_INVOKER_AVAILABLE_AFTER_FILTER)); given(directory.list(invocation)).willReturn(new ArrayList() { { add(firstInvoker); add(secondInvoker); } }); given(directory.getUrl()).willReturn(url); given(directory.getConsumerUrl()).willReturn(url); given(directory.getConsumerUrl()).willReturn(url); given(directory.getInterface()).willReturn(MenuService.class); mergeableClusterInvoker = new MergeableClusterInvoker<MenuService>(directory); // invoke try { Result result = mergeableClusterInvoker.invoke(invocation); fail(); Assertions.assertNull(result.getValue()); } catch (RpcException expected) { assertEquals(expected.getCode(), RpcException.NO_INVOKER_AVAILABLE_AFTER_FILTER); } } /** * test when network exception */ @Test void testInvokerToException() { String menu = "first"; List<String> menuItems = new ArrayList<String>() { { add("1"); add("2"); } }; given(invocation.getMethodName()).willReturn("addMenu"); given(invocation.getParameterTypes()).willReturn(new Class<?>[] {String.class, List.class}); given(invocation.getArguments()).willReturn(new Object[] {menu, menuItems}); given(invocation.getObjectAttachments()).willReturn(new HashMap<>()); given(invocation.getInvoker()).willReturn(firstInvoker); given(firstInvoker.getUrl()).willReturn(url.addParameter(GROUP_KEY, "first")); given(firstInvoker.getInterface()).willReturn(MenuService.class); given(firstInvoker.invoke(invocation)).willReturn(new AppResponse()); given(firstInvoker.isAvailable()).willReturn(true); given(firstInvoker.invoke(invocation)).willThrow(new RpcException(RpcException.NETWORK_EXCEPTION)); given(secondInvoker.getUrl()).willReturn(url.addParameter(GROUP_KEY, "second")); given(secondInvoker.getInterface()).willReturn(MenuService.class); given(secondInvoker.invoke(invocation)).willReturn(new AppResponse()); given(secondInvoker.isAvailable()).willReturn(true); given(secondInvoker.invoke(invocation)).willThrow(new RpcException(RpcException.NETWORK_EXCEPTION)); given(directory.list(invocation)).willReturn(new ArrayList() { { add(firstInvoker); add(secondInvoker); } }); given(directory.getUrl()).willReturn(url); given(directory.getConsumerUrl()).willReturn(url); given(directory.getConsumerUrl()).willReturn(url); given(directory.getInterface()).willReturn(MenuService.class); mergeableClusterInvoker = new MergeableClusterInvoker<MenuService>(directory); // invoke try { Result result = mergeableClusterInvoker.invoke(invocation); fail(); Assertions.assertNull(result.getValue()); } catch (RpcException expected) { assertEquals(expected.getCode(), RpcException.NETWORK_EXCEPTION); } } @Test void testGetMenuResultHasException() { // setup url = url.addParameter(MERGER_KEY, ".merge"); given(invocation.getMethodName()).willReturn("getMenu"); given(invocation.getParameterTypes()).willReturn(new Class<?>[] {}); given(invocation.getArguments()).willReturn(new Object[] {}); given(invocation.getObjectAttachments()).willReturn(new HashMap<>()); given(invocation.getInvoker()).willReturn(firstInvoker); given(firstInvoker.getUrl()).willReturn(url.addParameter(GROUP_KEY, "first")); given(firstInvoker.getInterface()).willReturn(MenuService.class); given(firstInvoker.invoke(invocation)).willReturn(new AppResponse()); given(firstInvoker.isAvailable()).willReturn(true); given(secondInvoker.getUrl()).willReturn(url.addParameter(GROUP_KEY, "second")); given(secondInvoker.getInterface()).willReturn(MenuService.class); given(secondInvoker.invoke(invocation)).willReturn(new AppResponse()); given(secondInvoker.isAvailable()).willReturn(true); given(directory.list(invocation)).willReturn(new ArrayList() { { add(firstInvoker); add(secondInvoker); } }); given(directory.getUrl()).willReturn(url); given(directory.getConsumerUrl()).willReturn(url); given(directory.getConsumerUrl()).willReturn(url); given(directory.getInterface()).willReturn(MenuService.class); mergeableClusterInvoker = new MergeableClusterInvoker<MenuService>(directory); // invoke try { Result result = mergeableClusterInvoker.invoke(invocation); fail(); Assertions.assertNull(result.getValue()); } catch (RpcException expected) { Assertions.assertTrue(expected.getMessage().contains("Failed to invoke service")); } } @Test void testGetMenuWithMergerDefault() { // setup url = url.addParameter(MERGER_KEY, "default"); given(invocation.getMethodName()).willReturn("getMenu"); given(invocation.getParameterTypes()).willReturn(new Class<?>[] {}); given(invocation.getArguments()).willReturn(new Object[] {}); given(invocation.getObjectAttachments()).willReturn(new HashMap<>()); given(invocation.getInvoker()).willReturn(firstInvoker); // mock ApplicationModel given(invocation.getModuleModel()).willReturn(moduleModel); given(invocation.getModuleModel().getApplicationModel()).willReturn(ApplicationModel.defaultModel()); firstInvoker = (Invoker) Proxy.newProxyInstance( getClass().getClassLoader(), new Class<?>[] {Invoker.class}, (proxy, method, args) -> { if ("getUrl".equals(method.getName())) { return url.addParameter(GROUP_KEY, "first"); } if ("getInterface".equals(method.getName())) { return MenuService.class; } if ("invoke".equals(method.getName())) { return AsyncRpcResult.newDefaultAsyncResult(firstMenu, invocation); } return null; }); secondInvoker = (Invoker) Proxy.newProxyInstance( getClass().getClassLoader(), new Class<?>[] {Invoker.class}, (proxy, method, args) -> { if ("getUrl".equals(method.getName())) { return url.addParameter(GROUP_KEY, "second"); } if ("getInterface".equals(method.getName())) { return MenuService.class; } if ("invoke".equals(method.getName())) { return AsyncRpcResult.newDefaultAsyncResult(secondMenu, invocation); } return null; }); given(directory.list(invocation)).willReturn(new ArrayList() { { add(firstInvoker); add(secondInvoker); } }); given(directory.getUrl()).willReturn(url); given(directory.getConsumerUrl()).willReturn(url); given(directory.getConsumerUrl()).willReturn(url); given(directory.getInterface()).willReturn(MenuService.class); mergeableClusterInvoker = new MergeableClusterInvoker<MenuService>(directory); // invoke try { mergeableClusterInvoker.invoke(invocation); } catch (RpcException exception) { Assertions.assertTrue(exception.getMessage().contains("There is no merger to merge result.")); } } @Test void testDestroy() { given(invocation.getMethodName()).willReturn("getMenu"); given(invocation.getParameterTypes()).willReturn(new Class<?>[] {}); given(invocation.getArguments()).willReturn(new Object[] {}); given(invocation.getObjectAttachments()).willReturn(new HashMap<>()); given(invocation.getInvoker()).willReturn(firstInvoker); given(firstInvoker.getUrl()).willReturn(url.addParameter(GROUP_KEY, "first")); given(firstInvoker.getInterface()).willReturn(MenuService.class); given(firstInvoker.invoke(invocation)).willReturn(new AppResponse()); given(secondInvoker.getUrl()).willReturn(url.addParameter(GROUP_KEY, "second")); given(secondInvoker.getInterface()).willReturn(MenuService.class); given(secondInvoker.invoke(invocation)).willReturn(new AppResponse()); given(directory.list(invocation)).willReturn(new ArrayList() { { add(firstInvoker); add(secondInvoker); } }); given(directory.getUrl()).willReturn(url); given(directory.getConsumerUrl()).willReturn(url); given(directory.getConsumerUrl()).willReturn(url); given(directory.getInterface()).willReturn(MenuService.class); mergeableClusterInvoker = new MergeableClusterInvoker<MenuService>(directory); mergeableClusterInvoker.destroy(); assertFalse(firstInvoker.isAvailable()); assertFalse(secondInvoker.isAvailable()); } }
7,754
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailoverClusterInvokerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.support; import org.apache.dubbo.common.URL; import org.apache.dubbo.metrics.event.MetricsDispatcher; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.cluster.Directory; import org.apache.dubbo.rpc.cluster.SingleRouterChain; import org.apache.dubbo.rpc.cluster.directory.StaticDirectory; import org.apache.dubbo.rpc.cluster.router.state.BitList; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.protocol.AbstractInvoker; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * FailoverClusterInvokerTest */ @SuppressWarnings("unchecked") class FailoverClusterInvokerTest { private final int retries = 5; private final URL url = URL.valueOf("test://test:11/test?retries=" + retries); private final Invoker<FailoverClusterInvokerTest> invoker1 = mock(Invoker.class); private final Invoker<FailoverClusterInvokerTest> invoker2 = mock(Invoker.class); private final RpcInvocation invocation = new RpcInvocation(); private final Result expectedResult = new AppResponse(); private final List<Invoker<FailoverClusterInvokerTest>> invokers = new ArrayList<>(); private Directory<FailoverClusterInvokerTest> dic; /** * @throws java.lang.Exception */ @BeforeEach public void setUp() throws Exception { ApplicationModel.defaultModel().getBeanFactory().registerBean(MetricsDispatcher.class); dic = mock(Directory.class); given(dic.getUrl()).willReturn(url); given(dic.getConsumerUrl()).willReturn(url); given(dic.list(invocation)).willReturn(invokers); given(dic.getInterface()).willReturn(FailoverClusterInvokerTest.class); invocation.setMethodName("method1"); invokers.add(invoker1); invokers.add(invoker2); } @Test void testInvokeWithRuntimeException() { given(invoker1.invoke(invocation)).willThrow(new RuntimeException()); given(invoker1.isAvailable()).willReturn(true); given(invoker1.getUrl()).willReturn(url); given(invoker1.getInterface()).willReturn(FailoverClusterInvokerTest.class); given(invoker2.invoke(invocation)).willThrow(new RuntimeException()); given(invoker2.isAvailable()).willReturn(true); given(invoker2.getUrl()).willReturn(url); given(invoker2.getInterface()).willReturn(FailoverClusterInvokerTest.class); FailoverClusterInvoker<FailoverClusterInvokerTest> invoker = new FailoverClusterInvoker<>(dic); try { invoker.invoke(invocation); fail(); } catch (RpcException actualException) { assertEquals(0, actualException.getCode()); assertFalse(actualException.getCause() instanceof RpcException); } } @Test void testInvokeWithRPCException() { given(invoker1.invoke(invocation)).willThrow(new RpcException()); given(invoker1.isAvailable()).willReturn(true); given(invoker1.getUrl()).willReturn(url); given(invoker1.getInterface()).willReturn(FailoverClusterInvokerTest.class); given(invoker2.invoke(invocation)).willReturn(expectedResult); given(invoker2.isAvailable()).willReturn(true); given(invoker2.getUrl()).willReturn(url); given(invoker2.getInterface()).willReturn(FailoverClusterInvokerTest.class); FailoverClusterInvoker<FailoverClusterInvokerTest> invoker = new FailoverClusterInvoker<>(dic); for (int i = 0; i < 100; i++) { Result actualResult = invoker.invoke(invocation); assertSame(expectedResult, actualResult); } } @Test void testInvoke_retryTimes() { given(invoker1.invoke(invocation)).willThrow(new RpcException(RpcException.TIMEOUT_EXCEPTION)); given(invoker1.isAvailable()).willReturn(false); given(invoker1.getUrl()).willReturn(url); given(invoker1.getInterface()).willReturn(FailoverClusterInvokerTest.class); given(invoker2.invoke(invocation)).willThrow(new RpcException()); given(invoker2.isAvailable()).willReturn(false); given(invoker2.getUrl()).willReturn(url); given(invoker2.getInterface()).willReturn(FailoverClusterInvokerTest.class); FailoverClusterInvoker<FailoverClusterInvokerTest> invoker = new FailoverClusterInvoker<>(dic); try { Result actualResult = invoker.invoke(invocation); assertSame(expectedResult, actualResult); fail(); } catch (RpcException actualException) { assertTrue((actualException.isTimeout() || actualException.getCode() == 0)); assertTrue(actualException.getMessage().indexOf((retries + 1) + " times") > 0); } } @Test void testInvoke_retryTimes2() { int finalRetries = 1; given(invoker1.invoke(invocation)).willThrow(new RpcException(RpcException.TIMEOUT_EXCEPTION)); given(invoker1.isAvailable()).willReturn(false); given(invoker1.getUrl()).willReturn(url); given(invoker1.getInterface()).willReturn(FailoverClusterInvokerTest.class); given(invoker2.invoke(invocation)).willThrow(new RpcException()); given(invoker2.isAvailable()).willReturn(false); given(invoker2.getUrl()).willReturn(url); given(invoker2.getInterface()).willReturn(FailoverClusterInvokerTest.class); RpcContext rpcContext = RpcContext.getContext(); rpcContext.setAttachment("retries", finalRetries); FailoverClusterInvoker<FailoverClusterInvokerTest> invoker = new FailoverClusterInvoker<>(dic); try { Result actualResult = invoker.invoke(invocation); assertSame(expectedResult, actualResult); fail(); } catch (RpcException actualException) { assertTrue((actualException.isTimeout() || actualException.getCode() == 0)); assertTrue(actualException.getMessage().indexOf((finalRetries + 1) + " times") > 0); } } @Test void testInvoke_retryTimes_withBizException() { given(invoker1.invoke(invocation)).willThrow(new RpcException(RpcException.BIZ_EXCEPTION)); given(invoker1.isAvailable()).willReturn(false); given(invoker1.getUrl()).willReturn(url); given(invoker1.getInterface()).willReturn(FailoverClusterInvokerTest.class); given(invoker2.invoke(invocation)).willThrow(new RpcException(RpcException.BIZ_EXCEPTION)); given(invoker2.isAvailable()).willReturn(false); given(invoker2.getUrl()).willReturn(url); given(invoker2.getInterface()).willReturn(FailoverClusterInvokerTest.class); FailoverClusterInvoker<FailoverClusterInvokerTest> invoker = new FailoverClusterInvoker<>(dic); try { Result actualResult = invoker.invoke(invocation); assertSame(expectedResult, actualResult); fail(); } catch (RpcException actualException) { assertEquals(RpcException.BIZ_EXCEPTION, actualException.getCode()); } } @Test void testInvoke_without_retry() { int withoutRetry = 0; final URL url = URL.valueOf( "test://localhost/" + Demo.class.getName() + "?loadbalance=roundrobin&retries=" + withoutRetry); RpcException exception = new RpcException(RpcException.TIMEOUT_EXCEPTION); MockInvoker<Demo> invoker1 = new MockInvoker<>(Demo.class, url); invoker1.setException(exception); MockInvoker<Demo> invoker2 = new MockInvoker<>(Demo.class, url); invoker2.setException(exception); final List<Invoker<Demo>> invokers = new ArrayList<>(); invokers.add(invoker1); invokers.add(invoker2); try { Directory<Demo> dic = new MockDirectory<>(url, invokers); FailoverClusterInvoker<Demo> clusterInvoker = new FailoverClusterInvoker<>(dic); RpcInvocation inv = new RpcInvocation(); inv.setMethodName("test"); clusterInvoker.invoke(inv); } catch (RpcException actualException) { assertTrue(actualException.getCause() instanceof RpcException); assertEquals(RpcException.TIMEOUT_EXCEPTION, actualException.getCode()); } } @Test void testInvoke_when_retry_illegal() { int illegalRetry = -1; final URL url = URL.valueOf( "test://localhost/" + Demo.class.getName() + "?loadbalance=roundrobin&retries=" + illegalRetry); RpcException exception = new RpcException(RpcException.TIMEOUT_EXCEPTION); MockInvoker<Demo> invoker1 = new MockInvoker<>(Demo.class, url); invoker1.setException(exception); MockInvoker<Demo> invoker2 = new MockInvoker<>(Demo.class, url); invoker2.setException(exception); final List<Invoker<Demo>> invokers = new ArrayList<>(); invokers.add(invoker1); invokers.add(invoker2); try { Directory<Demo> dic = new MockDirectory<>(url, invokers); FailoverClusterInvoker<Demo> clusterInvoker = new FailoverClusterInvoker<>(dic); RpcInvocation inv = new RpcInvocation(); inv.setMethodName("test"); clusterInvoker.invoke(inv); } catch (RpcException actualException) { assertTrue(actualException.getCause() instanceof RpcException); assertEquals(RpcException.TIMEOUT_EXCEPTION, actualException.getCode()); } } @Test void testNoInvoke() { dic = mock(Directory.class); given(dic.getUrl()).willReturn(url); given(dic.getConsumerUrl()).willReturn(url); given(dic.list(invocation)).willReturn(null); given(dic.getInterface()).willReturn(FailoverClusterInvokerTest.class); invocation.setMethodName("method1"); invokers.add(invoker1); FailoverClusterInvoker<FailoverClusterInvokerTest> invoker = new FailoverClusterInvoker<>(dic); try { invoker.invoke(invocation); fail(); } catch (RpcException actualException) { assertFalse(actualException.getCause() instanceof RpcException); } } /** * When invokers in directory changes after a failed request but just before a retry effort, * then we should reselect from the latest invokers before retry. */ @Test void testInvokerDestroyAndReList() { final URL url = URL.valueOf("test://localhost/" + Demo.class.getName() + "?loadbalance=roundrobin&retries=" + retries); RpcException exception = new RpcException(RpcException.TIMEOUT_EXCEPTION); MockInvoker<Demo> invoker1 = new MockInvoker<>(Demo.class, url); invoker1.setException(exception); MockInvoker<Demo> invoker2 = new MockInvoker<>(Demo.class, url); invoker2.setException(exception); final List<Invoker<Demo>> invokers = new ArrayList<>(); invokers.add(invoker1); invokers.add(invoker2); MockDirectory<Demo> dic = new MockDirectory<>(url, invokers); Callable<Object> callable = () -> { // Simulation: all invokers are destroyed for (Invoker<Demo> invoker : invokers) { invoker.destroy(); } invokers.clear(); MockInvoker<Demo> invoker3 = new MockInvoker<>(Demo.class, url); invoker3.setResult(AsyncRpcResult.newDefaultAsyncResult(mock(RpcInvocation.class))); invokers.add(invoker3); dic.notify(invokers); return null; }; invoker1.setCallable(callable); invoker2.setCallable(callable); RpcInvocation inv = new RpcInvocation(); inv.setMethodName("test"); FailoverClusterInvoker<Demo> clusterInvoker = new FailoverClusterInvoker<>(dic); clusterInvoker.invoke(inv); } public interface Demo {} public static class MockInvoker<T> extends AbstractInvoker<T> { URL url; boolean available = true; boolean destoryed = false; Result result; RpcException exception; Callable<?> callable; public MockInvoker(Class<T> type, URL url) { super(type, url); } public void setResult(Result result) { this.result = result; } public void setException(RpcException exception) { this.exception = exception; } public void setCallable(Callable<?> callable) { this.callable = callable; } @Override protected Result doInvoke(Invocation invocation) throws Throwable { if (callable != null) { try { callable.call(); } catch (Exception e) { throw new RpcException(e); } } if (exception != null) { throw exception; } else { return result; } } } public static class MockDirectory<T> extends StaticDirectory<T> { public MockDirectory(URL url, List<Invoker<T>> invokers) { super(url, invokers); } @Override protected List<Invoker<T>> doList( SingleRouterChain<T> singleRouterChain, BitList<Invoker<T>> invokers, Invocation invocation) throws RpcException { return super.doList(singleRouterChain, invokers, invocation); } } }
7,755
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/Menu.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.support; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; class Menu { private Map<String, List<String>> menus = new HashMap<String, List<String>>(); public Menu() {} public Menu(Map<String, List<String>> menus) { for (Map.Entry<String, List<String>> entry : menus.entrySet()) { this.menus.put(entry.getKey(), new ArrayList<String>(entry.getValue())); } } public void putMenuItem(String menu, String item) { List<String> items = menus.get(menu); if (item == null) { items = new ArrayList<String>(); menus.put(menu, items); } items.add(item); } public void addMenu(String menu, List<String> items) { List<String> menuItems = menus.get(menu); if (menuItems == null) { menus.put(menu, new ArrayList<String>(items)); } else { menuItems.addAll(new ArrayList<String>(items)); } } public Map<String, List<String>> getMenus() { return Collections.unmodifiableMap(menus); } public void merge(Menu menu) { for (Map.Entry<String, List<String>> entry : menu.menus.entrySet()) { addMenu(entry.getKey(), entry.getValue()); } } }
7,756
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailSafeClusterInvokerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.support; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.cluster.Directory; import org.apache.dubbo.rpc.cluster.filter.DemoService; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * FailfastClusterInvokerTest * */ @SuppressWarnings("unchecked") class FailSafeClusterInvokerTest { List<Invoker<DemoService>> invokers = new ArrayList<Invoker<DemoService>>(); URL url = URL.valueOf("test://test:11/test"); Invoker<DemoService> invoker = mock(Invoker.class); RpcInvocation invocation = new RpcInvocation(); Directory<DemoService> dic; Result result = new AppResponse(); /** * @throws java.lang.Exception */ @BeforeEach public void setUp() throws Exception { RpcContext.removeServiceContext(); dic = mock(Directory.class); given(dic.getUrl()).willReturn(url); given(dic.getConsumerUrl()).willReturn(url); given(dic.list(invocation)).willReturn(invokers); given(dic.getInterface()).willReturn(DemoService.class); invocation.setMethodName("method1"); invokers.add(invoker); } private void resetInvokerToException() { given(invoker.invoke(invocation)).willThrow(new RuntimeException()); given(invoker.getUrl()).willReturn(url); given(invoker.getInterface()).willReturn(DemoService.class); } private void resetInvokerToNoException() { given(invoker.invoke(invocation)).willReturn(result); given(invoker.getUrl()).willReturn(url); given(invoker.getInterface()).willReturn(DemoService.class); } // TODO assert error log @Test void testInvokeExceptoin() { resetInvokerToException(); FailsafeClusterInvoker<DemoService> invoker = new FailsafeClusterInvoker<DemoService>(dic); invoker.invoke(invocation); Assertions.assertNull(RpcContext.getServiceContext().getInvoker()); } @Test void testInvokeNoExceptoin() { resetInvokerToNoException(); FailsafeClusterInvoker<DemoService> invoker = new FailsafeClusterInvoker<DemoService>(dic); Result ret = invoker.invoke(invocation); Assertions.assertSame(result, ret); } @Test void testNoInvoke() { dic = mock(Directory.class); given(dic.getUrl()).willReturn(url); given(dic.getConsumerUrl()).willReturn(url); given(dic.list(invocation)).willReturn(null); given(dic.getInterface()).willReturn(DemoService.class); invocation.setMethodName("method1"); resetInvokerToNoException(); FailsafeClusterInvoker<DemoService> invoker = new FailsafeClusterInvoker<DemoService>(dic); try { invoker.invoke(invocation); } catch (RpcException e) { Assertions.assertTrue(e.getMessage().contains("No provider available")); assertFalse(e.getCause() instanceof RpcException); } } }
7,757
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AvailableClusterInvokerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.support; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.cluster.Directory; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * Test for AvailableClusterInvoker */ class AvailableClusterInvokerTest { private final URL url = URL.valueOf("test://test:80/test"); private final Invoker<AvailableClusterInvokerTest> invoker1 = mock(Invoker.class); private final Invoker<AvailableClusterInvokerTest> invoker2 = mock(Invoker.class); private final Invoker<AvailableClusterInvokerTest> invoker3 = mock(Invoker.class); private final RpcInvocation invocation = new RpcInvocation(); private final Result result = new AppResponse(); private final List<Invoker<AvailableClusterInvokerTest>> invokers = new ArrayList<>(); private Directory<AvailableClusterInvokerTest> dic; @BeforeEach public void setUp() throws Exception { dic = mock(Directory.class); given(dic.getUrl()).willReturn(url); given(dic.getConsumerUrl()).willReturn(url); given(dic.list(invocation)).willReturn(invokers); given(dic.getInterface()).willReturn(AvailableClusterInvokerTest.class); invocation.setMethodName("method1"); invokers.add(invoker1); invokers.add(invoker2); invokers.add(invoker3); } private void resetInvokerToNoException() { given(invoker1.invoke(invocation)).willReturn(result); given(invoker1.getUrl()).willReturn(url); given(invoker1.isAvailable()).willReturn(true); given(invoker1.getInterface()).willReturn(AvailableClusterInvokerTest.class); given(invoker2.invoke(invocation)).willReturn(result); given(invoker2.getUrl()).willReturn(url); given(invoker2.isAvailable()).willReturn(true); given(invoker2.getInterface()).willReturn(AvailableClusterInvokerTest.class); given(invoker3.invoke(invocation)).willReturn(result); given(invoker3.getUrl()).willReturn(url); given(invoker3.isAvailable()).willReturn(true); given(invoker3.getInterface()).willReturn(AvailableClusterInvokerTest.class); } @Test void testInvokeNoException() { resetInvokerToNoException(); AvailableClusterInvoker<AvailableClusterInvokerTest> invoker = new AvailableClusterInvoker<>(dic); Result ret = invoker.invoke(invocation); Assertions.assertSame(result, ret); } @Test void testInvokeWithException() { // remove invokers for test exception dic.list(invocation).removeAll(invokers); AvailableClusterInvoker<AvailableClusterInvokerTest> invoker = new AvailableClusterInvoker<>(dic); try { invoker.invoke(invocation); fail(); } catch (RpcException e) { Assertions.assertTrue(e.getMessage().contains("No provider available")); assertFalse(e.getCause() instanceof RpcException); } } }
7,758
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ForkingClusterInvokerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.support; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.cluster.Directory; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * ForkingClusterInvokerTest */ @SuppressWarnings("unchecked") class ForkingClusterInvokerTest { private List<Invoker<ForkingClusterInvokerTest>> invokers = new ArrayList<>(); private URL url = URL.valueOf("test://test:11/test?forks=2"); private Invoker<ForkingClusterInvokerTest> invoker1 = mock(Invoker.class); private Invoker<ForkingClusterInvokerTest> invoker2 = mock(Invoker.class); private Invoker<ForkingClusterInvokerTest> invoker3 = mock(Invoker.class); private RpcInvocation invocation = new RpcInvocation(); private Directory<ForkingClusterInvokerTest> dic; private Result result = new AppResponse(); @BeforeEach public void setUp() throws Exception { dic = mock(Directory.class); given(dic.getUrl()).willReturn(url); given(dic.getConsumerUrl()).willReturn(url); given(dic.list(invocation)).willReturn(invokers); given(dic.getInterface()).willReturn(ForkingClusterInvokerTest.class); invocation.setMethodName("method1"); invokers.add(invoker1); invokers.add(invoker2); invokers.add(invoker3); } private void resetInvokerToException() { given(invoker1.invoke(invocation)).willThrow(new RuntimeException()); given(invoker1.getUrl()).willReturn(url); given(invoker1.isAvailable()).willReturn(true); given(invoker1.getInterface()).willReturn(ForkingClusterInvokerTest.class); given(invoker2.invoke(invocation)).willThrow(new RuntimeException()); given(invoker2.getUrl()).willReturn(url); given(invoker2.isAvailable()).willReturn(true); given(invoker2.getInterface()).willReturn(ForkingClusterInvokerTest.class); given(invoker3.invoke(invocation)).willThrow(new RuntimeException()); given(invoker3.getUrl()).willReturn(url); given(invoker3.isAvailable()).willReturn(true); given(invoker3.getInterface()).willReturn(ForkingClusterInvokerTest.class); } private void resetInvokerToNoException() { given(invoker1.invoke(invocation)).willReturn(result); given(invoker1.getUrl()).willReturn(url); given(invoker1.isAvailable()).willReturn(true); given(invoker1.getInterface()).willReturn(ForkingClusterInvokerTest.class); given(invoker2.invoke(invocation)).willReturn(result); given(invoker2.getUrl()).willReturn(url); given(invoker2.isAvailable()).willReturn(true); given(invoker2.getInterface()).willReturn(ForkingClusterInvokerTest.class); given(invoker3.invoke(invocation)).willReturn(result); given(invoker3.getUrl()).willReturn(url); given(invoker3.isAvailable()).willReturn(true); given(invoker3.getInterface()).willReturn(ForkingClusterInvokerTest.class); } @Test void testInvokeException() { resetInvokerToException(); ForkingClusterInvoker<ForkingClusterInvokerTest> invoker = new ForkingClusterInvoker<>(dic); try { invoker.invoke(invocation); Assertions.fail(); } catch (RpcException expected) { Assertions.assertTrue(expected.getMessage().contains("Failed to forking invoke provider")); assertFalse(expected.getCause() instanceof RpcException); } } @Test void testClearRpcContext() { resetInvokerToException(); ForkingClusterInvoker<ForkingClusterInvokerTest> invoker = new ForkingClusterInvoker<>(dic); String attachKey = "attach"; String attachValue = "value"; RpcContext.getClientAttachment().setAttachment(attachKey, attachValue); Map<String, Object> attachments = RpcContext.getClientAttachment().getObjectAttachments(); Assertions.assertTrue(attachments != null && attachments.size() == 1, "set attachment failed!"); try { invoker.invoke(invocation); Assertions.fail(); } catch (RpcException expected) { Assertions.assertTrue( expected.getMessage().contains("Failed to forking invoke provider"), "Succeeded to forking invoke provider !"); assertFalse(expected.getCause() instanceof RpcException); } Map<String, Object> afterInvoke = RpcContext.getClientAttachment().getObjectAttachments(); Assertions.assertTrue(afterInvoke != null && afterInvoke.size() == 0, "clear attachment failed!"); } @Test void testInvokeNoException() { resetInvokerToNoException(); ForkingClusterInvoker<ForkingClusterInvokerTest> invoker = new ForkingClusterInvoker<>(dic); Result ret = invoker.invoke(invocation); Assertions.assertSame(result, ret); } @Test void testInvokeWithIllegalForksParam() { URL url = URL.valueOf("test://test:11/test?forks=-1"); given(dic.getUrl()).willReturn(url); given(dic.getConsumerUrl()).willReturn(url); given(invoker1.invoke(invocation)).willReturn(result); given(invoker1.getUrl()).willReturn(url); given(invoker1.isAvailable()).willReturn(true); given(invoker1.getInterface()).willReturn(ForkingClusterInvokerTest.class); ForkingClusterInvoker<ForkingClusterInvokerTest> invoker = new ForkingClusterInvoker<>(dic); Result ret = invoker.invoke(invocation); Assertions.assertSame(result, ret); } }
7,759
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailfastClusterInvokerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.support; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.cluster.Directory; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * FailfastClusterInvokerTest */ @SuppressWarnings("unchecked") class FailfastClusterInvokerTest { List<Invoker<FailfastClusterInvokerTest>> invokers = new ArrayList<>(); URL url = URL.valueOf("test://test:11/test"); Invoker<FailfastClusterInvokerTest> invoker1 = mock(Invoker.class); RpcInvocation invocation = new RpcInvocation(); Directory<FailfastClusterInvokerTest> dic; Result result = new AppResponse(); /** * @throws java.lang.Exception */ @BeforeEach public void setUp() throws Exception { dic = mock(Directory.class); given(dic.getUrl()).willReturn(url); given(dic.getConsumerUrl()).willReturn(url); given(dic.list(invocation)).willReturn(invokers); given(dic.getInterface()).willReturn(FailfastClusterInvokerTest.class); invocation.setMethodName("method1"); invokers.add(invoker1); } private void resetInvoker1ToException() { given(invoker1.invoke(invocation)).willThrow(new RuntimeException()); given(invoker1.getUrl()).willReturn(url); given(invoker1.getInterface()).willReturn(FailfastClusterInvokerTest.class); } private void resetInvoker1ToNoException() { given(invoker1.invoke(invocation)).willReturn(result); given(invoker1.getUrl()).willReturn(url); given(invoker1.getInterface()).willReturn(FailfastClusterInvokerTest.class); } @Test void testInvokeException() { Assertions.assertThrows(RpcException.class, () -> { resetInvoker1ToException(); FailfastClusterInvoker<FailfastClusterInvokerTest> invoker = new FailfastClusterInvoker<>(dic); invoker.invoke(invocation); assertSame(invoker1, RpcContext.getServiceContext().getInvoker()); }); } @Test void testInvokeBizException() { given(invoker1.invoke(invocation)).willThrow(new RpcException(RpcException.BIZ_EXCEPTION)); given(invoker1.getUrl()).willReturn(url); given(invoker1.getInterface()).willReturn(FailfastClusterInvokerTest.class); FailfastClusterInvoker<FailfastClusterInvokerTest> invoker = new FailfastClusterInvoker<>(dic); try { Result ret = invoker.invoke(invocation); assertSame(result, ret); fail(); } catch (RpcException expected) { assertEquals(expected.getCode(), RpcException.BIZ_EXCEPTION); } } @Test void testInvokeNoException() { resetInvoker1ToNoException(); FailfastClusterInvoker<FailfastClusterInvokerTest> invoker = new FailfastClusterInvoker<>(dic); Result ret = invoker.invoke(invocation); assertSame(result, ret); } @Test void testNoInvoke() { dic = mock(Directory.class); given(dic.getUrl()).willReturn(url); given(dic.getConsumerUrl()).willReturn(url); given(dic.list(invocation)).willReturn(null); given(dic.getInterface()).willReturn(FailfastClusterInvokerTest.class); invocation.setMethodName("method1"); invokers.add(invoker1); resetInvoker1ToNoException(); FailfastClusterInvoker<FailfastClusterInvokerTest> invoker = new FailfastClusterInvoker<>(dic); try { invoker.invoke(invocation); fail(); } catch (RpcException expected) { assertFalse(expected.getCause() instanceof RpcException); } } }
7,760
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailbackClusterInvokerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.support; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.utils.DubboAppender; import org.apache.dubbo.common.utils.LogUtil; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.cluster.Directory; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.apache.log4j.Level; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; import static org.apache.dubbo.common.constants.CommonConstants.RETRIES_KEY; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * FailbackClusterInvokerTest * <p> * add annotation @TestMethodOrder, the testARetryFailed Method must to first execution */ @TestMethodOrder(MethodOrderer.OrderAnnotation.class) class FailbackClusterInvokerTest { List<Invoker<FailbackClusterInvokerTest>> invokers = new ArrayList<>(); URL url = URL.valueOf("test://test:11/test?retries=2&failbacktasks=2"); Invoker<FailbackClusterInvokerTest> invoker = mock(Invoker.class); RpcInvocation invocation = new RpcInvocation(); Directory<FailbackClusterInvokerTest> dic; Result result = new AppResponse(); /** * @throws java.lang.Exception */ @BeforeEach public void setUp() throws Exception { RpcContext.removeServiceContext(); dic = mock(Directory.class); given(dic.getUrl()).willReturn(url); given(dic.getConsumerUrl()).willReturn(url); given(dic.list(invocation)).willReturn(invokers); given(dic.getInterface()).willReturn(FailbackClusterInvokerTest.class); invocation.setMethodName("method1"); invokers.add(invoker); } @AfterEach public void tearDown() { dic = null; invocation = new RpcInvocation(); invokers.clear(); } private void resetInvokerToException() { given(invoker.invoke(invocation)).willThrow(new RuntimeException()); given(invoker.getUrl()).willReturn(url); given(invoker.getInterface()).willReturn(FailbackClusterInvokerTest.class); } private void resetInvokerToNoException() { given(invoker.invoke(invocation)).willReturn(result); given(invoker.getUrl()).willReturn(url); given(invoker.getInterface()).willReturn(FailbackClusterInvokerTest.class); } @Test void testInvokeWithIllegalRetriesParam() { URL url = URL.valueOf("test://test:11/test?retries=-1&failbacktasks=2"); Directory<FailbackClusterInvokerTest> dic = mock(Directory.class); given(dic.getUrl()).willReturn(url); given(dic.getConsumerUrl()).willReturn(url); given(dic.getInterface()).willReturn(FailbackClusterInvokerTest.class); given(dic.list(invocation)).willReturn(invokers); given(invoker.getUrl()).willReturn(url); FailbackClusterInvoker<FailbackClusterInvokerTest> invoker = new FailbackClusterInvoker<>(dic); invoker.invoke(invocation); Assertions.assertNull(RpcContext.getServiceContext().getInvoker()); DubboAppender.clear(); } @Test void testInvokeWithIllegalFailbacktasksParam() { URL url = URL.valueOf("test://test:11/test?retries=2&failbacktasks=-1"); Directory<FailbackClusterInvokerTest> dic = mock(Directory.class); given(dic.getUrl()).willReturn(url); given(dic.getConsumerUrl()).willReturn(url); given(dic.getInterface()).willReturn(FailbackClusterInvokerTest.class); given(dic.list(invocation)).willReturn(invokers); given(invoker.getUrl()).willReturn(url); FailbackClusterInvoker<FailbackClusterInvokerTest> invoker = new FailbackClusterInvoker<>(dic); invoker.invoke(invocation); Assertions.assertNull(RpcContext.getServiceContext().getInvoker()); DubboAppender.clear(); } @Test @Order(1) public void testInvokeException() { resetInvokerToException(); FailbackClusterInvoker<FailbackClusterInvokerTest> invoker = new FailbackClusterInvoker<>(dic); invoker.invoke(invocation); Assertions.assertNull(RpcContext.getServiceContext().getInvoker()); DubboAppender.clear(); } @Test @Order(2) public void testInvokeNoException() { resetInvokerToNoException(); FailbackClusterInvoker<FailbackClusterInvokerTest> invoker = new FailbackClusterInvoker<>(dic); Result ret = invoker.invoke(invocation); Assertions.assertSame(result, ret); } @Test @Order(3) public void testNoInvoke() { dic = mock(Directory.class); given(dic.getUrl()).willReturn(url); given(dic.getConsumerUrl()).willReturn(url); given(dic.list(invocation)).willReturn(null); given(dic.getInterface()).willReturn(FailbackClusterInvokerTest.class); invocation.setMethodName("method1"); invokers.add(invoker); FailbackClusterInvoker<FailbackClusterInvokerTest> invoker = new FailbackClusterInvoker<>(dic); try { invoker.invoke(invocation); } catch (RpcException e) { Assertions.assertTrue(e.getMessage().contains("No provider available")); assertFalse(e.getCause() instanceof RpcException); } } @Disabled @Test @Order(4) public void testARetryFailed() throws Exception { // Test retries and resetInvokerToException(); FailbackClusterInvoker<FailbackClusterInvokerTest> invoker = new FailbackClusterInvoker<>(dic); LogUtil.start(); DubboAppender.clear(); invoker.invoke(invocation); invoker.invoke(invocation); invoker.invoke(invocation); Assertions.assertNull(RpcContext.getServiceContext().getInvoker()); // invoker.retryFailed();// when retry the invoker which get from failed map already is not the mocked // invoker,so // Ensure that the main thread is online CountDownLatch countDown = new CountDownLatch(1); countDown.await(15000L, TimeUnit.MILLISECONDS); LogUtil.stop(); Assertions.assertEquals( 4, LogUtil.findMessage(Level.ERROR, "Failed retry to invoke method"), "must have four error message "); Assertions.assertEquals( 2, LogUtil.findMessage(Level.ERROR, "Failed retry times exceed threshold"), "must have two error message "); Assertions.assertEquals( 1, LogUtil.findMessage(Level.ERROR, "Failback background works error"), "must have one error message "); // it can be invoke successfully } private long getRetryFailedPeriod() throws NoSuchFieldException, IllegalAccessException { Field retryFailedPeriod = FailbackClusterInvoker.class.getDeclaredField("RETRY_FAILED_PERIOD"); retryFailedPeriod.setAccessible(true); return retryFailedPeriod.getLong(FailbackClusterInvoker.class); } @Test @Order(5) public void testInvokeRetryTimesWithZeroValue() throws InterruptedException, NoSuchFieldException, IllegalAccessException { int retries = 0; resetInvokerToException(); given(dic.getConsumerUrl()).willReturn(url.addParameter(RETRIES_KEY, retries)); FailbackClusterInvoker<FailbackClusterInvokerTest> invoker = new FailbackClusterInvoker<>(dic); LogUtil.start(); DubboAppender.clear(); invocation.setMethodName("testInvokeRetryTimesWithZeroValue"); invoker.invoke(invocation); CountDownLatch countDown = new CountDownLatch(1); countDown.await(getRetryFailedPeriod() * (retries + 1), TimeUnit.SECONDS); LogUtil.stop(); Assertions.assertEquals( 0, LogUtil.findMessage( Level.INFO, "Attempt to retry to invoke method " + "testInvokeRetryTimesWithZeroValue"), "No retry messages allowed"); } @Test @Order(6) public void testInvokeRetryTimesWithTwoValue() throws InterruptedException, NoSuchFieldException, IllegalAccessException { int retries = 2; resetInvokerToException(); given(dic.getConsumerUrl()).willReturn(url.addParameter(RETRIES_KEY, retries)); FailbackClusterInvoker<FailbackClusterInvokerTest> invoker = new FailbackClusterInvoker<>(dic); LogUtil.start(); DubboAppender.clear(); invocation.setMethodName("testInvokeRetryTimesWithTwoValue"); invoker.invoke(invocation); CountDownLatch countDown = new CountDownLatch(1); countDown.await(getRetryFailedPeriod() * (retries + 1), TimeUnit.SECONDS); LogUtil.stop(); Assertions.assertEquals( 2, LogUtil.findMessage( Level.INFO, "Attempt to retry to invoke method " + "testInvokeRetryTimesWithTwoValue"), "Must have two error message "); } @Test @Order(7) public void testInvokeRetryTimesWithDefaultValue() throws InterruptedException, NoSuchFieldException, IllegalAccessException { resetInvokerToException(); given(dic.getConsumerUrl()).willReturn(URL.valueOf("test://test:11/test")); FailbackClusterInvoker<FailbackClusterInvokerTest> invoker = new FailbackClusterInvoker<>(dic); LogUtil.start(); DubboAppender.clear(); invocation.setMethodName("testInvokeRetryTimesWithDefaultValue"); invoker.invoke(invocation); CountDownLatch countDown = new CountDownLatch(1); countDown.await(getRetryFailedPeriod() * (CommonConstants.DEFAULT_FAILBACK_TIMES + 1), TimeUnit.SECONDS); LogUtil.stop(); Assertions.assertEquals( 3, LogUtil.findMessage( Level.INFO, "Attempt to retry to invoke method " + "testInvokeRetryTimesWithDefaultValue"), "Must have three error message "); } @Test @Order(8) public void testInvokeRetryTimesWithIllegalValue() throws InterruptedException, NoSuchFieldException, IllegalAccessException { resetInvokerToException(); given(dic.getConsumerUrl()).willReturn(url.addParameter(RETRIES_KEY, -100)); FailbackClusterInvoker<FailbackClusterInvokerTest> invoker = new FailbackClusterInvoker<>(dic); LogUtil.start(); DubboAppender.clear(); invocation.setMethodName("testInvokeRetryTimesWithIllegalValue"); invoker.invoke(invocation); CountDownLatch countDown = new CountDownLatch(1); countDown.await(getRetryFailedPeriod() * (CommonConstants.DEFAULT_FAILBACK_TIMES + 1), TimeUnit.SECONDS); LogUtil.stop(); Assertions.assertEquals( 3, LogUtil.findMessage( Level.INFO, "Attempt to retry to invoke method " + "testInvokeRetryTimesWithIllegalValue"), "Must have three error message "); } }
7,761
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/BroadCastClusterInvokerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.support; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.cluster.Directory; import org.apache.dubbo.rpc.cluster.filter.DemoService; import java.util.Arrays; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * @see BroadcastClusterInvoker */ class BroadCastClusterInvokerTest { private URL url; private Directory<DemoService> dic; private RpcInvocation invocation; private BroadcastClusterInvoker clusterInvoker; private MockInvoker invoker1; private MockInvoker invoker2; private MockInvoker invoker3; private MockInvoker invoker4; @BeforeEach public void setUp() throws Exception { dic = mock(Directory.class); invoker1 = new MockInvoker(); invoker2 = new MockInvoker(); invoker3 = new MockInvoker(); invoker4 = new MockInvoker(); url = URL.valueOf("test://127.0.0.1:8080/test"); given(dic.getUrl()).willReturn(url); given(dic.getConsumerUrl()).willReturn(url); given(dic.getInterface()).willReturn(DemoService.class); invocation = new RpcInvocation(); invocation.setMethodName("test"); clusterInvoker = new BroadcastClusterInvoker(dic); } @Test void testNormal() { given(dic.list(invocation)).willReturn(Arrays.asList(invoker1, invoker2, invoker3, invoker4)); // Every invoker will be called clusterInvoker.invoke(invocation); assertTrue(invoker1.isInvoked()); assertTrue(invoker2.isInvoked()); assertTrue(invoker3.isInvoked()); assertTrue(invoker4.isInvoked()); } @Test void testEx() { given(dic.list(invocation)).willReturn(Arrays.asList(invoker1, invoker2, invoker3, invoker4)); invoker1.invokeThrowEx(); assertThrows(RpcException.class, () -> { clusterInvoker.invoke(invocation); }); // The default failure percentage is 100, even if a certain invoker#invoke throws an exception, other invokers // will still be called assertTrue(invoker1.isInvoked()); assertTrue(invoker2.isInvoked()); assertTrue(invoker3.isInvoked()); assertTrue(invoker4.isInvoked()); } @Test void testFailPercent() { given(dic.list(invocation)).willReturn(Arrays.asList(invoker1, invoker2, invoker3, invoker4)); // We set the failure percentage to 75, which means that when the number of call failures is 4*(75/100) = 3, // an exception will be thrown directly and subsequent invokers will not be called. url = url.addParameter("broadcast.fail.percent", 75); given(dic.getConsumerUrl()).willReturn(url); invoker1.invokeThrowEx(); invoker2.invokeThrowEx(); invoker3.invokeThrowEx(); invoker4.invokeThrowEx(); assertThrows(RpcException.class, () -> { clusterInvoker.invoke(invocation); }); assertTrue(invoker1.isInvoked()); assertTrue(invoker2.isInvoked()); assertTrue(invoker3.isInvoked()); assertFalse(invoker4.isInvoked()); } } class MockInvoker implements Invoker<DemoService> { private static int count = 0; private URL url = URL.valueOf("test://127.0.0.1:8080/test"); private boolean throwEx = false; private boolean invoked = false; @Override public URL getUrl() { return url; } @Override public boolean isAvailable() { return false; } @Override public void destroy() {} @Override public Class<DemoService> getInterface() { return DemoService.class; } @Override public Result invoke(Invocation invocation) throws RpcException { invoked = true; if (throwEx) { throwEx = false; throw new RpcException(); } return null; } public void invokeThrowEx() { throwEx = true; } public boolean isInvoked() { return invoked; } }
7,762
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ConnectivityValidationTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.support; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.metrics.event.MetricsDispatcher; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.cluster.Directory; import org.apache.dubbo.rpc.cluster.LoadBalance; import org.apache.dubbo.rpc.cluster.directory.StaticDirectory; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.concurrent.ThreadLocalRandom; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.mockito.Mockito.when; @SuppressWarnings("all") class ConnectivityValidationTest { private Invoker invoker1; private Invoker invoker2; private Invoker invoker3; private Invoker invoker4; private Invoker invoker5; private Invoker invoker6; private Invoker invoker7; private Invoker invoker8; private Invoker invoker9; private Invoker invoker10; private Invoker invoker11; private Invoker invoker12; private Invoker invoker13; private Invoker invoker14; private Invoker invoker15; private List<Invoker> invokerList; private StaticDirectory directory; private ConnectivityClusterInvoker clusterInvoker; @BeforeEach public void setup() { ApplicationModel.defaultModel().getBeanFactory().registerBean(MetricsDispatcher.class); invoker1 = Mockito.mock(Invoker.class); invoker2 = Mockito.mock(Invoker.class); invoker3 = Mockito.mock(Invoker.class); invoker4 = Mockito.mock(Invoker.class); invoker5 = Mockito.mock(Invoker.class); invoker6 = Mockito.mock(Invoker.class); invoker7 = Mockito.mock(Invoker.class); invoker8 = Mockito.mock(Invoker.class); invoker9 = Mockito.mock(Invoker.class); invoker10 = Mockito.mock(Invoker.class); invoker11 = Mockito.mock(Invoker.class); invoker12 = Mockito.mock(Invoker.class); invoker13 = Mockito.mock(Invoker.class); invoker14 = Mockito.mock(Invoker.class); invoker15 = Mockito.mock(Invoker.class); configInvoker(invoker1); configInvoker(invoker2); configInvoker(invoker3); configInvoker(invoker4); configInvoker(invoker5); configInvoker(invoker6); configInvoker(invoker7); configInvoker(invoker8); configInvoker(invoker9); configInvoker(invoker10); configInvoker(invoker11); configInvoker(invoker12); configInvoker(invoker13); configInvoker(invoker14); configInvoker(invoker15); invokerList = new LinkedList<>(); invokerList.add(invoker1); invokerList.add(invoker2); invokerList.add(invoker3); invokerList.add(invoker4); invokerList.add(invoker5); directory = new StaticDirectory(invokerList); clusterInvoker = new ConnectivityClusterInvoker(directory); } @AfterEach public void tearDown() { clusterInvoker.destroy(); } private void configInvoker(Invoker invoker) { when(invoker.getUrl()).thenReturn(URL.valueOf("")); when(invoker.isAvailable()).thenReturn(true); } @BeforeAll public static void setupClass() { System.setProperty(CommonConstants.RECONNECT_TASK_PERIOD, "1"); } @AfterAll public static void clearAfterClass() { System.clearProperty(CommonConstants.RECONNECT_TASK_PERIOD); } @Test void testBasic() throws InterruptedException { Invocation invocation = new RpcInvocation(); LoadBalance loadBalance = new RandomLoadBalance(); Assertions.assertEquals(5, directory.list(invocation).size()); Assertions.assertNotNull( clusterInvoker.select(loadBalance, invocation, directory.list(invocation), Collections.emptyList())); when(invoker1.isAvailable()).thenReturn(false); when(invoker2.isAvailable()).thenReturn(false); when(invoker3.isAvailable()).thenReturn(false); when(invoker4.isAvailable()).thenReturn(false); when(invoker5.isAvailable()).thenReturn(false); clusterInvoker.select(loadBalance, invocation, directory.list(invocation), Collections.emptyList()); Assertions.assertEquals(0, directory.list(invocation).size()); when(invoker1.isAvailable()).thenReturn(true); Set<Invoker> invokerSet = new HashSet<>(); invokerSet.add(invoker1); waitRefresh(invokerSet); Assertions.assertEquals(1, directory.list(invocation).size()); Assertions.assertNotNull( clusterInvoker.select(loadBalance, invocation, directory.list(invocation), Collections.emptyList())); when(invoker2.isAvailable()).thenReturn(true); invokerSet.add(invoker2); waitRefresh(invokerSet); Assertions.assertEquals(2, directory.list(invocation).size()); Assertions.assertNotNull( clusterInvoker.select(loadBalance, invocation, directory.list(invocation), Collections.emptyList())); invokerList.remove(invoker5); directory.notify(invokerList); when(invoker2.isAvailable()).thenReturn(true); waitRefresh(invokerSet); Assertions.assertEquals(2, directory.list(invocation).size()); Assertions.assertNotNull( clusterInvoker.select(loadBalance, invocation, directory.list(invocation), Collections.emptyList())); when(invoker3.isAvailable()).thenReturn(true); when(invoker4.isAvailable()).thenReturn(true); invokerSet.add(invoker3); invokerSet.add(invoker4); waitRefresh(invokerSet); Assertions.assertEquals(4, directory.list(invocation).size()); Assertions.assertNotNull( clusterInvoker.select(loadBalance, invocation, directory.list(invocation), Collections.emptyList())); } @Test void testRetry() throws InterruptedException { Invocation invocation = new RpcInvocation(); LoadBalance loadBalance = new RandomLoadBalance(); invokerList.clear(); invokerList.add(invoker1); invokerList.add(invoker2); directory.notify(invokerList); Assertions.assertEquals(2, directory.list(invocation).size()); when(invoker1.isAvailable()).thenReturn(false); Assertions.assertEquals( invoker2, clusterInvoker.select( loadBalance, invocation, directory.list(invocation), Collections.singletonList(invoker2))); Assertions.assertEquals(1, directory.list(invocation).size()); when(invoker1.isAvailable()).thenReturn(true); Set<Invoker> invokerSet = new HashSet<>(); invokerSet.add(invoker1); waitRefresh(invokerSet); Assertions.assertEquals(2, directory.list(invocation).size()); } @Test void testRandomSelect() throws InterruptedException { Invocation invocation = new RpcInvocation(); LoadBalance loadBalance = new RandomLoadBalance(); invokerList.add(invoker6); invokerList.add(invoker7); invokerList.add(invoker8); invokerList.add(invoker9); invokerList.add(invoker10); invokerList.add(invoker11); invokerList.add(invoker12); invokerList.add(invoker13); invokerList.add(invoker14); invokerList.add(invoker15); directory.notify(invokerList); Assertions.assertEquals(15, directory.list(invocation).size()); when(invoker2.isAvailable()).thenReturn(false); when(invoker3.isAvailable()).thenReturn(false); when(invoker4.isAvailable()).thenReturn(false); when(invoker5.isAvailable()).thenReturn(false); when(invoker6.isAvailable()).thenReturn(false); when(invoker7.isAvailable()).thenReturn(false); when(invoker8.isAvailable()).thenReturn(false); when(invoker9.isAvailable()).thenReturn(false); when(invoker10.isAvailable()).thenReturn(false); when(invoker11.isAvailable()).thenReturn(false); when(invoker12.isAvailable()).thenReturn(false); when(invoker13.isAvailable()).thenReturn(false); when(invoker14.isAvailable()).thenReturn(false); when(invoker15.isAvailable()).thenReturn(false); for (int i = 0; i < 15; i++) { clusterInvoker.select(loadBalance, invocation, directory.list(invocation), Collections.emptyList()); } for (int i = 0; i < 5; i++) { Assertions.assertEquals( invoker1, clusterInvoker.select( loadBalance, invocation, directory.list(invocation), Collections.emptyList())); } when(invoker1.isAvailable()).thenReturn(false); clusterInvoker.select(loadBalance, invocation, directory.list(invocation), Collections.emptyList()); Assertions.assertEquals(0, directory.list(invocation).size()); when(invoker1.isAvailable()).thenReturn(true); when(invoker2.isAvailable()).thenReturn(true); when(invoker3.isAvailable()).thenReturn(true); when(invoker4.isAvailable()).thenReturn(true); when(invoker5.isAvailable()).thenReturn(true); when(invoker6.isAvailable()).thenReturn(true); when(invoker7.isAvailable()).thenReturn(true); when(invoker8.isAvailable()).thenReturn(true); when(invoker9.isAvailable()).thenReturn(true); when(invoker10.isAvailable()).thenReturn(true); when(invoker11.isAvailable()).thenReturn(true); when(invoker12.isAvailable()).thenReturn(true); when(invoker13.isAvailable()).thenReturn(true); when(invoker14.isAvailable()).thenReturn(true); when(invoker15.isAvailable()).thenReturn(true); Set<Invoker> invokerSet = new HashSet<>(); invokerSet.add(invoker1); invokerSet.add(invoker2); invokerSet.add(invoker3); invokerSet.add(invoker4); invokerSet.add(invoker5); invokerSet.add(invoker6); invokerSet.add(invoker7); invokerSet.add(invoker8); invokerSet.add(invoker9); invokerSet.add(invoker10); invokerSet.add(invoker11); invokerSet.add(invoker12); invokerSet.add(invoker13); invokerSet.add(invoker14); invokerSet.add(invoker15); waitRefresh(invokerSet); Assertions.assertTrue(directory.list(invocation).size() > 1); } private static class ConnectivityClusterInvoker<T> extends AbstractClusterInvoker<T> { public ConnectivityClusterInvoker(Directory<T> directory) { super(directory); } @Override public Invoker<T> select( LoadBalance loadbalance, Invocation invocation, List<Invoker<T>> invokers, List<Invoker<T>> selected) throws RpcException { return super.select(loadbalance, invocation, invokers, selected); } @Override protected Result doInvoke(Invocation invocation, List<Invoker<T>> invokers, LoadBalance loadbalance) throws RpcException { return null; } } private void waitRefresh(Set<Invoker> invokerSet) throws InterruptedException { directory.checkConnectivity(); while (true) { List<Invoker> reconnectList = directory.getInvokersToReconnect(); if (reconnectList.stream().anyMatch(invoker -> invokerSet.contains(invoker))) { Thread.sleep(10); continue; } break; } } private static class RandomLoadBalance implements LoadBalance { @Override public <T> Invoker<T> select(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException { return CollectionUtils.isNotEmpty(invokers) ? invokers.get(ThreadLocalRandom.current().nextInt(invokers.size())) : null; } } }
7,763
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.support; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.metrics.event.MetricsDispatcher; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.cluster.Directory; import org.apache.dubbo.rpc.cluster.LoadBalance; import org.apache.dubbo.rpc.cluster.directory.StaticDirectory; import org.apache.dubbo.rpc.cluster.filter.DemoService; import org.apache.dubbo.rpc.cluster.loadbalance.LeastActiveLoadBalance; import org.apache.dubbo.rpc.cluster.loadbalance.RandomLoadBalance; import org.apache.dubbo.rpc.cluster.loadbalance.RoundRobinLoadBalance; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER; import static org.apache.dubbo.common.constants.CommonConstants.ENABLE_CONNECTIVITY_VALIDATION; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; import static org.apache.dubbo.rpc.cluster.Constants.CLUSTER_AVAILABLE_CHECK_KEY; import static org.apache.dubbo.rpc.cluster.Constants.INVOCATION_NEED_MOCK; import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.same; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * AbstractClusterInvokerTest */ @SuppressWarnings("rawtypes") class AbstractClusterInvokerTest { List<Invoker<IHelloService>> invokers = new ArrayList<Invoker<IHelloService>>(); List<Invoker<IHelloService>> selectedInvokers = new ArrayList<Invoker<IHelloService>>(); AbstractClusterInvoker<IHelloService> cluster; AbstractClusterInvoker<IHelloService> cluster_nocheck; StaticDirectory<IHelloService> dic; RpcInvocation invocation = new RpcInvocation(); URL url = URL.valueOf( "registry://localhost:9090/org.apache.dubbo.rpc.cluster.support.AbstractClusterInvokerTest.IHelloService?refer=" + URL.encode("application=abstractClusterInvokerTest")); URL consumerUrl = URL.valueOf( "dubbo://localhost?application=abstractClusterInvokerTest&refer=application%3DabstractClusterInvokerTest"); Invoker<IHelloService> invoker1; Invoker<IHelloService> invoker2; Invoker<IHelloService> invoker3; Invoker<IHelloService> invoker4; Invoker<IHelloService> invoker5; Invoker<IHelloService> mockedInvoker1; @BeforeAll public static void setUpBeforeClass() throws Exception { System.setProperty(ENABLE_CONNECTIVITY_VALIDATION, "false"); } @AfterEach public void teardown() throws Exception { RpcContext.removeContext(); } @AfterAll public static void afterClass() { System.clearProperty(ENABLE_CONNECTIVITY_VALIDATION); } @SuppressWarnings({"unchecked"}) @BeforeEach public void setUp() throws Exception { ApplicationModel.defaultModel().getBeanFactory().registerBean(MetricsDispatcher.class); Map<String, Object> attributes = new HashMap<>(); attributes.put("application", "abstractClusterInvokerTest"); url = url.putAttribute(REFER_KEY, attributes); invocation.setMethodName("sayHello"); invoker1 = mock(Invoker.class); invoker2 = mock(Invoker.class); invoker3 = mock(Invoker.class); invoker4 = mock(Invoker.class); invoker5 = mock(Invoker.class); mockedInvoker1 = mock(Invoker.class); URL turl = URL.valueOf("test://test:11/test"); given(invoker1.isAvailable()).willReturn(false); given(invoker1.getInterface()).willReturn(IHelloService.class); given(invoker1.getUrl()).willReturn(turl.setPort(1).addParameter("name", "invoker1")); given(invoker2.isAvailable()).willReturn(true); given(invoker2.getInterface()).willReturn(IHelloService.class); given(invoker2.getUrl()).willReturn(turl.setPort(2).addParameter("name", "invoker2")); given(invoker3.isAvailable()).willReturn(false); given(invoker3.getInterface()).willReturn(IHelloService.class); given(invoker3.getUrl()).willReturn(turl.setPort(3).addParameter("name", "invoker3")); given(invoker4.isAvailable()).willReturn(true); given(invoker4.getInterface()).willReturn(IHelloService.class); given(invoker4.getUrl()).willReturn(turl.setPort(4).addParameter("name", "invoker4")); given(invoker5.isAvailable()).willReturn(false); given(invoker5.getInterface()).willReturn(IHelloService.class); given(invoker5.getUrl()).willReturn(turl.setPort(5).addParameter("name", "invoker5")); given(mockedInvoker1.isAvailable()).willReturn(false); given(mockedInvoker1.getInterface()).willReturn(IHelloService.class); given(mockedInvoker1.getUrl()).willReturn(turl.setPort(999).setProtocol("mock")); invokers.add(invoker1); dic = new StaticDirectory<IHelloService>(url, invokers, null); cluster = new AbstractClusterInvoker(dic) { @Override protected Result doInvoke(Invocation invocation, List invokers, LoadBalance loadbalance) throws RpcException { return null; } }; cluster_nocheck = new AbstractClusterInvoker( dic, url.addParameterIfAbsent(CLUSTER_AVAILABLE_CHECK_KEY, Boolean.FALSE.toString())) { @Override protected Result doInvoke(Invocation invocation, List invokers, LoadBalance loadbalance) throws RpcException { return null; } }; } @Disabled( "RpcContext attachments will be set to Invocation twice, first in ConsumerContextFilter, second AbstractInvoker") @Test void testBindingAttachment() { final String attachKey = "attach"; final String attachValue = "value"; // setup attachment RpcContext.getClientAttachment().setAttachment(attachKey, attachValue); Map<String, Object> attachments = RpcContext.getClientAttachment().getObjectAttachments(); Assertions.assertTrue(attachments != null && attachments.size() == 1, "set attachment failed!"); cluster = new AbstractClusterInvoker(dic) { @Override protected Result doInvoke(Invocation invocation, List invokers, LoadBalance loadbalance) throws RpcException { // attachment will be bind to invocation String value = invocation.getAttachment(attachKey); Assertions.assertNotNull(value); Assertions.assertEquals(attachValue, value, "binding attachment failed!"); return null; } }; // invoke cluster.invoke(invocation); } @Test void testSelect_Invokersize0() { LoadBalance l = cluster.initLoadBalance(invokers, invocation); Assertions.assertNotNull(l, "cluster.initLoadBalance returns null!"); { Invoker invoker = cluster.select(l, null, null, null); Assertions.assertNull(invoker); } { invokers.clear(); selectedInvokers.clear(); Invoker invoker = cluster.select(l, null, invokers, null); Assertions.assertNull(invoker); } } @Test void testSelectedInvokers() { cluster = new AbstractClusterInvoker(dic) { @Override protected Result doInvoke(Invocation invocation, List invokers, LoadBalance loadbalance) throws RpcException { checkInvokers(invokers, invocation); Invoker invoker = select(loadbalance, invocation, invokers, null); return invokeWithContext(invoker, invocation); } }; // invoke cluster.invoke(invocation); Assertions.assertEquals(Collections.singletonList(invoker1), invocation.getInvokedInvokers()); } @Test void testSelect_Invokersize1() { invokers.clear(); invokers.add(invoker1); LoadBalance l = cluster.initLoadBalance(invokers, invocation); Assertions.assertNotNull(l, "cluster.initLoadBalance returns null!"); Invoker invoker = cluster.select(l, null, invokers, null); Assertions.assertEquals(invoker1, invoker); } @Test void testSelect_Invokersize2AndselectNotNull() { invokers.clear(); invokers.add(invoker2); invokers.add(invoker4); LoadBalance l = cluster.initLoadBalance(invokers, invocation); Assertions.assertNotNull(l, "cluster.initLoadBalance returns null!"); { selectedInvokers.clear(); selectedInvokers.add(invoker4); Invoker invoker = cluster.select(l, invocation, invokers, selectedInvokers); Assertions.assertEquals(invoker2, invoker); } { selectedInvokers.clear(); selectedInvokers.add(invoker2); Invoker invoker = cluster.select(l, invocation, invokers, selectedInvokers); Assertions.assertEquals(invoker4, invoker); } } @Test void testSelect_multiInvokers() { testSelect_multiInvokers(RoundRobinLoadBalance.NAME); testSelect_multiInvokers(LeastActiveLoadBalance.NAME); testSelect_multiInvokers(RandomLoadBalance.NAME); } @Test void testCloseAvailablecheck() { LoadBalance lb = mock(LoadBalance.class); Map<String, String> queryMap = (Map<String, String>) url.getAttribute(REFER_KEY); URL tmpUrl = turnRegistryUrlToConsumerUrl(url, queryMap); when(lb.select(same(invokers), eq(tmpUrl), same(invocation))).thenReturn(invoker1); initlistsize5(); Invoker sinvoker = cluster_nocheck.select(lb, invocation, invokers, selectedInvokers); Assertions.assertFalse(sinvoker.isAvailable()); Assertions.assertEquals(invoker1, sinvoker); } private URL turnRegistryUrlToConsumerUrl(URL url, Map<String, String> queryMap) { String host = StringUtils.isNotEmpty(queryMap.get("register.ip")) ? queryMap.get("register.ip") : this.url.getHost(); String path = queryMap.get(PATH_KEY); String consumedProtocol = queryMap.get(PROTOCOL_KEY) == null ? CONSUMER : queryMap.get(PROTOCOL_KEY); URL consumerUrlFrom = this.url .setHost(host) .setPort(0) .setProtocol(consumedProtocol) .setPath(path == null ? queryMap.get(INTERFACE_KEY) : path); return consumerUrlFrom.addParameters(queryMap).removeParameter(MONITOR_KEY); } @Test void testDonotSelectAgainAndNoCheckAvailable() { LoadBalance lb = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(RoundRobinLoadBalance.NAME); initlistsize5(); { // Boundary condition test . selectedInvokers.clear(); selectedInvokers.add(invoker2); selectedInvokers.add(invoker3); selectedInvokers.add(invoker4); selectedInvokers.add(invoker5); Invoker sinvoker = cluster_nocheck.select(lb, invocation, invokers, selectedInvokers); Assertions.assertSame(invoker1, sinvoker); } { // Boundary condition test . selectedInvokers.clear(); selectedInvokers.add(invoker1); selectedInvokers.add(invoker3); selectedInvokers.add(invoker4); selectedInvokers.add(invoker5); Invoker sinvoker = cluster_nocheck.select(lb, invocation, invokers, selectedInvokers); Assertions.assertSame(invoker2, sinvoker); } { // Boundary condition test . selectedInvokers.clear(); selectedInvokers.add(invoker1); selectedInvokers.add(invoker2); selectedInvokers.add(invoker4); selectedInvokers.add(invoker5); Invoker sinvoker = cluster_nocheck.select(lb, invocation, invokers, selectedInvokers); Assertions.assertSame(invoker3, sinvoker); } { // Boundary condition test . selectedInvokers.clear(); selectedInvokers.add(invoker1); selectedInvokers.add(invoker2); selectedInvokers.add(invoker3); selectedInvokers.add(invoker4); Invoker sinvoker = cluster_nocheck.select(lb, invocation, invokers, selectedInvokers); Assertions.assertSame(invoker5, sinvoker); } { // Boundary condition test . selectedInvokers.clear(); selectedInvokers.add(invoker1); selectedInvokers.add(invoker2); selectedInvokers.add(invoker3); selectedInvokers.add(invoker4); selectedInvokers.add(invoker5); Invoker sinvoker = cluster_nocheck.select(lb, invocation, invokers, selectedInvokers); Assertions.assertTrue(invokers.contains(sinvoker)); } } @Test void testSelectAgainAndCheckAvailable() { LoadBalance lb = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(RoundRobinLoadBalance.NAME); initlistsize5(); { // Boundary condition test . selectedInvokers.clear(); selectedInvokers.add(invoker1); selectedInvokers.add(invoker2); selectedInvokers.add(invoker3); selectedInvokers.add(invoker5); Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers); Assertions.assertSame(sinvoker, invoker4); } { // Boundary condition test . selectedInvokers.clear(); selectedInvokers.add(invoker2); selectedInvokers.add(invoker3); selectedInvokers.add(invoker4); selectedInvokers.add(invoker5); Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers); Assertions.assertTrue(sinvoker == invoker2 || sinvoker == invoker4); } { // Boundary condition test . for (int i = 0; i < 100; i++) { selectedInvokers.clear(); Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers); Assertions.assertTrue(sinvoker == invoker2 || sinvoker == invoker4); } } { // Boundary condition test . for (int i = 0; i < 100; i++) { selectedInvokers.clear(); selectedInvokers.add(invoker1); selectedInvokers.add(invoker3); selectedInvokers.add(invoker5); Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers); Assertions.assertTrue(sinvoker == invoker2 || sinvoker == invoker4); } } { // Boundary condition test . for (int i = 0; i < 100; i++) { selectedInvokers.clear(); selectedInvokers.add(invoker1); selectedInvokers.add(invoker3); selectedInvokers.add(invoker2); selectedInvokers.add(invoker4); selectedInvokers.add(invoker5); Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers); Assertions.assertTrue(sinvoker == invoker2 || sinvoker == invoker4); } } } public void testSelect_multiInvokers(String lbname) { int min = 100, max = 500; Double d = (Math.random() * (max - min + 1) + min); int runs = d.intValue(); Assertions.assertTrue(runs >= min); LoadBalance lb = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(lbname); initlistsize5(); for (int i = 0; i < runs; i++) { Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers); Assertions.assertTrue(sinvoker.isAvailable()); Mockito.clearInvocations(invoker1, invoker2, invoker3, invoker4, invoker5); } for (int i = 0; i < runs; i++) { selectedInvokers.clear(); selectedInvokers.add(invoker1); Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers); Assertions.assertTrue(sinvoker.isAvailable()); Mockito.clearInvocations(invoker1, invoker2, invoker3, invoker4, invoker5); } for (int i = 0; i < runs; i++) { selectedInvokers.clear(); selectedInvokers.add(invoker2); Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers); Assertions.assertTrue(sinvoker.isAvailable()); Mockito.clearInvocations(invoker1, invoker2, invoker3, invoker4, invoker5); } for (int i = 0; i < runs; i++) { selectedInvokers.clear(); selectedInvokers.add(invoker2); selectedInvokers.add(invoker4); Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers); Assertions.assertTrue(sinvoker.isAvailable()); Mockito.clearInvocations(invoker1, invoker2, invoker3, invoker4, invoker5); } for (int i = 0; i < runs; i++) { selectedInvokers.clear(); selectedInvokers.add(invoker1); selectedInvokers.add(invoker3); selectedInvokers.add(invoker5); Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers); Assertions.assertTrue(sinvoker.isAvailable()); Mockito.clearInvocations(invoker1, invoker2, invoker3, invoker4, invoker5); } for (int i = 0; i < runs; i++) { selectedInvokers.clear(); selectedInvokers.add(invoker1); selectedInvokers.add(invoker2); selectedInvokers.add(invoker3); Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers); Assertions.assertTrue(sinvoker.isAvailable()); Mockito.clearInvocations(invoker1, invoker2, invoker3, invoker4, invoker5); } } /** * Test balance. */ @Test void testSelectBalance() { LoadBalance lb = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(RoundRobinLoadBalance.NAME); initlistsize5(); Map<Invoker, AtomicLong> counter = new ConcurrentHashMap<Invoker, AtomicLong>(); for (Invoker invoker : invokers) { counter.put(invoker, new AtomicLong(0)); } int runs = 1000; for (int i = 0; i < runs; i++) { selectedInvokers.clear(); Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers); counter.get(sinvoker).incrementAndGet(); } for (Map.Entry<Invoker, AtomicLong> entry : counter.entrySet()) { Long count = entry.getValue().get(); // System.out.println(count); if (entry.getKey().isAvailable()) Assertions.assertTrue(count > runs / invokers.size(), "count should > avg"); } Assertions.assertEquals( runs, counter.get(invoker2).get() + counter.get(invoker4).get()); } private void initlistsize5() { invokers.clear(); selectedInvokers .clear(); // Clear first, previous test case will make sure that the right invoker2 will be used. invokers.add(invoker1); invokers.add(invoker2); invokers.add(invoker3); invokers.add(invoker4); invokers.add(invoker5); } private void initDic() { dic.notify(invokers); dic.buildRouterChain(); } @Test void testTimeoutExceptionCode() { List<Invoker<DemoService>> invokers = new ArrayList<Invoker<DemoService>>(); invokers.add(new Invoker<DemoService>() { @Override public Class<DemoService> getInterface() { return DemoService.class; } public URL getUrl() { return URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":20880/" + DemoService.class.getName()); } @Override public boolean isAvailable() { return false; } @Override public Result invoke(Invocation invocation) throws RpcException { throw new RpcException(RpcException.TIMEOUT_EXCEPTION, "test timeout"); } @Override public void destroy() {} }); Directory<DemoService> directory = new StaticDirectory<DemoService>(invokers); FailoverClusterInvoker<DemoService> failoverClusterInvoker = new FailoverClusterInvoker<DemoService>(directory); RpcInvocation invocation = new RpcInvocation("sayHello", DemoService.class.getName(), "", new Class<?>[0], new Object[0]); try { failoverClusterInvoker.invoke(invocation); Assertions.fail(); } catch (RpcException e) { Assertions.assertEquals(RpcException.TIMEOUT_EXCEPTION, e.getCode()); } ForkingClusterInvoker<DemoService> forkingClusterInvoker = new ForkingClusterInvoker<DemoService>(directory); invocation = new RpcInvocation("sayHello", DemoService.class.getName(), "", new Class<?>[0], new Object[0]); try { forkingClusterInvoker.invoke(invocation); Assertions.fail(); } catch (RpcException e) { Assertions.assertEquals(RpcException.TIMEOUT_EXCEPTION, e.getCode()); } FailfastClusterInvoker<DemoService> failfastClusterInvoker = new FailfastClusterInvoker<DemoService>(directory); invocation = new RpcInvocation("sayHello", DemoService.class.getName(), "", new Class<?>[0], new Object[0]); try { failfastClusterInvoker.invoke(invocation); Assertions.fail(); } catch (RpcException e) { Assertions.assertEquals(RpcException.TIMEOUT_EXCEPTION, e.getCode()); } } /** * Test mock invoker selector works as expected */ @Test void testMockedInvokerSelect() { initlistsize5(); invokers.add(mockedInvoker1); initDic(); RpcInvocation mockedInvocation = new RpcInvocation(); mockedInvocation.setMethodName("sayHello"); mockedInvocation.setAttachment(INVOCATION_NEED_MOCK, "true"); List<Invoker<IHelloService>> mockedInvokers = dic.list(mockedInvocation); Assertions.assertEquals(1, mockedInvokers.size()); List<Invoker<IHelloService>> invokers = dic.list(invocation); Assertions.assertEquals(5, invokers.size()); } public static interface IHelloService {} }
7,764
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MyMockException.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.support.wrapper; public class MyMockException extends RuntimeException { private static final long serialVersionUID = 2851692379597990457L; public MyMockException(String message) { super(message); } }
7,765
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockProviderRpcExceptionTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.support.wrapper; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.metrics.event.MetricsDispatcher; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.ProxyFactory; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.cluster.LoadBalance; import org.apache.dubbo.rpc.cluster.directory.StaticDirectory; import org.apache.dubbo.rpc.cluster.support.AbstractClusterInvoker; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.rpc.Constants.MOCK_KEY; import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY; class MockProviderRpcExceptionTest { List<Invoker<IHelloRpcService>> invokers = new ArrayList<Invoker<IHelloRpcService>>(); @BeforeEach public void beforeMethod() { ApplicationModel.defaultModel().getBeanFactory().registerBean(MetricsDispatcher.class); invokers.clear(); } /** * Test if mock policy works fine: ProviderRpcException */ @Test void testMockInvokerProviderRpcException() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloRpcService.class.getName()); url = url.addParameter(MOCK_KEY, "true") .addParameter("invoke_return_error", "true") .addParameter( REFER_KEY, URL.encode(PATH_KEY + "=" + MockProviderRpcExceptionTest.IHelloRpcService.class.getName() + "&" + "mock=true" + "&" + "proxy=jdk")); Invoker<IHelloRpcService> cluster = getClusterInvoker(url); RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething4"); Result ret = cluster.invoke(invocation); Assertions.assertEquals("something4mock", ret.getValue()); } private Invoker<IHelloRpcService> getClusterInvokerMock(URL url, Invoker<IHelloRpcService> mockInvoker) { // As `javassist` have a strict restriction of argument types, request will fail if Invocation do not contains // complete parameter type information final URL durl = url.addParameter("proxy", "jdk"); invokers.clear(); ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getExtension("jdk"); Invoker<IHelloRpcService> invoker1 = proxy.getInvoker(new HelloRpcService(), IHelloRpcService.class, durl); invokers.add(invoker1); if (mockInvoker != null) { invokers.add(mockInvoker); } StaticDirectory<IHelloRpcService> dic = new StaticDirectory<IHelloRpcService>(durl, invokers, null); dic.buildRouterChain(); AbstractClusterInvoker<IHelloRpcService> cluster = new AbstractClusterInvoker(dic) { @Override protected Result doInvoke(Invocation invocation, List invokers, LoadBalance loadbalance) throws RpcException { if (durl.getParameter("invoke_return_error", false)) { throw new RpcException(RpcException.TIMEOUT_EXCEPTION, "test rpc exception "); } else { return ((Invoker<?>) invokers.get(0)).invoke(invocation); } } }; return new MockClusterInvoker<IHelloRpcService>(dic, cluster); } @SuppressWarnings({"unchecked", "rawtypes"}) private Invoker<IHelloRpcService> getClusterInvoker(URL url) { return getClusterInvokerMock(url, null); } public static interface IHelloRpcService { String getSomething(); String getSomething2(); String getSomething3(); String getSomething4(); int getInt1(); boolean getBoolean1(); Boolean getBoolean2(); public List<String> getListString(); public List<User> getUsers(); void sayHello(); } public static class HelloRpcService implements IHelloRpcService { public String getSomething() { return "something"; } public String getSomething2() { return "something2"; } public String getSomething3() { return "something3"; } public String getSomething4() { throw new RpcException("getSomething4|RpcException"); } public int getInt1() { return 1; } public boolean getBoolean1() { return false; } public Boolean getBoolean2() { return Boolean.FALSE; } public List<String> getListString() { return Arrays.asList(new String[] {"Tom", "Jerry"}); } public List<User> getUsers() { return Arrays.asList(new User[] {new User(1, "Tom"), new User(2, "Jerry")}); } public void sayHello() { System.out.println("hello prety"); } } public static class IHelloRpcServiceMock implements IHelloRpcService { public IHelloRpcServiceMock() {} public String getSomething() { return "somethingmock"; } public String getSomething2() { return "something2mock"; } public String getSomething3() { return "something3mock"; } public String getSomething4() { return "something4mock"; } public List<String> getListString() { return Arrays.asList(new String[] {"Tommock", "Jerrymock"}); } public List<User> getUsers() { return Arrays.asList(new User[] {new User(1, "Tommock"), new User(2, "Jerrymock")}); } public int getInt1() { return 1; } public boolean getBoolean1() { return false; } public Boolean getBoolean2() { return Boolean.FALSE; } public void sayHello() { System.out.println("hello prety"); } } public static class User { private int id; private String name; public User() {} public User(int id, String name) { super(); this.id = id; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } }
7,766
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/AbstractClusterTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.support.wrapper; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.cluster.Directory; import org.apache.dubbo.rpc.cluster.LoadBalance; import org.apache.dubbo.rpc.cluster.filter.DemoService; import org.apache.dubbo.rpc.cluster.filter.FilterChainBuilder; import org.apache.dubbo.rpc.cluster.support.AbstractClusterInvoker; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.REFERENCE_FILTER_KEY; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; class AbstractClusterTest { @Test void testBuildClusterInvokerChain() { Map<String, String> parameters = new HashMap<>(); parameters.put(INTERFACE_KEY, DemoService.class.getName()); parameters.put("registry", "zookeeper"); parameters.put(REFERENCE_FILTER_KEY, "demo"); ServiceConfigURL url = new ServiceConfigURL( "registry", "127.0.0.1", 2181, "org.apache.dubbo.registry.RegistryService", parameters); URL consumerUrl = new ServiceConfigURL("dubbo", "127.0.0.1", 20881, DemoService.class.getName(), parameters); consumerUrl = consumerUrl.setScopeModel(ApplicationModel.defaultModel().getInternalModule()); Directory<?> directory = mock(Directory.class); when(directory.getUrl()).thenReturn(url); when(directory.getConsumerUrl()).thenReturn(consumerUrl); DemoCluster demoCluster = new DemoCluster(); Invoker<?> invoker = demoCluster.join(directory, true); Assertions.assertTrue(invoker instanceof AbstractCluster.ClusterFilterInvoker); Assertions.assertTrue( ((AbstractCluster.ClusterFilterInvoker<?>) invoker).getFilterInvoker() instanceof FilterChainBuilder.ClusterCallbackRegistrationInvoker); } static class DemoCluster extends AbstractCluster { @Override public <T> Invoker<T> join(Directory<T> directory, boolean buildFilterChain) throws RpcException { return super.join(directory, buildFilterChain); } @Override protected <T> AbstractClusterInvoker<T> doJoin(Directory<T> directory) throws RpcException { return new DemoAbstractClusterInvoker<>(directory, directory.getUrl()); } } static class DemoAbstractClusterInvoker<T> extends AbstractClusterInvoker<T> { @Override public URL getUrl() { return super.getUrl(); } public DemoAbstractClusterInvoker(Directory<T> directory, URL url) { super(directory, url); } @Override protected Result doInvoke(Invocation invocation, List list, LoadBalance loadbalance) throws RpcException { return null; } } }
7,767
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/ScopeClusterInvokerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.support.wrapper; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.metrics.event.MetricsDispatcher; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.ProxyFactory; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.cluster.LoadBalance; import org.apache.dubbo.rpc.cluster.directory.StaticDirectory; import org.apache.dubbo.rpc.cluster.support.AbstractClusterInvoker; import org.apache.dubbo.rpc.model.ApplicationModel; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.EXPORTER_LISTENER_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.LOCALHOST_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.rpc.Constants.LOCAL_PROTOCOL; import static org.apache.dubbo.rpc.Constants.SCOPE_LOCAL; import static org.apache.dubbo.rpc.cluster.Constants.PEER_KEY; import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY; import static org.apache.dubbo.rpc.cluster.Constants.SCOPE_KEY; class ScopeClusterInvokerTest { private final List<Invoker<DemoService>> invokers = new ArrayList<>(); private final Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); private final ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); private final List<Exporter<?>> exporters = new ArrayList<>(); @BeforeEach void beforeMonth() { ApplicationModel.defaultModel().getBeanFactory().registerBean(MetricsDispatcher.class); } @AfterEach void after() throws Exception { for (Exporter<?> exporter : exporters) { exporter.unexport(); } exporters.clear(); for (Invoker<DemoService> invoker : invokers) { invoker.destroy(); if (invoker instanceof ScopeClusterInvoker) { Assertions.assertTrue(((ScopeClusterInvoker) invoker).isDestroyed()); } } invokers.clear(); } @Test void testScopeNull_RemoteInvoke() { URL url = URL.valueOf("remote://1.2.3.4/" + DemoService.class.getName()); url = url.addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + DemoService.class.getName())); url = url.setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); Invoker<DemoService> cluster = getClusterInvoker(url); invokers.add(cluster); // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("doSomething1"); Result ret = cluster.invoke(invocation); Assertions.assertEquals("doSomething1", ret.getValue()); } @Test void testScopeNull_LocalInvoke() { URL url = URL.valueOf("remote://1.2.3.4/" + DemoService.class.getName()); url = url.addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + DemoService.class.getName())); url = url.setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); URL injvmUrl = URL.valueOf("injvm://127.0.0.1/TestService") .addParameter(INTERFACE_KEY, DemoService.class.getName()) .setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); Exporter<?> exporter = protocol.export(proxy.getInvoker(new DemoServiceImpl(), DemoService.class, injvmUrl)); exporters.add(exporter); Invoker<DemoService> cluster = getClusterInvoker(url); invokers.add(cluster); // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("doSomething2"); invocation.setParameterTypes(new Class[] {}); Result ret = cluster.invoke(invocation); Assertions.assertEquals("doSomething2", ret.getValue()); } @Test void testScopeRemoteInvoke() { URL url = URL.valueOf("remote://1.2.3.4/" + DemoService.class.getName()); url = url.addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + DemoService.class.getName())); url = url.addParameter(SCOPE_KEY, "remote"); url = url.setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); URL injvmUrl = URL.valueOf("injvm://127.0.0.1/TestService") .addParameter(INTERFACE_KEY, DemoService.class.getName()) .setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); Exporter<?> exporter = protocol.export(proxy.getInvoker(new DemoServiceImpl(), DemoService.class, injvmUrl)); exporters.add(exporter); Invoker<DemoService> cluster = getClusterInvoker(url); invokers.add(cluster); // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("doSomething3"); invocation.setParameterTypes(new Class[] {}); Result ret = cluster.invoke(invocation); Assertions.assertEquals("doSomething3", ret.getValue()); } @Test void testScopeLocalInvoke() { URL url = URL.valueOf("remote://1.2.3.4/" + DemoService.class.getName()); url = url.addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + DemoService.class.getName())); url = url.addParameter(SCOPE_KEY, SCOPE_LOCAL); url = url.setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); Invoker<DemoService> cluster = getClusterInvoker(url); invokers.add(cluster); RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("doSomething4"); invocation.setParameterTypes(new Class[] {}); Assertions.assertFalse(cluster.isAvailable(), ""); RpcInvocation finalInvocation = invocation; Assertions.assertThrows(RpcException.class, () -> cluster.invoke(finalInvocation)); URL injvmUrl = URL.valueOf("injvm://127.0.0.1/TestService").addParameter(INTERFACE_KEY, DemoService.class.getName()); injvmUrl = injvmUrl.addParameter(EXPORTER_LISTENER_KEY, LOCAL_PROTOCOL) .setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); Exporter<?> exporter = protocol.export(proxy.getInvoker(new DemoServiceImpl(), DemoService.class, injvmUrl)); exporters.add(exporter); invocation = new RpcInvocation(); invocation.setMethodName("doSomething4"); invocation.setParameterTypes(new Class[] {}); Assertions.assertTrue(cluster.isAvailable(), ""); Result ret2 = cluster.invoke(invocation); Assertions.assertEquals("doSomething4", ret2.getValue()); } @Test void testInjvmRefer() { URL url = new URL(LOCAL_PROTOCOL, LOCALHOST_VALUE, 0, DemoService.class.getName()); url = url.addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + DemoService.class.getName())); url = url.setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); URL injvmUrl = URL.valueOf("injvm://127.0.0.1/TestService") .addParameter(INTERFACE_KEY, DemoService.class.getName()) .setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); Exporter<?> exporter = protocol.export(proxy.getInvoker(new DemoServiceImpl(), DemoService.class, injvmUrl)); exporters.add(exporter); Invoker<DemoService> cluster = getClusterInvoker(url); invokers.add(cluster); RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("doSomething5"); invocation.setParameterTypes(new Class[] {}); Assertions.assertTrue(cluster.isAvailable(), ""); Result ret = cluster.invoke(invocation); Assertions.assertEquals("doSomething5", ret.getValue()); } @Test void testListenUnExport() throws NoSuchFieldException, IllegalAccessException { URL url = URL.valueOf("remote://1.2.3.4/" + DemoService.class.getName()); url = url.addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + DemoService.class.getName())); url = url.addParameter(SCOPE_KEY, "local"); url = url.setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); URL injvmUrl = URL.valueOf("injvm://127.0.0.1/TestService") .addParameter(INTERFACE_KEY, DemoService.class.getName()) .setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); Exporter<?> exporter = protocol.export(proxy.getInvoker(new DemoServiceImpl(), DemoService.class, injvmUrl)); Invoker<DemoService> cluster = getClusterInvoker(url); invokers.add(cluster); exporter.unexport(); Assertions.assertTrue(cluster instanceof ScopeClusterInvoker); Field injvmInvoker = cluster.getClass().getDeclaredField("injvmInvoker"); injvmInvoker.setAccessible(true); Assertions.assertNull(injvmInvoker.get(cluster)); Field isExported = cluster.getClass().getDeclaredField("isExported"); isExported.setAccessible(true); Assertions.assertFalse(((AtomicBoolean) isExported.get(cluster)).get()); } @Test void testPeerInvoke() { URL url = URL.valueOf("remote://1.2.3.4/" + DemoService.class.getName()); url = url.addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + DemoService.class.getName())); Map<String, Object> peer = new HashMap<>(); peer.put(PEER_KEY, true); url = url.addAttributes(peer); url = url.setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); Invoker<DemoService> cluster = getClusterInvoker(url); invokers.add(cluster); // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("doSomething6"); invocation.setParameterTypes(new Class[] {}); Result ret = cluster.invoke(invocation); Assertions.assertEquals("doSomething6", ret.getValue()); } @Test void testInjvmUrlInvoke() { URL url = URL.valueOf("injvm://1.2.3.4/" + DemoService.class.getName()); url = url.addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + DemoService.class.getName())); url = url.setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); Invoker<DemoService> cluster = getClusterInvoker(url); invokers.add(cluster); // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("doSomething7"); invocation.setParameterTypes(new Class[] {}); Result ret = cluster.invoke(invocation); Assertions.assertEquals("doSomething7", ret.getValue()); } @Test void testDynamicInvoke() { URL url = URL.valueOf("remote://1.2.3.4/" + DemoService.class.getName()); url = url.addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + DemoService.class.getName())); url = url.setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); Invoker<DemoService> cluster = getClusterInvoker(url); invokers.add(cluster); RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("doSomething8"); invocation.setParameterTypes(new Class[] {}); Result ret1 = cluster.invoke(invocation); Assertions.assertEquals("doSomething8", ret1.getValue()); RpcContext.getServiceContext().setLocalInvoke(true); invocation = new RpcInvocation(); invocation.setMethodName("doSomething8"); invocation.setParameterTypes(new Class[] {}); RpcInvocation finalInvocation = invocation; Assertions.assertThrows(RpcException.class, () -> cluster.invoke(finalInvocation)); URL injvmUrl = URL.valueOf("injvm://127.0.0.1/TestService") .addParameter(INTERFACE_KEY, DemoService.class.getName()) .setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); Exporter<?> exporter = protocol.export(proxy.getInvoker(new DemoServiceImpl(), DemoService.class, injvmUrl)); exporters.add(exporter); invocation = new RpcInvocation(); invocation.setMethodName("doSomething8"); invocation.setParameterTypes(new Class[] {}); Result ret2 = cluster.invoke(invocation); Assertions.assertEquals("doSomething8", ret2.getValue()); RpcContext.getServiceContext().setLocalInvoke(false); invocation = new RpcInvocation(); invocation.setMethodName("doSomething8"); invocation.setParameterTypes(new Class[] {}); Result ret3 = cluster.invoke(invocation); Assertions.assertEquals("doSomething8", ret3.getValue()); } @Test void testBroadcast() { URL url = URL.valueOf("remote://1.2.3.4/" + DemoService.class.getName()); url = url.addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + DemoService.class.getName())); url = url.addParameter("cluster", "broadcast"); url = url.setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); Invoker<DemoService> cluster = getClusterInvoker(url); invokers.add(cluster); RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("doSomething8"); invocation.setParameterTypes(new Class[] {}); Result ret = cluster.invoke(invocation); Assertions.assertEquals("doSomething8", ret.getValue()); } private Invoker<DemoService> getClusterInvoker(URL url) { final URL durl = url.addParameter("proxy", "jdk"); invokers.clear(); ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getExtension("jdk"); Invoker<DemoService> invoker1 = proxy.getInvoker(new DemoServiceImpl(), DemoService.class, durl); invokers.add(invoker1); StaticDirectory<DemoService> dic = new StaticDirectory<>(durl, invokers, null); dic.buildRouterChain(); AbstractClusterInvoker<DemoService> cluster = new AbstractClusterInvoker(dic) { @Override protected Result doInvoke(Invocation invocation, List invokers, LoadBalance loadbalance) throws RpcException { if (durl.getParameter("invoke_return_error", false)) { throw new RpcException(RpcException.TIMEOUT_EXCEPTION, "test rpc exception"); } else { return ((Invoker<?>) invokers.get(0)).invoke(invocation); } } }; ScopeClusterInvoker<DemoService> demoServiceScopeClusterInvoker = new ScopeClusterInvoker<>(dic, cluster); Assertions.assertNotNull(demoServiceScopeClusterInvoker.getDirectory()); Assertions.assertNotNull(demoServiceScopeClusterInvoker.getInvoker()); return demoServiceScopeClusterInvoker; } public static interface DemoService { String doSomething1(); String doSomething2(); String doSomething3(); String doSomething4(); String doSomething5(); String doSomething6(); String doSomething7(); String doSomething8(); } public static class DemoServiceImpl implements DemoService { @Override public String doSomething1() { return "doSomething1"; } @Override public String doSomething2() { return "doSomething2"; } @Override public String doSomething3() { return "doSomething3"; } @Override public String doSomething4() { return "doSomething4"; } @Override public String doSomething5() { return "doSomething5"; } @Override public String doSomething6() { return "doSomething6"; } @Override public String doSomething7() { return "doSomething7"; } @Override public String doSomething8() { return "doSomething8"; } } }
7,768
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/DemoClusterFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.support.wrapper; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.cluster.filter.ClusterFilter; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER; @Activate( value = "demo", group = {CONSUMER}) public class DemoClusterFilter implements ClusterFilter { @Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { return invoker.invoke(invocation); } }
7,769
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvokerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.support.wrapper; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.metrics.event.MetricsDispatcher; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.ProxyFactory; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.cluster.LoadBalance; import org.apache.dubbo.rpc.cluster.directory.StaticDirectory; import org.apache.dubbo.rpc.cluster.support.AbstractClusterInvoker; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.support.MockProtocol; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY; class MockClusterInvokerTest { List<Invoker<IHelloService>> invokers = new ArrayList<Invoker<IHelloService>>(); @BeforeEach public void beforeMethod() { ApplicationModel.defaultModel().getBeanFactory().registerBean(MetricsDispatcher.class); invokers.clear(); } /** * Test if mock policy works fine: fail-mock */ @Test void testMockInvokerInvoke_normal() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()); url = url.addParameter( REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "mock=fail")); Invoker<IHelloService> cluster = getClusterInvoker(url); URL mockUrl = URL.valueOf("mock://localhost/" + IHelloService.class.getName() + "?getSomething.mock=return aa"); Protocol protocol = new MockProtocol(); Invoker<IHelloService> mInvoker1 = protocol.refer(IHelloService.class, mockUrl); invokers.add(mInvoker1); // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); Result ret = cluster.invoke(invocation); Assertions.assertEquals("something", ret.getValue()); // If no mock was configured, return null directly invocation = new RpcInvocation(); invocation.setMethodName("sayHello"); ret = cluster.invoke(invocation); Assertions.assertNull(ret.getValue()); } /** * Test if mock policy works fine: fail-mock */ @Test void testMockInvokerInvoke_failmock() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) .addParameter( REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "mock=fail:return null")) .addParameter("invoke_return_error", "true"); URL mockUrl = URL.valueOf("mock://localhost/" + IHelloService.class.getName()) .addParameter("mock", "fail:return null") .addParameter("getSomething.mock", "return aa") .addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName())) .addParameter("invoke_return_error", "true"); Protocol protocol = new MockProtocol(); Invoker<IHelloService> mInvoker1 = protocol.refer(IHelloService.class, mockUrl); Invoker<IHelloService> cluster = getClusterInvokerMock(url, mInvoker1); // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); Result ret = cluster.invoke(invocation); Assertions.assertEquals("aa", ret.getValue()); // If no mock was configured, return null directly invocation = new RpcInvocation(); invocation.setMethodName("getSomething2"); ret = cluster.invoke(invocation); Assertions.assertNull(ret.getValue()); // If no mock was configured, return null directly invocation = new RpcInvocation(); invocation.setMethodName("sayHello"); ret = cluster.invoke(invocation); Assertions.assertNull(ret.getValue()); } /** * Test if mock policy works fine: force-mock */ @Test void testMockInvokerInvoke_forcemock() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) .addParameter( REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "mock=force:return null")); URL mockUrl = URL.valueOf("mock://localhost/" + IHelloService.class.getName()) .addParameter("mock", "force:return null") .addParameter("getSomething.mock", "return aa") .addParameter("getSomething3xx.mock", "return xx") .addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName())); Protocol protocol = new MockProtocol(); Invoker<IHelloService> mInvoker1 = protocol.refer(IHelloService.class, mockUrl); Invoker<IHelloService> cluster = getClusterInvokerMock(url, mInvoker1); // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); Result ret = cluster.invoke(invocation); Assertions.assertEquals("aa", ret.getValue()); // If no mock was configured, return null directly invocation = new RpcInvocation(); invocation.setMethodName("getSomething2"); ret = cluster.invoke(invocation); Assertions.assertNull(ret.getValue()); // If no mock was configured, return null directly invocation = new RpcInvocation(); invocation.setMethodName("sayHello"); ret = cluster.invoke(invocation); Assertions.assertNull(ret.getValue()); } @Test void testMockInvokerInvoke_forcemock_defaultreturn() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) .addParameter( REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "mock=force")); Invoker<IHelloService> cluster = getClusterInvoker(url); URL mockUrl = URL.valueOf("mock://localhost/" + IHelloService.class.getName() + "?getSomething.mock=return aa&getSomething3xx.mock=return xx&sayHello.mock=return ") .addParameters(url.getParameters()); Protocol protocol = new MockProtocol(); Invoker<IHelloService> mInvoker1 = protocol.refer(IHelloService.class, mockUrl); invokers.add(mInvoker1); RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("sayHello"); Result ret = cluster.invoke(invocation); Assertions.assertNull(ret.getValue()); } /** * Test if mock policy works fine: fail-mock */ @Test void testMockInvokerFromOverride_Invoke_Fock_someMethods() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) .addParameter( REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "getSomething.mock=fail:return x" + "&" + "getSomething2.mock=force:return y")); Invoker<IHelloService> cluster = getClusterInvoker(url); // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); Result ret = cluster.invoke(invocation); Assertions.assertEquals("something", ret.getValue()); // If no mock was configured, return null directly invocation = new RpcInvocation(); invocation.setMethodName("getSomething2"); ret = cluster.invoke(invocation); Assertions.assertEquals("y", ret.getValue()); // If no mock was configured, return null directly invocation = new RpcInvocation(); invocation.setMethodName("getSomething3"); ret = cluster.invoke(invocation); Assertions.assertEquals("something3", ret.getValue()); // If no mock was configured, return null directly invocation = new RpcInvocation(); invocation.setMethodName("sayHello"); ret = cluster.invoke(invocation); Assertions.assertNull(ret.getValue()); } /** * Test if mock policy works fine: fail-mock */ @Test void testMockInvokerFromOverride_Invoke_Fock_WithOutDefault() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) .addParameter( REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "getSomething.mock=fail:return x" + "&" + "getSomething2.mock=fail:return y")) .addParameter("invoke_return_error", "true"); Invoker<IHelloService> cluster = getClusterInvoker(url); // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); Result ret = cluster.invoke(invocation); Assertions.assertEquals("x", ret.getValue()); // If no mock was configured, return null directly invocation = new RpcInvocation(); invocation.setMethodName("getSomething2"); ret = cluster.invoke(invocation); Assertions.assertEquals("y", ret.getValue()); // If no mock was configured, return null directly invocation = new RpcInvocation(); invocation.setMethodName("getSomething3"); try { ret = cluster.invoke(invocation); Assertions.fail(); } catch (RpcException e) { } } /** * Test if mock policy works fine: fail-mock */ @Test void testMockInvokerFromOverride_Invoke_Fock_WithDefault() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) .addParameter( REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "mock" + "=" + "fail:return null" + "&" + "getSomething.mock" + "=" + "fail:return x" + "&" + "getSomething2.mock" + "=" + "fail:return y")) .addParameter("invoke_return_error", "true"); Invoker<IHelloService> cluster = getClusterInvoker(url); // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); Result ret = cluster.invoke(invocation); Assertions.assertEquals("x", ret.getValue()); // If no mock was configured, return null directly invocation = new RpcInvocation(); invocation.setMethodName("getSomething2"); ret = cluster.invoke(invocation); Assertions.assertEquals("y", ret.getValue()); // If no mock was configured, return null directly invocation = new RpcInvocation(); invocation.setMethodName("getSomething3"); ret = cluster.invoke(invocation); Assertions.assertNull(ret.getValue()); // If no mock was configured, return null directly invocation = new RpcInvocation(); invocation.setMethodName("sayHello"); ret = cluster.invoke(invocation); Assertions.assertNull(ret.getValue()); } /** * Test if mock policy works fine: fail-mock */ @Test void testMockInvokerFromOverride_Invoke_Fock_WithFailDefault() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) .addParameter( REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "mock=fail:return z" + "&" + "getSomething.mock=fail:return x" + "&" + "getSomething2.mock=force:return y")) .addParameter("invoke_return_error", "true"); Invoker<IHelloService> cluster = getClusterInvoker(url); // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); Result ret = cluster.invoke(invocation); Assertions.assertEquals("x", ret.getValue()); // If no mock was configured, return null directly invocation = new RpcInvocation(); invocation.setMethodName("getSomething2"); ret = cluster.invoke(invocation); Assertions.assertEquals("y", ret.getValue()); // If no mock was configured, return null directly invocation = new RpcInvocation(); invocation.setMethodName("getSomething3"); ret = cluster.invoke(invocation); Assertions.assertEquals("z", ret.getValue()); // If no mock was configured, return null directly invocation = new RpcInvocation(); invocation.setMethodName("sayHello"); ret = cluster.invoke(invocation); Assertions.assertEquals("z", ret.getValue()); } /** * Test if mock policy works fine: fail-mock */ @Test void testMockInvokerFromOverride_Invoke_Fock_WithForceDefault() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) .addParameter( REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "mock=force:return z" + "&" + "getSomething.mock=fail:return x" + "&" + "getSomething2.mock=force:return y")) .addParameter("invoke_return_error", "true"); Invoker<IHelloService> cluster = getClusterInvoker(url); // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); Result ret = cluster.invoke(invocation); Assertions.assertEquals("x", ret.getValue()); // If no mock was configured, return null directly invocation = new RpcInvocation(); invocation.setMethodName("getSomething2"); ret = cluster.invoke(invocation); Assertions.assertEquals("y", ret.getValue()); // If no mock was configured, return null directly invocation = new RpcInvocation(); invocation.setMethodName("getSomething3"); ret = cluster.invoke(invocation); Assertions.assertEquals("z", ret.getValue()); // If no mock was configured, return null directly invocation = new RpcInvocation(); invocation.setMethodName("sayHello"); ret = cluster.invoke(invocation); Assertions.assertEquals("z", ret.getValue()); } /** * Test if mock policy works fine: fail-mock */ @Test void testMockInvokerFromOverride_Invoke_Fock_Default() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) .addParameter( REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "mock=fail:return x")) .addParameter("invoke_return_error", "true"); Invoker<IHelloService> cluster = getClusterInvoker(url); // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); Result ret = cluster.invoke(invocation); Assertions.assertEquals("x", ret.getValue()); // If no mock was configured, return null directly invocation = new RpcInvocation(); invocation.setMethodName("getSomething2"); ret = cluster.invoke(invocation); Assertions.assertEquals("x", ret.getValue()); // If no mock was configured, return null directly invocation = new RpcInvocation(); invocation.setMethodName("sayHello"); ret = cluster.invoke(invocation); Assertions.assertEquals("x", ret.getValue()); } /** * Test if mock policy works fine: fail-mock */ @Test void testMockInvokerFromOverride_Invoke_checkCompatible_return() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) .addParameter( REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "getSomething.mock=return x")) .addParameter("invoke_return_error", "true"); Invoker<IHelloService> cluster = getClusterInvoker(url); // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); Result ret = cluster.invoke(invocation); Assertions.assertEquals("x", ret.getValue()); // If no mock was configured, return null directly invocation = new RpcInvocation(); invocation.setMethodName("getSomething3"); try { ret = cluster.invoke(invocation); Assertions.fail("fail invoke"); } catch (RpcException e) { } } /** * Test if mock policy works fine: fail-mock */ @Test void testMockInvokerFromOverride_Invoke_checkCompatible_ImplMock() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) .addParameter( REFER_KEY, URL.encode( PATH_KEY + "=" + IHelloService.class.getName() + "&" + "mock=true" + "&" + "proxy=jdk")) .addParameter("invoke_return_error", "true"); Invoker<IHelloService> cluster = getClusterInvoker(url); // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); Result ret = cluster.invoke(invocation); Assertions.assertEquals("somethingmock", ret.getValue()); } /** * Test if mock policy works fine: fail-mock */ @Test void testMockInvokerFromOverride_Invoke_checkCompatible_ImplMock2() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) .addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "mock=fail")) .addParameter("invoke_return_error", "true"); Invoker<IHelloService> cluster = getClusterInvoker(url); // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); Result ret = cluster.invoke(invocation); Assertions.assertEquals("somethingmock", ret.getValue()); } /** * Test if mock policy works fine: fail-mock */ @Test void testMockInvokerFromOverride_Invoke_checkCompatible_ImplMock3() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) .addParameter( REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "mock=force")); Invoker<IHelloService> cluster = getClusterInvoker(url); // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); Result ret = cluster.invoke(invocation); Assertions.assertEquals("somethingmock", ret.getValue()); } @Test void testMockInvokerFromOverride_Invoke_check_String() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) .addParameter("getSomething.mock", "force:return 1688") .addParameter( REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "getSomething.mock=force:return 1688")) .addParameter("invoke_return_error", "true"); Invoker<IHelloService> cluster = getClusterInvoker(url); // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); Result ret = cluster.invoke(invocation); Assertions.assertTrue( ret.getValue() instanceof String, "result type must be String but was : " + ret.getValue().getClass()); Assertions.assertEquals("1688", ret.getValue()); } @Test void testMockInvokerFromOverride_Invoke_check_int() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) .addParameter( REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "getInt1.mock=force:return 1688")) .addParameter("invoke_return_error", "true"); Invoker<IHelloService> cluster = getClusterInvoker(url); // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getInt1"); Result ret = cluster.invoke(invocation); Assertions.assertTrue( ret.getValue() instanceof Integer, "result type must be integer but was : " + ret.getValue().getClass()); Assertions.assertEquals(new Integer(1688), (Integer) ret.getValue()); } @Test void testMockInvokerFromOverride_Invoke_check_boolean() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) .addParameter( REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "getBoolean1.mock=force:return true")) .addParameter("invoke_return_error", "true"); Invoker<IHelloService> cluster = getClusterInvoker(url); // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getBoolean1"); Result ret = cluster.invoke(invocation); Assertions.assertTrue( ret.getValue() instanceof Boolean, "result type must be Boolean but was : " + ret.getValue().getClass()); Assertions.assertTrue(Boolean.parseBoolean(ret.getValue().toString())); } @Test void testMockInvokerFromOverride_Invoke_check_Boolean() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) .addParameter( REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "getBoolean2.mock=force:return true")) .addParameter("invoke_return_error", "true"); Invoker<IHelloService> cluster = getClusterInvoker(url); // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getBoolean2"); Result ret = cluster.invoke(invocation); Assertions.assertTrue(Boolean.parseBoolean(ret.getValue().toString())); } @SuppressWarnings("unchecked") @Test void testMockInvokerFromOverride_Invoke_check_ListString_empty() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) .addParameter( REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "getListString.mock=force:return empty")) .addParameter("invoke_return_error", "true"); Invoker<IHelloService> cluster = getClusterInvoker(url); // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getListString"); Result ret = cluster.invoke(invocation); Assertions.assertEquals(0, ((List<String>) ret.getValue()).size()); } @SuppressWarnings("unchecked") @Test void testMockInvokerFromOverride_Invoke_check_ListString() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) .addParameter( REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "getListString.mock=force:return [\"hi\",\"hi2\"]")) .addParameter("invoke_return_error", "true"); Invoker<IHelloService> cluster = getClusterInvoker(url); // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getListString"); Result ret = cluster.invoke(invocation); List<String> rl = (List<String>) ret.getValue(); Assertions.assertEquals(2, rl.size()); Assertions.assertEquals("hi", rl.get(0)); } @SuppressWarnings("unchecked") @Test void testMockInvokerFromOverride_Invoke_check_ListPojo_empty() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) .addParameter( REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "getUsers.mock=force:return empty")) .addParameter("invoke_return_error", "true"); Invoker<IHelloService> cluster = getClusterInvoker(url); // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getUsers"); Result ret = cluster.invoke(invocation); Assertions.assertEquals(0, ((List<User>) ret.getValue()).size()); } @Test void testMockInvokerFromOverride_Invoke_check_ListPojoAsync() throws ExecutionException, InterruptedException { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) .addParameter( REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "getUsersAsync.mock=force")) .addParameter("invoke_return_error", "true"); Invoker<IHelloService> cluster = getClusterInvoker(url); // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getUsersAsync"); invocation.setReturnType(CompletableFuture.class); Result ret = cluster.invoke(invocation); CompletableFuture<List<User>> cf = null; try { cf = (CompletableFuture<List<User>>) ret.recreate(); } catch (Throwable e) { e.printStackTrace(); } Assertions.assertEquals(2, cf.get().size()); Assertions.assertEquals("Tommock", cf.get().get(0).getName()); } @SuppressWarnings("unchecked") @Test void testMockInvokerFromOverride_Invoke_check_ListPojo() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) .addParameter( REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "getUsers.mock=force:return [{id:1, name:\"hi1\"}, {id:2, name:\"hi2\"}]")) .addParameter("invoke_return_error", "true"); Invoker<IHelloService> cluster = getClusterInvoker(url); // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getUsers"); Result ret = cluster.invoke(invocation); List<User> rl = (List<User>) ret.getValue(); System.out.println(rl); Assertions.assertEquals(2, rl.size()); Assertions.assertEquals("hi1", rl.get(0).getName()); } @Test void testMockInvokerFromOverride_Invoke_check_ListPojo_error() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) .addParameter( REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "getUsers.mock=force:return [{id:x, name:\"hi1\"}]")) .addParameter("invoke_return_error", "true"); Invoker<IHelloService> cluster = getClusterInvoker(url); // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getUsers"); try { cluster.invoke(invocation); } catch (RpcException e) { } } @Test void testMockInvokerFromOverride_Invoke_force_throw() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) .addParameter( REFER_KEY, URL.encode( PATH_KEY + "=" + IHelloService.class.getName() + "&" + "getBoolean2.mock=force:throw ")) .addParameter("invoke_return_error", "true"); Invoker<IHelloService> cluster = getClusterInvoker(url); // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getBoolean2"); try { cluster.invoke(invocation); Assertions.fail(); } catch (RpcException e) { Assertions.assertFalse(e.isBiz(), "not custom exception"); } } @Test void testMockInvokerFromOverride_Invoke_force_throwCustemException() throws Throwable { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) .addParameter( REFER_KEY, URL.encode( PATH_KEY + "=" + IHelloService.class.getName() + "&" + "getBoolean2.mock=force:throw org.apache.dubbo.rpc.cluster.support.wrapper.MyMockException")) .addParameter("invoke_return_error", "true"); Invoker<IHelloService> cluster = getClusterInvoker(url); // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getBoolean2"); try { cluster.invoke(invocation).recreate(); Assertions.fail(); } catch (MyMockException e) { } } @Test void testMockInvokerFromOverride_Invoke_force_throwCustemExceptionNotFound() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) .addParameter( REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "getBoolean2.mock=force:throw java.lang.RuntimeException2")) .addParameter("invoke_return_error", "true"); Invoker<IHelloService> cluster = getClusterInvoker(url); // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getBoolean2"); try { cluster.invoke(invocation); Assertions.fail(); } catch (Exception e) { Assertions.assertTrue(e.getCause() instanceof IllegalStateException); } } @Test void testMockInvokerFromOverride_Invoke_mock_false() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) .addParameter( REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "mock=false")) .addParameter("invoke_return_error", "true"); Invoker<IHelloService> cluster = getClusterInvoker(url); // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getBoolean2"); try { cluster.invoke(invocation); Assertions.fail(); } catch (RpcException e) { Assertions.assertTrue(e.isTimeout()); } } private Invoker<IHelloService> getClusterInvokerMock(URL url, Invoker<IHelloService> mockInvoker) { // As `javassist` have a strict restriction of argument types, request will fail if Invocation do not contains // complete parameter type information final URL durl = url.addParameter("proxy", "jdk"); invokers.clear(); ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getExtension("jdk"); Invoker<IHelloService> invoker1 = proxy.getInvoker(new HelloService(), IHelloService.class, durl); invokers.add(invoker1); if (mockInvoker != null) { invokers.add(mockInvoker); } StaticDirectory<IHelloService> dic = new StaticDirectory<IHelloService>(durl, invokers, null); dic.buildRouterChain(); AbstractClusterInvoker<IHelloService> cluster = new AbstractClusterInvoker(dic) { @Override protected Result doInvoke(Invocation invocation, List invokers, LoadBalance loadbalance) throws RpcException { if (durl.getParameter("invoke_return_error", false)) { throw new RpcException(RpcException.TIMEOUT_EXCEPTION, "test rpc exception"); } else { return ((Invoker<?>) invokers.get(0)).invoke(invocation); } } }; return new MockClusterInvoker<IHelloService>(dic, cluster); } @SuppressWarnings({"unchecked", "rawtypes"}) private Invoker<IHelloService> getClusterInvoker(URL url) { return getClusterInvokerMock(url, null); } public interface IHelloService { String getSomething(); String getSomething2(); String getSomething3(); String getSomething4(); int getInt1(); boolean getBoolean1(); Boolean getBoolean2(); List<String> getListString(); List<User> getUsers(); CompletableFuture<List<User>> getUsersAsync(); void sayHello(); } public static class HelloService implements IHelloService { public String getSomething() { return "something"; } public String getSomething2() { return "something2"; } public String getSomething3() { return "something3"; } public String getSomething4() { throw new RpcException("getSomething4|RpcException"); } public int getInt1() { return 1; } public boolean getBoolean1() { return false; } public Boolean getBoolean2() { return Boolean.FALSE; } public List<String> getListString() { return Arrays.asList(new String[] {"Tom", "Jerry"}); } public List<User> getUsers() { return Arrays.asList(new User[] {new User(1, "Tom"), new User(2, "Jerry")}); } @Override public CompletableFuture<List<User>> getUsersAsync() { CompletableFuture<List<User>> cf = new CompletableFuture<>(); cf.complete(Arrays.asList(new User[] {new User(1, "Tom"), new User(2, "Jerry")})); return cf; } public void sayHello() { System.out.println("hello prety"); } } public static class IHelloServiceMock implements IHelloService { public IHelloServiceMock() {} public String getSomething() { return "somethingmock"; } public String getSomething2() { return "something2mock"; } public String getSomething3() { return "something3mock"; } public String getSomething4() { return "something4mock"; } public List<String> getListString() { return Arrays.asList(new String[] {"Tommock", "Jerrymock"}); } public List<User> getUsers() { return Arrays.asList(new User[] {new User(1, "Tommock"), new User(2, "Jerrymock")}); } @Override public CompletableFuture<List<User>> getUsersAsync() { CompletableFuture<List<User>> cf = new CompletableFuture<>(); cf.complete(Arrays.asList(new User[] {new User(1, "Tommock"), new User(2, "Jerrymock")})); return cf; } public int getInt1() { return 1; } public boolean getBoolean1() { return false; } public Boolean getBoolean2() { return Boolean.FALSE; } public void sayHello() { System.out.println("hello prety"); } } public static class User { private int id; private String name; public User() {} public User(int id, String name) { super(); this.id = id; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } }
7,770
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/merger/DefaultProviderURLMergeProcessorTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.support.merger; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; import org.apache.dubbo.rpc.cluster.ProviderURLMergeProcessor; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.ALIVE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.CLUSTER_KEY; import static org.apache.dubbo.common.constants.CommonConstants.CORE_THREADS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY_PREFIX; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PROTOCOL; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.LOADBALANCE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PID_KEY; import static org.apache.dubbo.common.constants.CommonConstants.QUEUES_KEY; import static org.apache.dubbo.common.constants.CommonConstants.REFERENCE_FILTER_KEY; import static org.apache.dubbo.common.constants.CommonConstants.RELEASE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TAG_KEY; import static org.apache.dubbo.common.constants.CommonConstants.THREADPOOL_KEY; import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; class DefaultProviderURLMergeProcessorTest { private ProviderURLMergeProcessor providerURLMergeProcessor; @BeforeEach public void setup() { providerURLMergeProcessor = new DefaultProviderURLMergeProcessor(); } @Test void testMergeUrl() { URL providerURL = URL.valueOf("dubbo://localhost:55555"); providerURL = providerURL.setPath("path").setUsername("username").setPassword("password"); providerURL = URLBuilder.from(providerURL) .addParameter(GROUP_KEY, "dubbo") .addParameter(VERSION_KEY, "1.2.3") .addParameter(DUBBO_VERSION_KEY, "2.3.7") .addParameter(THREADPOOL_KEY, "fixed") .addParameter(THREADS_KEY, Integer.MAX_VALUE) .addParameter(THREAD_NAME_KEY, "test") .addParameter(CORE_THREADS_KEY, Integer.MAX_VALUE) .addParameter(QUEUES_KEY, Integer.MAX_VALUE) .addParameter(ALIVE_KEY, Integer.MAX_VALUE) .addParameter(DEFAULT_KEY_PREFIX + THREADS_KEY, Integer.MAX_VALUE) .addParameter(DEFAULT_KEY_PREFIX + THREADPOOL_KEY, "fixed") .addParameter(DEFAULT_KEY_PREFIX + CORE_THREADS_KEY, Integer.MAX_VALUE) .addParameter(DEFAULT_KEY_PREFIX + QUEUES_KEY, Integer.MAX_VALUE) .addParameter(DEFAULT_KEY_PREFIX + ALIVE_KEY, Integer.MAX_VALUE) .addParameter(DEFAULT_KEY_PREFIX + THREAD_NAME_KEY, "test") .addParameter(APPLICATION_KEY, "provider") .addParameter(REFERENCE_FILTER_KEY, "filter1,filter2") .addParameter(TAG_KEY, "TTT") .build(); URL consumerURL = new URLBuilder(DUBBO_PROTOCOL, "localhost", 55555) .addParameter(PID_KEY, "1234") .addParameter(THREADPOOL_KEY, "foo") .addParameter(APPLICATION_KEY, "consumer") .addParameter(REFERENCE_FILTER_KEY, "filter3") .addParameter(TAG_KEY, "UUU") .build(); URL url = providerURLMergeProcessor.mergeUrl(providerURL, consumerURL.getParameters()); Assertions.assertFalse(url.hasParameter(THREADS_KEY)); Assertions.assertFalse(url.hasParameter(DEFAULT_KEY_PREFIX + THREADS_KEY)); Assertions.assertFalse(url.hasParameter(DEFAULT_KEY_PREFIX + THREADPOOL_KEY)); Assertions.assertFalse(url.hasParameter(CORE_THREADS_KEY)); Assertions.assertFalse(url.hasParameter(DEFAULT_KEY_PREFIX + CORE_THREADS_KEY)); Assertions.assertFalse(url.hasParameter(QUEUES_KEY)); Assertions.assertFalse(url.hasParameter(DEFAULT_KEY_PREFIX + QUEUES_KEY)); Assertions.assertFalse(url.hasParameter(ALIVE_KEY)); Assertions.assertFalse(url.hasParameter(DEFAULT_KEY_PREFIX + ALIVE_KEY)); Assertions.assertFalse(url.hasParameter(THREAD_NAME_KEY)); Assertions.assertFalse(url.hasParameter(DEFAULT_KEY_PREFIX + THREAD_NAME_KEY)); Assertions.assertEquals("path", url.getPath()); Assertions.assertEquals("username", url.getUsername()); Assertions.assertEquals("password", url.getPassword()); Assertions.assertEquals("1234", url.getParameter(PID_KEY)); Assertions.assertEquals("foo", url.getParameter(THREADPOOL_KEY)); Assertions.assertEquals("consumer", url.getApplication()); Assertions.assertEquals("provider", url.getRemoteApplication()); Assertions.assertEquals("filter1,filter2,filter3", url.getParameter(REFERENCE_FILTER_KEY)); Assertions.assertEquals("TTT", url.getParameter(TAG_KEY)); } @Test void testUseProviderParams() { // present in both local and remote, but uses remote value. URL localURL = URL.valueOf("dubbo://localhost:20880/DemoService?version=local&group=local&dubbo=local&release=local" + "&methods=local&tag=local&timestamp=local"); URL remoteURL = URL.valueOf( "dubbo://localhost:20880/DemoService?version=remote&group=remote&dubbo=remote&release=remote" + "&methods=remote&tag=remote&timestamp=remote"); URL mergedUrl = providerURLMergeProcessor.mergeUrl(remoteURL, localURL.getParameters()); Assertions.assertEquals(remoteURL.getVersion(), mergedUrl.getVersion()); Assertions.assertEquals(remoteURL.getGroup(), mergedUrl.getGroup()); Assertions.assertEquals(remoteURL.getParameter(DUBBO_VERSION_KEY), mergedUrl.getParameter(DUBBO_VERSION_KEY)); Assertions.assertEquals(remoteURL.getParameter(RELEASE_KEY), mergedUrl.getParameter(RELEASE_KEY)); Assertions.assertEquals(remoteURL.getParameter(METHODS_KEY), mergedUrl.getParameter(METHODS_KEY)); Assertions.assertEquals(remoteURL.getParameter(TIMESTAMP_KEY), mergedUrl.getParameter(TIMESTAMP_KEY)); Assertions.assertEquals(remoteURL.getParameter(TAG_KEY), mergedUrl.getParameter(TAG_KEY)); // present in local url but not in remote url, parameters of remote url is empty localURL = URL.valueOf("dubbo://localhost:20880/DemoService?version=local&group=local&dubbo=local&release=local" + "&methods=local&tag=local&timestamp=local"); remoteURL = URL.valueOf("dubbo://localhost:20880/DemoService"); mergedUrl = providerURLMergeProcessor.mergeUrl(remoteURL, localURL.getParameters()); Assertions.assertEquals(localURL.getVersion(), mergedUrl.getVersion()); Assertions.assertEquals(localURL.getGroup(), mergedUrl.getGroup()); Assertions.assertNull(mergedUrl.getParameter(DUBBO_VERSION_KEY)); Assertions.assertNull(mergedUrl.getParameter(RELEASE_KEY)); Assertions.assertNull(mergedUrl.getParameter(METHODS_KEY)); Assertions.assertNull(mergedUrl.getParameter(TIMESTAMP_KEY)); Assertions.assertNull(mergedUrl.getParameter(TAG_KEY)); // present in local url but not in remote url localURL = URL.valueOf("dubbo://localhost:20880/DemoService?version=local&group=local&dubbo=local&release=local" + "&methods=local&tag=local&timestamp=local"); remoteURL = URL.valueOf("dubbo://localhost:20880/DemoService?key=value"); mergedUrl = providerURLMergeProcessor.mergeUrl(remoteURL, localURL.getParameters()); Assertions.assertEquals(localURL.getVersion(), mergedUrl.getVersion()); Assertions.assertEquals(localURL.getGroup(), mergedUrl.getGroup()); Assertions.assertNull(mergedUrl.getParameter(DUBBO_VERSION_KEY)); Assertions.assertNull(mergedUrl.getParameter(RELEASE_KEY)); Assertions.assertNull(mergedUrl.getParameter(METHODS_KEY)); Assertions.assertNull(mergedUrl.getParameter(TIMESTAMP_KEY)); Assertions.assertNull(mergedUrl.getParameter(TAG_KEY)); // present in both local and remote, uses local url params localURL = URL.valueOf("dubbo://localhost:20880/DemoService?loadbalance=local&timeout=1000&cluster=local"); remoteURL = URL.valueOf("dubbo://localhost:20880/DemoService?loadbalance=remote&timeout=2000&cluster=remote"); mergedUrl = providerURLMergeProcessor.mergeUrl(remoteURL, localURL.getParameters()); Assertions.assertEquals(localURL.getParameter(CLUSTER_KEY), mergedUrl.getParameter(CLUSTER_KEY)); Assertions.assertEquals(localURL.getParameter(TIMEOUT_KEY), mergedUrl.getParameter(TIMEOUT_KEY)); Assertions.assertEquals(localURL.getParameter(LOADBALANCE_KEY), mergedUrl.getParameter(LOADBALANCE_KEY)); } }
7,771
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/registry/ZoneAwareClusterInvokerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.support.registry; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.cluster.ClusterInvoker; import org.apache.dubbo.rpc.cluster.Directory; import java.lang.reflect.Proxy; import java.util.ArrayList; import java.util.HashMap; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.PREFERRED_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_ZONE; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_ZONE_FORCE; import static org.apache.dubbo.common.constants.RegistryConstants.ZONE_KEY; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; class ZoneAwareClusterInvokerTest { private Directory directory = mock(Directory.class); private ClusterInvoker firstInvoker = mock(ClusterInvoker.class); private ClusterInvoker secondInvoker = mock(ClusterInvoker.class); private ClusterInvoker thirdInvoker = mock(ClusterInvoker.class); private Invocation invocation = mock(Invocation.class); private ZoneAwareClusterInvoker<ZoneAwareClusterInvokerTest> zoneAwareClusterInvoker; private URL url = URL.valueOf("test://test"); private URL registryUrl = URL.valueOf("localhost://test"); String expectedValue = "expected"; String unexpectedValue = "unexpected"; @Test void testPreferredStrategy() { given(invocation.getParameterTypes()).willReturn(new Class<?>[] {}); given(invocation.getArguments()).willReturn(new Object[] {}); given(invocation.getObjectAttachments()).willReturn(new HashMap<>()); firstInvoker = newUnexpectedInvoker(); thirdInvoker = newUnexpectedInvoker(); secondInvoker = (ClusterInvoker) Proxy.newProxyInstance( getClass().getClassLoader(), new Class<?>[] {ClusterInvoker.class}, (proxy, method, args) -> { if ("getUrl".equals(method.getName())) { return url; } if ("getRegistryUrl".equals(method.getName())) { return registryUrl.addParameter(PREFERRED_KEY, true); } if ("isAvailable".equals(method.getName())) { return true; } if ("invoke".equals(method.getName())) { return new AppResponse(expectedValue); } return null; }); given(directory.list(invocation)).willReturn(new ArrayList() { { add(firstInvoker); add(secondInvoker); add(thirdInvoker); } }); given(directory.getUrl()).willReturn(url); given(directory.getConsumerUrl()).willReturn(url); zoneAwareClusterInvoker = new ZoneAwareClusterInvoker<>(directory); AppResponse response = (AppResponse) zoneAwareClusterInvoker.invoke(invocation); Assertions.assertEquals(expectedValue, response.getValue()); } @Test void testRegistryZoneStrategy() { String zoneKey = "zone"; given(invocation.getParameterTypes()).willReturn(new Class<?>[] {}); given(invocation.getArguments()).willReturn(new Object[] {}); given(invocation.getObjectAttachments()).willReturn(new HashMap<>()); RpcContext.getClientAttachment().setAttachment(REGISTRY_ZONE, zoneKey); firstInvoker = newUnexpectedInvoker(); thirdInvoker = newUnexpectedInvoker(); secondInvoker = (ClusterInvoker) Proxy.newProxyInstance( getClass().getClassLoader(), new Class<?>[] {ClusterInvoker.class}, (proxy, method, args) -> { if ("getUrl".equals(method.getName())) { return url; } if ("getRegistryUrl".equals(method.getName())) { return registryUrl.addParameter(ZONE_KEY, zoneKey); } if ("isAvailable".equals(method.getName())) { return true; } if ("invoke".equals(method.getName())) { return new AppResponse(expectedValue); } return null; }); given(directory.list(invocation)).willReturn(new ArrayList() { { add(firstInvoker); add(secondInvoker); add(thirdInvoker); } }); given(directory.getUrl()).willReturn(url); given(directory.getConsumerUrl()).willReturn(url); zoneAwareClusterInvoker = new ZoneAwareClusterInvoker<>(directory); AppResponse response = (AppResponse) zoneAwareClusterInvoker.invoke(invocation); Assertions.assertEquals(expectedValue, response.getValue()); } @Test void testRegistryZoneForceStrategy() { String zoneKey = "zone"; given(invocation.getParameterTypes()).willReturn(new Class<?>[] {}); given(invocation.getArguments()).willReturn(new Object[] {}); given(invocation.getObjectAttachments()).willReturn(new HashMap<>()); RpcContext.getClientAttachment().setAttachment(REGISTRY_ZONE, zoneKey); RpcContext.getClientAttachment().setAttachment(REGISTRY_ZONE_FORCE, "true"); firstInvoker = newUnexpectedInvoker(); secondInvoker = newUnexpectedInvoker(); thirdInvoker = newUnexpectedInvoker(); given(directory.list(invocation)).willReturn(new ArrayList() { { add(firstInvoker); add(secondInvoker); add(thirdInvoker); } }); given(directory.getUrl()).willReturn(url); given(directory.getConsumerUrl()).willReturn(url); zoneAwareClusterInvoker = new ZoneAwareClusterInvoker<>(directory); Assertions.assertThrows(IllegalStateException.class, () -> zoneAwareClusterInvoker.invoke(invocation)); } @Test public void testNoAvailableInvoker() { given(directory.getUrl()).willReturn(url); given(directory.getConsumerUrl()).willReturn(url); given(directory.list(invocation)).willReturn(new ArrayList<>(0)); given(directory.getInterface()).willReturn(ZoneAwareClusterInvokerTest.class); zoneAwareClusterInvoker = new ZoneAwareClusterInvoker<>(directory); Assertions.assertThrows(RpcException.class, () -> zoneAwareClusterInvoker.invoke(invocation)); } private ClusterInvoker newUnexpectedInvoker() { return (ClusterInvoker) Proxy.newProxyInstance( getClass().getClassLoader(), new Class<?>[] {ClusterInvoker.class}, (proxy, method, args) -> { if ("getUrl".equals(method.getName())) { return url; } if ("getRegistryUrl".equals(method.getName())) { return registryUrl; } if ("isAvailable".equals(method.getName())) { return true; } if ("invoke".equals(method.getName())) { return new AppResponse(unexpectedValue); } return null; }); } }
7,772
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/absent/AbsentConfiguratorTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.configurator.absent; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.rpc.cluster.configurator.consts.UrlConstant; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * OverrideConfiguratorTest */ class AbsentConfiguratorTest { @Test void testOverrideApplication() { AbsentConfigurator configurator = new AbsentConfigurator(URL.valueOf("override://[email protected]/com.foo.BarService?timeout=200")); URL url = configurator.configure(URL.valueOf(UrlConstant.URL_CONSUMER)); Assertions.assertEquals("200", url.getParameter("timeout")); url = configurator.configure(URL.valueOf(UrlConstant.URL_ONE)); Assertions.assertEquals("1000", url.getParameter("timeout")); url = configurator.configure(URL.valueOf(UrlConstant.APPLICATION_BAR_SIDE_CONSUMER_11)); Assertions.assertNull(url.getParameter("timeout")); url = configurator.configure(URL.valueOf(UrlConstant.TIMEOUT_1000_SIDE_CONSUMER_11)); Assertions.assertEquals("1000", url.getParameter("timeout")); } @Test void testOverrideHost() { AbsentConfigurator configurator = new AbsentConfigurator( URL.valueOf("override://" + NetUtils.getLocalHost() + "/com.foo.BarService?timeout=200")); URL url = configurator.configure(URL.valueOf(UrlConstant.URL_CONSUMER)); Assertions.assertEquals("200", url.getParameter("timeout")); url = configurator.configure(URL.valueOf(UrlConstant.URL_ONE)); Assertions.assertEquals("1000", url.getParameter("timeout")); AbsentConfigurator configurator1 = new AbsentConfigurator(URL.valueOf(UrlConstant.SERVICE_TIMEOUT_200)); url = configurator1.configure(URL.valueOf(UrlConstant.APPLICATION_BAR_SIDE_CONSUMER_10)); Assertions.assertNull(url.getParameter("timeout")); url = configurator1.configure(URL.valueOf(UrlConstant.TIMEOUT_1000_SIDE_CONSUMER_10)); Assertions.assertEquals("1000", url.getParameter("timeout")); } // Test the version after 2.7 @Test void testAbsentForVersion27() { { String consumerUrlV27 = "dubbo://172.24.160.179/com.foo.BarService?application=foo&side=consumer&timeout=100"; URL consumerConfiguratorUrl = URL.valueOf("absent://0.0.0.0/com.foo.BarService"); Map<String, String> params = new HashMap<>(); params.put("side", "consumer"); params.put("configVersion", "2.7"); params.put("application", "foo"); params.put("timeout", "10000"); params.put("weight", "200"); consumerConfiguratorUrl = consumerConfiguratorUrl.addParameters(params); AbsentConfigurator configurator = new AbsentConfigurator(consumerConfiguratorUrl); // Meet the configured conditions: // same side // The port of configuratorUrl is 0 // The host of configuratorUrl is 0.0.0.0 or the local address is the same as consumerUrlV27 // same appName URL url = configurator.configure(URL.valueOf(consumerUrlV27)); Assertions.assertEquals("100", url.getParameter("timeout")); Assertions.assertEquals("200", url.getParameter("weight")); } { String providerUrlV27 = "dubbo://172.24.160.179:21880/com.foo.BarService?application=foo&side=provider&weight=100"; URL providerConfiguratorUrl = URL.valueOf("absent://172.24.160.179:21880/com.foo.BarService"); Map<String, String> params = new HashMap<>(); params.put("side", "provider"); params.put("configVersion", "2.7"); params.put("application", "foo"); params.put("timeout", "20000"); params.put("weight", "200"); providerConfiguratorUrl = providerConfiguratorUrl.addParameters(params); // Meet the configured conditions: // same side // same port // The host of configuratorUrl is 0.0.0.0 or the host of providerConfiguratorUrl is the same as // consumerUrlV27 // same appName AbsentConfigurator configurator = new AbsentConfigurator(providerConfiguratorUrl); URL url = configurator.configure(URL.valueOf(providerUrlV27)); Assertions.assertEquals("20000", url.getParameter("timeout")); Assertions.assertEquals("100", url.getParameter("weight")); } } }
7,773
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/override/OverrideConfiguratorTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.configurator.override; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.rpc.cluster.configurator.absent.AbsentConfigurator; import org.apache.dubbo.rpc.cluster.configurator.consts.UrlConstant; import org.apache.dubbo.rpc.cluster.configurator.parser.model.ConditionMatch; import org.apache.dubbo.rpc.cluster.configurator.parser.model.ParamMatch; import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match.StringMatch; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.apache.dubbo.rpc.cluster.configurator.parser.model.ConfiguratorConfig.MATCH_CONDITION; /** * OverrideConfiguratorTest */ class OverrideConfiguratorTest { @Test void testOverride_Application() { OverrideConfigurator configurator = new OverrideConfigurator(URL.valueOf("override://[email protected]/com.foo.BarService?timeout=200")); URL url = configurator.configure(URL.valueOf(UrlConstant.URL_CONSUMER)); Assertions.assertEquals("200", url.getParameter("timeout")); url = configurator.configure(URL.valueOf(UrlConstant.URL_ONE)); Assertions.assertEquals("200", url.getParameter("timeout")); url = configurator.configure(URL.valueOf(UrlConstant.APPLICATION_BAR_SIDE_CONSUMER_11)); Assertions.assertNull(url.getParameter("timeout")); url = configurator.configure(URL.valueOf(UrlConstant.TIMEOUT_1000_SIDE_CONSUMER_11)); Assertions.assertEquals("1000", url.getParameter("timeout")); } @Test void testOverride_Host() { OverrideConfigurator configurator = new OverrideConfigurator( URL.valueOf("override://" + NetUtils.getLocalHost() + "/com.foo.BarService?timeout=200")); URL url = configurator.configure(URL.valueOf(UrlConstant.URL_CONSUMER)); Assertions.assertEquals("200", url.getParameter("timeout")); url = configurator.configure(URL.valueOf(UrlConstant.URL_ONE)); Assertions.assertEquals("200", url.getParameter("timeout")); AbsentConfigurator configurator1 = new AbsentConfigurator(URL.valueOf("override://10.20.153.10/com.foo.BarService?timeout=200")); url = configurator1.configure(URL.valueOf(UrlConstant.APPLICATION_BAR_SIDE_CONSUMER_10)); Assertions.assertNull(url.getParameter("timeout")); url = configurator1.configure(URL.valueOf(UrlConstant.TIMEOUT_1000_SIDE_CONSUMER_10)); Assertions.assertEquals("1000", url.getParameter("timeout")); } // Test the version after 2.7 @Test void testOverrideForVersion27() { { String consumerUrlV27 = "dubbo://172.24.160.179/com.foo.BarService?application=foo&side=consumer&timeout=100"; URL consumerConfiguratorUrl = URL.valueOf("override://0.0.0.0/com.foo.BarService"); Map<String, String> params = new HashMap<>(); params.put("side", "consumer"); params.put("configVersion", "2.7"); params.put("application", "foo"); params.put("timeout", "10000"); consumerConfiguratorUrl = consumerConfiguratorUrl.addParameters(params); OverrideConfigurator configurator = new OverrideConfigurator(consumerConfiguratorUrl); // Meet the configured conditions: // same side // The port of configuratorUrl is 0 // The host of configuratorUrl is 0.0.0.0 or the local address is the same as consumerUrlV27 // same appName URL url = configurator.configure(URL.valueOf(consumerUrlV27)); Assertions.assertEquals(url.getParameter("timeout"), "10000"); } { String providerUrlV27 = "dubbo://172.24.160.179:21880/com.foo.BarService?application=foo&side=provider&weight=100"; URL providerConfiguratorUrl = URL.valueOf("override://172.24.160.179:21880/com.foo.BarService"); Map<String, String> params = new HashMap<>(); params.put("side", "provider"); params.put("configVersion", "2.7"); params.put("application", "foo"); params.put("weight", "200"); providerConfiguratorUrl = providerConfiguratorUrl.addParameters(params); // Meet the configured conditions: // same side // same port // The host of configuratorUrl is 0.0.0.0 or the host of providerConfiguratorUrl is the same as // consumerUrlV27 // same appName OverrideConfigurator configurator = new OverrideConfigurator(providerConfiguratorUrl); URL url = configurator.configure(URL.valueOf(providerUrlV27)); Assertions.assertEquals(url.getParameter("weight"), "200"); } } // Test the version after 2.7 @Test void testOverrideForVersion3() { // match { String consumerUrlV3 = "dubbo://172.24.160.179/com.foo.BarService?match_key=value&application=foo&side=consumer&timeout=100"; URL consumerConfiguratorUrl = URL.valueOf("override://0.0.0.0/com.foo.BarService"); Map<String, String> params = new HashMap<>(); params.put("side", "consumer"); params.put("configVersion", "v3.0"); params.put("application", "foo"); params.put("timeout", "10000"); ConditionMatch matcher = new ConditionMatch(); ParamMatch paramMatch = new ParamMatch(); paramMatch.setKey("match_key"); StringMatch stringMatch = new StringMatch(); stringMatch.setExact("value"); paramMatch.setValue(stringMatch); matcher.setParam(Arrays.asList(paramMatch)); consumerConfiguratorUrl = consumerConfiguratorUrl.putAttribute(MATCH_CONDITION, matcher); consumerConfiguratorUrl = consumerConfiguratorUrl.addParameters(params); OverrideConfigurator configurator = new OverrideConfigurator(consumerConfiguratorUrl); // Meet the configured conditions: // same side // The port of configuratorUrl is 0 // The host of configuratorUrl is 0.0.0.0 or the local address is the same as consumerUrlV27 // same appName URL originalURL = URL.valueOf(consumerUrlV3); Assertions.assertEquals("100", originalURL.getParameter("timeout")); URL url = configurator.configure(originalURL); Assertions.assertEquals("10000", url.getParameter("timeout")); } // mismatch { String consumerUrlV3 = "dubbo://172.24.160.179/com.foo.BarService?match_key=value&application=foo&side=consumer&timeout=100"; URL consumerConfiguratorUrl = URL.valueOf("override://0.0.0.0/com.foo.BarService"); Map<String, String> params = new HashMap<>(); params.put("side", "consumer"); params.put("configVersion", "v3.0"); params.put("application", "foo"); params.put("timeout", "10000"); ConditionMatch matcher = new ConditionMatch(); ParamMatch paramMatch = new ParamMatch(); paramMatch.setKey("match_key"); StringMatch stringMatch = new StringMatch(); stringMatch.setExact("not_match_value"); paramMatch.setValue(stringMatch); matcher.setParam(Arrays.asList(paramMatch)); consumerConfiguratorUrl = consumerConfiguratorUrl.putAttribute(MATCH_CONDITION, matcher); consumerConfiguratorUrl = consumerConfiguratorUrl.addParameters(params); OverrideConfigurator configurator = new OverrideConfigurator(consumerConfiguratorUrl); // Meet the configured conditions: // same side // The port of configuratorUrl is 0 // The host of configuratorUrl is 0.0.0.0 or the local address is the same as consumerUrlV27 // same appName URL originalURL = URL.valueOf(consumerUrlV3); Assertions.assertEquals("100", originalURL.getParameter("timeout")); URL url = configurator.configure(originalURL); Assertions.assertEquals("100", url.getParameter("timeout")); } } }
7,774
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParserTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.configurator.parser; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.cluster.configurator.parser.model.ConditionMatch; import org.apache.dubbo.rpc.cluster.configurator.parser.model.ConfiguratorConfig; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.yaml.snakeyaml.LoaderOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.SafeConstructor; import static org.apache.dubbo.common.constants.CommonConstants.LOADBALANCE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.rpc.cluster.Constants.OVERRIDE_PROVIDERS_KEY; import static org.apache.dubbo.rpc.cluster.Constants.WEIGHT_KEY; import static org.apache.dubbo.rpc.cluster.configurator.parser.model.ConfiguratorConfig.MATCH_CONDITION; /** * */ class ConfigParserTest { private String streamToString(InputStream stream) throws IOException { byte[] bytes = new byte[stream.available()]; stream.read(bytes); return new String(bytes); } @Test void snakeYamlBasicTest() throws IOException { try (InputStream yamlStream = this.getClass().getResourceAsStream("/ServiceNoApp.yml")) { Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions())); Map<String, Object> map = yaml.load(yamlStream); ConfiguratorConfig config = ConfiguratorConfig.parseFromMap(map); Assertions.assertNotNull(config); } } @Test void parseConfiguratorsServiceNoAppTest() throws Exception { try (InputStream yamlStream = this.getClass().getResourceAsStream("/ServiceNoApp.yml")) { List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream)); Assertions.assertNotNull(urls); Assertions.assertEquals(2, urls.size()); URL url = urls.get(0); Assertions.assertEquals("127.0.0.1:20880", url.getAddress()); Assertions.assertEquals(222, url.getParameter(WEIGHT_KEY, 0)); } } @Test void parseConfiguratorsServiceGroupVersionTest() throws Exception { try (InputStream yamlStream = this.getClass().getResourceAsStream("/ServiceGroupVersion.yml")) { List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream)); Assertions.assertNotNull(urls); Assertions.assertEquals(1, urls.size()); URL url = urls.get(0); Assertions.assertEquals("testgroup", url.getGroup()); Assertions.assertEquals("1.0.0", url.getVersion()); } } @Test void parseConfiguratorsServiceMultiAppsTest() throws IOException { try (InputStream yamlStream = this.getClass().getResourceAsStream("/ServiceMultiApps.yml")) { List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream)); Assertions.assertNotNull(urls); Assertions.assertEquals(4, urls.size()); URL url = urls.get(0); Assertions.assertEquals("127.0.0.1", url.getAddress()); Assertions.assertEquals(6666, url.getParameter(TIMEOUT_KEY, 0)); Assertions.assertNotNull(url.getApplication()); } } @Test void parseConfiguratorsServiceNoRuleTest() { Assertions.assertThrows(IllegalStateException.class, () -> { try (InputStream yamlStream = this.getClass().getResourceAsStream("/ServiceNoRule.yml")) { ConfigParser.parseConfigurators(streamToString(yamlStream)); Assertions.fail(); } }); } @Test void parseConfiguratorsAppMultiServicesTest() throws IOException { try (InputStream yamlStream = this.getClass().getResourceAsStream("/AppMultiServices.yml")) { String yamlFile = streamToString(yamlStream); List<URL> urls = ConfigParser.parseConfigurators(yamlFile); Assertions.assertNotNull(urls); Assertions.assertEquals(4, urls.size()); URL url = urls.get(0); Assertions.assertEquals("127.0.0.1", url.getAddress()); Assertions.assertEquals("service1", url.getServiceInterface()); Assertions.assertEquals(6666, url.getParameter(TIMEOUT_KEY, 0)); Assertions.assertEquals("random", url.getParameter(LOADBALANCE_KEY)); Assertions.assertEquals("demo-consumer", url.getApplication()); } } @Test void parseConfiguratorsAppAnyServicesTest() throws IOException { try (InputStream yamlStream = this.getClass().getResourceAsStream("/AppAnyServices.yml")) { List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream)); Assertions.assertNotNull(urls); Assertions.assertEquals(2, urls.size()); URL url = urls.get(0); Assertions.assertEquals("127.0.0.1", url.getAddress()); Assertions.assertEquals("*", url.getServiceInterface()); Assertions.assertEquals(6666, url.getParameter(TIMEOUT_KEY, 0)); Assertions.assertEquals("random", url.getParameter(LOADBALANCE_KEY)); Assertions.assertEquals("demo-consumer", url.getApplication()); } } @Test void parseConfiguratorsAppNoServiceTest() throws IOException { try (InputStream yamlStream = this.getClass().getResourceAsStream("/AppNoService.yml")) { List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream)); Assertions.assertNotNull(urls); Assertions.assertEquals(1, urls.size()); URL url = urls.get(0); Assertions.assertEquals("127.0.0.1", url.getAddress()); Assertions.assertEquals("*", url.getServiceInterface()); Assertions.assertEquals(6666, url.getParameter(TIMEOUT_KEY, 0)); Assertions.assertEquals("random", url.getParameter(LOADBALANCE_KEY)); Assertions.assertEquals("demo-consumer", url.getApplication()); } } @Test void parseConsumerSpecificProvidersTest() throws IOException { try (InputStream yamlStream = this.getClass().getResourceAsStream("/ConsumerSpecificProviders.yml")) { List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream)); Assertions.assertNotNull(urls); Assertions.assertEquals(1, urls.size()); URL url = urls.get(0); Assertions.assertEquals("127.0.0.1", url.getAddress()); Assertions.assertEquals("*", url.getServiceInterface()); Assertions.assertEquals(6666, url.getParameter(TIMEOUT_KEY, 0)); Assertions.assertEquals("random", url.getParameter(LOADBALANCE_KEY)); Assertions.assertEquals("127.0.0.1:20880", url.getParameter(OVERRIDE_PROVIDERS_KEY)); Assertions.assertEquals("demo-consumer", url.getApplication()); } } @Test void parseProviderConfigurationV3() throws IOException { try (InputStream yamlStream = this.getClass().getResourceAsStream("/ConfiguratorV3.yml")) { List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream)); Assertions.assertNotNull(urls); Assertions.assertEquals(1, urls.size()); URL url = urls.get(0); Assertions.assertEquals("0.0.0.0", url.getAddress()); Assertions.assertEquals("*", url.getServiceInterface()); Assertions.assertEquals(200, url.getParameter(WEIGHT_KEY, 0)); Assertions.assertEquals("demo-provider", url.getApplication()); URL matchURL1 = URL.valueOf("dubbo://10.0.0.1:20880/DemoService?match_key1=value1"); URL matchURL2 = URL.valueOf("dubbo://10.0.0.1:20880/DemoService2?match_key1=value1"); URL notMatchURL1 = URL.valueOf("dubbo://10.0.0.2:20880/DemoService?match_key1=value1"); // address not match URL notMatchURL2 = URL.valueOf("dubbo://10.0.0.1:20880/DemoServiceNotMatch?match_key1=value1"); // service not match URL notMatchURL3 = URL.valueOf("dubbo://10.0.0.1:20880/DemoService?match_key1=value_not_match"); // key not match ConditionMatch matcher = (ConditionMatch) url.getAttribute(MATCH_CONDITION); Assertions.assertTrue(matcher.isMatch(matchURL1.getAddress(), matchURL1)); Assertions.assertTrue(matcher.isMatch(matchURL2.getAddress(), matchURL2)); Assertions.assertFalse(matcher.isMatch(notMatchURL1.getAddress(), notMatchURL1)); Assertions.assertFalse(matcher.isMatch(notMatchURL2.getAddress(), notMatchURL2)); Assertions.assertFalse(matcher.isMatch(notMatchURL3.getAddress(), notMatchURL3)); } } @Test void parseProviderConfigurationV3Compatibility() throws IOException { try (InputStream yamlStream = this.getClass().getResourceAsStream("/ConfiguratorV3Compatibility.yml")) { List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream)); Assertions.assertNotNull(urls); Assertions.assertEquals(1, urls.size()); URL url = urls.get(0); Assertions.assertEquals("10.0.0.1:20880", url.getAddress()); Assertions.assertEquals("DemoService", url.getServiceInterface()); Assertions.assertEquals(200, url.getParameter(WEIGHT_KEY, 0)); Assertions.assertEquals("demo-provider", url.getApplication()); URL matchURL = URL.valueOf("dubbo://10.0.0.1:20880/DemoService?match_key1=value1"); URL notMatchURL = URL.valueOf("dubbo://10.0.0.1:20880/DemoService?match_key1=value_not_match"); // key not match ConditionMatch matcher = (ConditionMatch) url.getAttribute(MATCH_CONDITION); Assertions.assertTrue(matcher.isMatch(matchURL.getAddress(), matchURL)); Assertions.assertFalse(matcher.isMatch(notMatchURL.getAddress(), notMatchURL)); } } @Test void parseProviderConfigurationV3Conflict() throws IOException { try (InputStream yamlStream = this.getClass().getResourceAsStream("/ConfiguratorV3Duplicate.yml")) { List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream)); Assertions.assertNotNull(urls); Assertions.assertEquals(1, urls.size()); URL url = urls.get(0); Assertions.assertEquals("10.0.0.1:20880", url.getAddress()); Assertions.assertEquals("DemoService", url.getServiceInterface()); Assertions.assertEquals(200, url.getParameter(WEIGHT_KEY, 0)); Assertions.assertEquals("demo-provider", url.getApplication()); URL matchURL = URL.valueOf("dubbo://10.0.0.1:20880/DemoService?match_key1=value1"); URL notMatchURL = URL.valueOf("dubbo://10.0.0.1:20880/DemoService?match_key1=value_not_match"); // key not match ConditionMatch matcher = (ConditionMatch) url.getAttribute(MATCH_CONDITION); Assertions.assertTrue(matcher.isMatch(matchURL.getAddress(), matchURL)); Assertions.assertFalse(matcher.isMatch(notMatchURL.getAddress(), notMatchURL)); } } @Test void parseURLJsonArrayCompatible() { String configData = "[\"override://0.0.0.0/com.xx.Service?category=configurators&timeout=6666&disabled=true&dynamic=false&enabled=true&group=dubbo&priority=1&version=1.0\" ]"; List<URL> urls = ConfigParser.parseConfigurators(configData); Assertions.assertNotNull(urls); Assertions.assertEquals(1, urls.size()); URL url = urls.get(0); Assertions.assertEquals("0.0.0.0", url.getAddress()); Assertions.assertEquals("com.xx.Service", url.getServiceInterface()); Assertions.assertEquals(6666, url.getParameter(TIMEOUT_KEY, 0)); } }
7,775
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/consts/UrlConstant.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.configurator.consts; /** * test case url constant */ public class UrlConstant { public static final String URL_CONSUMER = "dubbo://10.20.153.10:20880/com.foo.BarService?application=foo&side=consumer"; public static final String URL_ONE = "dubbo://10.20.153.10:20880/com.foo.BarService?application=foo&timeout=1000&side=consumer"; public static final String APPLICATION_BAR_SIDE_CONSUMER_11 = "dubbo://10.20.153.11:20880/com.foo.BarService?application=bar&side=consumer"; public static final String TIMEOUT_1000_SIDE_CONSUMER_11 = "dubbo://10.20.153.11:20880/com.foo.BarService?application=bar&timeout=1000&side=consumer"; public static final String SERVICE_TIMEOUT_200 = "override://10.20.153.10/com.foo.BarService?timeout=200"; public static final String APPLICATION_BAR_SIDE_CONSUMER_10 = "dubbo://10.20.153.10:20880/com.foo.BarService?application=bar&side=consumer"; public static final String TIMEOUT_1000_SIDE_CONSUMER_10 = "dubbo://10.20.153.10:20880/com.foo.BarService?application=bar&timeout=1000&side=consumer"; }
7,776
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/DemoServiceStub.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.filter; /** * <code>TestService</code> */ class DemoServiceStub implements DemoService { public DemoServiceStub(DemoService demoService) {} public String sayHello(String name) { return name; } public int plus(int a, int b) { return a + b; } }
7,777
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/MockInvocation.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.filter; import org.apache.dubbo.rpc.AttachmentsAdapter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.model.ServiceModel; import java.util.HashMap; import java.util.Map; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; /** * MockInvocation.java */ public class MockInvocation extends RpcInvocation { private Map<String, Object> attachments; public MockInvocation() { attachments = new HashMap<>(); attachments.put(PATH_KEY, "dubbo"); attachments.put(GROUP_KEY, "dubbo"); attachments.put(VERSION_KEY, "1.0.0"); attachments.put(DUBBO_VERSION_KEY, "1.0.0"); attachments.put(TOKEN_KEY, "sfag"); attachments.put(TIMEOUT_KEY, "1000"); } @Override public String getTargetServiceUniqueName() { return null; } @Override public String getProtocolServiceKey() { return null; } public String getMethodName() { return "echo"; } @Override public String getServiceName() { return "DemoService"; } public Class<?>[] getParameterTypes() { return new Class[] {String.class}; } public Object[] getArguments() { return new Object[] {"aa"}; } public Map<String, String> getAttachments() { return new AttachmentsAdapter.ObjectToStringMap(attachments); } @Override public Map<String, Object> getObjectAttachments() { return attachments; } @Override public void setAttachment(String key, String value) { setObjectAttachment(key, value); } @Override public void setAttachment(String key, Object value) { setObjectAttachment(key, value); } @Override public void setObjectAttachment(String key, Object value) { attachments.put(key, value); } @Override public void setAttachmentIfAbsent(String key, String value) { setObjectAttachmentIfAbsent(key, value); } @Override public void setAttachmentIfAbsent(String key, Object value) { setObjectAttachmentIfAbsent(key, value); } @Override public void setObjectAttachmentIfAbsent(String key, Object value) { attachments.put(key, value); } public Invoker<?> getInvoker() { return null; } @Override public void setServiceModel(ServiceModel serviceModel) {} @Override public ServiceModel getServiceModel() { return null; } @Override public Object put(Object key, Object value) { return null; } @Override public Object get(Object key) { return null; } @Override public Map<Object, Object> getAttributes() { return null; } public String getAttachment(String key) { return (String) getObjectAttachments().get(key); } @Override public Object getObjectAttachment(String key) { return attachments.get(key); } public String getAttachment(String key, String defaultValue) { return (String) getObjectAttachments().get(key); } @Override public Object getObjectAttachment(String key, Object defaultValue) { Object result = attachments.get(key); if (result == null) { return defaultValue; } return result; } }
7,778
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/DefaultFilterChainBuilderTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.filter; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.protocol.AbstractInvoker; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.REFERENCE_FILTER_KEY; class DefaultFilterChainBuilderTest { @Test void testBuildInvokerChainForLocalReference() { DefaultFilterChainBuilder defaultFilterChainBuilder = new DefaultFilterChainBuilder(); // verify that no filter is built by default URL urlWithoutFilter = URL.valueOf("injvm://127.0.0.1/DemoService").addParameter(INTERFACE_KEY, DemoService.class.getName()); urlWithoutFilter = urlWithoutFilter.setScopeModel(ApplicationModel.defaultModel()); AbstractInvoker<DemoService> invokerWithoutFilter = new AbstractInvoker<DemoService>(DemoService.class, urlWithoutFilter) { @Override protected Result doInvoke(Invocation invocation) { return null; } }; Invoker<?> invokerAfterBuild = defaultFilterChainBuilder.buildInvokerChain(invokerWithoutFilter, REFERENCE_FILTER_KEY, CONSUMER); // verify that if LogFilter is configured, LogFilter should exist in the filter chain URL urlWithFilter = URL.valueOf("injvm://127.0.0.1/DemoService") .addParameter(INTERFACE_KEY, DemoService.class.getName()) .addParameter(REFERENCE_FILTER_KEY, "log"); urlWithFilter = urlWithFilter.setScopeModel(ApplicationModel.defaultModel()); AbstractInvoker<DemoService> invokerWithFilter = new AbstractInvoker<DemoService>(DemoService.class, urlWithFilter) { @Override protected Result doInvoke(Invocation invocation) { return null; } }; invokerAfterBuild = defaultFilterChainBuilder.buildInvokerChain(invokerWithFilter, REFERENCE_FILTER_KEY, CONSUMER); Assertions.assertTrue(invokerAfterBuild instanceof FilterChainBuilder.CallbackRegistrationInvoker); } @Test void testBuildInvokerChainForRemoteReference() { DefaultFilterChainBuilder defaultFilterChainBuilder = new DefaultFilterChainBuilder(); // verify that no filter is built by default URL urlWithoutFilter = URL.valueOf("dubbo://127.0.0.1:20880/DemoService") .addParameter(INTERFACE_KEY, DemoService.class.getName()); urlWithoutFilter = urlWithoutFilter.setScopeModel(ApplicationModel.defaultModel()); AbstractInvoker<DemoService> invokerWithoutFilter = new AbstractInvoker<DemoService>(DemoService.class, urlWithoutFilter) { @Override protected Result doInvoke(Invocation invocation) { return null; } }; Invoker<?> invokerAfterBuild = defaultFilterChainBuilder.buildInvokerChain(invokerWithoutFilter, REFERENCE_FILTER_KEY, CONSUMER); // Assertions.assertTrue(invokerAfterBuild instanceof AbstractInvoker); // verify that if LogFilter is configured, LogFilter should exist in the filter chain URL urlWithFilter = URL.valueOf("dubbo://127.0.0.1:20880/DemoService") .addParameter(INTERFACE_KEY, DemoService.class.getName()) .addParameter(REFERENCE_FILTER_KEY, "log"); urlWithFilter = urlWithFilter.setScopeModel(ApplicationModel.defaultModel()); AbstractInvoker<DemoService> invokerWithFilter = new AbstractInvoker<DemoService>(DemoService.class, urlWithFilter) { @Override protected Result doInvoke(Invocation invocation) { return null; } }; invokerAfterBuild = defaultFilterChainBuilder.buildInvokerChain(invokerWithFilter, REFERENCE_FILTER_KEY, CONSUMER); Assertions.assertTrue(invokerAfterBuild instanceof FilterChainBuilder.CallbackRegistrationInvoker); } }
7,779
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/LogFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.filter; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER; @Activate(group = CONSUMER, value = "log") public class LogFilter implements Filter, Filter.Listener { @Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { return invoker.invoke(invocation); } @Override public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) {} @Override public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) {} }
7,780
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/AbstractObservationFilterTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.filter; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.TracingConfig; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.BaseFilter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.model.ApplicationModel; import io.micrometer.tracing.test.SampleTestRunner; import org.junit.jupiter.api.AfterEach; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; abstract class AbstractObservationFilterTest extends SampleTestRunner { ApplicationModel applicationModel; RpcInvocation invocation; BaseFilter filter; Invoker<?> invoker = mock(Invoker.class); static final String INTERFACE_NAME = "org.apache.dubbo.MockInterface"; static final String METHOD_NAME = "mockMethod"; static final String GROUP = "mockGroup"; static final String VERSION = "1.0.0"; @AfterEach public void teardown() { if (applicationModel != null) { applicationModel.destroy(); } } abstract BaseFilter createFilter(ApplicationModel applicationModel); void setupConfig() { ApplicationConfig config = new ApplicationConfig(); config.setName("MockObservations"); applicationModel = ApplicationModel.defaultModel(); applicationModel.getApplicationConfigManager().setApplication(config); invocation = new RpcInvocation(new MockInvocation()); invocation.addInvokedInvoker(invoker); applicationModel.getBeanFactory().registerBean(getObservationRegistry()); TracingConfig tracingConfig = new TracingConfig(); tracingConfig.setEnabled(true); applicationModel.getApplicationConfigManager().setTracing(tracingConfig); filter = createFilter(applicationModel); given(invoker.invoke(invocation)).willReturn(new AppResponse("success")); initParam(); } private void initParam() { invocation.setTargetServiceUniqueName(GROUP + "/" + INTERFACE_NAME + ":" + VERSION); invocation.setMethodName(METHOD_NAME); invocation.setParameterTypes(new Class[] {String.class}); } }
7,781
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/ObservationSenderFilterTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.filter; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.cluster.filter.support.ObservationSenderFilter; import org.apache.dubbo.rpc.model.ApplicationModel; import io.micrometer.common.KeyValues; import io.micrometer.core.tck.MeterRegistryAssert; import io.micrometer.tracing.test.SampleTestRunner; import io.micrometer.tracing.test.simple.SpansAssert; import org.assertj.core.api.BDDAssertions; class ObservationSenderFilterTest extends AbstractObservationFilterTest { @Override public SampleTestRunner.SampleTestRunnerConsumer yourCode() { return (buildingBlocks, meterRegistry) -> { setupConfig(); setupAttachments(); ObservationSenderFilter senderFilter = (ObservationSenderFilter) filter; senderFilter.invoke(invoker, invocation); senderFilter.onResponse(null, invoker, invocation); BDDAssertions.then(invocation.getObjectAttachment("X-B3-TraceId")).isNotNull(); MeterRegistryAssert.then(meterRegistry) .hasMeterWithNameAndTags( "rpc.client.duration", KeyValues.of( "net.peer.name", "foo.bar.com", "net.peer.port", "8080", "rpc.method", "mockMethod", "rpc.service", "DemoService", "rpc.system", "apache_dubbo")); SpansAssert.then(buildingBlocks.getFinishedSpans()) .hasASpanWithNameIgnoreCase("DemoService/mockMethod", spanAssert -> spanAssert .hasTag("net.peer.name", "foo.bar.com") .hasTag("net.peer.port", "8080") .hasTag("rpc.method", "mockMethod") .hasTag("rpc.service", "DemoService") .hasTag("rpc.system", "apache_dubbo")); }; } void setupAttachments() { RpcContext.getClientAttachment() .setUrl(URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&side=consumer")); RpcContext.getClientAttachment().setRemoteAddress("foo.bar.com", 8080); } @Override ClusterFilter createFilter(ApplicationModel applicationModel) { return new ObservationSenderFilter(applicationModel); } }
7,782
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/DemoServiceImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.filter; class DemoServiceImpl implements DemoService { @Override public String sayHello(String name) { return name; } @Override public int plus(int a, int b) { return 0; } }
7,783
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/DemoServiceLocal.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.filter; /** * <code>TestService</code> */ class DemoServiceLocal implements DemoService { public DemoServiceLocal(DemoService demoService) {} public String sayHello(String name) { return name; } public int plus(int a, int b) { return a + b; } public void ondisconnect() {} public void onconnect() {} }
7,784
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/MockService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.filter; /** * MockService.java * */ class MockService implements DemoService { public String sayHello(String name) { return name; } public int plus(int a, int b) { return a + b; } }
7,785
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/DemoService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.filter; /** * <code>TestService</code> */ public interface DemoService { String sayHello(String name); int plus(int a, int b); }
7,786
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/MetricsClusterFilterTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.filter; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.metrics.collector.DefaultMetricsCollector; import org.apache.dubbo.metrics.filter.MetricsFilter; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.model.sample.CounterMetricSample; import org.apache.dubbo.metrics.model.sample.MetricSample; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.cluster.filter.support.MetricsClusterFilter; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; import java.util.stream.Collectors; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; class MetricsClusterFilterTest { private ApplicationModel applicationModel; private MetricsFilter filter; private MetricsClusterFilter metricsClusterFilter; private DefaultMetricsCollector collector; private RpcInvocation invocation; private final Invoker<?> invoker = mock(Invoker.class); private static final String INTERFACE_NAME = "org.apache.dubbo.MockInterface"; private static final String METHOD_NAME = "mockMethod"; private static final String GROUP = "mockGroup"; private static final String VERSION = "1.0.0"; private String side; private AtomicBoolean initApplication = new AtomicBoolean(false); @BeforeEach public void setup() { ApplicationConfig config = new ApplicationConfig(); config.setName("MockMetrics"); // RpcContext.getContext().setAttachment("MockMetrics","MockMetrics"); applicationModel = ApplicationModel.defaultModel(); applicationModel.getApplicationConfigManager().setApplication(config); invocation = new RpcInvocation(); filter = new MetricsFilter(); collector = applicationModel.getBeanFactory().getOrRegisterBean(DefaultMetricsCollector.class); if (!initApplication.get()) { collector.collectApplication(); initApplication.set(true); } filter.setApplicationModel(applicationModel); side = CommonConstants.CONSUMER; invocation.setInvoker(new TestMetricsInvoker(side)); RpcContext.getServiceContext() .setUrl(URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&side=" + side)); metricsClusterFilter = new MetricsClusterFilter(); metricsClusterFilter.setApplicationModel(applicationModel); } @AfterEach public void teardown() { applicationModel.destroy(); } @Test public void testNoProvider() { testClusterFilterError( RpcException.FORBIDDEN_EXCEPTION, MetricsKey.METRIC_REQUESTS_SERVICE_UNAVAILABLE_FAILED.getNameByType(CommonConstants.CONSUMER)); } private void testClusterFilterError(int errorCode, String name) { collector.setCollectEnabled(true); given(invoker.invoke(invocation)).willThrow(new RpcException(errorCode)); initParam(); Long count = 1L; for (int i = 0; i < count; i++) { try { metricsClusterFilter.invoke(invoker, invocation); } catch (Exception e) { Assertions.assertTrue(e instanceof RpcException); metricsClusterFilter.onError(e, invoker, invocation); } } Map<String, MetricSample> metricsMap = getMetricsMap(); Assertions.assertTrue(metricsMap.containsKey(name)); MetricSample sample = metricsMap.get(name); Assertions.assertSame(((CounterMetricSample) sample).getValue().longValue(), count); teardown(); } private void initParam() { invocation.setTargetServiceUniqueName(GROUP + "/" + INTERFACE_NAME + ":" + VERSION); invocation.setMethodName(METHOD_NAME); invocation.setParameterTypes(new Class[] {String.class}); } private Map<String, MetricSample> getMetricsMap() { List<MetricSample> samples = collector.collect(); List<MetricSample> samples1 = new ArrayList<>(); for (MetricSample sample : samples) { if (sample.getName().contains("dubbo.thread.pool")) { continue; } samples1.add(sample); } return samples1.stream().collect(Collectors.toMap(MetricSample::getName, Function.identity())); } public class TestMetricsInvoker implements Invoker { private String side; public TestMetricsInvoker(String side) { this.side = side; } @Override public Class getInterface() { return null; } @Override public Result invoke(Invocation invocation) throws RpcException { return null; } @Override public URL getUrl() { return URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&side=" + side); } @Override public boolean isAvailable() { return true; } @Override public void destroy() {} } }
7,787
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/DemoServiceMock.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.filter; /** * MockService.java * */ class DemoServiceMock implements DemoService { public String sayHello(String name) { return name; } public int plus(int a, int b) { return a + b; } }
7,788
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/RouterSnapshotFilterTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.router; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ServiceModel; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.mockito.Mockito; class RouterSnapshotFilterTest { @BeforeAll static void setUp() { RpcContext.getServiceContext().setNeedPrintRouterSnapshot(false); } @Test void test() { FrameworkModel frameworkModel = new FrameworkModel(); RouterSnapshotSwitcher routerSnapshotSwitcher = frameworkModel.getBeanFactory().getBean(RouterSnapshotSwitcher.class); RouterSnapshotFilter routerSnapshotFilter = new RouterSnapshotFilter(frameworkModel); Invoker invoker = Mockito.mock(Invoker.class); Invocation invocation = Mockito.mock(Invocation.class); ServiceModel serviceModel = Mockito.mock(ServiceModel.class); Mockito.when(serviceModel.getServiceKey()).thenReturn("TestKey"); Mockito.when(invocation.getServiceModel()).thenReturn(serviceModel); routerSnapshotFilter.invoke(invoker, invocation); Mockito.verify(invoker, Mockito.times(1)).invoke(invocation); Assertions.assertFalse(RpcContext.getServiceContext().isNeedPrintRouterSnapshot()); routerSnapshotSwitcher.addEnabledService("Test"); routerSnapshotFilter.invoke(invoker, invocation); Assertions.assertFalse(RpcContext.getServiceContext().isNeedPrintRouterSnapshot()); routerSnapshotSwitcher.removeEnabledService("Test"); routerSnapshotFilter.invoke(invoker, invocation); Assertions.assertFalse(RpcContext.getServiceContext().isNeedPrintRouterSnapshot()); routerSnapshotSwitcher.addEnabledService("TestKey"); routerSnapshotFilter.invoke(invoker, invocation); Assertions.assertTrue(RpcContext.getServiceContext().isNeedPrintRouterSnapshot()); routerSnapshotFilter.onResponse(null, null, null); Assertions.assertFalse(RpcContext.getServiceContext().isNeedPrintRouterSnapshot()); routerSnapshotSwitcher.addEnabledService("TestKey"); routerSnapshotFilter.invoke(invoker, invocation); Assertions.assertTrue(RpcContext.getServiceContext().isNeedPrintRouterSnapshot()); routerSnapshotFilter.onError(null, null, null); Assertions.assertFalse(RpcContext.getServiceContext().isNeedPrintRouterSnapshot()); routerSnapshotSwitcher.removeEnabledService("TestKey"); routerSnapshotFilter.invoke(invoker, invocation); Assertions.assertFalse(RpcContext.getServiceContext().isNeedPrintRouterSnapshot()); routerSnapshotFilter.onError(null, null, null); Assertions.assertFalse(RpcContext.getServiceContext().isNeedPrintRouterSnapshot()); } }
7,789
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/ConfigConditionRouterTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.router; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.ExponentialBackoffRetry; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @Disabled("FIXME This is not a formal UT") class ConfigConditionRouterTest { private static CuratorFramework client; @BeforeEach public void init() { client = CuratorFrameworkFactory.newClient( "127.0.0.1:2181", 60 * 1000, 60 * 1000, new ExponentialBackoffRetry(1000, 3)); client.start(); } @Test void normalConditionRuleApplicationLevelTest() { String serviceStr = "---\n" + "scope: application\n" + "force: true\n" + "runtime: true\n" + "enabled: true\n" + "priority: 2\n" + "key: demo-consumer\n" + "conditions:\n" + " - method=notExitMethod => \n" + "..."; try { String servicePath = "/dubbo/config/demo-consumer/condition-router"; if (client.checkExists().forPath(servicePath) == null) { client.create().creatingParentsIfNeeded().forPath(servicePath); } setData(servicePath, serviceStr); } catch (Exception e) { e.printStackTrace(); } } @Test void normalConditionRuleApplicationServiceLevelTest() { String serviceStr = "---\n" + "scope: application\n" + "force: true\n" + "runtime: false\n" + "enabled: true\n" + "priority: 2\n" + "key: demo-consumer\n" + "conditions:\n" + " - interface=org.apache.dubbo.demo.DemoService&method=sayHello => host=30.5.120.37\n" + " - method=routeMethod1 => host=30.5.120.37\n" + "..."; try { String servicePath = "/dubbo/config/demo-consumer/condition-router"; if (client.checkExists().forPath(servicePath) == null) { client.create().creatingParentsIfNeeded().forPath(servicePath); } setData(servicePath, serviceStr); } catch (Exception e) { e.printStackTrace(); } } @Test void normalConditionRuleServiceLevelTest() { String serviceStr = "---\n" + "scope: service\n" + "force: true\n" + "runtime: true\n" + "enabled: true\n" + "priority: 1\n" + "key: org.apache.dubbo.demo.DemoService\n" + "conditions:\n" + " - method!=sayHello =>\n" + " - method=routeMethod1 => address=30.5.120.37:20880\n" + "..."; // String serviceStr = ""; try { String servicePath = "/dubbo/config/org.apache.dubbo.demo.DemoService/condition-router"; if (client.checkExists().forPath(servicePath) == null) { client.create().creatingParentsIfNeeded().forPath(servicePath); } setData(servicePath, serviceStr); } catch (Exception e) { e.printStackTrace(); } } @Test void abnormalNoruleConditionRuleTest() { String serviceStr = "---\n" + "scope: service\n" + "force: true\n" + "runtime: false\n" + "enabled: true\n" + "priority: 1\n" + "key: org.apache.dubbo.demo.DemoService\n" + "..."; try { String servicePath = "/dubbo/config/org.apache.dubbo.demo.DemoService/condition-router"; if (client.checkExists().forPath(servicePath) == null) { client.create().creatingParentsIfNeeded().forPath(servicePath); } setData(servicePath, serviceStr); } catch (Exception e) { e.printStackTrace(); } } private void setData(String path, String data) throws Exception { client.setData().forPath(path, data.getBytes()); } }
7,790
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/MockInvoker.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.router; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; public class MockInvoker<T> implements Invoker<T> { private boolean available = false; private URL url; public MockInvoker() {} public MockInvoker(URL url) { super(); this.url = url; } public MockInvoker(URL url, boolean available) { super(); this.url = url; this.available = available; } public MockInvoker(boolean available) { this.available = available; } @Override public Class<T> getInterface() { return null; } public URL getUrl() { return url; } @Override public boolean isAvailable() { return available; } @Override public Result invoke(Invocation invocation) throws RpcException { return null; } @Override public void destroy() {} }
7,791
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshAppRuleListenerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.router.mesh.route; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.configcenter.ConfigChangeType; import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent; import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; import org.apache.dubbo.rpc.cluster.router.mesh.util.MeshRuleListener; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import org.yaml.snakeyaml.LoaderOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.SafeConstructor; import static org.apache.dubbo.rpc.cluster.router.mesh.route.MeshRuleConstants.MESH_RULE_DATA_ID_SUFFIX; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; class MeshAppRuleListenerTest { private static final String rule1 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: DestinationRule\n" + "metadata: { name: demo-route }\n" + "spec:\n" + " host: demo\n" + " subsets:\n" + " - labels: { env-sign: xxx, tag1: hello }\n" + " name: isolation\n" + " - labels: { env-sign: yyy }\n" + " name: testing-trunk\n" + " - labels: { env-sign: zzz }\n" + " name: testing\n" + " trafficPolicy:\n" + " loadBalancer: { simple: ROUND_ROBIN }\n" + "\n"; private static final String rule2 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: VirtualService\n" + "metadata: { name: demo-route }\n" + "spec:\n" + " dubbo:\n" + " - routedetail:\n" + " - match:\n" + " - sourceLabels: {trafficLabel: xxx}\n" + " name: xxx-project\n" + " route:\n" + " - destination: {host: demo, subset: isolation}\n" + " - match:\n" + " - sourceLabels: {trafficLabel: testing-trunk}\n" + " name: testing-trunk\n" + " route:\n" + " - destination: {host: demo, subset: testing-trunk}\n" + " - name: testing\n" + " route:\n" + " - destination: {host: demo, subset: testing}\n" + " services:\n" + " - {regex: ccc}\n" + " hosts: [demo]\n"; private static final String rule3 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: DestinationRule\n" + "spec:\n" + " host: demo\n" + " subsets:\n" + " - labels: { env-sign: xxx, tag1: hello }\n" + " name: isolation\n" + " - labels: { env-sign: yyy }\n" + " name: testing-trunk\n" + " - labels: { env-sign: zzz }\n" + " name: testing\n" + " trafficPolicy:\n" + " loadBalancer: { simple: ROUND_ROBIN }\n"; private static final String rule4 = "apiVersionservice.dubbo.apache.org/v1alpha1\n"; private static final String rule5 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: DestinationRule\n" + "metadata: { name: demo-route.Type1 }\n" + "spec:\n" + " host: demo\n" + "\n"; private static final String rule6 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: VirtualService\n" + "metadata: { name: demo-route.Type1 }\n" + "spec:\n" + " hosts: [demo]\n"; private static final String rule7 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: DestinationRule\n" + "metadata: { name: demo-route.Type2 }\n" + "spec:\n" + " host: demo\n" + "\n"; private static final String rule8 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: VirtualService\n" + "metadata: { name: demo-route.Type2 }\n" + "spec:\n" + " hosts: [demo]\n"; @Test void testStandard() { MeshAppRuleListener meshAppRuleListener = new MeshAppRuleListener("demo-route"); StandardMeshRuleRouter standardMeshRuleRouter = Mockito.spy(new StandardMeshRuleRouter(URL.valueOf(""))); meshAppRuleListener.register(standardMeshRuleRouter); meshAppRuleListener.receiveConfigInfo(rule1 + "---\n" + rule2); ArgumentCaptor<String> appCaptor = ArgumentCaptor.forClass(String.class); ArgumentCaptor<List<Map<String, Object>>> ruleCaptor = ArgumentCaptor.forClass(List.class); verify(standardMeshRuleRouter, times(1)).onRuleChange(appCaptor.capture(), ruleCaptor.capture()); List<Map<String, Object>> rulesReceived = ruleCaptor.getValue(); assertEquals(2, rulesReceived.size()); Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions())); Assertions.assertTrue(rulesReceived.contains(yaml.load(rule1))); Assertions.assertTrue(rulesReceived.contains(yaml.load(rule2))); Assertions.assertEquals("demo-route", appCaptor.getValue()); meshAppRuleListener.receiveConfigInfo(""); verify(standardMeshRuleRouter, times(1)).clearRule("demo-route"); } @Test void register() { MeshAppRuleListener meshAppRuleListener = new MeshAppRuleListener("demo-route"); StandardMeshRuleRouter standardMeshRuleRouter1 = Mockito.spy(new StandardMeshRuleRouter(URL.valueOf(""))); StandardMeshRuleRouter standardMeshRuleRouter2 = Mockito.spy(new StandardMeshRuleRouter(URL.valueOf(""))); meshAppRuleListener.register(standardMeshRuleRouter1); Assertions.assertEquals( 1, meshAppRuleListener .getMeshRuleDispatcher() .getListenerMap() .get(MeshRuleConstants.STANDARD_ROUTER_KEY) .size()); meshAppRuleListener.receiveConfigInfo(rule1 + "---\n" + rule2); meshAppRuleListener.register(standardMeshRuleRouter2); Assertions.assertEquals( 2, meshAppRuleListener .getMeshRuleDispatcher() .getListenerMap() .get(MeshRuleConstants.STANDARD_ROUTER_KEY) .size()); ArgumentCaptor<String> appCaptor = ArgumentCaptor.forClass(String.class); ArgumentCaptor<List<Map<String, Object>>> ruleCaptor = ArgumentCaptor.forClass(List.class); verify(standardMeshRuleRouter1, times(1)).onRuleChange(appCaptor.capture(), ruleCaptor.capture()); List<Map<String, Object>> rulesReceived = ruleCaptor.getValue(); assertEquals(2, rulesReceived.size()); Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions())); Assertions.assertTrue(rulesReceived.contains(yaml.load(rule1))); Assertions.assertTrue(rulesReceived.contains(yaml.load(rule2))); Assertions.assertEquals("demo-route", appCaptor.getValue()); verify(standardMeshRuleRouter2, times(1)).onRuleChange(appCaptor.capture(), ruleCaptor.capture()); rulesReceived = ruleCaptor.getValue(); assertEquals(2, rulesReceived.size()); Assertions.assertTrue(rulesReceived.contains(yaml.load(rule1))); Assertions.assertTrue(rulesReceived.contains(yaml.load(rule2))); Assertions.assertEquals("demo-route", appCaptor.getValue()); } @Test void unregister() { MeshAppRuleListener meshAppRuleListener = new MeshAppRuleListener("demo-route"); StandardMeshRuleRouter standardMeshRuleRouter1 = Mockito.spy(new StandardMeshRuleRouter(URL.valueOf(""))); StandardMeshRuleRouter standardMeshRuleRouter2 = Mockito.spy(new StandardMeshRuleRouter(URL.valueOf(""))); meshAppRuleListener.register(standardMeshRuleRouter1); Assertions.assertEquals( 1, meshAppRuleListener .getMeshRuleDispatcher() .getListenerMap() .get(MeshRuleConstants.STANDARD_ROUTER_KEY) .size()); meshAppRuleListener.receiveConfigInfo(rule1 + "---\n" + rule2); meshAppRuleListener.register(standardMeshRuleRouter2); Assertions.assertEquals( 2, meshAppRuleListener .getMeshRuleDispatcher() .getListenerMap() .get(MeshRuleConstants.STANDARD_ROUTER_KEY) .size()); meshAppRuleListener.unregister(standardMeshRuleRouter1); Assertions.assertEquals( 1, meshAppRuleListener .getMeshRuleDispatcher() .getListenerMap() .get(MeshRuleConstants.STANDARD_ROUTER_KEY) .size()); meshAppRuleListener.unregister(standardMeshRuleRouter2); Assertions.assertEquals( 0, meshAppRuleListener.getMeshRuleDispatcher().getListenerMap().size()); } @Test void process() { MeshAppRuleListener meshAppRuleListener = new MeshAppRuleListener("demo-route"); StandardMeshRuleRouter standardMeshRuleRouter = Mockito.spy(new StandardMeshRuleRouter(URL.valueOf(""))); meshAppRuleListener.register(standardMeshRuleRouter); ConfigChangedEvent configChangedEvent = new ConfigChangedEvent( "demo-route" + MESH_RULE_DATA_ID_SUFFIX, DynamicConfiguration.DEFAULT_GROUP, rule1 + "---\n" + rule2, ConfigChangeType.ADDED); meshAppRuleListener.process(configChangedEvent); ArgumentCaptor<String> appCaptor = ArgumentCaptor.forClass(String.class); ArgumentCaptor<List<Map<String, Object>>> ruleCaptor = ArgumentCaptor.forClass(List.class); verify(standardMeshRuleRouter, times(1)).onRuleChange(appCaptor.capture(), ruleCaptor.capture()); List<Map<String, Object>> rulesReceived = ruleCaptor.getValue(); assertEquals(2, rulesReceived.size()); Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions())); Assertions.assertTrue(rulesReceived.contains(yaml.load(rule1))); Assertions.assertTrue(rulesReceived.contains(yaml.load(rule2))); configChangedEvent = new ConfigChangedEvent( "demo-route" + MESH_RULE_DATA_ID_SUFFIX, DynamicConfiguration.DEFAULT_GROUP, rule1 + "---\n" + rule2, ConfigChangeType.MODIFIED); meshAppRuleListener.process(configChangedEvent); verify(standardMeshRuleRouter, times(2)).onRuleChange(appCaptor.capture(), ruleCaptor.capture()); rulesReceived = ruleCaptor.getValue(); assertEquals(2, rulesReceived.size()); Assertions.assertTrue(rulesReceived.contains(yaml.load(rule1))); Assertions.assertTrue(rulesReceived.contains(yaml.load(rule2))); configChangedEvent = new ConfigChangedEvent( "demo-route" + MESH_RULE_DATA_ID_SUFFIX, DynamicConfiguration.DEFAULT_GROUP, "", ConfigChangeType.DELETED); meshAppRuleListener.process(configChangedEvent); verify(standardMeshRuleRouter, times(1)).clearRule("demo-route"); } @Test void testUnknownRule() { MeshAppRuleListener meshAppRuleListener = new MeshAppRuleListener("demo-route"); StandardMeshRuleRouter standardMeshRuleRouter = Mockito.spy(new StandardMeshRuleRouter(URL.valueOf(""))); meshAppRuleListener.register(standardMeshRuleRouter); meshAppRuleListener.receiveConfigInfo(rule3 + "---\n" + rule2); ArgumentCaptor<String> appCaptor = ArgumentCaptor.forClass(String.class); ArgumentCaptor<List<Map<String, Object>>> ruleCaptor = ArgumentCaptor.forClass(List.class); verify(standardMeshRuleRouter, times(1)).onRuleChange(appCaptor.capture(), ruleCaptor.capture()); List<Map<String, Object>> rulesReceived = ruleCaptor.getValue(); assertEquals(1, rulesReceived.size()); Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions())); Assertions.assertTrue(rulesReceived.contains(yaml.load(rule2))); meshAppRuleListener.receiveConfigInfo(rule1 + "---\n" + rule4); verify(standardMeshRuleRouter, times(2)).onRuleChange(appCaptor.capture(), ruleCaptor.capture()); rulesReceived = ruleCaptor.getValue(); assertEquals(1, rulesReceived.size()); Assertions.assertTrue(rulesReceived.contains(yaml.load(rule1))); meshAppRuleListener.receiveConfigInfo(rule3 + "---\n" + rule4); verify(standardMeshRuleRouter, times(1)).clearRule("demo-route"); } @Test void testMultipleRule() { MeshAppRuleListener meshAppRuleListener = new MeshAppRuleListener("demo-route"); AtomicInteger count = new AtomicInteger(0); MeshRuleListener listener1 = new MeshRuleListener() { @Override public void onRuleChange(String appName, List<Map<String, Object>> rules) { Assertions.assertEquals("demo-route", appName); Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions())); Assertions.assertTrue(rules.contains(yaml.load(rule5))); Assertions.assertTrue(rules.contains(yaml.load(rule6))); count.incrementAndGet(); } @Override public void clearRule(String appName) {} @Override public String ruleSuffix() { return "Type1"; } }; MeshRuleListener listener2 = new MeshRuleListener() { @Override public void onRuleChange(String appName, List<Map<String, Object>> rules) { Assertions.assertEquals("demo-route", appName); Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions())); Assertions.assertTrue(rules.contains(yaml.load(rule7))); Assertions.assertTrue(rules.contains(yaml.load(rule8))); count.incrementAndGet(); } @Override public void clearRule(String appName) {} @Override public String ruleSuffix() { return "Type2"; } }; MeshRuleListener listener4 = new MeshRuleListener() { @Override public void onRuleChange(String appName, List<Map<String, Object>> rules) { Assertions.fail(); } @Override public void clearRule(String appName) { Assertions.assertEquals("demo-route", appName); count.incrementAndGet(); } @Override public String ruleSuffix() { return "Type4"; } }; StandardMeshRuleRouter standardMeshRuleRouter = Mockito.spy(new StandardMeshRuleRouter(URL.valueOf(""))); meshAppRuleListener.register(standardMeshRuleRouter); meshAppRuleListener.register(listener1); meshAppRuleListener.register(listener2); meshAppRuleListener.register(listener4); meshAppRuleListener.receiveConfigInfo( rule1 + "---\n" + rule2 + "---\n" + rule5 + "---\n" + rule6 + "---\n" + rule7 + "---\n" + rule8); ArgumentCaptor<String> appCaptor = ArgumentCaptor.forClass(String.class); ArgumentCaptor<List<Map<String, Object>>> ruleCaptor = ArgumentCaptor.forClass(List.class); verify(standardMeshRuleRouter, times(1)).onRuleChange(appCaptor.capture(), ruleCaptor.capture()); List<Map<String, Object>> rulesReceived = ruleCaptor.getValue(); assertEquals(2, rulesReceived.size()); Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions())); Assertions.assertTrue(rulesReceived.contains(yaml.load(rule1))); Assertions.assertTrue(rulesReceived.contains(yaml.load(rule2))); Assertions.assertEquals("demo-route", appCaptor.getValue()); Assertions.assertEquals(3, count.get()); } }
7,792
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleRouterTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.router.mesh.route; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.Holder; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.cluster.router.mesh.util.TracingContextProvider; import org.apache.dubbo.rpc.cluster.router.state.BitList; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ModuleModel; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.yaml.snakeyaml.LoaderOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.SafeConstructor; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; class MeshRuleRouterTest { private static final String rule1 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: DestinationRule\n" + "metadata: { name: demo-route }\n" + "spec:\n" + " host: demo\n" + " subsets:\n" + " - labels: { env-sign: xxx, tag1: hello }\n" + " name: isolation\n" + " - labels: { env-sign: yyy }\n" + " name: testing-trunk\n" + " - labels: { env-sign: zzz }\n" + " name: testing\n" + " trafficPolicy:\n" + " loadBalancer: { simple: ROUND_ROBIN }\n" + "\n"; private static final String rule2 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: VirtualService\n" + "metadata: { name: demo-route }\n" + "spec:\n" + " dubbo:\n" + " - routedetail:\n" + " - match:\n" + " - attachments: \n" + " dubboContext: {trafficLabel: {regex: xxx}}\n" + " name: xxx-project\n" + " route:\n" + " - destination: {host: demo, subset: isolation}\n" + " - match:\n" + " - attachments: \n" + " dubboContext: {trafficLabel: {regex: testing-trunk}}\n" + " name: testing-trunk\n" + " route:\n" + " - destination:\n" + " host: demo\n" + " subset: testing-trunk\n" + " fallback:\n" + " host: demo\n" + " subset: testing\n" + " - name: testing\n" + " route:\n" + " - destination: {host: demo, subset: testing}\n" + " services:\n" + " - {regex: ccc}\n" + " hosts: [demo]\n"; private static final String rule3 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: VirtualService\n" + "metadata: { name: demo-route }\n" + "spec:\n" + " dubbo:\n" + " - routedetail:\n" + " - match:\n" + " - attachments: \n" + " dubboContext: {trafficLabel: {regex: xxx}}\n" + " name: xxx-project\n" + " route:\n" + " - destination: {host: demo, subset: isolation}\n" + " - match:\n" + " - attachments: \n" + " dubboContext: {trafficLabel: {regex: testing-trunk}}\n" + " name: testing-trunk\n" + " route:\n" + " - destination:\n" + " host: demo\n" + " subset: testing-trunk\n" + " fallback:\n" + " host: demo\n" + " subset: testing\n" + " - match:\n" + " - attachments: \n" + " dubboContext: {trafficLabel: {regex: testing}}\n" + " name: testing\n" + " route:\n" + " - destination: {host: demo, subset: testing}\n" + " hosts: [demo]\n"; private static final String rule4 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: VirtualService\n" + "metadata: { name: demo-route }\n" + "spec:\n" + " dubbo:\n" + " - routedetail:\n" + " - match:\n" + " - attachments: \n" + " dubboContext: {trafficLabel: {regex: xxx}}\n" + " name: xxx-project\n" + " route:\n" + " - destination: {host: demo, subset: isolation}\n" + " - match:\n" + " - attachments: \n" + " dubboContext: {trafficLabel: {regex: testing-trunk}}\n" + " name: testing-trunk\n" + " route:\n" + " - destination:\n" + " host: demo\n" + " subset: testing-trunk\n" + " fallback:\n" + " destination:\n" + " host: demo\n" + " subset: testing\n" + " - weight: 10\n" + " destination:\n" + " host: demo\n" + " subset: isolation\n" + " - match:\n" + " - attachments: \n" + " dubboContext: {trafficLabel: {regex: testing}}\n" + " name: testing\n" + " route:\n" + " - destination: {host: demo, subset: testing}\n" + " hosts: [demo]\n"; private ModuleModel originModel; private ModuleModel moduleModel; private MeshRuleManager meshRuleManager; private Set<TracingContextProvider> tracingContextProviders; private URL url; @BeforeEach public void setup() { originModel = ApplicationModel.defaultModel().getDefaultModule(); moduleModel = Mockito.spy(originModel); ScopeBeanFactory originBeanFactory = originModel.getBeanFactory(); ScopeBeanFactory beanFactory = Mockito.spy(originBeanFactory); when(moduleModel.getBeanFactory()).thenReturn(beanFactory); meshRuleManager = Mockito.mock(MeshRuleManager.class); when(beanFactory.getBean(MeshRuleManager.class)).thenReturn(meshRuleManager); ExtensionLoader<TracingContextProvider> extensionLoader = Mockito.mock(ExtensionLoader.class); tracingContextProviders = new HashSet<>(); when(extensionLoader.getSupportedExtensionInstances()).thenReturn(tracingContextProviders); when(moduleModel.getExtensionLoader(TracingContextProvider.class)).thenReturn(extensionLoader); url = URL.valueOf("test://localhost/DemoInterface").setScopeModel(moduleModel); } @AfterEach public void teardown() { originModel.destroy(); } private Invoker<Object> createInvoker(String app) { URL url = URL.valueOf( "dubbo://localhost/DemoInterface?" + (StringUtils.isEmpty(app) ? "" : "remote.application=" + app)); Invoker invoker = Mockito.mock(Invoker.class); when(invoker.getUrl()).thenReturn(url); return invoker; } private Invoker<Object> createInvoker(Map<String, String> parameters) { URL url = URL.valueOf("dubbo://localhost/DemoInterface?remote.application=app1") .addParameters(parameters); Invoker invoker = Mockito.mock(Invoker.class); when(invoker.getUrl()).thenReturn(url); return invoker; } @Test void testNotify() { StandardMeshRuleRouter<Object> meshRuleRouter = new StandardMeshRuleRouter<>(url); meshRuleRouter.notify(null); assertEquals(0, meshRuleRouter.getRemoteAppName().size()); BitList<Invoker<Object>> invokers = new BitList<>(Arrays.asList(createInvoker(""), createInvoker("unknown"), createInvoker("app1"))); meshRuleRouter.notify(invokers); assertEquals(1, meshRuleRouter.getRemoteAppName().size()); assertTrue(meshRuleRouter.getRemoteAppName().contains("app1")); assertEquals(invokers, meshRuleRouter.getInvokerList()); verify(meshRuleManager, times(1)).register("app1", meshRuleRouter); invokers = new BitList<>(Arrays.asList(createInvoker("unknown"), createInvoker("app2"))); meshRuleRouter.notify(invokers); verify(meshRuleManager, times(1)).register("app2", meshRuleRouter); verify(meshRuleManager, times(1)).unregister("app1", meshRuleRouter); assertEquals(invokers, meshRuleRouter.getInvokerList()); meshRuleRouter.stop(); verify(meshRuleManager, times(1)).unregister("app2", meshRuleRouter); } @Test void testRuleChange() { StandardMeshRuleRouter<Object> meshRuleRouter = new StandardMeshRuleRouter<>(url); Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions())); List<Map<String, Object>> rules = new LinkedList<>(); rules.add(yaml.load(rule1)); meshRuleRouter.onRuleChange("app1", rules); assertEquals(0, meshRuleRouter.getMeshRuleCache().getAppToVDGroup().size()); rules.add(yaml.load(rule2)); meshRuleRouter.onRuleChange("app1", rules); assertEquals(1, meshRuleRouter.getMeshRuleCache().getAppToVDGroup().size()); assertTrue(meshRuleRouter.getMeshRuleCache().getAppToVDGroup().containsKey("app1")); meshRuleRouter.onRuleChange("app2", rules); assertEquals(2, meshRuleRouter.getMeshRuleCache().getAppToVDGroup().size()); assertTrue(meshRuleRouter.getMeshRuleCache().getAppToVDGroup().containsKey("app1")); assertTrue(meshRuleRouter.getMeshRuleCache().getAppToVDGroup().containsKey("app2")); meshRuleRouter.clearRule("app1"); assertEquals(1, meshRuleRouter.getMeshRuleCache().getAppToVDGroup().size()); assertTrue(meshRuleRouter.getMeshRuleCache().getAppToVDGroup().containsKey("app2")); } @Test void testRoute1() { StandardMeshRuleRouter<Object> meshRuleRouter = new StandardMeshRuleRouter<>(url); BitList<Invoker<Object>> invokers = new BitList<>(Arrays.asList(createInvoker(""), createInvoker("unknown"), createInvoker("app1"))); assertEquals(invokers, meshRuleRouter.route(invokers.clone(), null, null, false, null)); Holder<String> message = new Holder<>(); meshRuleRouter.doRoute(invokers.clone(), null, null, true, null, message); assertEquals("MeshRuleCache has not been built. Skip route.", message.get()); } @Test void testRoute2() { StandardMeshRuleRouter<Object> meshRuleRouter = new StandardMeshRuleRouter<>(url); Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions())); List<Map<String, Object>> rules = new LinkedList<>(); rules.add(yaml.load(rule1)); rules.add(yaml.load(rule2)); meshRuleRouter.onRuleChange("app1", rules); Invoker<Object> isolation = createInvoker(new HashMap<String, String>() { { put("env-sign", "xxx"); put("tag1", "hello"); } }); Invoker<Object> testingTrunk = createInvoker(Collections.singletonMap("env-sign", "yyy")); Invoker<Object> testing = createInvoker(Collections.singletonMap("env-sign", "zzz")); BitList<Invoker<Object>> invokers = new BitList<>(Arrays.asList(isolation, testingTrunk, testing)); meshRuleRouter.notify(invokers); RpcInvocation rpcInvocation = new RpcInvocation(); rpcInvocation.setServiceName("ccc"); rpcInvocation.setAttachment("trafficLabel", "xxx"); assertEquals( 1, meshRuleRouter .route(invokers.clone(), null, rpcInvocation, false, null) .size()); assertEquals( isolation, meshRuleRouter .route(invokers.clone(), null, rpcInvocation, false, null) .get(0)); Holder<String> message = new Holder<>(); meshRuleRouter.doRoute(invokers.clone(), null, rpcInvocation, true, null, message); assertEquals("Match App: app1 Subset: isolation ", message.get()); rpcInvocation.setAttachment("trafficLabel", "testing-trunk"); assertEquals( 1, meshRuleRouter .route(invokers.clone(), null, rpcInvocation, false, null) .size()); assertEquals( testingTrunk, meshRuleRouter .route(invokers.clone(), null, rpcInvocation, false, null) .get(0)); rpcInvocation.setAttachment("trafficLabel", null); assertEquals( 1, meshRuleRouter .route(invokers.clone(), null, rpcInvocation, false, null) .size()); assertEquals( testing, meshRuleRouter .route(invokers.clone(), null, rpcInvocation, false, null) .get(0)); rpcInvocation.setServiceName("aaa"); assertEquals(invokers, meshRuleRouter.route(invokers.clone(), null, rpcInvocation, false, null)); message = new Holder<>(); meshRuleRouter.doRoute(invokers.clone(), null, rpcInvocation, true, null, message); assertEquals("Empty protection after routed.", message.get()); rules = new LinkedList<>(); rules.add(yaml.load(rule1)); rules.add(yaml.load(rule3)); meshRuleRouter.onRuleChange("app1", rules); rpcInvocation.setServiceName("ccc"); rpcInvocation.setAttachment("trafficLabel", "xxx"); assertEquals( 1, meshRuleRouter .route(invokers.clone(), null, rpcInvocation, false, null) .size()); assertEquals( isolation, meshRuleRouter .route(invokers.clone(), null, rpcInvocation, false, null) .get(0)); rpcInvocation.setAttachment("trafficLabel", "testing-trunk"); assertEquals( 1, meshRuleRouter .route(invokers.clone(), null, rpcInvocation, false, null) .size()); assertEquals( testingTrunk, meshRuleRouter .route(invokers.clone(), null, rpcInvocation, false, null) .get(0)); rpcInvocation.setAttachment("trafficLabel", "testing"); assertEquals( 1, meshRuleRouter .route(invokers.clone(), null, rpcInvocation, false, null) .size()); assertEquals( testing, meshRuleRouter .route(invokers.clone(), null, rpcInvocation, false, null) .get(0)); rpcInvocation.setServiceName("aaa"); assertEquals( 1, meshRuleRouter .route(invokers.clone(), null, rpcInvocation, false, null) .size()); assertEquals( testing, meshRuleRouter .route(invokers.clone(), null, rpcInvocation, false, null) .get(0)); rpcInvocation.setAttachment("trafficLabel", null); assertEquals(invokers, meshRuleRouter.route(invokers.clone(), null, rpcInvocation, false, null)); rules = new LinkedList<>(); rules.add(yaml.load(rule1)); rules.add(yaml.load(rule4)); meshRuleRouter.onRuleChange("app1", rules); rpcInvocation.setAttachment("trafficLabel", "testing-trunk"); int testingCount = 0; int isolationCount = 0; for (int i = 0; i < 1000; i++) { BitList<Invoker<Object>> result = meshRuleRouter.route(invokers.clone(), null, rpcInvocation, false, null); assertEquals(1, result.size()); if (result.contains(testing)) { testingCount++; } else { isolationCount++; } } assertTrue(isolationCount > testingCount * 10); invokers.removeAll(Arrays.asList(isolation, testingTrunk)); for (int i = 0; i < 1000; i++) { assertEquals( 1, meshRuleRouter .route(invokers.clone(), null, rpcInvocation, false, null) .size()); assertEquals( testing, meshRuleRouter .route(invokers.clone(), null, rpcInvocation, false, null) .get(0)); } meshRuleRouter.notify(invokers); for (int i = 0; i < 1000; i++) { assertEquals( 1, meshRuleRouter .route(invokers.clone(), null, rpcInvocation, false, null) .size()); assertEquals( testing, meshRuleRouter .route(invokers.clone(), null, rpcInvocation, false, null) .get(0)); } Invoker<Object> mock = createInvoker(Collections.singletonMap("env-sign", "mock")); invokers = new BitList<>(Arrays.asList(isolation, testingTrunk, testing, mock)); meshRuleRouter.notify(invokers); invokers.removeAll(Arrays.asList(isolation, testingTrunk, testing)); assertEquals(invokers, meshRuleRouter.route(invokers.clone(), null, rpcInvocation, false, null)); } }
7,793
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/StandardMeshRuleRouterFactoryTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.router.mesh.route; import org.apache.dubbo.common.URL; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class StandardMeshRuleRouterFactoryTest { @Test void getRouter() { StandardMeshRuleRouterFactory ruleRouterFactory = new StandardMeshRuleRouterFactory(); Assertions.assertTrue( ruleRouterFactory.getRouter(Object.class, URL.valueOf("")) instanceof StandardMeshRuleRouter); } }
7,794
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleCacheTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.router.mesh.route; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.cluster.router.mesh.rule.VsDestinationGroup; import org.apache.dubbo.rpc.cluster.router.mesh.rule.destination.DestinationRule; import org.apache.dubbo.rpc.cluster.router.mesh.rule.destination.DestinationRuleSpec; import org.apache.dubbo.rpc.cluster.router.mesh.rule.destination.Subset; import org.apache.dubbo.rpc.cluster.router.state.BitList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; class MeshRuleCacheTest { private Invoker<Object> createInvoker(String app) { URL url = URL.valueOf( "dubbo://localhost/DemoInterface?" + (StringUtils.isEmpty(app) ? "" : "remote.application=" + app)); Invoker invoker = Mockito.mock(Invoker.class); when(invoker.getUrl()).thenReturn(url); return invoker; } @Test void containMapKeyValue() { URL url = mock(URL.class); when(url.getOriginalServiceParameter("test", "key1")).thenReturn("value1"); when(url.getOriginalServiceParameter("test", "key2")).thenReturn("value2"); when(url.getOriginalServiceParameter("test", "key3")).thenReturn("value3"); when(url.getOriginalServiceParameter("test", "key4")).thenReturn("value4"); Map<String, String> originMap = new HashMap<>(); originMap.put("key1", "value1"); originMap.put("key2", "value2"); originMap.put("key3", "value3"); Map<String, String> inputMap = new HashMap<>(); inputMap.put("key1", "value1"); inputMap.put("key2", "value2"); assertTrue(MeshRuleCache.isLabelMatch(url, "test", inputMap)); inputMap.put("key4", "value4"); assertTrue(MeshRuleCache.isLabelMatch(url, "test", inputMap)); } @Test void testBuild() { BitList<Invoker<Object>> invokers = new BitList<>(Arrays.asList(createInvoker(""), createInvoker("unknown"), createInvoker("app1"))); Subset subset = new Subset(); subset.setName("TestSubset"); DestinationRule destinationRule = new DestinationRule(); DestinationRuleSpec destinationRuleSpec = new DestinationRuleSpec(); destinationRuleSpec.setSubsets(Collections.singletonList(subset)); destinationRule.setSpec(destinationRuleSpec); VsDestinationGroup vsDestinationGroup = new VsDestinationGroup(); vsDestinationGroup.getDestinationRuleList().add(destinationRule); Map<String, VsDestinationGroup> vsDestinationGroupMap = new HashMap<>(); vsDestinationGroupMap.put("app1", vsDestinationGroup); MeshRuleCache<Object> cache = MeshRuleCache.build("test", invokers, vsDestinationGroupMap); assertEquals(2, cache.getUnmatchedInvokers().size()); assertEquals(1, cache.getSubsetInvokers("app1", "TestSubset").size()); subset.setLabels(Collections.singletonMap("test", "test")); cache = MeshRuleCache.build("test", invokers, vsDestinationGroupMap); assertEquals(3, cache.getUnmatchedInvokers().size()); assertEquals(0, cache.getSubsetInvokers("app1", "TestSubset").size()); invokers = new BitList<>(Arrays.asList( createInvoker(""), createInvoker("unknown"), createInvoker("app1"), createInvoker("app2"))); subset.setLabels(null); cache = MeshRuleCache.build("test", invokers, vsDestinationGroupMap); assertEquals(3, cache.getUnmatchedInvokers().size()); assertEquals(1, cache.getSubsetInvokers("app1", "TestSubset").size()); assertEquals(0, cache.getSubsetInvokers("app2", "TestSubset").size()); } }
7,795
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleManagerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.router.mesh.route; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.rpc.cluster.governance.GovernanceRuleRepository; import org.apache.dubbo.rpc.cluster.router.mesh.util.MeshRuleListener; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ModuleModel; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.yaml.snakeyaml.LoaderOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.SafeConstructor; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; class MeshRuleManagerTest { private static final String rule1 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: DestinationRule\n" + "metadata: { name: demo-route.Type1 }\n" + "spec:\n" + " host: demo\n" + "\n"; private static final String rule2 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: VirtualService\n" + "metadata: { name: demo-route.Type1 }\n" + "spec:\n" + " hosts: [demo]\n"; private static final String rule3 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: DestinationRule\n" + "metadata: { name: demo-route.Type2 }\n" + "spec:\n" + " host: demo\n" + "\n"; private static final String rule4 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: VirtualService\n" + "metadata: { name: demo-route.Type2 }\n" + "spec:\n" + " hosts: [demo]\n"; private ModuleModel originModule; private ModuleModel moduleModel; private GovernanceRuleRepository ruleRepository; private Set<MeshEnvListenerFactory> envListenerFactories; @BeforeEach public void setup() { originModule = ApplicationModel.defaultModel().getDefaultModule(); moduleModel = Mockito.spy(originModule); ruleRepository = Mockito.mock(GovernanceRuleRepository.class); when(moduleModel.getDefaultExtension(GovernanceRuleRepository.class)).thenReturn(ruleRepository); ExtensionLoader<MeshEnvListenerFactory> envListenerFactoryLoader = Mockito.mock(ExtensionLoader.class); envListenerFactories = new HashSet<>(); when(envListenerFactoryLoader.getSupportedExtensionInstances()).thenReturn(envListenerFactories); when(moduleModel.getExtensionLoader(MeshEnvListenerFactory.class)).thenReturn(envListenerFactoryLoader); } @AfterEach public void teardown() { originModule.destroy(); } @Test void testRegister1() { MeshRuleManager meshRuleManager = new MeshRuleManager(moduleModel); MeshRuleListener meshRuleListener1 = new MeshRuleListener() { @Override public void onRuleChange(String appName, List<Map<String, Object>> rules) { fail(); } @Override public void clearRule(String appName) {} @Override public String ruleSuffix() { return "Type1"; } }; meshRuleManager.register("dubbo-demo", meshRuleListener1); assertEquals(1, meshRuleManager.getAppRuleListeners().size()); verify(ruleRepository, times(1)).getRule("dubbo-demo.MESHAPPRULE", "dubbo", 5000L); MeshAppRuleListener meshAppRuleListener = meshRuleManager.getAppRuleListeners().values().iterator().next(); verify(ruleRepository, times(1)).addListener("dubbo-demo.MESHAPPRULE", "dubbo", meshAppRuleListener); meshRuleManager.register("dubbo-demo", meshRuleListener1); assertEquals(1, meshRuleManager.getAppRuleListeners().size()); MeshRuleListener meshRuleListener2 = new MeshRuleListener() { @Override public void onRuleChange(String appName, List<Map<String, Object>> rules) { fail(); } @Override public void clearRule(String appName) {} @Override public String ruleSuffix() { return "Type2"; } }; meshRuleManager.register("dubbo-demo", meshRuleListener2); assertEquals(1, meshRuleManager.getAppRuleListeners().size()); assertEquals( 2, meshAppRuleListener.getMeshRuleDispatcher().getListenerMap().size()); meshRuleManager.unregister("dubbo-demo", meshRuleListener1); assertEquals(1, meshRuleManager.getAppRuleListeners().size()); assertEquals( 1, meshAppRuleListener.getMeshRuleDispatcher().getListenerMap().size()); meshRuleManager.unregister("dubbo-demo", meshRuleListener2); assertEquals(0, meshRuleManager.getAppRuleListeners().size()); verify(ruleRepository, times(1)).removeListener("dubbo-demo.MESHAPPRULE", "dubbo", meshAppRuleListener); } @Test void testRegister2() { MeshRuleManager meshRuleManager = new MeshRuleManager(moduleModel); AtomicInteger invokeTimes = new AtomicInteger(0); MeshRuleListener meshRuleListener = new MeshRuleListener() { @Override public void onRuleChange(String appName, List<Map<String, Object>> rules) { assertEquals("dubbo-demo", appName); Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions())); assertTrue(rules.contains(yaml.load(rule1))); assertTrue(rules.contains(yaml.load(rule2))); invokeTimes.incrementAndGet(); } @Override public void clearRule(String appName) {} @Override public String ruleSuffix() { return "Type1"; } }; when(ruleRepository.getRule("dubbo-demo.MESHAPPRULE", "dubbo", 5000L)).thenReturn(rule1 + "---\n" + rule2); meshRuleManager.register("dubbo-demo", meshRuleListener); assertEquals(1, meshRuleManager.getAppRuleListeners().size()); verify(ruleRepository, times(1)).getRule("dubbo-demo.MESHAPPRULE", "dubbo", 5000L); verify(ruleRepository, times(1)) .addListener( "dubbo-demo.MESHAPPRULE", "dubbo", meshRuleManager .getAppRuleListeners() .values() .iterator() .next()); assertEquals(1, invokeTimes.get()); meshRuleManager.register("dubbo-demo", meshRuleListener); assertEquals(1, meshRuleManager.getAppRuleListeners().size()); } @Test void testRegister3() { MeshEnvListenerFactory meshEnvListenerFactory1 = Mockito.mock(MeshEnvListenerFactory.class); MeshEnvListenerFactory meshEnvListenerFactory2 = Mockito.mock(MeshEnvListenerFactory.class); MeshEnvListener meshEnvListener1 = Mockito.mock(MeshEnvListener.class); when(meshEnvListenerFactory1.getListener()).thenReturn(meshEnvListener1); MeshEnvListener meshEnvListener2 = Mockito.mock(MeshEnvListener.class); when(meshEnvListenerFactory2.getListener()).thenReturn(meshEnvListener2); envListenerFactories.add(meshEnvListenerFactory1); envListenerFactories.add(meshEnvListenerFactory2); MeshRuleManager meshRuleManager = new MeshRuleManager(moduleModel); MeshRuleListener meshRuleListener1 = new MeshRuleListener() { @Override public void onRuleChange(String appName, List<Map<String, Object>> rules) { fail(); } @Override public void clearRule(String appName) {} @Override public String ruleSuffix() { return "Type1"; } }; when(meshEnvListener1.isEnable()).thenReturn(false); when(meshEnvListener2.isEnable()).thenReturn(true); meshRuleManager.register("dubbo-demo", meshRuleListener1); assertEquals(1, meshRuleManager.getAppRuleListeners().size()); verify(ruleRepository, times(1)).getRule("dubbo-demo.MESHAPPRULE", "dubbo", 5000L); MeshAppRuleListener meshAppRuleListener = meshRuleManager.getAppRuleListeners().values().iterator().next(); verify(ruleRepository, times(1)).addListener("dubbo-demo.MESHAPPRULE", "dubbo", meshAppRuleListener); verify(meshEnvListener2, times(1)).onSubscribe("dubbo-demo", meshAppRuleListener); meshRuleManager.register("dubbo-demo", meshRuleListener1); assertEquals(1, meshRuleManager.getAppRuleListeners().size()); MeshRuleListener meshRuleListener2 = new MeshRuleListener() { @Override public void onRuleChange(String appName, List<Map<String, Object>> rules) { fail(); } @Override public void clearRule(String appName) {} @Override public String ruleSuffix() { return "Type2"; } }; meshRuleManager.register("dubbo-demo", meshRuleListener2); assertEquals(1, meshRuleManager.getAppRuleListeners().size()); assertEquals( 2, meshAppRuleListener.getMeshRuleDispatcher().getListenerMap().size()); meshRuleManager.unregister("dubbo-demo", meshRuleListener1); assertEquals(1, meshRuleManager.getAppRuleListeners().size()); assertEquals( 1, meshAppRuleListener.getMeshRuleDispatcher().getListenerMap().size()); meshRuleManager.unregister("dubbo-demo", meshRuleListener2); assertEquals(0, meshRuleManager.getAppRuleListeners().size()); verify(ruleRepository, times(1)).removeListener("dubbo-demo.MESHAPPRULE", "dubbo", meshAppRuleListener); verify(meshEnvListener2, times(1)).onUnSubscribe("dubbo-demo"); } }
7,796
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/util/MeshRuleDispatcherTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.router.mesh.util; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class MeshRuleDispatcherTest { @Test void post() { MeshRuleDispatcher meshRuleDispatcher = new MeshRuleDispatcher("TestApp"); Map<String, List<Map<String, Object>>> ruleMap = new HashMap<>(); List<Map<String, Object>> type1 = new LinkedList<>(); List<Map<String, Object>> type2 = new LinkedList<>(); List<Map<String, Object>> type3 = new LinkedList<>(); ruleMap.put("Type1", type1); ruleMap.put("Type2", type2); ruleMap.put("Type3", type3); AtomicInteger count = new AtomicInteger(0); MeshRuleListener listener1 = new MeshRuleListener() { @Override public void onRuleChange(String appName, List<Map<String, Object>> rules) { Assertions.assertEquals("TestApp", appName); Assertions.assertEquals(System.identityHashCode(type1), System.identityHashCode(rules)); count.incrementAndGet(); } @Override public void clearRule(String appName) {} @Override public String ruleSuffix() { return "Type1"; } }; MeshRuleListener listener2 = new MeshRuleListener() { @Override public void onRuleChange(String appName, List<Map<String, Object>> rules) { Assertions.assertEquals("TestApp", appName); Assertions.assertEquals(System.identityHashCode(type2), System.identityHashCode(rules)); count.incrementAndGet(); } @Override public void clearRule(String appName) {} @Override public String ruleSuffix() { return "Type2"; } }; MeshRuleListener listener4 = new MeshRuleListener() { @Override public void onRuleChange(String appName, List<Map<String, Object>> rules) { Assertions.fail(); } @Override public void clearRule(String appName) { Assertions.assertEquals("TestApp", appName); count.incrementAndGet(); } @Override public String ruleSuffix() { return "Type4"; } }; meshRuleDispatcher.register(listener1); meshRuleDispatcher.register(listener2); meshRuleDispatcher.register(listener4); meshRuleDispatcher.post(ruleMap); Assertions.assertEquals(3, count.get()); } @Test void register() { MeshRuleDispatcher meshRuleDispatcher = new MeshRuleDispatcher("TestApp"); MeshRuleListener listener1 = new MeshRuleListener() { @Override public void onRuleChange(String appName, List<Map<String, Object>> rules) {} @Override public void clearRule(String appName) {} @Override public String ruleSuffix() { return "Type1"; } }; meshRuleDispatcher.register(listener1); meshRuleDispatcher.register(listener1); Assertions.assertEquals( 1, meshRuleDispatcher.getListenerMap().get("Type1").size()); Assertions.assertTrue(meshRuleDispatcher.getListenerMap().get("Type1").contains(listener1)); } @Test void unregister() { MeshRuleDispatcher meshRuleDispatcher = new MeshRuleDispatcher("TestApp"); MeshRuleListener listener1 = new MeshRuleListener() { @Override public void onRuleChange(String appName, List<Map<String, Object>> rules) {} @Override public void clearRule(String appName) {} @Override public String ruleSuffix() { return "Type1"; } }; MeshRuleListener listener2 = new MeshRuleListener() { @Override public void onRuleChange(String appName, List<Map<String, Object>> rules) {} @Override public void clearRule(String appName) {} @Override public String ruleSuffix() { return "Type1"; } }; MeshRuleListener listener3 = new MeshRuleListener() { @Override public void onRuleChange(String appName, List<Map<String, Object>> rules) {} @Override public void clearRule(String appName) {} @Override public String ruleSuffix() { return "Type2"; } }; meshRuleDispatcher.register(listener1); meshRuleDispatcher.register(listener2); meshRuleDispatcher.register(listener3); Assertions.assertEquals( 2, meshRuleDispatcher.getListenerMap().get("Type1").size()); Assertions.assertTrue(meshRuleDispatcher.getListenerMap().get("Type1").contains(listener1)); Assertions.assertTrue(meshRuleDispatcher.getListenerMap().get("Type1").contains(listener2)); Assertions.assertEquals( 1, meshRuleDispatcher.getListenerMap().get("Type2").size()); Assertions.assertTrue(meshRuleDispatcher.getListenerMap().get("Type2").contains(listener3)); meshRuleDispatcher.unregister(listener1); Assertions.assertEquals( 1, meshRuleDispatcher.getListenerMap().get("Type1").size()); Assertions.assertTrue(meshRuleDispatcher.getListenerMap().get("Type1").contains(listener2)); Assertions.assertEquals( 1, meshRuleDispatcher.getListenerMap().get("Type2").size()); Assertions.assertTrue(meshRuleDispatcher.getListenerMap().get("Type2").contains(listener3)); meshRuleDispatcher.unregister(listener2); Assertions.assertNull(meshRuleDispatcher.getListenerMap().get("Type1")); Assertions.assertEquals( 1, meshRuleDispatcher.getListenerMap().get("Type2").size()); Assertions.assertTrue(meshRuleDispatcher.getListenerMap().get("Type2").contains(listener3)); meshRuleDispatcher.unregister(listener3); Assertions.assertNull(meshRuleDispatcher.getListenerMap().get("Type1")); Assertions.assertNull(meshRuleDispatcher.getListenerMap().get("Type2")); } }
7,797
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/DestinationRuleTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.router.mesh.rule; import org.apache.dubbo.rpc.cluster.router.mesh.rule.destination.DestinationRule; import org.apache.dubbo.rpc.cluster.router.mesh.rule.destination.loadbalance.SimpleLB; import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.VirtualServiceRule; import java.util.Map; import org.junit.jupiter.api.Test; import org.yaml.snakeyaml.Yaml; import static org.apache.dubbo.rpc.cluster.router.mesh.route.MeshRuleConstants.DESTINATION_RULE_KEY; import static org.apache.dubbo.rpc.cluster.router.mesh.route.MeshRuleConstants.KIND_KEY; import static org.apache.dubbo.rpc.cluster.router.mesh.route.MeshRuleConstants.VIRTUAL_SERVICE_KEY; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; class DestinationRuleTest { @Test void parserTest() { Yaml yaml = new Yaml(); DestinationRule destinationRule = yaml.loadAs( this.getClass().getClassLoader().getResourceAsStream("DestinationRuleTest.yaml"), DestinationRule.class); System.out.println(destinationRule); // apiVersion: service.dubbo.apache.org/v1alpha1 // kind: DestinationRule // metadata: { name: demo-route } // spec: // host: demo // subsets: // - labels: { env-sign: xxx,tag1: hello } // name: isolation // - labels: { env-sign: yyy } // name: testing-trunk // - labels: { env-sign: zzz } // name: testing assertEquals("service.dubbo.apache.org/v1alpha1", destinationRule.getApiVersion()); assertEquals(DESTINATION_RULE_KEY, destinationRule.getKind()); assertEquals("demo-route", destinationRule.getMetadata().get("name")); assertEquals("demo", destinationRule.getSpec().getHost()); assertEquals(3, destinationRule.getSpec().getSubsets().size()); assertEquals("isolation", destinationRule.getSpec().getSubsets().get(0).getName()); assertEquals( 2, destinationRule.getSpec().getSubsets().get(0).getLabels().size()); assertEquals( "xxx", destinationRule.getSpec().getSubsets().get(0).getLabels().get("env-sign")); assertEquals( "hello", destinationRule.getSpec().getSubsets().get(0).getLabels().get("tag1")); assertEquals( "testing-trunk", destinationRule.getSpec().getSubsets().get(1).getName()); assertEquals( 1, destinationRule.getSpec().getSubsets().get(1).getLabels().size()); assertEquals( "yyy", destinationRule.getSpec().getSubsets().get(1).getLabels().get("env-sign")); assertEquals("testing", destinationRule.getSpec().getSubsets().get(2).getName()); assertEquals( 1, destinationRule.getSpec().getSubsets().get(2).getLabels().size()); assertEquals( "zzz", destinationRule.getSpec().getSubsets().get(2).getLabels().get("env-sign")); assertEquals( SimpleLB.ROUND_ROBIN, destinationRule.getSpec().getTrafficPolicy().getLoadBalancer().getSimple()); assertEquals( null, destinationRule.getSpec().getTrafficPolicy().getLoadBalancer().getConsistentHash()); } @Test void parserMultiRuleTest() { Yaml yaml = new Yaml(); Yaml yaml2 = new Yaml(); Iterable objectIterable = yaml.loadAll(this.getClass().getClassLoader().getResourceAsStream("DestinationRuleTest2.yaml")); for (Object result : objectIterable) { Map resultMap = (Map) result; if (resultMap.get("kind").equals(DESTINATION_RULE_KEY)) { DestinationRule destinationRule = yaml2.loadAs(yaml2.dump(result), DestinationRule.class); System.out.println(destinationRule); assertNotNull(destinationRule); } else if (resultMap.get(KIND_KEY).equals(VIRTUAL_SERVICE_KEY)) { VirtualServiceRule virtualServiceRule = yaml2.loadAs(yaml2.dump(result), VirtualServiceRule.class); System.out.println(virtualServiceRule); assertNotNull(virtualServiceRule); } } } }
7,798
0
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/VirtualServiceRuleTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.router.mesh.rule; import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.DubboRoute; import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.DubboRouteDetail; import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.VirtualServiceRule; import java.util.List; import org.junit.jupiter.api.Test; import org.yaml.snakeyaml.Yaml; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; class VirtualServiceRuleTest { @Test void parserTest() { Yaml yaml = new Yaml(); VirtualServiceRule virtualServiceRule = yaml.loadAs( this.getClass().getClassLoader().getResourceAsStream("VirtualServiceTest.yaml"), VirtualServiceRule.class); System.out.println(virtualServiceRule); assertNotNull(virtualServiceRule); assertEquals("service.dubbo.apache.org/v1alpha1", virtualServiceRule.getApiVersion()); assertEquals("VirtualService", virtualServiceRule.getKind()); assertEquals("demo-route", virtualServiceRule.getMetadata().get("name")); List<String> hosts = virtualServiceRule.getSpec().getHosts(); assertEquals(1, hosts.size()); assertEquals("demo", hosts.get(0)); List<DubboRoute> dubboRoutes = virtualServiceRule.getSpec().getDubbo(); assertEquals(1, dubboRoutes.size()); DubboRoute dubboRoute = dubboRoutes.get(0); assertNull(dubboRoute.getName()); assertEquals(1, dubboRoute.getServices().size()); assertEquals("ccc", dubboRoute.getServices().get(0).getRegex()); List<DubboRouteDetail> routedetail = dubboRoute.getRoutedetail(); DubboRouteDetail firstDubboRouteDetail = routedetail.get(0); DubboRouteDetail secondDubboRouteDetail = routedetail.get(1); DubboRouteDetail thirdDubboRouteDetail = routedetail.get(2); assertEquals("xxx-project", firstDubboRouteDetail.getName()); assertEquals( "xxx", firstDubboRouteDetail.getMatch().get(0).getSourceLabels().get("trafficLabel")); assertEquals( "demo", firstDubboRouteDetail.getRoute().get(0).getDestination().getHost()); assertEquals( "isolation", firstDubboRouteDetail.getRoute().get(0).getDestination().getSubset()); assertEquals("testing-trunk", secondDubboRouteDetail.getName()); assertEquals( "testing-trunk", secondDubboRouteDetail.getMatch().get(0).getSourceLabels().get("trafficLabel")); assertEquals( "demo", secondDubboRouteDetail.getRoute().get(0).getDestination().getHost()); assertEquals( "testing-trunk", secondDubboRouteDetail.getRoute().get(0).getDestination().getSubset()); assertEquals("testing", thirdDubboRouteDetail.getName()); assertNull(thirdDubboRouteDetail.getMatch()); assertEquals( "demo", thirdDubboRouteDetail.getRoute().get(0).getDestination().getHost()); assertEquals( "testing", thirdDubboRouteDetail.getRoute().get(0).getDestination().getSubset()); } }
7,799