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-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos | Create_ds/dubbo/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/util/NacosNamingServiceUtils.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.registry.nacos.util;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.registry.client.DefaultServiceInstance;
import org.apache.dubbo.registry.client.ServiceInstance;
import org.apache.dubbo.registry.nacos.NacosConnectionManager;
import org.apache.dubbo.registry.nacos.NacosNamingServiceWrapper;
import org.apache.dubbo.rpc.model.ScopeModelUtil;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.utils.NamingUtils;
import static com.alibaba.nacos.api.common.Constants.DEFAULT_GROUP;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
/**
* The utilities class for {@link NamingService}
*
* @since 2.7.5
*/
public class NacosNamingServiceUtils {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(NacosNamingServiceUtils.class);
private static final String NACOS_GROUP_KEY = "nacos.group";
private static final String NACOS_RETRY_KEY = "nacos.retry";
private static final String NACOS_RETRY_WAIT_KEY = "nacos.retry-wait";
private static final String NACOS_CHECK_KEY = "nacos.check";
private NacosNamingServiceUtils() {
throw new IllegalStateException("NacosNamingServiceUtils should not be instantiated");
}
/**
* Convert the {@link ServiceInstance} to {@link Instance}
*
* @param serviceInstance {@link ServiceInstance}
* @return non-null
* @since 2.7.5
*/
public static Instance toInstance(ServiceInstance serviceInstance) {
Instance instance = new Instance();
instance.setServiceName(serviceInstance.getServiceName());
instance.setIp(serviceInstance.getHost());
instance.setPort(serviceInstance.getPort());
instance.setMetadata(serviceInstance.getSortedMetadata());
instance.setEnabled(serviceInstance.isEnabled());
instance.setHealthy(serviceInstance.isHealthy());
return instance;
}
/**
* Convert the {@link Instance} to {@link ServiceInstance}
*
* @param instance {@link Instance}
* @return non-null
* @since 2.7.5
*/
public static ServiceInstance toServiceInstance(URL registryUrl, Instance instance) {
DefaultServiceInstance serviceInstance = new DefaultServiceInstance(
NamingUtils.getServiceName(instance.getServiceName()),
instance.getIp(),
instance.getPort(),
ScopeModelUtil.getApplicationModel(registryUrl.getScopeModel()));
serviceInstance.setMetadata(instance.getMetadata());
serviceInstance.setEnabled(instance.isEnabled());
serviceInstance.setHealthy(instance.isHealthy());
return serviceInstance;
}
/**
* The group of {@link NamingService} to register
*
* @param connectionURL {@link URL connection url}
* @return non-null, "default" as default
* @since 2.7.5
*/
public static String getGroup(URL connectionURL) {
// Compatible with nacos grouping via group.
String group = connectionURL.getParameter(GROUP_KEY, DEFAULT_GROUP);
return connectionURL.getParameter(NACOS_GROUP_KEY, group);
}
/**
* Create an instance of {@link NamingService} from specified {@link URL connection url}
*
* @param connectionURL {@link URL connection url}
* @return {@link NamingService}
* @since 2.7.5
*/
public static NacosNamingServiceWrapper createNamingService(URL connectionURL) {
boolean check = connectionURL.getParameter(NACOS_CHECK_KEY, true);
int retryTimes = connectionURL.getPositiveParameter(NACOS_RETRY_KEY, 10);
int sleepMsBetweenRetries = connectionURL.getPositiveParameter(NACOS_RETRY_WAIT_KEY, 10);
NacosConnectionManager nacosConnectionManager =
new NacosConnectionManager(connectionURL, check, retryTimes, sleepMsBetweenRetries);
return new NacosNamingServiceWrapper(nacosConnectionManager, retryTimes, sleepMsBetweenRetries);
}
}
| 5,400 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos | Create_ds/dubbo/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/function/NacosConsumer.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.registry.nacos.function;
import java.util.function.Function;
import com.alibaba.nacos.api.exception.NacosException;
/**
* A function interface for action with {@link NacosException}
*
* @see Function
* @see NacosException
* @since 3.1.5
*/
@FunctionalInterface
public interface NacosConsumer {
/**
* Applies this function to the given argument.
*
* @throws NacosException if met with any error
*/
void accept() throws NacosException;
}
| 5,401 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos | Create_ds/dubbo/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/function/NacosFunction.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.registry.nacos.function;
import java.util.function.Function;
import com.alibaba.nacos.api.exception.NacosException;
/**
* A function interface for action with {@link NacosException}
*
* @see Function
* @see NacosException
* @since 3.1.5
*/
@FunctionalInterface
public interface NacosFunction<R> {
/**
* Applies this function to the given argument.
*
* @return the function result
* @throws NacosException if met with any error
*/
R apply() throws NacosException;
}
| 5,402 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-zookeeper/src/test/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-zookeeper/src/test/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistryTest.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.registry.zookeeper;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.status.Status;
import org.apache.dubbo.registry.NotifyListener;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.status.RegistryStatusChecker;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
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 static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.mock;
class ZookeeperRegistryTest {
private static String zookeeperConnectionAddress1;
private ZookeeperRegistry zookeeperRegistry;
private String service = "org.apache.dubbo.test.injvmServie";
private URL serviceUrl = URL.valueOf("zookeeper://zookeeper/" + service + "?notify=false&methods=test1,test2");
private URL anyUrl = URL.valueOf("zookeeper://zookeeper/*");
private URL registryUrl;
private ZookeeperRegistryFactory zookeeperRegistryFactory;
private NotifyListener listener;
@BeforeAll
public static void beforeAll() {
zookeeperConnectionAddress1 = System.getProperty("zookeeper.connection.address.1");
}
@BeforeEach
public void setUp() throws Exception {
this.registryUrl = URL.valueOf(zookeeperConnectionAddress1);
zookeeperRegistryFactory = new ZookeeperRegistryFactory(ApplicationModel.defaultModel());
this.zookeeperRegistry = (ZookeeperRegistry) zookeeperRegistryFactory.createRegistry(registryUrl);
}
@Test
void testAnyHost() {
Assertions.assertThrows(IllegalStateException.class, () -> {
URL errorUrl = URL.valueOf("multicast://0.0.0.0/");
new ZookeeperRegistryFactory(ApplicationModel.defaultModel()).createRegistry(errorUrl);
});
}
@Test
void testRegister() {
Set<URL> registered;
for (int i = 0; i < 2; i++) {
zookeeperRegistry.register(serviceUrl);
registered = zookeeperRegistry.getRegistered();
assertThat(registered.contains(serviceUrl), is(true));
}
registered = zookeeperRegistry.getRegistered();
assertThat(registered.size(), is(1));
}
@Test
void testSubscribe() {
NotifyListener listener = mock(NotifyListener.class);
zookeeperRegistry.subscribe(serviceUrl, listener);
Map<URL, Set<NotifyListener>> subscribed = zookeeperRegistry.getSubscribed();
assertThat(subscribed.size(), is(1));
assertThat(subscribed.get(serviceUrl).size(), is(1));
zookeeperRegistry.unsubscribe(serviceUrl, listener);
subscribed = zookeeperRegistry.getSubscribed();
assertThat(subscribed.size(), is(1));
assertThat(subscribed.get(serviceUrl).size(), is(0));
}
@Test
void testAvailable() {
zookeeperRegistry.register(serviceUrl);
assertThat(zookeeperRegistry.isAvailable(), is(true));
zookeeperRegistry.destroy();
assertThat(zookeeperRegistry.isAvailable(), is(false));
}
@Test
void testLookup() {
List<URL> lookup = zookeeperRegistry.lookup(serviceUrl);
assertThat(lookup.size(), is(1));
zookeeperRegistry.register(serviceUrl);
lookup = zookeeperRegistry.lookup(serviceUrl);
assertThat(lookup.size(), is(1));
}
@Test
void testLookupIllegalUrl() {
try {
zookeeperRegistry.lookup(null);
fail();
} catch (IllegalArgumentException expected) {
assertThat(expected.getMessage(), containsString("lookup url == null"));
}
}
@Test
void testLookupWithException() {
URL errorUrl = URL.valueOf("multicast://0.0.0.0/");
Assertions.assertThrows(RpcException.class, () -> zookeeperRegistry.lookup(errorUrl));
}
@Disabled
@Test
/*
This UT is unstable, consider remove it later.
@see https://github.com/apache/dubbo/issues/1787
*/
public void testStatusChecker() {
RegistryStatusChecker registryStatusChecker = new RegistryStatusChecker(ApplicationModel.defaultModel());
Status status = registryStatusChecker.check();
assertThat(status.getLevel(), is(Status.Level.UNKNOWN));
Registry registry = zookeeperRegistryFactory.getRegistry(registryUrl);
assertThat(registry, not(nullValue()));
status = registryStatusChecker.check();
assertThat(status.getLevel(), is(Status.Level.ERROR));
registry.register(serviceUrl);
status = registryStatusChecker.check();
assertThat(status.getLevel(), is(Status.Level.OK));
}
@Test
void testSubscribeAnyValue() throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(1);
zookeeperRegistry.register(serviceUrl);
zookeeperRegistry.subscribe(anyUrl, urls -> latch.countDown());
zookeeperRegistry.register(serviceUrl);
latch.await();
}
@Test
void testDestroy() {
zookeeperRegistry.destroy();
assertThat(zookeeperRegistry.isAvailable(), is(false));
}
@Test
void testDoRegisterWithException() {
Assertions.assertThrows(RpcException.class, () -> {
URL errorUrl = URL.valueOf("multicast://0.0.0.0/");
zookeeperRegistry.doRegister(errorUrl);
});
}
@Test
void testDoUnregisterWithException() {
Assertions.assertThrows(RpcException.class, () -> {
URL errorUrl = URL.valueOf("multicast://0.0.0.0/");
zookeeperRegistry.doUnregister(errorUrl);
});
}
@Test
void testDoSubscribeWithException() {
Assertions.assertThrows(RpcException.class, () -> zookeeperRegistry.doSubscribe(anyUrl, listener));
}
}
| 5,403 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-zookeeper/src/test/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-zookeeper/src/test/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscoveryTest.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.registry.zookeeper;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.registry.client.DefaultServiceInstance;
import org.apache.dubbo.registry.client.ServiceInstance;
import org.apache.dubbo.registry.client.event.ServiceInstancesChangedEvent;
import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledForJreRange;
import org.junit.jupiter.api.condition.JRE;
import org.mockito.internal.util.collections.Sets;
import static java.util.Arrays.asList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link ZookeeperServiceDiscovery} Test
*
* @since 2.7.5
*/
@DisabledForJreRange(min = JRE.JAVA_16)
class ZookeeperServiceDiscoveryTest {
private static final String SERVICE_NAME = "A";
private static final String LOCALHOST = "127.0.0.1";
private URL registryUrl;
private ZookeeperServiceDiscovery discovery;
private static String zookeeperConnectionAddress1;
@BeforeAll
public static void beforeAll() {
zookeeperConnectionAddress1 = System.getProperty("zookeeper.connection.address.1");
}
@BeforeEach
public void init() throws Exception {
this.registryUrl = URL.valueOf(zookeeperConnectionAddress1);
ApplicationModel applicationModel = ApplicationModel.defaultModel();
applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig(SERVICE_NAME));
registryUrl.setScopeModel(applicationModel);
this.discovery = new ZookeeperServiceDiscovery(applicationModel, registryUrl);
}
@AfterEach
public void close() throws Exception {
discovery.destroy();
}
@Test
void testRegistration() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
// Add Listener
discovery.addServiceInstancesChangedListener(
new ServiceInstancesChangedListener(Sets.newSet(SERVICE_NAME), discovery) {
@Override
public void onEvent(ServiceInstancesChangedEvent event) {
latch.countDown();
}
});
discovery.register();
latch.await();
List<ServiceInstance> serviceInstances = discovery.getInstances(SERVICE_NAME);
assertEquals(0, serviceInstances.size());
discovery.register(URL.valueOf("dubbo://1.1.2.3:20880/DemoService"));
discovery.register();
serviceInstances = discovery.getInstances(SERVICE_NAME);
DefaultServiceInstance serviceInstance = (DefaultServiceInstance) discovery.getLocalInstance();
assertTrue(serviceInstances.contains(serviceInstance));
assertEquals(asList(serviceInstance), serviceInstances);
Map<String, String> metadata = new HashMap<>();
metadata.put("message", "Hello,World");
serviceInstance.setMetadata(metadata);
discovery.register(URL.valueOf("dubbo://1.1.2.3:20880/DemoService1"));
discovery.update();
serviceInstances = discovery.getInstances(SERVICE_NAME);
assertEquals(serviceInstance, serviceInstances.get(0));
discovery.unregister();
serviceInstances = discovery.getInstances(SERVICE_NAME);
assertTrue(serviceInstances.isEmpty());
}
}
| 5,404 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-zookeeper/src/test/java/org/apache/dubbo/registry/zookeeper | Create_ds/dubbo/dubbo-registry/dubbo-registry-zookeeper/src/test/java/org/apache/dubbo/registry/zookeeper/util/CuratorFrameworkUtilsTest.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.registry.zookeeper.util;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.metadata.report.MetadataReport;
import org.apache.dubbo.registry.client.DefaultServiceInstance;
import org.apache.dubbo.registry.client.ServiceInstance;
import org.apache.dubbo.registry.zookeeper.ZookeeperInstance;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.x.discovery.ServiceDiscovery;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.EXPORTED_SERVICES_REVISION_PROPERTY_NAME;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.METADATA_STORAGE_TYPE_PROPERTY_NAME;
import static org.apache.dubbo.registry.zookeeper.util.CuratorFrameworkParams.ROOT_PATH;
/**
* {@link CuratorFrameworkUtils} Test
*/
class CuratorFrameworkUtilsTest {
private static URL registryUrl;
private static String zookeeperConnectionAddress1;
private static MetadataReport metadataReport;
@BeforeAll
public static void init() throws Exception {
zookeeperConnectionAddress1 = System.getProperty("zookeeper.connection.address.1");
registryUrl = URL.valueOf(zookeeperConnectionAddress1);
registryUrl.setScopeModel(ApplicationModel.defaultModel());
metadataReport = Mockito.mock(MetadataReport.class);
}
@Test
void testBuildCuratorFramework() throws Exception {
CuratorFramework curatorFramework = CuratorFrameworkUtils.buildCuratorFramework(registryUrl, null);
Assertions.assertNotNull(curatorFramework);
Assertions.assertTrue(curatorFramework.getZookeeperClient().isConnected());
curatorFramework.getZookeeperClient().close();
}
@Test
void testBuildServiceDiscovery() throws Exception {
CuratorFramework curatorFramework = CuratorFrameworkUtils.buildCuratorFramework(registryUrl, null);
ServiceDiscovery<ZookeeperInstance> discovery =
CuratorFrameworkUtils.buildServiceDiscovery(curatorFramework, ROOT_PATH.getParameterValue(registryUrl));
Assertions.assertNotNull(discovery);
discovery.close();
curatorFramework.getZookeeperClient().close();
}
@Test
void testBuild() {
ServiceInstance dubboServiceInstance =
new DefaultServiceInstance("A", "127.0.0.1", 8888, ApplicationModel.defaultModel());
Map<String, String> metadata = dubboServiceInstance.getMetadata();
metadata.put(METADATA_STORAGE_TYPE_PROPERTY_NAME, "remote");
metadata.put(EXPORTED_SERVICES_REVISION_PROPERTY_NAME, "111");
metadata.put("site", "dubbo");
// convert {org.apache.dubbo.registry.client.ServiceInstance} to
// {org.apache.curator.x.discovery.ServiceInstance<ZookeeperInstance>}
org.apache.curator.x.discovery.ServiceInstance<ZookeeperInstance> curatorServiceInstance =
CuratorFrameworkUtils.build(dubboServiceInstance);
Assertions.assertEquals(curatorServiceInstance.getId(), dubboServiceInstance.getAddress());
Assertions.assertEquals(curatorServiceInstance.getName(), dubboServiceInstance.getServiceName());
Assertions.assertEquals(curatorServiceInstance.getAddress(), dubboServiceInstance.getHost());
Assertions.assertEquals(curatorServiceInstance.getPort(), dubboServiceInstance.getPort());
ZookeeperInstance payload = curatorServiceInstance.getPayload();
Assertions.assertNotNull(payload);
Assertions.assertEquals(payload.getMetadata(), metadata);
Assertions.assertEquals(payload.getName(), dubboServiceInstance.getServiceName());
// convert {org.apache.curator.x.discovery.ServiceInstance<ZookeeperInstance>} to
// {org.apache.dubbo.registry.client.ServiceInstance}
ServiceInstance serviceInstance = CuratorFrameworkUtils.build(registryUrl, curatorServiceInstance);
Assertions.assertEquals(serviceInstance, dubboServiceInstance);
// convert {Collection<org.apache.curator.x.discovery.ServiceInstance<ZookeeperInstance>>} to
// {List<org.apache.dubbo.registry.client.ServiceInstance>}
List<ServiceInstance> serviceInstances =
CuratorFrameworkUtils.build(registryUrl, Arrays.asList(curatorServiceInstance));
Assertions.assertNotNull(serviceInstances);
Assertions.assertEquals(serviceInstances.get(0), dubboServiceInstance);
}
}
| 5,405 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperInstance.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.registry.zookeeper;
import java.util.HashMap;
import java.util.Map;
/**
* Represents the default payload of a registered service in Zookeeper.
* <p>
* It's compatible with Spring Cloud
*
* @since 2.7.5
*/
public class ZookeeperInstance {
private String id;
private String name;
private Map<String, String> metadata = new HashMap<>();
@SuppressWarnings("unused")
private ZookeeperInstance() {}
public ZookeeperInstance(String id, String name, Map<String, String> metadata) {
this.id = id;
this.name = name;
this.metadata = metadata;
}
public String getId() {
return this.id;
}
public String getName() {
return this.name;
}
public void setId(String id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public Map<String, String> getMetadata() {
return this.metadata;
}
public void setMetadata(Map<String, String> metadata) {
this.metadata = metadata;
}
@Override
public String toString() {
return "ZookeeperInstance{" + "id='" + this.id + '\'' + ", name='" + this.name + '\'' + ", metadata="
+ this.metadata + '}';
}
}
| 5,406 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscovery.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.registry.zookeeper;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.function.ThrowableConsumer;
import org.apache.dubbo.common.function.ThrowableFunction;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.registry.client.AbstractServiceDiscovery;
import org.apache.dubbo.registry.client.ServiceDiscovery;
import org.apache.dubbo.registry.client.ServiceInstance;
import org.apache.dubbo.registry.client.event.ServiceInstancesChangedEvent;
import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.io.IOException;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.api.CuratorWatcher;
import org.apache.curator.x.discovery.ServiceCache;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ZOOKEEPER_EXCEPTION;
import static org.apache.dubbo.common.function.ThrowableFunction.execute;
import static org.apache.dubbo.metadata.RevisionResolver.EMPTY_REVISION;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.EXPORTED_SERVICES_REVISION_PROPERTY_NAME;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.getExportedServicesRevision;
import static org.apache.dubbo.registry.zookeeper.util.CuratorFrameworkUtils.build;
import static org.apache.dubbo.registry.zookeeper.util.CuratorFrameworkUtils.buildCuratorFramework;
import static org.apache.dubbo.registry.zookeeper.util.CuratorFrameworkUtils.buildServiceDiscovery;
import static org.apache.dubbo.registry.zookeeper.util.CuratorFrameworkUtils.getRootPath;
import static org.apache.dubbo.rpc.RpcException.REGISTRY_EXCEPTION;
/**
* Zookeeper {@link ServiceDiscovery} implementation based on
* <a href="https://curator.apache.org/curator-x-discovery/index.html">Apache Curator X Discovery</a>
* <p>
* TODO, replace curator CuratorFramework with dubbo ZookeeperClient
*/
public class ZookeeperServiceDiscovery extends AbstractServiceDiscovery {
private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
public static final String DEFAULT_GROUP = "/services";
private final CuratorFramework curatorFramework;
private final String rootPath;
private final org.apache.curator.x.discovery.ServiceDiscovery<ZookeeperInstance> serviceDiscovery;
/**
* The Key is watched Zookeeper path, the value is an instance of {@link CuratorWatcher}
*/
private final Map<String, ZookeeperServiceDiscoveryChangeWatcher> watcherCaches = new ConcurrentHashMap<>();
public ZookeeperServiceDiscovery(ApplicationModel applicationModel, URL registryURL) {
super(applicationModel, registryURL);
try {
this.curatorFramework = buildCuratorFramework(registryURL, this);
this.rootPath = getRootPath(registryURL);
this.serviceDiscovery = buildServiceDiscovery(curatorFramework, rootPath);
this.serviceDiscovery.start();
} catch (Exception e) {
throw new IllegalStateException("Create zookeeper service discovery failed.", e);
}
}
@Override
public void doDestroy() throws Exception {
serviceDiscovery.close();
curatorFramework.close();
watcherCaches.clear();
}
@Override
public void doRegister(ServiceInstance serviceInstance) {
try {
serviceDiscovery.registerService(build(serviceInstance));
} catch (Exception e) {
throw new RpcException(REGISTRY_EXCEPTION, "Failed register instance " + serviceInstance.toString(), e);
}
}
@Override
public void doUnregister(ServiceInstance serviceInstance) throws RuntimeException {
if (serviceInstance != null) {
doInServiceRegistry(serviceDiscovery -> serviceDiscovery.unregisterService(build(serviceInstance)));
}
}
@Override
protected void doUpdate(ServiceInstance oldServiceInstance, ServiceInstance newServiceInstance)
throws RuntimeException {
if (EMPTY_REVISION.equals(getExportedServicesRevision(newServiceInstance))
|| EMPTY_REVISION.equals(
oldServiceInstance.getMetadata().get(EXPORTED_SERVICES_REVISION_PROPERTY_NAME))) {
super.doUpdate(oldServiceInstance, newServiceInstance);
return;
}
org.apache.curator.x.discovery.ServiceInstance<ZookeeperInstance> oldInstance = build(oldServiceInstance);
org.apache.curator.x.discovery.ServiceInstance<ZookeeperInstance> newInstance = build(newServiceInstance);
if (!Objects.equals(newInstance.getName(), oldInstance.getName())
|| !Objects.equals(newInstance.getId(), oldInstance.getId())) {
// Ignore if id changed. Should unregister first.
super.doUpdate(oldServiceInstance, newServiceInstance);
return;
}
try {
this.serviceInstance = newServiceInstance;
reportMetadata(newServiceInstance.getServiceMetadata());
serviceDiscovery.updateService(newInstance);
} catch (Exception e) {
throw new RpcException(REGISTRY_EXCEPTION, "Failed register instance " + newServiceInstance.toString(), e);
}
}
@Override
public Set<String> getServices() {
return doInServiceDiscovery(s -> new LinkedHashSet<>(s.queryForNames()));
}
@Override
public List<ServiceInstance> getInstances(String serviceName) throws NullPointerException {
return doInServiceDiscovery(s -> build(registryURL, s.queryForInstances(serviceName)));
}
@Override
public void addServiceInstancesChangedListener(ServiceInstancesChangedListener listener)
throws NullPointerException, IllegalArgumentException {
// check if listener has already been added through another interface/service
if (!instanceListeners.add(listener)) {
return;
}
listener.getServiceNames().forEach(serviceName -> registerServiceWatcher(serviceName, listener));
}
@Override
public void removeServiceInstancesChangedListener(ServiceInstancesChangedListener listener)
throws IllegalArgumentException {
if (!instanceListeners.remove(listener)) {
return;
}
listener.getServiceNames().forEach(serviceName -> {
ZookeeperServiceDiscoveryChangeWatcher watcher = watcherCaches.get(serviceName);
if (watcher != null) {
watcher.getListeners().remove(listener);
if (watcher.getListeners().isEmpty()) {
watcherCaches.remove(serviceName);
try {
watcher.getCacheInstance().close();
} catch (IOException e) {
logger.error(
REGISTRY_ZOOKEEPER_EXCEPTION,
"curator stop watch failed",
"",
"Curator Stop service discovery watch failed. Service Name: " + serviceName);
}
}
}
});
}
@Override
public boolean isAvailable() {
// Fix the issue of timeout for all calls to the isAvailable method after the zookeeper is disconnected
return !isDestroy() && isConnected() && CollectionUtils.isNotEmpty(getServices());
}
private boolean isConnected() {
if (curatorFramework == null || curatorFramework.getZookeeperClient() == null) {
return false;
}
return curatorFramework.getZookeeperClient().isConnected();
}
private void doInServiceRegistry(ThrowableConsumer<org.apache.curator.x.discovery.ServiceDiscovery> consumer) {
ThrowableConsumer.execute(serviceDiscovery, s -> consumer.accept(s));
}
private <R> R doInServiceDiscovery(ThrowableFunction<org.apache.curator.x.discovery.ServiceDiscovery, R> function) {
return execute(serviceDiscovery, function);
}
protected void registerServiceWatcher(String serviceName, ServiceInstancesChangedListener listener) {
CountDownLatch latch = new CountDownLatch(1);
ZookeeperServiceDiscoveryChangeWatcher watcher = watcherCaches.computeIfAbsent(serviceName, name -> {
ServiceCache<ZookeeperInstance> serviceCache =
serviceDiscovery.serviceCacheBuilder().name(name).build();
ZookeeperServiceDiscoveryChangeWatcher newer =
new ZookeeperServiceDiscoveryChangeWatcher(this, serviceCache, name, latch);
serviceCache.addListener(newer);
try {
serviceCache.start();
} catch (Exception e) {
throw new RpcException(REGISTRY_EXCEPTION, "Failed subscribe service: " + name, e);
}
return newer;
});
watcher.addListener(listener);
listener.onEvent(new ServiceInstancesChangedEvent(serviceName, this.getInstances(serviceName)));
latch.countDown();
}
}
| 5,407 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistry.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.registry.zookeeper;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.common.utils.ConcurrentHashSet;
import org.apache.dubbo.common.utils.UrlUtils;
import org.apache.dubbo.registry.NotifyListener;
import org.apache.dubbo.registry.support.CacheableFailbackRegistry;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.remoting.zookeeper.ChildListener;
import org.apache.dubbo.remoting.zookeeper.StateListener;
import org.apache.dubbo.remoting.zookeeper.ZookeeperClient;
import org.apache.dubbo.remoting.zookeeper.ZookeeperTransporter;
import org.apache.dubbo.rpc.RpcException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CountDownLatch;
import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE;
import static org.apache.dubbo.common.constants.CommonConstants.CHECK_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ZOOKEEPER_EXCEPTION;
import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_CATEGORY;
import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMERS_CATEGORY;
import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_CATEGORY;
import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDERS_CATEGORY;
import static org.apache.dubbo.common.constants.RegistryConstants.ROUTERS_CATEGORY;
/**
* ZookeeperRegistry
*/
public class ZookeeperRegistry extends CacheableFailbackRegistry {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ZookeeperRegistry.class);
private static final String DEFAULT_ROOT = "dubbo";
private final String root;
private final Set<String> anyServices = new ConcurrentHashSet<>();
private final ConcurrentMap<URL, ConcurrentMap<NotifyListener, ChildListener>> zkListeners =
new ConcurrentHashMap<>();
private ZookeeperClient zkClient;
public ZookeeperRegistry(URL url, ZookeeperTransporter zookeeperTransporter) {
super(url);
if (url.isAnyHost()) {
throw new IllegalStateException("registry address == null");
}
String group = url.getGroup(DEFAULT_ROOT);
if (!group.startsWith(PATH_SEPARATOR)) {
group = PATH_SEPARATOR + group;
}
this.root = group;
this.zkClient = zookeeperTransporter.connect(url);
this.zkClient.addStateListener((state) -> {
if (state == StateListener.RECONNECTED) {
logger.warn(
REGISTRY_ZOOKEEPER_EXCEPTION,
"",
"",
"Trying to fetch the latest urls, in case there are provider changes during connection loss.\n"
+ " Since ephemeral ZNode will not get deleted for a connection lose, "
+ "there's no need to re-register url of this instance.");
ZookeeperRegistry.this.fetchLatestAddresses();
} else if (state == StateListener.NEW_SESSION_CREATED) {
logger.warn(
REGISTRY_ZOOKEEPER_EXCEPTION,
"",
"",
"Trying to re-register urls and re-subscribe listeners of this instance to registry...");
try {
ZookeeperRegistry.this.recover();
} catch (Exception e) {
logger.error(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", e.getMessage(), e);
}
} else if (state == StateListener.SESSION_LOST) {
logger.warn(
REGISTRY_ZOOKEEPER_EXCEPTION,
"",
"",
"Url of this instance will be deleted from registry soon. "
+ "Dubbo client will try to re-register once a new session is created.");
} else if (state == StateListener.SUSPENDED) {
} else if (state == StateListener.CONNECTED) {
}
});
}
@Override
public boolean isAvailable() {
return zkClient != null && zkClient.isConnected();
}
@Override
public void destroy() {
super.destroy();
// remove child listener
Set<URL> urls = zkListeners.keySet();
for (URL url : urls) {
ConcurrentMap<NotifyListener, ChildListener> map = zkListeners.get(url);
if (CollectionUtils.isEmptyMap(map)) {
continue;
}
Collection<ChildListener> childListeners = map.values();
if (CollectionUtils.isEmpty(childListeners)) {
continue;
}
if (ANY_VALUE.equals(url.getServiceInterface())) {
String root = toRootPath();
childListeners.stream().forEach(childListener -> zkClient.removeChildListener(root, childListener));
} else {
for (String path : toCategoriesPath(url)) {
childListeners.stream().forEach(childListener -> zkClient.removeChildListener(path, childListener));
}
}
}
zkListeners.clear();
// Just release zkClient reference, but can not close zk client here for zk client is shared somewhere else.
// See org.apache.dubbo.remoting.zookeeper.AbstractZookeeperTransporter#destroy()
zkClient = null;
}
private void checkDestroyed() {
if (zkClient == null) {
throw new IllegalStateException("registry is destroyed");
}
}
@Override
public void doRegister(URL url) {
try {
checkDestroyed();
zkClient.create(toUrlPath(url), url.getParameter(DYNAMIC_KEY, true), true);
} catch (Throwable e) {
throw new RpcException(
"Failed to register " + url + " to zookeeper " + getUrl() + ", cause: " + e.getMessage(), e);
}
}
@Override
public void doUnregister(URL url) {
try {
checkDestroyed();
zkClient.delete(toUrlPath(url));
} catch (Throwable e) {
throw new RpcException(
"Failed to unregister " + url + " to zookeeper " + getUrl() + ", cause: " + e.getMessage(), e);
}
}
@Override
public void doSubscribe(final URL url, final NotifyListener listener) {
try {
checkDestroyed();
if (ANY_VALUE.equals(url.getServiceInterface())) {
String root = toRootPath();
boolean check = url.getParameter(CHECK_KEY, false);
ConcurrentMap<NotifyListener, ChildListener> listeners =
ConcurrentHashMapUtils.computeIfAbsent(zkListeners, url, k -> new ConcurrentHashMap<>());
ChildListener zkListener = ConcurrentHashMapUtils.computeIfAbsent(
listeners, listener, k -> (parentPath, currentChildren) -> {
for (String child : currentChildren) {
child = URL.decode(child);
if (!anyServices.contains(child)) {
anyServices.add(child);
subscribe(
url.setPath(child)
.addParameters(
INTERFACE_KEY,
child,
Constants.CHECK_KEY,
String.valueOf(check)),
k);
}
}
});
zkClient.create(root, false, true);
List<String> services = zkClient.addChildListener(root, zkListener);
if (CollectionUtils.isNotEmpty(services)) {
for (String service : services) {
service = URL.decode(service);
anyServices.add(service);
subscribe(
url.setPath(service)
.addParameters(
INTERFACE_KEY, service, Constants.CHECK_KEY, String.valueOf(check)),
listener);
}
}
} else {
CountDownLatch latch = new CountDownLatch(1);
try {
List<URL> urls = new ArrayList<>();
/*
Iterate over the category value in URL.
With default settings, the path variable can be when url is a consumer URL:
/dubbo/[service name]/providers,
/dubbo/[service name]/configurators
/dubbo/[service name]/routers
*/
for (String path : toCategoriesPath(url)) {
ConcurrentMap<NotifyListener, ChildListener> listeners = ConcurrentHashMapUtils.computeIfAbsent(
zkListeners, url, k -> new ConcurrentHashMap<>());
ChildListener zkListener = ConcurrentHashMapUtils.computeIfAbsent(
listeners, listener, k -> new RegistryChildListenerImpl(url, k, latch));
if (zkListener instanceof RegistryChildListenerImpl) {
((RegistryChildListenerImpl) zkListener).setLatch(latch);
}
// create "directories".
zkClient.create(path, false, true);
// Add children (i.e. service items).
List<String> children = zkClient.addChildListener(path, zkListener);
if (children != null) {
// The invocation point that may cause 1-1.
urls.addAll(toUrlsWithEmpty(url, path, children));
}
}
notify(url, listener, urls);
} finally {
// tells the listener to run only after the sync notification of main thread finishes.
latch.countDown();
}
}
} catch (Throwable e) {
throw new RpcException(
"Failed to subscribe " + url + " to zookeeper " + getUrl() + ", cause: " + e.getMessage(), e);
}
}
@Override
public void doUnsubscribe(URL url, NotifyListener listener) {
super.doUnsubscribe(url, listener);
checkDestroyed();
ConcurrentMap<NotifyListener, ChildListener> listeners = zkListeners.get(url);
if (listeners != null) {
ChildListener zkListener = listeners.remove(listener);
if (zkListener != null) {
if (ANY_VALUE.equals(url.getServiceInterface())) {
String root = toRootPath();
zkClient.removeChildListener(root, zkListener);
} else {
for (String path : toCategoriesPath(url)) {
zkClient.removeChildListener(path, zkListener);
}
}
}
if (listeners.isEmpty()) {
zkListeners.remove(url);
}
}
}
@Override
public List<URL> lookup(URL url) {
if (url == null) {
throw new IllegalArgumentException("lookup url == null");
}
try {
checkDestroyed();
List<String> providers = new ArrayList<>();
for (String path : toCategoriesPath(url)) {
List<String> children = zkClient.getChildren(path);
if (children != null) {
providers.addAll(children);
}
}
return toUrlsWithoutEmpty(url, providers);
} catch (Throwable e) {
throw new RpcException(
"Failed to lookup " + url + " from zookeeper " + getUrl() + ", cause: " + e.getMessage(), e);
}
}
private String toRootDir() {
if (root.equals(PATH_SEPARATOR)) {
return root;
}
return root + PATH_SEPARATOR;
}
private String toRootPath() {
return root;
}
private String toServicePath(URL url) {
String name = url.getServiceInterface();
if (ANY_VALUE.equals(name)) {
return toRootPath();
}
return toRootDir() + URL.encode(name);
}
private String[] toCategoriesPath(URL url) {
String[] categories;
if (ANY_VALUE.equals(url.getCategory())) {
categories =
new String[] {PROVIDERS_CATEGORY, CONSUMERS_CATEGORY, ROUTERS_CATEGORY, CONFIGURATORS_CATEGORY};
} else {
categories = url.getCategory(new String[] {DEFAULT_CATEGORY});
}
String[] paths = new String[categories.length];
for (int i = 0; i < categories.length; i++) {
paths[i] = toServicePath(url) + PATH_SEPARATOR + categories[i];
}
return paths;
}
private String toCategoryPath(URL url) {
return toServicePath(url) + PATH_SEPARATOR + url.getCategory(DEFAULT_CATEGORY);
}
private String toUrlPath(URL url) {
return toCategoryPath(url) + PATH_SEPARATOR + URL.encode(url.toFullString());
}
/**
* When zookeeper connection recovered from a connection loss, it needs to fetch the latest provider list.
* re-register watcher is only a side effect and is not mandate.
*/
private void fetchLatestAddresses() {
// subscribe
Map<URL, Set<NotifyListener>> recoverSubscribed = new HashMap<>(getSubscribed());
if (!recoverSubscribed.isEmpty()) {
if (logger.isInfoEnabled()) {
logger.info("Fetching the latest urls of " + recoverSubscribed.keySet());
}
for (Map.Entry<URL, Set<NotifyListener>> entry : recoverSubscribed.entrySet()) {
URL url = entry.getKey();
for (NotifyListener listener : entry.getValue()) {
removeFailedSubscribed(url, listener);
addFailedSubscribed(url, listener);
}
}
}
}
@Override
protected boolean isMatch(URL subscribeUrl, URL providerUrl) {
return UrlUtils.isMatch(subscribeUrl, providerUrl);
}
/**
* Triggered when children get changed. It will be invoked by implementation of CuratorWatcher.
* <p>
* 'org.apache.dubbo.remoting.zookeeper.curator5.Curator5ZookeeperClient.CuratorWatcherImpl' (Curator 5)
*/
private class RegistryChildListenerImpl implements ChildListener {
private final ZookeeperRegistryNotifier notifier;
private volatile CountDownLatch latch;
public RegistryChildListenerImpl(URL consumerUrl, NotifyListener listener, CountDownLatch latch) {
this.latch = latch;
this.notifier = new ZookeeperRegistryNotifier(consumerUrl, listener, ZookeeperRegistry.this.getDelay());
}
public void setLatch(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void childChanged(String path, List<String> children) {
// Notify 'notifiers' one by one.
try {
latch.await();
} catch (InterruptedException e) {
logger.warn(
REGISTRY_ZOOKEEPER_EXCEPTION,
"",
"",
"Zookeeper children listener thread was interrupted unexpectedly, may cause race condition with the main thread.");
}
notifier.notify(path, children);
}
}
/**
* Customized Registry Notifier for zookeeper registry.
*/
public class ZookeeperRegistryNotifier {
private long lastExecuteTime;
private final URL consumerUrl;
private final NotifyListener listener;
private final long delayTime;
public ZookeeperRegistryNotifier(URL consumerUrl, NotifyListener listener, long delayTime) {
this.consumerUrl = consumerUrl;
this.listener = listener;
this.delayTime = delayTime;
}
public void notify(String path, Object rawAddresses) {
// notify immediately if it's notification of governance rules.
if (path.endsWith(CONFIGURATORS_CATEGORY) || path.endsWith(ROUTERS_CATEGORY)) {
this.doNotify(path, rawAddresses);
}
// if address notification, check if delay is necessary.
if (delayTime <= 0) {
this.doNotify(path, rawAddresses);
} else {
long interval = delayTime - (System.currentTimeMillis() - lastExecuteTime);
if (interval > 0) {
try {
Thread.sleep(interval);
} catch (InterruptedException e) {
// ignore
}
}
lastExecuteTime = System.currentTimeMillis();
this.doNotify(path, rawAddresses);
}
}
protected void doNotify(String path, Object rawAddresses) {
ZookeeperRegistry.this.notify(
consumerUrl, listener, ZookeeperRegistry.this.toUrlsWithEmpty(consumerUrl, path, (List<String>)
rawAddresses));
}
}
}
| 5,408 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscoveryFactory.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.registry.zookeeper;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.registry.client.AbstractServiceDiscoveryFactory;
import org.apache.dubbo.registry.client.ServiceDiscovery;
public class ZookeeperServiceDiscoveryFactory extends AbstractServiceDiscoveryFactory {
@Override
protected ServiceDiscovery createDiscovery(URL registryURL) {
return new ZookeeperServiceDiscovery(applicationModel, registryURL);
}
}
| 5,409 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistryFactory.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.registry.zookeeper;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.DisableInject;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.support.AbstractRegistryFactory;
import org.apache.dubbo.remoting.zookeeper.ZookeeperTransporter;
import org.apache.dubbo.rpc.model.ApplicationModel;
/**
* ZookeeperRegistryFactory.
*/
public class ZookeeperRegistryFactory extends AbstractRegistryFactory {
private ZookeeperTransporter zookeeperTransporter;
// for compatible usage
public ZookeeperRegistryFactory() {
this(ApplicationModel.defaultModel());
}
public ZookeeperRegistryFactory(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
this.zookeeperTransporter = ZookeeperTransporter.getExtension(applicationModel);
}
@DisableInject
public void setZookeeperTransporter(ZookeeperTransporter zookeeperTransporter) {
this.zookeeperTransporter = zookeeperTransporter;
}
@Override
public Registry createRegistry(URL url) {
return new ZookeeperRegistry(url, zookeeperTransporter);
}
}
| 5,410 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscoveryChangeWatcher.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.registry.zookeeper;
import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository;
import org.apache.dubbo.common.utils.ConcurrentHashSet;
import org.apache.dubbo.registry.RegistryNotifier;
import org.apache.dubbo.registry.client.ServiceDiscovery;
import org.apache.dubbo.registry.client.ServiceInstance;
import org.apache.dubbo.registry.client.event.ServiceInstancesChangedEvent;
import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener;
import org.apache.dubbo.rpc.model.ScopeModelUtil;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.api.CuratorWatcher;
import org.apache.curator.framework.state.ConnectionState;
import org.apache.curator.x.discovery.ServiceCache;
import org.apache.curator.x.discovery.details.ServiceCacheListener;
import org.apache.zookeeper.Watcher;
/**
* Zookeeper {@link ServiceDiscovery} Change {@link CuratorWatcher watcher} only interests in
* {@link Watcher.Event.EventType#NodeChildrenChanged} and {@link Watcher.Event.EventType#NodeDataChanged} event types,
* which will multicast a {@link ServiceInstancesChangedEvent} when the service node has been changed.
*
* @since 2.7.5
*/
public class ZookeeperServiceDiscoveryChangeWatcher implements ServiceCacheListener {
private final Set<ServiceInstancesChangedListener> listeners = new ConcurrentHashSet<>();
private final ServiceCache<ZookeeperInstance> cacheInstance;
private final ZookeeperServiceDiscovery zookeeperServiceDiscovery;
private final RegistryNotifier notifier;
private final String serviceName;
private final CountDownLatch latch;
public ZookeeperServiceDiscoveryChangeWatcher(
ZookeeperServiceDiscovery zookeeperServiceDiscovery,
ServiceCache<ZookeeperInstance> cacheInstance,
String serviceName,
CountDownLatch latch) {
this.zookeeperServiceDiscovery = zookeeperServiceDiscovery;
this.cacheInstance = cacheInstance;
this.serviceName = serviceName;
this.notifier =
new RegistryNotifier(
zookeeperServiceDiscovery.getUrl(),
zookeeperServiceDiscovery.getDelay(),
ScopeModelUtil.getFrameworkModel(
zookeeperServiceDiscovery.getUrl().getScopeModel())
.getBeanFactory()
.getBean(FrameworkExecutorRepository.class)
.getServiceDiscoveryAddressNotificationExecutor()) {
@Override
protected void doNotify(Object rawAddresses) {
listeners.forEach(listener -> listener.onEvent((ServiceInstancesChangedEvent) rawAddresses));
}
};
this.latch = latch;
}
@Override
public void cacheChanged() {
try {
latch.await();
} catch (InterruptedException ignore) {
Thread.currentThread().interrupt();
}
List<ServiceInstance> instanceList = zookeeperServiceDiscovery.getInstances(serviceName);
notifier.notify(new ServiceInstancesChangedEvent(serviceName, instanceList));
}
@Override
public void stateChanged(CuratorFramework curatorFramework, ConnectionState connectionState) {
// ignore: taken care by curator ServiceDiscovery
}
public ServiceCache<ZookeeperInstance> getCacheInstance() {
return cacheInstance;
}
public Set<ServiceInstancesChangedListener> getListeners() {
return listeners;
}
public void addListener(ServiceInstancesChangedListener listener) {
listeners.add(listener);
}
}
| 5,411 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper | Create_ds/dubbo/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/util/CuratorFrameworkParams.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.registry.zookeeper.util;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.registry.client.ServiceInstance;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import org.apache.curator.framework.CuratorFramework;
import static org.apache.dubbo.registry.zookeeper.ZookeeperServiceDiscovery.DEFAULT_GROUP;
/**
* The enumeration for the parameters of {@link CuratorFramework}
*
* @see CuratorFramework
* @since 2.7.5
*/
public enum CuratorFrameworkParams {
/**
* The root path of Dubbo Service
*/
ROOT_PATH("rootPath", DEFAULT_GROUP, value -> value),
GROUP_PATH("group", DEFAULT_GROUP, value -> value),
/**
* The host of current {@link ServiceInstance service instance} that will be registered
*/
INSTANCE_HOST("instanceHost", null, value -> value),
/**
* The port of current {@link ServiceInstance service instance} that will be registered
*/
INSTANCE_PORT("instancePort", null, value -> value),
/**
* Initial amount of time to wait between retries
*/
BASE_SLEEP_TIME("baseSleepTimeMs", 50, Integer::valueOf),
/**
* Max number of times to retry.
*/
MAX_RETRIES("maxRetries", 10, Integer::valueOf),
/**
* Max time in ms to sleep on each retry.
*/
MAX_SLEEP("maxSleepMs", 500, Integer::valueOf),
/**
* Wait time to block on connection to Zookeeper.
*/
BLOCK_UNTIL_CONNECTED_WAIT("blockUntilConnectedWait", 10, Integer::valueOf),
/**
* The unit of time related to blocking on connection to Zookeeper.
*/
BLOCK_UNTIL_CONNECTED_UNIT("blockUntilConnectedUnit", TimeUnit.SECONDS, TimeUnit::valueOf),
;
private final String name;
private final Object defaultValue;
private final Function<String, Object> converter;
<T> CuratorFrameworkParams(String name, T defaultValue, Function<String, T> converter) {
this.name = name;
this.defaultValue = defaultValue;
this.converter = (Function<String, Object>) converter;
}
/**
* Get the parameter value from the specified {@link URL}
*
* @param url the Dubbo registry {@link URL}
* @param <T> the type of value
* @return the parameter value if present, or return <code>null</code>
*/
public <T> T getParameterValue(URL url) {
String param = url.getParameter(name);
Object value = param != null ? converter.apply(param) : defaultValue;
return (T) value;
}
}
| 5,412 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper | Create_ds/dubbo/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/util/CuratorFrameworkUtils.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.registry.zookeeper.util;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.registry.client.DefaultServiceInstance;
import org.apache.dubbo.registry.client.ServiceInstance;
import org.apache.dubbo.registry.zookeeper.ZookeeperInstance;
import org.apache.dubbo.registry.zookeeper.ZookeeperServiceDiscovery;
import org.apache.dubbo.rpc.model.ScopeModelUtil;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.ACLProvider;
import org.apache.curator.framework.imps.CuratorFrameworkState;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.x.discovery.ServiceDiscovery;
import org.apache.curator.x.discovery.ServiceDiscoveryBuilder;
import org.apache.curator.x.discovery.ServiceInstanceBuilder;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.ACL;
import static org.apache.curator.x.discovery.ServiceInstance.builder;
import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR;
import static org.apache.dubbo.registry.zookeeper.ZookeeperServiceDiscovery.DEFAULT_GROUP;
import static org.apache.dubbo.registry.zookeeper.util.CuratorFrameworkParams.BASE_SLEEP_TIME;
import static org.apache.dubbo.registry.zookeeper.util.CuratorFrameworkParams.BLOCK_UNTIL_CONNECTED_UNIT;
import static org.apache.dubbo.registry.zookeeper.util.CuratorFrameworkParams.BLOCK_UNTIL_CONNECTED_WAIT;
import static org.apache.dubbo.registry.zookeeper.util.CuratorFrameworkParams.GROUP_PATH;
import static org.apache.dubbo.registry.zookeeper.util.CuratorFrameworkParams.MAX_RETRIES;
import static org.apache.dubbo.registry.zookeeper.util.CuratorFrameworkParams.MAX_SLEEP;
import static org.apache.dubbo.registry.zookeeper.util.CuratorFrameworkParams.ROOT_PATH;
/**
* Curator Framework Utilities Class
*
* @since 2.7.5
*/
public abstract class CuratorFrameworkUtils {
public static ServiceDiscovery<ZookeeperInstance> buildServiceDiscovery(
CuratorFramework curatorFramework, String basePath) {
return ServiceDiscoveryBuilder.builder(ZookeeperInstance.class)
.client(curatorFramework)
.basePath(basePath)
.build();
}
public static CuratorFramework buildCuratorFramework(URL connectionURL, ZookeeperServiceDiscovery serviceDiscovery)
throws Exception {
CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder()
.connectString(connectionURL.getBackupAddress())
.retryPolicy(buildRetryPolicy(connectionURL));
String userInformation = connectionURL.getUserInformation();
if (StringUtils.isNotEmpty(userInformation)) {
builder = builder.authorization("digest", userInformation.getBytes());
builder.aclProvider(new ACLProvider() {
@Override
public List<ACL> getDefaultAcl() {
return ZooDefs.Ids.CREATOR_ALL_ACL;
}
@Override
public List<ACL> getAclForPath(String path) {
return ZooDefs.Ids.CREATOR_ALL_ACL;
}
});
}
CuratorFramework curatorFramework = builder.build();
curatorFramework.start();
curatorFramework.blockUntilConnected(
BLOCK_UNTIL_CONNECTED_WAIT.getParameterValue(connectionURL),
BLOCK_UNTIL_CONNECTED_UNIT.getParameterValue(connectionURL));
if (!curatorFramework.getState().equals(CuratorFrameworkState.STARTED)) {
throw new IllegalStateException("zookeeper client initialization failed");
}
if (!curatorFramework.getZookeeperClient().isConnected()) {
throw new IllegalStateException("failed to connect to zookeeper server");
}
return curatorFramework;
}
public static RetryPolicy buildRetryPolicy(URL connectionURL) {
int baseSleepTimeMs = BASE_SLEEP_TIME.getParameterValue(connectionURL);
int maxRetries = MAX_RETRIES.getParameterValue(connectionURL);
int getMaxSleepMs = MAX_SLEEP.getParameterValue(connectionURL);
return new ExponentialBackoffRetry(baseSleepTimeMs, maxRetries, getMaxSleepMs);
}
public static List<ServiceInstance> build(
URL registryUrl, Collection<org.apache.curator.x.discovery.ServiceInstance<ZookeeperInstance>> instances) {
return instances.stream().map((i) -> build(registryUrl, i)).collect(Collectors.toList());
}
public static ServiceInstance build(
URL registryUrl, org.apache.curator.x.discovery.ServiceInstance<ZookeeperInstance> instance) {
String name = instance.getName();
String host = instance.getAddress();
int port = instance.getPort();
ZookeeperInstance zookeeperInstance = instance.getPayload();
DefaultServiceInstance serviceInstance = new DefaultServiceInstance(
name, host, port, ScopeModelUtil.getApplicationModel(registryUrl.getScopeModel()));
serviceInstance.setMetadata(zookeeperInstance.getMetadata());
return serviceInstance;
}
public static org.apache.curator.x.discovery.ServiceInstance<ZookeeperInstance> build(
ServiceInstance serviceInstance) {
ServiceInstanceBuilder builder;
String serviceName = serviceInstance.getServiceName();
String host = serviceInstance.getHost();
int port = serviceInstance.getPort();
Map<String, String> metadata = serviceInstance.getSortedMetadata();
String id = generateId(host, port);
ZookeeperInstance zookeeperInstance = new ZookeeperInstance(id, serviceName, metadata);
try {
builder =
builder().id(id).name(serviceName).address(host).port(port).payload(zookeeperInstance);
} catch (Exception e) {
throw new RuntimeException(e);
}
return builder.build();
}
public static String generateId(String host, int port) {
return host + ":" + port;
}
public static String getRootPath(URL registryURL) {
String group = ROOT_PATH.getParameterValue(registryURL);
if (group.equalsIgnoreCase(DEFAULT_GROUP)) {
group = GROUP_PATH.getParameterValue(registryURL);
if (!group.startsWith(PATH_SEPARATOR)) {
group = PATH_SEPARATOR + group;
}
}
return group;
}
}
| 5,413 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/RegistryServiceListener2.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.registry;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Activate;
@Activate(order = 2, value = "listener-two")
public class RegistryServiceListener2 implements RegistryServiceListener {
static RegistryServiceListener delegate;
@Override
public void onRegister(URL url, Registry registry) {
delegate.onRegister(url, registry);
}
@Override
public void onUnregister(URL url, Registry registry) {
delegate.onUnregister(url, registry);
}
@Override
public void onSubscribe(URL url, Registry registry) {
delegate.onSubscribe(url, registry);
}
@Override
public void onUnsubscribe(URL url, Registry registry) {
delegate.onUnsubscribe(url, registry);
}
}
| 5,414 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/ListenerRegistryWrapperTest.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.registry;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.url.component.ServiceConfigURL;
import org.apache.dubbo.registry.integration.DemoService;
import java.util.HashMap;
import java.util.Map;
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.registry.Constants.REGISTER_IP_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class ListenerRegistryWrapperTest {
@Test
void testSubscribe() {
Map<String, String> parameters = new HashMap<>();
parameters.put(INTERFACE_KEY, DemoService.class.getName());
parameters.put("registry", "zookeeper");
parameters.put("register", "true");
parameters.put(REGISTER_IP_KEY, "172.23.236.180");
parameters.put("registry.listeners", "listener-one");
Map<String, Object> attributes = new HashMap<>();
ServiceConfigURL serviceConfigURL = new ServiceConfigURL(
"registry", "127.0.0.1", 2181, "org.apache.dubbo.registry.RegistryService", parameters);
Map<String, String> refer = new HashMap<>();
attributes.put(REFER_KEY, refer);
attributes.put("key1", "value1");
URL url = serviceConfigURL.addAttributes(attributes);
RegistryFactory registryFactory = mock(RegistryFactory.class);
Registry registry = mock(Registry.class);
NotifyListener notifyListener = mock(NotifyListener.class);
when(registryFactory.getRegistry(url)).thenReturn(registry);
RegistryFactoryWrapper registryFactoryWrapper = new RegistryFactoryWrapper(registryFactory);
Registry registryWrapper = registryFactoryWrapper.getRegistry(url);
Assertions.assertTrue(registryWrapper instanceof ListenerRegistryWrapper);
URL subscribeUrl = new ServiceConfigURL("dubbo", "127.0.0.1", 20881, DemoService.class.getName(), parameters);
RegistryServiceListener listener = Mockito.mock(RegistryServiceListener.class);
RegistryServiceListener1.delegate = listener;
registryWrapper.subscribe(subscribeUrl, notifyListener);
verify(listener, times(1)).onSubscribe(subscribeUrl, registry);
}
}
| 5,415 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/MockLogger.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.registry;
import org.apache.dubbo.common.logger.Logger;
import java.util.HashSet;
import java.util.Set;
public class MockLogger implements Logger {
public Set<String> printedLogs = new HashSet<>();
public boolean checkLogHappened(String msgPrefix) {
for (String printedLog : printedLogs) {
if (printedLog.contains(msgPrefix)) {
return true;
}
}
return false;
}
@Override
public void trace(String msg) {}
@Override
public void trace(Throwable e) {}
@Override
public void trace(String msg, Throwable e) {}
@Override
public void debug(String msg) {}
@Override
public void debug(Throwable e) {}
@Override
public void debug(String msg, Throwable e) {}
@Override
public void info(String msg) {}
@Override
public void info(Throwable e) {}
@Override
public void info(String msg, Throwable e) {}
@Override
public void warn(String msg) {}
@Override
public void warn(Throwable e) {}
@Override
public void warn(String msg, Throwable e) {
printedLogs.add(msg);
}
@Override
public void error(String msg) {}
@Override
public void error(Throwable e) {}
@Override
public void error(String msg, Throwable e) {}
@Override
public boolean isTraceEnabled() {
return false;
}
@Override
public boolean isDebugEnabled() {
return false;
}
@Override
public boolean isInfoEnabled() {
return false;
}
@Override
public boolean isWarnEnabled() {
return false;
}
@Override
public boolean isErrorEnabled() {
return false;
}
}
| 5,416 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/ZKTools.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.registry;
import org.apache.dubbo.common.utils.NamedThreadFactory;
import org.apache.dubbo.common.utils.StringUtils;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.framework.api.CuratorListener;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.TreeCache;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import org.apache.curator.framework.recipes.cache.TreeCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
/**
*
*/
public class ZKTools {
private static CuratorFramework client;
private static ExecutorService executor =
Executors.newFixedThreadPool(1, new NamedThreadFactory("ZKTools-test", true));
public static void main(String[] args) throws Exception {
client = CuratorFrameworkFactory.newClient(
"127.0.0.1:2181", 60 * 1000, 60 * 1000, new ExponentialBackoffRetry(1000, 3));
client.start();
client.getCuratorListenable()
.addListener(
new CuratorListener() {
@Override
public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception {
System.out.println("event notification: " + event.getPath());
System.out.println(event);
}
},
executor);
// testMigrationRule();
testAppMigrationRule();
// tesConditionRule();
// testStartupConfig();
// testProviderConfig();
// testPathCache();
// testTreeCache();
// testCuratorListener();
// Thread.sleep(100000);
}
public static void testMigrationRule() {
String serviceStr = "key: demo-consumer\n" + "interfaces:\n"
+ " - serviceKey: org.apache.dubbo.demo.DemoService:1.0.0\n"
+ " threshold: 1.0\n"
+ " step: FORCE_APPLICATION";
try {
String servicePath = "/dubbo/config/DUBBO_SERVICEDISCOVERY_MIGRATION/demo-consumer.migration";
if (client.checkExists().forPath(servicePath) == null) {
client.create().creatingParentsIfNeeded().forPath(servicePath);
}
setData(servicePath, serviceStr);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void testAppMigrationRule() {
String serviceStr = "key: demo-consumer\n" + "applications:\n"
+ " - name: demo-provider\n"
+ " step: FORCE_APPLICATION\n"
+ " threshold: 0.8\n"
+ "interfaces:\n"
+ " - serviceKey: org.apache.dubbo.demo.DemoService\n"
+ " threshold: 1.0\n"
+ " step: FORCE_APPLICATION";
try {
String servicePath = "/dubbo/config/DUBBO_SERVICEDISCOVERY_MIGRATION/demo-consumer.migration";
if (client.checkExists().forPath(servicePath) == null) {
client.create().creatingParentsIfNeeded().forPath(servicePath);
}
setData(servicePath, serviceStr);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void testStartupConfig() {
String str =
"dubbo.registry.address=zookeeper://127.0.0.1:2181\n" + "dubbo.registry.group=dubboregistrygroup1\n"
+ "dubbo.metadata-report.address=zookeeper://127.0.0.1:2181\n"
+ "dubbo.protocol.port=20990\n"
+ "dubbo.service.org.apache.dubbo.demo.DemoService.timeout=9999\n";
// System.out.println(str);
try {
String path = "/dubboregistrygroup1/config/dubbo/dubbo.properties";
if (client.checkExists().forPath(path) == null) {
client.create().creatingParentsIfNeeded().forPath(path);
}
setData(path, str);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void testProviderConfig() {
String str = "---\n" + "apiVersion: v2.7\n"
+ "scope: service\n"
+ "key: dd-test/org.apache.dubbo.demo.DemoService:1.0.4\n"
+ "enabled: true\n"
+ "configs:\n"
+ "- addresses: ['0.0.0.0:20880']\n"
+ " side: provider\n"
+ " parameters:\n"
+ " timeout: 6000\n"
+ "...";
// System.out.println(str);
try {
String path = "/dubbo/config/dd-test*org.apache.dubbo.demo.DemoService:1.0.4/configurators";
if (client.checkExists().forPath(path) == null) {
client.create().creatingParentsIfNeeded().inBackground().forPath(path);
}
setData(path, str);
String pathaa = "/dubboregistrygroup1/config/aaa/dubbo.properties";
if (client.checkExists().forPath(pathaa) == null) {
client.create().creatingParentsIfNeeded().forPath(pathaa);
}
setData(pathaa, "aaaa");
String pathaaa = "/dubboregistrygroup1/config/aaa";
if (client.checkExists().forPath(pathaaa) == null) {
client.create().creatingParentsIfNeeded().inBackground().forPath(pathaaa);
}
setData(pathaaa, "aaaa");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void testConsumerConfig() {
String serviceStr = "---\n" + "scope: service\n"
+ "key: org.apache.dubbo.demo.DemoService\n"
+ "configs:\n"
+ " - addresses: [30.5.121.156]\n"
+ " side: consumer\n"
+ " rules:\n"
+ " cluster:\n"
+ " loadbalance: random\n"
+ " cluster: failfast\n"
+ " config:\n"
+ " timeout: 9999\n"
+ " weight: 222\n"
+ "...";
String appStr = "---\n" + "scope: application\n"
+ "key: demo-consumer\n"
+ "configs:\n"
+ " - addresses: [30.5.121.156]\n"
+ " services: [org.apache.dubbo.demo.DemoService]\n"
+ " side: consumer\n"
+ " rules:\n"
+ " cluster:\n"
+ " loadbalance: random\n"
+ " cluster: failfast\n"
+ " config:\n"
+ " timeout: 4444\n"
+ " weight: 222\n"
+ "...";
try {
String servicePath = "/dubbo/config/org.apache.dubbo.demo.DemoService/configurators";
if (client.checkExists().forPath(servicePath) == null) {
client.create().creatingParentsIfNeeded().forPath(servicePath);
}
setData(servicePath, serviceStr);
String appPath = "/dubbo/config/demo-consumer/configurators";
if (client.checkExists().forPath(appPath) == null) {
client.create().creatingParentsIfNeeded().forPath(appPath);
}
setData(appPath, appStr);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void tesConditionRule() {
String serviceStr = "---\n" + "scope: application\n"
+ "force: true\n"
+ "runtime: false\n"
+ "conditions:\n"
+ " - method!=sayHello =>\n"
+ " - method=routeMethod1 => 30.5.121.156:20880\n"
+ "...";
try {
String servicePath = "/dubbo/config/demo-consumer/routers";
if (client.checkExists().forPath(servicePath) == null) {
client.create().creatingParentsIfNeeded().forPath(servicePath);
}
setData(servicePath, serviceStr);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void setData(String path, String data) throws Exception {
client.setData().inBackground().forPath(path, data.getBytes());
}
public static void testPathCache() throws Exception {
CuratorFramework client = CuratorFrameworkFactory.newClient(
"127.0.0.1:2181", 60 * 1000, 60 * 1000, new ExponentialBackoffRetry(1000, 3));
client.start();
PathChildrenCache pathChildrenCache = new PathChildrenCache(client, "/dubbo/config", true);
pathChildrenCache.start(true);
pathChildrenCache
.getListenable()
.addListener(
(zkClient, event) -> {
System.out.println(event.getData().getPath());
},
Executors.newFixedThreadPool(1));
List<ChildData> dataList = pathChildrenCache.getCurrentData();
dataList.stream().map(ChildData::getPath).forEach(System.out::println);
}
public static void testTreeCache() throws Exception {
CuratorFramework client = CuratorFrameworkFactory.newClient(
"127.0.0.1:2181", 60 * 1000, 60 * 1000, new ExponentialBackoffRetry(1000, 3));
client.start();
CountDownLatch latch = new CountDownLatch(1);
TreeCache treeCache =
TreeCache.newBuilder(client, "/dubbo/config").setCacheData(true).build();
treeCache.start();
treeCache.getListenable().addListener(new TreeCacheListener() {
@Override
public void childEvent(CuratorFramework client, TreeCacheEvent event) {
TreeCacheEvent.Type type = event.getType();
ChildData data = event.getData();
if (type == TreeCacheEvent.Type.INITIALIZED) {
latch.countDown();
}
System.out.println(data.getPath() + "\n");
if (data.getPath().split("/").length == 5) {
byte[] value = data.getData();
String stringValue = new String(value, StandardCharsets.UTF_8);
// fire event to all listeners
Map<String, Object> added = null;
Map<String, Object> changed = null;
Map<String, Object> deleted = null;
switch (type) {
case NODE_ADDED:
added = new HashMap<>(1);
added.put(pathToKey(data.getPath()), stringValue);
added.forEach((k, v) -> System.out.println(k + " " + v));
break;
case NODE_REMOVED:
deleted = new HashMap<>(1);
deleted.put(pathToKey(data.getPath()), stringValue);
deleted.forEach((k, v) -> System.out.println(k + " " + v));
break;
case NODE_UPDATED:
changed = new HashMap<>(1);
changed.put(pathToKey(data.getPath()), stringValue);
changed.forEach((k, v) -> System.out.println(k + " " + v));
}
}
}
});
latch.await();
/* Map<String, ChildData> dataMap = treeCache.getCurrentChildren("/dubbo/config");
dataMap.forEach((k, v) -> {
System.out.println(k);
treeCache.getCurrentChildren("/dubbo/config/" + k).forEach((ck, cv) -> {
System.out.println(ck);
});
});*/
}
private static String pathToKey(String path) {
if (StringUtils.isEmpty(path)) {
return path;
}
return path.replace("/dubbo/config/", "").replaceAll("/", ".");
}
public static void testCuratorListener() throws Exception {
CuratorFramework client = CuratorFrameworkFactory.newClient(
"127.0.0.1:2181", 60 * 1000, 60 * 1000, new ExponentialBackoffRetry(1000, 3));
client.start();
List<String> children = client.getChildren().forPath("/dubbo/config");
children.forEach(System.out::println);
/*
client.getCuratorListenable().addListener(new CuratorListener() {
@Override
public void eventReceived(CuratorFramework curatorFramework, CuratorEvent curatorEvent) throws Exception {
curatorEvent.get
}
});
*/
/*client.getChildren().usingWatcher(new CuratorWatcher() {
@Override
public void process(WatchedEvent watchedEvent) throws Exception {
System.out.println(watchedEvent.getPath());
client.getChildren().usingWatcher(this).forPath("/dubbo/config");
System.out.println(watchedEvent.getWrapper().getPath());
}
}).forPath("/dubbo/config");*/
}
}
| 5,417 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/CacheableFailbackRegistryTest.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.registry;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.URLStrParser;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL;
import static org.apache.dubbo.common.constants.RegistryConstants.ENABLE_EMPTY_PROTECTION_KEY;
import static org.junit.jupiter.api.Assertions.assertEquals;
class CacheableFailbackRegistryTest {
static String service;
static URL serviceUrl;
static URL registryUrl;
static String urlStr;
static String urlStr2;
static String urlStr3;
MockCacheableRegistryImpl registry;
@BeforeAll
static void setProperty() {
System.setProperty("dubbo.application.url.cache.task.interval", "0");
System.setProperty("dubbo.application.url.cache.clear.waiting", "0");
FrameworkModel.destroyAll();
}
@BeforeEach
public void setUp() throws Exception {
service = "org.apache.dubbo.test.DemoService";
serviceUrl = URL.valueOf("dubbo://127.0.0.1/org.apache.dubbo.test.DemoService?category=providers");
registryUrl = URL.valueOf("http://1.2.3.4:9090/registry?check=false&file=N/A");
urlStr =
"dubbo%3A%2F%2F172.19.4.113%3A20880%2Forg.apache.dubbo.demo.DemoService%3Fside%3Dprovider%26timeout%3D3000";
urlStr2 =
"dubbo%3A%2F%2F172.19.4.114%3A20880%2Forg.apache.dubbo.demo.DemoService%3Fside%3Dprovider%26timeout%3D3000";
urlStr3 =
"dubbo%3A%2F%2F172.19.4.115%3A20880%2Forg.apache.dubbo.demo.DemoService%3Fside%3Dprovider%26timeout%3D3000";
}
@AfterEach
public void tearDown() {
registry.getStringUrls().clear();
registry.getStringAddress().clear();
registry.getStringParam().clear();
}
@Test
void testFullURLCache() {
final AtomicReference<Integer> resCount = new AtomicReference<>(0);
registry = new MockCacheableRegistryImpl(registryUrl);
URL url = URLStrParser.parseEncodedStr(urlStr);
NotifyListener listener = urls -> resCount.set(urls.size());
registry.addChildren(url);
registry.subscribe(serviceUrl, listener);
assertEquals(1, registry.getStringUrls().get(serviceUrl).size());
assertEquals(1, resCount.get());
registry.addChildren(url);
registry.subscribe(serviceUrl, listener);
assertEquals(1, registry.getStringUrls().get(serviceUrl).size());
assertEquals(1, resCount.get());
URL url1 = url.addParameter("k1", "v1");
registry.addChildren(url1);
registry.subscribe(serviceUrl, listener);
assertEquals(2, registry.getStringUrls().get(serviceUrl).size());
assertEquals(2, resCount.get());
URL url2 = url1.setHost("192.168.1.1");
registry.addChildren(url2);
registry.subscribe(serviceUrl, listener);
assertEquals(3, registry.getStringUrls().get(serviceUrl).size());
assertEquals(3, resCount.get());
}
@Test
void testURLAddressCache() {
final AtomicReference<Integer> resCount = new AtomicReference<>(0);
registry = new MockCacheableRegistryImpl(registryUrl);
URL url = URLStrParser.parseEncodedStr(urlStr);
NotifyListener listener = urls -> resCount.set(urls.size());
registry.addChildren(url);
registry.subscribe(serviceUrl, listener);
assertEquals(1, registry.getStringAddress().size());
assertEquals(1, resCount.get());
URL url1 = url.addParameter("k1", "v1");
registry.addChildren(url1);
registry.subscribe(serviceUrl, listener);
assertEquals(1, registry.getStringAddress().size());
assertEquals(2, resCount.get());
URL url2 = url1.setHost("192.168.1.1");
registry.addChildren(url2);
registry.subscribe(serviceUrl, listener);
assertEquals(2, registry.getStringAddress().size());
assertEquals(3, resCount.get());
}
@Test
void testURLParamCache() {
final AtomicReference<Integer> resCount = new AtomicReference<>(0);
registry = new MockCacheableRegistryImpl(registryUrl);
URL url = URLStrParser.parseEncodedStr(urlStr);
NotifyListener listener = urls -> resCount.set(urls.size());
registry.addChildren(url);
registry.subscribe(serviceUrl, listener);
assertEquals(1, registry.getStringParam().size());
assertEquals(1, resCount.get());
URL url1 = url.addParameter("k1", "v1");
registry.addChildren(url1);
registry.subscribe(serviceUrl, listener);
assertEquals(2, registry.getStringParam().size());
assertEquals(2, resCount.get());
URL url2 = url1.setHost("192.168.1.1");
registry.addChildren(url2);
registry.subscribe(serviceUrl, listener);
assertEquals(2, registry.getStringParam().size());
assertEquals(3, resCount.get());
}
@Test
void testRemove() {
final AtomicReference<Integer> resCount = new AtomicReference<>(0);
registry = new MockCacheableRegistryImpl(registryUrl);
URL url = URLStrParser.parseEncodedStr(urlStr);
NotifyListener listener = urls -> resCount.set(urls.size());
registry.addChildren(url);
registry.subscribe(serviceUrl, listener);
assertEquals(1, registry.getStringUrls().get(serviceUrl).size());
assertEquals(1, registry.getStringAddress().size());
assertEquals(1, registry.getStringParam().size());
assertEquals(1, resCount.get());
registry.clearChildren();
URL url1 = url.addParameter("k1", "v1");
registry.addChildren(url1);
registry.subscribe(serviceUrl, listener);
assertEquals(1, registry.getStringUrls().get(serviceUrl).size());
assertEquals(1, resCount.get());
// After RemovalTask
assertEquals(1, registry.getStringParam().size());
// StringAddress will be deleted because the related stringUrls cache has been deleted.
assertEquals(0, registry.getStringAddress().size());
registry.clearChildren();
URL url2 = url1.setHost("192.168.1.1");
registry.addChildren(url2);
registry.subscribe(serviceUrl, listener);
assertEquals(1, registry.getStringUrls().get(serviceUrl).size());
assertEquals(1, resCount.get());
// After RemovalTask
assertEquals(1, registry.getStringAddress().size());
// StringParam will be deleted because the related stringUrls cache has been deleted.
assertEquals(0, registry.getStringParam().size());
}
@Test
void testEmptyProtection() {
final AtomicReference<Integer> resCount = new AtomicReference<>(0);
final AtomicReference<List<URL>> currentUrls = new AtomicReference<>();
final List<URL> EMPTY_LIST = new ArrayList<>();
registry = new MockCacheableRegistryImpl(registryUrl.addParameter(ENABLE_EMPTY_PROTECTION_KEY, true));
URL url = URLStrParser.parseEncodedStr(urlStr);
URL url2 = URLStrParser.parseEncodedStr(urlStr2);
URL url3 = URLStrParser.parseEncodedStr(urlStr3);
NotifyListener listener = urls -> {
if (CollectionUtils.isEmpty(urls)) {
// do nothing
} else if (urls.size() == 1 && urls.get(0).getProtocol().equals(EMPTY_PROTOCOL)) {
resCount.set(0);
currentUrls.set(EMPTY_LIST);
} else {
resCount.set(urls.size());
currentUrls.set(urls);
}
};
registry.addChildren(url);
registry.addChildren(url2);
registry.addChildren(url3);
registry.subscribe(serviceUrl, listener);
assertEquals(3, resCount.get());
registry.removeChildren(url);
assertEquals(2, resCount.get());
registry.clearChildren();
assertEquals(2, resCount.get());
URL emptyRegistryURL = registryUrl.addParameter(ENABLE_EMPTY_PROTECTION_KEY, false);
MockCacheableRegistryImpl emptyRegistry = new MockCacheableRegistryImpl(emptyRegistryURL);
emptyRegistry.addChildren(url);
emptyRegistry.addChildren(url2);
emptyRegistry.subscribe(serviceUrl, listener);
assertEquals(2, resCount.get());
emptyRegistry.clearChildren();
assertEquals(0, currentUrls.get().size());
assertEquals(EMPTY_LIST, currentUrls.get());
}
@Test
void testNoEmptyProtection() {
final AtomicReference<Integer> resCount = new AtomicReference<>(0);
final AtomicReference<List<URL>> currentUrls = new AtomicReference<>();
final List<URL> EMPTY_LIST = new ArrayList<>();
registry = new MockCacheableRegistryImpl(registryUrl);
URL url = URLStrParser.parseEncodedStr(urlStr);
URL url2 = URLStrParser.parseEncodedStr(urlStr2);
URL url3 = URLStrParser.parseEncodedStr(urlStr3);
NotifyListener listener = urls -> {
if (CollectionUtils.isEmpty(urls)) {
// do nothing
} else if (urls.size() == 1 && urls.get(0).getProtocol().equals(EMPTY_PROTOCOL)) {
resCount.set(0);
currentUrls.set(EMPTY_LIST);
} else {
resCount.set(urls.size());
currentUrls.set(urls);
}
};
registry.addChildren(url);
registry.addChildren(url2);
registry.addChildren(url3);
registry.subscribe(serviceUrl, listener);
assertEquals(3, resCount.get());
registry.removeChildren(url);
assertEquals(2, resCount.get());
registry.clearChildren();
assertEquals(0, resCount.get());
URL emptyRegistryURL = registryUrl.addParameter(ENABLE_EMPTY_PROTECTION_KEY, true);
MockCacheableRegistryImpl emptyRegistry = new MockCacheableRegistryImpl(emptyRegistryURL);
emptyRegistry.addChildren(url);
emptyRegistry.addChildren(url2);
emptyRegistry.subscribe(serviceUrl, listener);
assertEquals(2, resCount.get());
emptyRegistry.clearChildren();
assertEquals(2, currentUrls.get().size());
}
}
| 5,418 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/PerformanceRegistryTest.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.registry;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.NetUtils;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_UNDEFINED_ARGUMENT;
/**
* RegistryPerformanceTest
*/
class PerformanceRegistryTest {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(PerformanceRegistryTest.class);
@Test
void testRegistry() {
// read server info from property
if (PerformanceUtils.getProperty("server", null) == null) {
logger.warn(CONFIG_UNDEFINED_ARGUMENT, "", "", "Please set -Dserver=127.0.0.1:9090");
return;
}
final int base = PerformanceUtils.getIntProperty("base", 0);
final int concurrent = PerformanceUtils.getIntProperty("concurrent", 100);
int r = PerformanceUtils.getIntProperty("runs", 1000);
final int runs = r > 0 ? r : Integer.MAX_VALUE;
final Registry registry = ExtensionLoader.getExtensionLoader(RegistryFactory.class)
.getAdaptiveExtension()
.getRegistry(URL.valueOf(
"remote://admin:hello1234@" + PerformanceUtils.getProperty("server", "10.20.153.28:9090")));
for (int i = 0; i < concurrent; i++) {
final int t = i;
new Thread(new Runnable() {
public void run() {
for (int j = 0; j < runs; j++) {
registry.register(
URL.valueOf("remote://" + NetUtils.getLocalHost() + ":8080/demoService" + t
+ "_" + j + "?version=1.0.0&application=demo&dubbo=2.0&interface="
+ "org.apache.dubbo.demo.DemoService" + (base + t) + "_" + (base + j)));
}
}
})
.start();
}
synchronized (PerformanceRegistryTest.class) {
while (true) {
try {
PerformanceRegistryTest.class.wait();
} catch (InterruptedException e) {
}
}
}
}
}
| 5,419 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/RegistryFactoryWrapperTest.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.registry;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
class RegistryFactoryWrapperTest {
private RegistryFactory registryFactory =
ExtensionLoader.getExtensionLoader(RegistryFactory.class).getAdaptiveExtension();
@Test
void test() throws Exception {
RegistryServiceListener listener1 = Mockito.mock(RegistryServiceListener.class);
RegistryServiceListener1.delegate = listener1;
RegistryServiceListener listener2 = Mockito.mock(RegistryServiceListener.class);
RegistryServiceListener2.delegate = listener2;
Registry registry = registryFactory.getRegistry(
URL.valueOf("simple://localhost:8080/registry-service?registry.listeners=listener-one,listener-two"));
URL url = URL.valueOf("dubbo://localhost:8081/simple.service");
registry.register(url);
Mockito.verify(listener1, Mockito.times(1)).onRegister(url, SimpleRegistryFactory.registry);
Mockito.verify(listener2, Mockito.times(1)).onRegister(url, SimpleRegistryFactory.registry);
registry.unregister(url);
Mockito.verify(listener1, Mockito.times(1)).onUnregister(url, SimpleRegistryFactory.registry);
Mockito.verify(listener2, Mockito.times(1)).onUnregister(url, SimpleRegistryFactory.registry);
registry.subscribe(url, Mockito.mock(NotifyListener.class));
Mockito.verify(listener1, Mockito.times(1)).onSubscribe(url, SimpleRegistryFactory.registry);
Mockito.verify(listener2, Mockito.times(1)).onSubscribe(url, SimpleRegistryFactory.registry);
registry.unsubscribe(url, Mockito.mock(NotifyListener.class));
Mockito.verify(listener1, Mockito.times(1)).onUnsubscribe(url, SimpleRegistryFactory.registry);
Mockito.verify(listener2, Mockito.times(1)).onUnsubscribe(url, SimpleRegistryFactory.registry);
}
}
| 5,420 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/MockCacheableRegistryImpl.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.registry;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.url.component.ServiceAddressURL;
import org.apache.dubbo.common.url.component.URLAddress;
import org.apache.dubbo.common.url.component.URLParam;
import org.apache.dubbo.common.utils.UrlUtils;
import org.apache.dubbo.registry.support.CacheableFailbackRegistry;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Semaphore;
/**
*
*/
public class MockCacheableRegistryImpl extends CacheableFailbackRegistry {
private final List<String> children = new ArrayList<>();
NotifyListener listener;
public MockCacheableRegistryImpl(URL url) {
super(url);
}
@Override
public int getDelay() {
return 0;
}
@Override
protected boolean isMatch(URL subscribeUrl, URL providerUrl) {
return UrlUtils.isMatch(subscribeUrl, providerUrl);
}
@Override
public void doRegister(URL url) {}
@Override
public void doUnregister(URL url) {}
@Override
public void doSubscribe(URL url, NotifyListener listener) {
List<URL> res = toUrlsWithoutEmpty(url, children);
Semaphore semaphore = getSemaphore();
while (semaphore.availablePermits() != 1) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// ignore
}
}
listener.notify(res);
this.listener = listener;
}
@Override
public void doUnsubscribe(URL url, NotifyListener listener) {
super.doUnsubscribe(url, listener);
}
@Override
public boolean isAvailable() {
return false;
}
public void addChildren(URL url) {
children.add(URL.encode(url.toFullString()));
}
public void removeChildren(URL url) {
children.remove(URL.encode(url.toFullString()));
if (listener != null) {
listener.notify(toUrlsWithEmpty(getUrl(), "providers", children));
}
}
public List<String> getChildren() {
return children;
}
public void clearChildren() {
children.clear();
if (listener != null) {
listener.notify(toUrlsWithEmpty(getUrl(), "providers", children));
}
}
public Map<URL, Map<String, ServiceAddressURL>> getStringUrls() {
return stringUrls;
}
public Map<String, URLAddress> getStringAddress() {
return stringAddress;
}
public Map<String, URLParam> getStringParam() {
return stringParam;
}
}
| 5,421 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/PerformanceUtils.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.registry;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
/**
* PerformanceUtils
*
*/
public class PerformanceUtils {
private static final int WIDTH = 64;
public static String getProperty(String key, String defaultValue) {
String value = System.getProperty(key);
if (value == null || value.trim().length() == 0 || value.startsWith("$")) {
return defaultValue;
}
return value.trim();
}
public static int getIntProperty(String key, int defaultValue) {
String value = System.getProperty(key);
if (value == null || value.trim().length() == 0 || value.startsWith("$")) {
return defaultValue;
}
return Integer.parseInt(value.trim());
}
public static boolean getBooleanProperty(String key, boolean defaultValue) {
String value = System.getProperty(key);
if (value == null || value.trim().length() == 0 || value.startsWith("$")) {
return defaultValue;
}
return Boolean.parseBoolean(value.trim());
}
public static List<String> getEnvironment() {
List<String> environment = new ArrayList<String>();
environment.add("OS: " + System.getProperty("os.name") + " " + System.getProperty("os.version") + " "
+ System.getProperty("os.arch", ""));
environment.add("CPU: " + Runtime.getRuntime().availableProcessors() + " cores");
environment.add(
"JVM: " + System.getProperty("java.vm.name") + " " + System.getProperty("java.runtime.version"));
environment.add("Memory: "
+ DecimalFormat.getIntegerInstance().format(Runtime.getRuntime().totalMemory()) + " bytes (Max: "
+ DecimalFormat.getIntegerInstance().format(Runtime.getRuntime().maxMemory()) + " bytes)");
NetworkInterface ni = PerformanceUtils.getNetworkInterface();
if (ni != null) {
environment.add("Network: " + ni.getDisplayName());
}
return environment;
}
public static void printSeparator() {
StringBuilder pad = new StringBuilder();
for (int i = 0; i < WIDTH; i++) {
pad.append('-');
}
System.out.println("+" + pad + "+");
}
public static void printBorder() {
StringBuilder pad = new StringBuilder();
for (int i = 0; i < WIDTH; i++) {
pad.append('=');
}
System.out.println("+" + pad + "+");
}
public static void printBody(String msg) {
StringBuilder pad = new StringBuilder();
int len = WIDTH - msg.length() - 1;
if (len > 0) {
for (int i = 0; i < len; i++) {
pad.append(' ');
}
}
System.out.println("| " + msg + pad + "|");
}
public static void printHeader(String msg) {
StringBuilder pad = new StringBuilder();
int len = WIDTH - msg.length();
if (len > 0) {
int half = len / 2;
for (int i = 0; i < half; i++) {
pad.append(' ');
}
}
System.out.println("|" + pad + msg + pad + ((len % 2 == 0) ? "" : " ") + "|");
}
public static NetworkInterface getNetworkInterface() {
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
if (interfaces != null) {
while (interfaces.hasMoreElements()) {
try {
return interfaces.nextElement();
} catch (Throwable e) {
}
}
}
} catch (SocketException e) {
}
return null;
}
}
| 5,422 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/RegistryServiceListener1.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.registry;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Activate;
@Activate(order = 1, value = "listener-one")
public class RegistryServiceListener1 implements RegistryServiceListener {
static RegistryServiceListener delegate;
@Override
public void onRegister(URL url, Registry registry) {
delegate.onRegister(url, registry);
}
@Override
public void onUnregister(URL url, Registry registry) {
delegate.onUnregister(url, registry);
}
@Override
public void onSubscribe(URL url, Registry registry) {
delegate.onSubscribe(url, registry);
}
@Override
public void onUnsubscribe(URL url, Registry registry) {
delegate.onUnsubscribe(url, registry);
}
}
| 5,423 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/SimpleRegistryFactory.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.registry;
import org.apache.dubbo.common.URL;
import org.mockito.Mockito;
public class SimpleRegistryFactory implements RegistryFactory {
static Registry registry = Mockito.mock(Registry.class);
@Override
public Registry getRegistry(URL url) {
return registry;
}
}
| 5,424 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/integration/CountRegistryProtocolListener.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.registry.integration;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Exporter;
import org.apache.dubbo.rpc.cluster.ClusterInvoker;
import java.util.concurrent.atomic.AtomicInteger;
public class CountRegistryProtocolListener implements RegistryProtocolListener {
private static final AtomicInteger referCounter = new AtomicInteger(0);
@Override
public void onExport(RegistryProtocol registryProtocol, Exporter<?> exporter) {}
@Override
public void onRefer(RegistryProtocol registryProtocol, ClusterInvoker<?> invoker, URL url, URL registryURL) {
referCounter.incrementAndGet();
}
@Override
public void onDestroy() {}
public static AtomicInteger getReferCounter() {
return referCounter;
}
}
| 5,425 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/integration/RegistryProtocolTest.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.registry.integration;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.CompositeConfiguration;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.url.component.ServiceConfigURL;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.RegistryFactory;
import org.apache.dubbo.registry.client.migration.MigrationInvoker;
import org.apache.dubbo.registry.client.migration.MigrationRuleListener;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.cluster.Cluster;
import org.apache.dubbo.rpc.cluster.support.FailoverCluster;
import org.apache.dubbo.rpc.cluster.support.MergeableCluster;
import org.apache.dubbo.rpc.cluster.support.wrapper.MockClusterWrapper;
import org.apache.dubbo.rpc.cluster.support.wrapper.ScopeClusterWrapper;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
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.DUBBO;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.REGISTRY_PROTOCOL_LISTENER_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMERS_CATEGORY;
import static org.apache.dubbo.registry.Constants.ENABLE_CONFIGURATION_LISTEN;
import static org.apache.dubbo.registry.Constants.REGISTER_IP_KEY;
import static org.apache.dubbo.remoting.Constants.CHECK_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.CONSUMER_URL_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class RegistryProtocolTest {
@AfterEach
public void tearDown() throws IOException {
Mockito.framework().clearInlineMocks();
ApplicationModel.defaultModel().destroy();
}
/**
* verify the generated consumer url information
*/
@Test
void testConsumerUrlWithoutProtocol() {
ApplicationConfig applicationConfig = new ApplicationConfig();
applicationConfig.setName("application1");
ConfigManager configManager = mock(ConfigManager.class);
when(configManager.getApplicationOrElseThrow()).thenReturn(applicationConfig);
CompositeConfiguration compositeConfiguration = mock(CompositeConfiguration.class);
when(compositeConfiguration.convert(Boolean.class, ENABLE_CONFIGURATION_LISTEN, true))
.thenReturn(true);
Map<String, String> parameters = new HashMap<>();
parameters.put(INTERFACE_KEY, DemoService.class.getName());
parameters.put("registry", "zookeeper");
parameters.put("register", "false");
parameters.put(REGISTER_IP_KEY, "172.23.236.180");
Map<String, Object> attributes = new HashMap<>();
ServiceConfigURL serviceConfigURL = new ServiceConfigURL(
"registry", "127.0.0.1", 2181, "org.apache.dubbo.registry.RegistryService", parameters);
Map<String, String> refer = new HashMap<>();
attributes.put(REFER_KEY, refer);
attributes.put("key1", "value1");
URL url = serviceConfigURL.addAttributes(attributes);
RegistryFactory registryFactory = mock(RegistryFactory.class);
Registry registry = mock(Registry.class);
RegistryProtocol registryProtocol = new RegistryProtocol();
MigrationRuleListener migrationRuleListener = mock(MigrationRuleListener.class);
List<RegistryProtocolListener> registryProtocolListeners = new ArrayList<>();
registryProtocolListeners.add(migrationRuleListener);
ModuleModel moduleModel = Mockito.spy(ApplicationModel.defaultModel().getDefaultModule());
moduleModel
.getApplicationModel()
.getApplicationConfigManager()
.setApplication(new ApplicationConfig("application1"));
ExtensionLoader<RegistryProtocolListener> extensionLoaderMock = mock(ExtensionLoader.class);
Mockito.when(moduleModel.getExtensionLoader(RegistryProtocolListener.class))
.thenReturn(extensionLoaderMock);
Mockito.when(extensionLoaderMock.getActivateExtension(url, REGISTRY_PROTOCOL_LISTENER_KEY))
.thenReturn(registryProtocolListeners);
url = url.setScopeModel(moduleModel);
when(registryFactory.getRegistry(registryProtocol.getRegistryUrl(url))).thenReturn(registry);
Cluster cluster = mock(Cluster.class);
Invoker<?> invoker = registryProtocol.doRefer(cluster, registry, DemoService.class, url, parameters);
Assertions.assertTrue(invoker instanceof MigrationInvoker);
URL consumerUrl = ((MigrationInvoker<?>) invoker).getConsumerUrl();
Assertions.assertTrue((consumerUrl != null));
// verify that the protocol header of consumerUrl is set to "consumer"
Assertions.assertEquals("consumer", consumerUrl.getProtocol());
Assertions.assertEquals(parameters.get(REGISTER_IP_KEY), consumerUrl.getHost());
Assertions.assertFalse(consumerUrl.getAttributes().containsKey(REFER_KEY));
Assertions.assertEquals("value1", consumerUrl.getAttribute("key1"));
}
/**
* verify that when the protocol is configured, the protocol of consumer url is the configured protocol
*/
@Test
void testConsumerUrlWithProtocol() {
ApplicationConfig applicationConfig = new ApplicationConfig();
applicationConfig.setName("application1");
ConfigManager configManager = mock(ConfigManager.class);
when(configManager.getApplicationOrElseThrow()).thenReturn(applicationConfig);
CompositeConfiguration compositeConfiguration = mock(CompositeConfiguration.class);
when(compositeConfiguration.convert(Boolean.class, ENABLE_CONFIGURATION_LISTEN, true))
.thenReturn(true);
Map<String, String> parameters = new HashMap<>();
parameters.put(INTERFACE_KEY, DemoService.class.getName());
parameters.put("registry", "zookeeper");
parameters.put("register", "false");
parameters.put(REGISTER_IP_KEY, "172.23.236.180");
parameters.put(PROTOCOL_KEY, "tri");
Map<String, Object> attributes = new HashMap<>();
ServiceConfigURL serviceConfigURL = new ServiceConfigURL(
"registry", "127.0.0.1", 2181, "org.apache.dubbo.registry.RegistryService", parameters);
Map<String, String> refer = new HashMap<>();
attributes.put(REFER_KEY, refer);
attributes.put("key1", "value1");
URL url = serviceConfigURL.addAttributes(attributes);
RegistryFactory registryFactory = mock(RegistryFactory.class);
RegistryProtocol registryProtocol = new RegistryProtocol();
Registry registry = mock(Registry.class);
MigrationRuleListener migrationRuleListener = mock(MigrationRuleListener.class);
List<RegistryProtocolListener> registryProtocolListeners = new ArrayList<>();
registryProtocolListeners.add(migrationRuleListener);
ModuleModel moduleModel = Mockito.spy(ApplicationModel.defaultModel().getDefaultModule());
moduleModel
.getApplicationModel()
.getApplicationConfigManager()
.setApplication(new ApplicationConfig("application1"));
ExtensionLoader<RegistryProtocolListener> extensionLoaderMock = mock(ExtensionLoader.class);
Mockito.when(moduleModel.getExtensionLoader(RegistryProtocolListener.class))
.thenReturn(extensionLoaderMock);
Mockito.when(extensionLoaderMock.getActivateExtension(url, REGISTRY_PROTOCOL_LISTENER_KEY))
.thenReturn(registryProtocolListeners);
url = url.setScopeModel(moduleModel);
when(registryFactory.getRegistry(registryProtocol.getRegistryUrl(url))).thenReturn(registry);
Cluster cluster = mock(Cluster.class);
Invoker<?> invoker = registryProtocol.doRefer(cluster, registry, DemoService.class, url, parameters);
Assertions.assertTrue(invoker instanceof MigrationInvoker);
URL consumerUrl = ((MigrationInvoker<?>) invoker).getConsumerUrl();
Assertions.assertTrue((consumerUrl != null));
// verify that the protocol of consumer url
Assertions.assertEquals("tri", consumerUrl.getProtocol());
Assertions.assertEquals(parameters.get(REGISTER_IP_KEY), consumerUrl.getHost());
Assertions.assertFalse(consumerUrl.getAttributes().containsKey(REFER_KEY));
Assertions.assertEquals("value1", consumerUrl.getAttribute("key1"));
}
/**
* verify that if multiple groups are not configured, the service reference of the registration center
* the default is FailoverCluster
*
* @see FailoverCluster
*/
@Test
void testReferWithoutGroup() {
ApplicationConfig applicationConfig = new ApplicationConfig();
applicationConfig.setName("application1");
ConfigManager configManager = mock(ConfigManager.class);
when(configManager.getApplicationOrElseThrow()).thenReturn(applicationConfig);
CompositeConfiguration compositeConfiguration = mock(CompositeConfiguration.class);
when(compositeConfiguration.convert(Boolean.class, ENABLE_CONFIGURATION_LISTEN, true))
.thenReturn(true);
Map<String, String> parameters = new HashMap<>();
parameters.put(INTERFACE_KEY, DemoService.class.getName());
parameters.put("registry", "zookeeper");
parameters.put("register", "false");
Map<String, Object> attributes = new HashMap<>();
ServiceConfigURL serviceConfigURL = new ServiceConfigURL(
"registry", "127.0.0.1", 2181, "org.apache.dubbo.registry.RegistryService", parameters);
Map<String, String> refer = new HashMap<>();
attributes.put(REFER_KEY, refer);
URL url = serviceConfigURL.addAttributes(attributes);
RegistryFactory registryFactory = mock(RegistryFactory.class);
Registry registry = mock(Registry.class);
MigrationRuleListener migrationRuleListener = mock(MigrationRuleListener.class);
List<RegistryProtocolListener> registryProtocolListeners = new ArrayList<>();
registryProtocolListeners.add(migrationRuleListener);
RegistryProtocol registryProtocol = new RegistryProtocol();
ModuleModel moduleModel = Mockito.spy(ApplicationModel.defaultModel().getDefaultModule());
moduleModel
.getApplicationModel()
.getApplicationConfigManager()
.setApplication(new ApplicationConfig("application1"));
ExtensionLoader extensionLoaderMock = mock(ExtensionLoader.class);
Mockito.when(moduleModel.getExtensionLoader(RegistryProtocolListener.class))
.thenReturn(extensionLoaderMock);
Mockito.when(extensionLoaderMock.getActivateExtension(url, REGISTRY_PROTOCOL_LISTENER_KEY))
.thenReturn(registryProtocolListeners);
Mockito.when(moduleModel.getExtensionLoader(RegistryFactory.class)).thenReturn(extensionLoaderMock);
Mockito.when(extensionLoaderMock.getAdaptiveExtension()).thenReturn(registryFactory);
url = url.setScopeModel(moduleModel);
when(registryFactory.getRegistry(registryProtocol.getRegistryUrl(url))).thenReturn(registry);
Invoker<?> invoker = registryProtocol.refer(DemoService.class, url);
Assertions.assertTrue(invoker instanceof MigrationInvoker);
Assertions.assertTrue(((MigrationInvoker<?>) invoker).getCluster() instanceof ScopeClusterWrapper);
Assertions.assertTrue(
((ScopeClusterWrapper) ((MigrationInvoker<?>) invoker).getCluster()).getCluster()
instanceof MockClusterWrapper);
Assertions.assertTrue(
((MockClusterWrapper) ((ScopeClusterWrapper) ((MigrationInvoker<?>) invoker).getCluster()).getCluster())
.getCluster()
instanceof FailoverCluster);
}
/**
* verify that if multiple groups are configured, the service reference of the registration center
*
* @see MergeableCluster
*/
@Test
void testReferWithGroup() {
ApplicationConfig applicationConfig = new ApplicationConfig();
applicationConfig.setName("application1");
ConfigManager configManager = mock(ConfigManager.class);
when(configManager.getApplicationOrElseThrow()).thenReturn(applicationConfig);
CompositeConfiguration compositeConfiguration = mock(CompositeConfiguration.class);
when(compositeConfiguration.convert(Boolean.class, ENABLE_CONFIGURATION_LISTEN, true))
.thenReturn(true);
Map<String, String> parameters = new HashMap<>();
parameters.put(INTERFACE_KEY, DemoService.class.getName());
parameters.put("registry", "zookeeper");
parameters.put("register", "false");
Map<String, Object> attributes = new HashMap<>();
ServiceConfigURL serviceConfigURL = new ServiceConfigURL(
"registry", "127.0.0.1", 2181, "org.apache.dubbo.registry.RegistryService", parameters);
Map<String, String> refer = new HashMap<>();
refer.put(GROUP_KEY, "group1,group2");
attributes.put(REFER_KEY, refer);
URL url = serviceConfigURL.addAttributes(attributes);
RegistryFactory registryFactory = mock(RegistryFactory.class);
Registry registry = mock(Registry.class);
MigrationRuleListener migrationRuleListener = mock(MigrationRuleListener.class);
List<RegistryProtocolListener> registryProtocolListeners = new ArrayList<>();
registryProtocolListeners.add(migrationRuleListener);
RegistryProtocol registryProtocol = new RegistryProtocol();
ModuleModel moduleModel = Mockito.spy(ApplicationModel.defaultModel().getDefaultModule());
moduleModel
.getApplicationModel()
.getApplicationConfigManager()
.setApplication(new ApplicationConfig("application1"));
ExtensionLoader extensionLoaderMock = mock(ExtensionLoader.class);
Mockito.when(moduleModel.getExtensionLoader(RegistryProtocolListener.class))
.thenReturn(extensionLoaderMock);
Mockito.when(extensionLoaderMock.getActivateExtension(url, REGISTRY_PROTOCOL_LISTENER_KEY))
.thenReturn(registryProtocolListeners);
Mockito.when(moduleModel.getExtensionLoader(RegistryFactory.class)).thenReturn(extensionLoaderMock);
Mockito.when(extensionLoaderMock.getAdaptiveExtension()).thenReturn(registryFactory);
url = url.setScopeModel(moduleModel);
when(registryFactory.getRegistry(registryProtocol.getRegistryUrl(url))).thenReturn(registry);
Invoker<?> invoker = registryProtocol.refer(DemoService.class, url);
Assertions.assertTrue(invoker instanceof MigrationInvoker);
Assertions.assertTrue(((MigrationInvoker<?>) invoker).getCluster() instanceof ScopeClusterWrapper);
Assertions.assertTrue(
((ScopeClusterWrapper) ((MigrationInvoker<?>) invoker).getCluster()).getCluster()
instanceof MockClusterWrapper);
Assertions.assertTrue(
((MockClusterWrapper) ((ScopeClusterWrapper) ((MigrationInvoker<?>) invoker).getCluster()).getCluster())
.getCluster()
instanceof MergeableCluster);
}
/**
* verify that the default RegistryProtocolListener will be executed
*
* @see MigrationRuleListener
*/
@Test
void testInterceptInvokerForMigrationRuleListener() {
ApplicationConfig applicationConfig = new ApplicationConfig();
applicationConfig.setName("application1");
ConfigManager configManager = mock(ConfigManager.class);
when(configManager.getApplicationOrElseThrow()).thenReturn(applicationConfig);
CompositeConfiguration compositeConfiguration = mock(CompositeConfiguration.class);
when(compositeConfiguration.convert(Boolean.class, ENABLE_CONFIGURATION_LISTEN, true))
.thenReturn(true);
Map<String, String> parameters = new HashMap<>();
parameters.put(INTERFACE_KEY, DemoService.class.getName());
parameters.put("registry", "zookeeper");
parameters.put("register", "false");
Map<String, Object> attributes = new HashMap<>();
ServiceConfigURL serviceConfigURL = new ServiceConfigURL(
"registry", "127.0.0.1", 2181, "org.apache.dubbo.registry.RegistryService", parameters);
Map<String, String> refer = new HashMap<>();
refer.put(GROUP_KEY, "group1,group2");
attributes.put(REFER_KEY, refer);
URL url = serviceConfigURL.addAttributes(attributes);
MigrationInvoker<?> clusterInvoker = mock(MigrationInvoker.class);
Map<String, Object> consumerAttribute = new HashMap<>(url.getAttributes());
consumerAttribute.remove(REFER_KEY);
URL consumerUrl = new ServiceConfigURL(
parameters.get(PROTOCOL_KEY) == null ? DUBBO : parameters.get(PROTOCOL_KEY),
null,
null,
parameters.get(REGISTER_IP_KEY),
0,
url.getPath(),
parameters,
consumerAttribute);
url = url.putAttribute(CONSUMER_URL_KEY, consumerUrl);
MigrationRuleListener migrationRuleListener = mock(MigrationRuleListener.class);
List<RegistryProtocolListener> registryProtocolListeners = new ArrayList<>();
registryProtocolListeners.add(migrationRuleListener);
RegistryProtocol registryProtocol = new RegistryProtocol();
ModuleModel moduleModel = Mockito.spy(ApplicationModel.defaultModel().getDefaultModule());
moduleModel
.getApplicationModel()
.getApplicationConfigManager()
.setApplication(new ApplicationConfig("application1"));
ExtensionLoader<RegistryProtocolListener> extensionLoaderMock = mock(ExtensionLoader.class);
Mockito.when(moduleModel.getExtensionLoader(RegistryProtocolListener.class))
.thenReturn(extensionLoaderMock);
Mockito.when(extensionLoaderMock.getActivateExtension(url, REGISTRY_PROTOCOL_LISTENER_KEY))
.thenReturn(registryProtocolListeners);
url = url.setScopeModel(moduleModel);
registryProtocol.interceptInvoker(clusterInvoker, url, consumerUrl);
verify(migrationRuleListener, times(1)).onRefer(registryProtocol, clusterInvoker, consumerUrl, url);
}
/**
* Verify that if registry.protocol.listener is configured,
* whether the corresponding RegistryProtocolListener will be executed normally
*
* @see CountRegistryProtocolListener
*/
@Test
void testInterceptInvokerForCustomRegistryProtocolListener() {
ApplicationConfig applicationConfig = new ApplicationConfig();
applicationConfig.setName("application1");
ConfigManager configManager = mock(ConfigManager.class);
when(configManager.getApplicationOrElseThrow()).thenReturn(applicationConfig);
CompositeConfiguration compositeConfiguration = mock(CompositeConfiguration.class);
when(compositeConfiguration.convert(Boolean.class, ENABLE_CONFIGURATION_LISTEN, true))
.thenReturn(true);
Map<String, String> parameters = new HashMap<>();
parameters.put(INTERFACE_KEY, DemoService.class.getName());
parameters.put("registry", "zookeeper");
parameters.put("register", "false");
parameters.put(REGISTRY_PROTOCOL_LISTENER_KEY, "count");
Map<String, Object> attributes = new HashMap<>();
ServiceConfigURL serviceConfigURL = new ServiceConfigURL(
"registry", "127.0.0.1", 2181, "org.apache.dubbo.registry.RegistryService", parameters);
Map<String, String> refer = new HashMap<>();
refer.put(GROUP_KEY, "group1,group2");
attributes.put(REFER_KEY, refer);
URL url = serviceConfigURL.addAttributes(attributes);
RegistryProtocol registryProtocol = new RegistryProtocol();
MigrationInvoker<?> clusterInvoker = mock(MigrationInvoker.class);
Map<String, Object> consumerAttribute = new HashMap<>(url.getAttributes());
consumerAttribute.remove(REFER_KEY);
URL consumerUrl = new ServiceConfigURL(
parameters.get(PROTOCOL_KEY) == null ? DUBBO : parameters.get(PROTOCOL_KEY),
null,
null,
parameters.get(REGISTER_IP_KEY),
0,
url.getPath(),
parameters,
consumerAttribute);
url = url.putAttribute(CONSUMER_URL_KEY, consumerUrl);
List<RegistryProtocolListener> registryProtocolListeners = new ArrayList<>();
registryProtocolListeners.add(new CountRegistryProtocolListener());
ModuleModel moduleModel = Mockito.spy(ApplicationModel.defaultModel().getDefaultModule());
moduleModel
.getApplicationModel()
.getApplicationConfigManager()
.setApplication(new ApplicationConfig("application1"));
ExtensionLoader<RegistryProtocolListener> extensionLoaderMock = mock(ExtensionLoader.class);
Mockito.when(moduleModel.getExtensionLoader(RegistryProtocolListener.class))
.thenReturn(extensionLoaderMock);
Mockito.when(extensionLoaderMock.getActivateExtension(url, REGISTRY_PROTOCOL_LISTENER_KEY))
.thenReturn(registryProtocolListeners);
url = url.setScopeModel(moduleModel);
registryProtocol.interceptInvoker(clusterInvoker, url, consumerUrl);
Assertions.assertEquals(
1, CountRegistryProtocolListener.getReferCounter().get());
}
/**
* verify the registered consumer url
*/
@Test
void testRegisterConsumerUrl() {
ApplicationConfig applicationConfig = new ApplicationConfig();
applicationConfig.setName("application1");
ConfigManager configManager = mock(ConfigManager.class);
when(configManager.getApplicationOrElseThrow()).thenReturn(applicationConfig);
CompositeConfiguration compositeConfiguration = mock(CompositeConfiguration.class);
when(compositeConfiguration.convert(Boolean.class, ENABLE_CONFIGURATION_LISTEN, true))
.thenReturn(true);
Map<String, String> parameters = new HashMap<>();
parameters.put(INTERFACE_KEY, DemoService.class.getName());
parameters.put("registry", "zookeeper");
parameters.put("register", "true");
parameters.put(REGISTER_IP_KEY, "172.23.236.180");
Map<String, Object> attributes = new HashMap<>();
ServiceConfigURL serviceConfigURL = new ServiceConfigURL(
"registry", "127.0.0.1", 2181, "org.apache.dubbo.registry.RegistryService", parameters);
Map<String, String> refer = new HashMap<>();
attributes.put(REFER_KEY, refer);
attributes.put("key1", "value1");
URL url = serviceConfigURL.addAttributes(attributes);
RegistryFactory registryFactory = mock(RegistryFactory.class);
Registry registry = mock(Registry.class);
ModuleModel moduleModel = Mockito.spy(ApplicationModel.defaultModel().getDefaultModule());
moduleModel
.getApplicationModel()
.getApplicationConfigManager()
.setApplication(new ApplicationConfig("application1"));
ExtensionLoader extensionLoaderMock = mock(ExtensionLoader.class);
Mockito.when(moduleModel.getExtensionLoader(RegistryFactory.class)).thenReturn(extensionLoaderMock);
Mockito.when(extensionLoaderMock.getAdaptiveExtension()).thenReturn(registryFactory);
url = url.setScopeModel(moduleModel);
RegistryProtocol registryProtocol = new RegistryProtocol();
when(registryFactory.getRegistry(registryProtocol.getRegistryUrl(url))).thenReturn(registry);
Cluster cluster = mock(Cluster.class);
Invoker<?> invoker = registryProtocol.doRefer(cluster, registry, DemoService.class, url, parameters);
Assertions.assertTrue(invoker instanceof MigrationInvoker);
URL consumerUrl = ((MigrationInvoker<?>) invoker).getConsumerUrl();
Assertions.assertTrue((consumerUrl != null));
Map<String, String> urlParameters = consumerUrl.getParameters();
URL urlToRegistry = new ServiceConfigURL(
urlParameters.get(PROTOCOL_KEY) == null ? CONSUMER : urlParameters.get(PROTOCOL_KEY),
urlParameters.remove(REGISTER_IP_KEY),
0,
consumerUrl.getPath(),
urlParameters);
URL registeredConsumerUrl = urlToRegistry
.addParameters(CATEGORY_KEY, CONSUMERS_CATEGORY, CHECK_KEY, String.valueOf(false))
.setScopeModel(moduleModel);
verify(registry, times(1)).register(registeredConsumerUrl);
}
}
| 5,426 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/integration/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.registry.integration;
public interface DemoService {}
| 5,427 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/integration/DynamicDirectoryTest.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.registry.integration;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.url.component.ServiceConfigURL;
import org.apache.dubbo.registry.Registry;
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.RegistryConstants.CATEGORY_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMERS_CATEGORY;
import static org.apache.dubbo.registry.Constants.REGISTER_IP_KEY;
import static org.apache.dubbo.registry.Constants.SIMPLIFIED_KEY;
import static org.apache.dubbo.registry.integration.RegistryProtocol.DEFAULT_REGISTER_CONSUMER_KEYS;
import static org.apache.dubbo.remoting.Constants.CHECK_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
class DynamicDirectoryTest {
/**
* verify simplified consumer url information that needs to be registered
*/
@Test
void testSimplifiedUrl() {
// verify that the consumer url information that needs to be registered is not simplified by default
Map<String, String> parameters = new HashMap<>();
parameters.put(INTERFACE_KEY, DemoService.class.getName());
parameters.put("registry", "zookeeper");
parameters.put("register", "true");
parameters.put(REGISTER_IP_KEY, "172.23.236.180");
Map<String, Object> attributes = new HashMap<>();
ServiceConfigURL serviceConfigURLWithoutSimplified = new ServiceConfigURL(
"registry", "127.0.0.1", 2181, "org.apache.dubbo.registry.RegistryService", parameters);
Map<String, String> refer = new HashMap<>();
attributes.put(REFER_KEY, refer);
attributes.put("key1", "value1");
URL urlWithoutSimplified = serviceConfigURLWithoutSimplified.addAttributes(attributes);
DemoDynamicDirectory<DemoService> dynamicDirectoryWithoutSimplified =
new DemoDynamicDirectory<>(DemoService.class, urlWithoutSimplified);
URL registeredConsumerUrlWithoutSimplified =
new ServiceConfigURL("dubbo", "127.0.0.1", 2181, DemoService.class.getName(), parameters);
dynamicDirectoryWithoutSimplified.setRegisteredConsumerUrl(registeredConsumerUrlWithoutSimplified);
URL urlForNotSimplified = registeredConsumerUrlWithoutSimplified.addParameters(
CATEGORY_KEY, CONSUMERS_CATEGORY, CHECK_KEY, String.valueOf(false));
Assertions.assertEquals(urlForNotSimplified, dynamicDirectoryWithoutSimplified.getRegisteredConsumerUrl());
// verify simplified consumer url information that needs to be registered
parameters.put(SIMPLIFIED_KEY, "true");
ServiceConfigURL serviceConfigURLWithSimplified = new ServiceConfigURL(
"registry", "127.0.0.1", 2181, "org.apache.dubbo.registry.RegistryService", parameters);
URL urlWithSimplified = serviceConfigURLWithSimplified.addAttributes(attributes);
DemoDynamicDirectory<DemoService> dynamicDirectoryWithSimplified =
new DemoDynamicDirectory<>(DemoService.class, urlWithSimplified);
URL registeredConsumerUrlWithSimplified =
new ServiceConfigURL("dubbo", "127.0.0.1", 2181, DemoService.class.getName(), parameters);
dynamicDirectoryWithSimplified.setRegisteredConsumerUrl(registeredConsumerUrlWithSimplified);
URL urlForSimplified = URL.valueOf(registeredConsumerUrlWithSimplified, DEFAULT_REGISTER_CONSUMER_KEYS, null)
.addParameters(CATEGORY_KEY, CONSUMERS_CATEGORY, CHECK_KEY, String.valueOf(false));
Assertions.assertEquals(urlForSimplified, dynamicDirectoryWithSimplified.getRegisteredConsumerUrl());
}
@Test
void testSubscribe() {
Map<String, String> parameters = new HashMap<>();
parameters.put(INTERFACE_KEY, DemoService.class.getName());
parameters.put("registry", "zookeeper");
parameters.put("register", "true");
parameters.put(REGISTER_IP_KEY, "172.23.236.180");
Map<String, Object> attributes = new HashMap<>();
ServiceConfigURL serviceConfigUrl = new ServiceConfigURL(
"registry", "127.0.0.1", 2181, "org.apache.dubbo.registry.RegistryService", parameters);
Map<String, String> refer = new HashMap<>();
attributes.put(REFER_KEY, refer);
attributes.put("key1", "value1");
URL url = serviceConfigUrl.addAttributes(attributes);
DemoDynamicDirectory<DemoService> demoDynamicDirectory = new DemoDynamicDirectory<>(DemoService.class, url);
URL subscribeUrl = new ServiceConfigURL("dubbo", "127.0.0.1", 20881, DemoService.class.getName(), parameters);
Registry registry = mock(Registry.class);
demoDynamicDirectory.setRegistry(registry);
demoDynamicDirectory.subscribe(subscribeUrl);
verify(registry, times(1)).subscribe(subscribeUrl, demoDynamicDirectory);
Assertions.assertEquals(subscribeUrl, demoDynamicDirectory.getSubscribeUrl());
}
static class DemoDynamicDirectory<T> extends DynamicDirectory<T> {
public DemoDynamicDirectory(Class<T> serviceType, URL url) {
super(serviceType, url);
}
@Override
protected void destroyAllInvokers() {}
@Override
protected void refreshOverrideAndInvoker(List<URL> urls) {}
@Override
public boolean isAvailable() {
return false;
}
@Override
public void notify(List<URL> urls) {}
}
}
| 5,428 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/FailbackRegistryTest.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.registry.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.registry.NotifyListener;
import java.util.Arrays;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.registry.Constants.CONSUMER_PROTOCOL;
import static org.apache.dubbo.registry.Constants.REGISTRY_RETRY_PERIOD_KEY;
import static org.junit.jupiter.api.Assertions.assertEquals;
class FailbackRegistryTest {
protected final Logger logger = LoggerFactory.getLogger(getClass());
private URL serviceUrl;
private URL registryUrl;
private MockRegistry registry;
private final int FAILED_PERIOD = 200;
private final int sleepTime = 100;
private final int tryTimes = 5;
/**
* @throws java.lang.Exception
*/
@BeforeEach
public void setUp() throws Exception {
String failedPeriod = String.valueOf(FAILED_PERIOD);
serviceUrl = URL.valueOf("remote://127.0.0.1/demoservice?method=get")
.addParameter(REGISTRY_RETRY_PERIOD_KEY, failedPeriod);
registryUrl = URL.valueOf("http://1.2.3.4:9090/registry?check=false&file=N/A")
.addParameter(REGISTRY_RETRY_PERIOD_KEY, failedPeriod);
}
/**
* Test method for retry
*
* @throws Exception
*/
@Test
void testDoRetry() throws Exception {
final AtomicReference<Boolean> notified = new AtomicReference<Boolean>(false);
// the latest latch just for 3. Because retry method has been removed.
final CountDownLatch latch = new CountDownLatch(2);
NotifyListener listener = urls -> notified.set(Boolean.TRUE);
URL subscribeUrl =
serviceUrl.setProtocol(CONSUMER_PROTOCOL).addParameters(CollectionUtils.toStringMap("check", "false"));
registry = new MockRegistry(registryUrl, serviceUrl, latch);
registry.setBad(true);
registry.register(serviceUrl);
registry.unregister(serviceUrl);
registry.subscribe(subscribeUrl, listener);
registry.unsubscribe(subscribeUrl, listener);
// Failure can not be called to listener.
assertEquals(false, notified.get());
assertEquals(2, latch.getCount());
registry.setBad(false);
for (int i = 0; i < 20; i++) {
logger.info("failback registry retry, times:" + i);
// System.out.println(latch.getCount());
if (latch.getCount() == 0) break;
Thread.sleep(sleepTime);
}
assertEquals(0, latch.getCount());
// The failed subscribe corresponding key will be cleared when unsubscribing
assertEquals(false, notified.get());
}
@Test
void testDoRetryRegister() throws Exception {
final CountDownLatch latch = new CountDownLatch(
1); // All of them are called 4 times. A successful attempt to lose 1. subscribe will not be done
registry = new MockRegistry(registryUrl, serviceUrl, latch);
registry.setBad(true);
registry.register(serviceUrl);
registry.setBad(false);
for (int i = 0; i < tryTimes; i++) {
System.out.println("failback registry retry ,times:" + i);
if (latch.getCount() == 0) break;
Thread.sleep(sleepTime);
}
assertEquals(0, latch.getCount());
}
@Test
void testDoRetrySubscribe() throws Exception {
final AtomicReference<Boolean> notified = new AtomicReference<Boolean>(false);
final CountDownLatch latch = new CountDownLatch(
1); // All of them are called 4 times. A successful attempt to lose 1. subscribe will not be done
NotifyListener listener = urls -> notified.set(Boolean.TRUE);
registry = new MockRegistry(registryUrl, serviceUrl, latch);
registry.setBad(true);
registry.subscribe(
serviceUrl.setProtocol(CONSUMER_PROTOCOL).addParameters(CollectionUtils.toStringMap("check", "false")),
listener);
// Failure can not be called to listener.
assertEquals(false, notified.get());
assertEquals(1, latch.getCount());
registry.setBad(false);
for (int i = 0; i < tryTimes; i++) {
System.out.println("failback registry retry ,times:" + i);
if (latch.getCount() == 0) break;
Thread.sleep(sleepTime);
}
assertEquals(0, latch.getCount());
// The failed subscribe corresponding key will be cleared when unsubscribing
assertEquals(true, notified.get());
}
@Test
void testRecover() throws Exception {
CountDownLatch countDownLatch = new CountDownLatch(6);
final AtomicReference<Boolean> notified = new AtomicReference<Boolean>(false);
NotifyListener listener = urls -> notified.set(Boolean.TRUE);
MockRegistry mockRegistry = new MockRegistry(registryUrl, serviceUrl, countDownLatch);
mockRegistry.register(serviceUrl);
mockRegistry.subscribe(serviceUrl, listener);
Assertions.assertEquals(1, mockRegistry.getRegistered().size());
Assertions.assertEquals(1, mockRegistry.getSubscribed().size());
mockRegistry.recover();
countDownLatch.await();
Assertions.assertEquals(0, mockRegistry.getFailedRegistered().size());
FailbackRegistry.Holder h = new FailbackRegistry.Holder(registryUrl, listener);
Assertions.assertNull(mockRegistry.getFailedSubscribed().get(h));
Assertions.assertEquals(countDownLatch.getCount(), 0);
}
private static class MockRegistry extends FailbackRegistry {
private final URL serviceUrl;
CountDownLatch latch;
private volatile boolean bad = false;
/**
* @param url
* @param serviceUrl
*/
public MockRegistry(URL url, URL serviceUrl, CountDownLatch latch) {
super(url);
this.serviceUrl = serviceUrl;
this.latch = latch;
}
/**
* @param bad the bad to set
*/
public void setBad(boolean bad) {
this.bad = bad;
}
@Override
public void doRegister(URL url) {
if (bad) {
throw new RuntimeException("can not invoke!");
}
latch.countDown();
}
@Override
public void doUnregister(URL url) {
if (bad) {
throw new RuntimeException("can not invoke!");
}
latch.countDown();
}
@Override
public void doSubscribe(URL url, NotifyListener listener) {
if (bad) {
throw new RuntimeException("can not invoke!");
}
super.notify(url, listener, Arrays.asList(new URL[] {serviceUrl}));
latch.countDown();
}
@Override
public void doUnsubscribe(URL url, NotifyListener listener) {
if (bad) {
throw new RuntimeException("can not invoke!");
}
latch.countDown();
}
@Override
public boolean isAvailable() {
return true;
}
@Override
public void removeFailedRegisteredTask(URL url) {
if (bad) {
throw new RuntimeException("can not invoke!");
}
super.removeFailedRegisteredTask(url);
latch.countDown();
}
@Override
public void removeFailedSubscribedTask(URL url, NotifyListener listener) {
if (bad) {
throw new RuntimeException("can not invoke!");
}
super.removeFailedSubscribedTask(url, listener);
latch.countDown();
}
}
}
| 5,429 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/AbstractRegistryTest.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.registry.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.url.component.ServiceConfigURL;
import org.apache.dubbo.registry.NotifyListener;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
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.RegistryConstants.EMPTY_PROTOCOL;
/**
* AbstractRegistryTest
*/
class AbstractRegistryTest {
private URL testUrl;
private URL mockUrl;
private NotifyListener listener;
private AbstractRegistry abstractRegistry;
private boolean notifySuccess;
private Map<String, String> parametersConsumer = new LinkedHashMap<>();
@BeforeEach
public void init() {
URL url = URL.valueOf("dubbo://192.168.0.2:2233");
// sync update cache file
url = url.addParameter("save.file", true);
testUrl = URL.valueOf("http://192.168.0.3:9090/registry?check=false&file=N/A&interface=com.test");
mockUrl = new ServiceConfigURL("dubbo", "192.168.0.1", 2200);
parametersConsumer.put("application", "demo-consumer");
parametersConsumer.put("category", "consumer");
parametersConsumer.put("check", "false");
parametersConsumer.put("dubbo", "2.0.2");
parametersConsumer.put("interface", "org.apache.dubbo.demo.DemoService");
parametersConsumer.put("methods", "sayHello");
parametersConsumer.put("pid", "1676");
parametersConsumer.put("qos.port", "333333");
parametersConsumer.put("side", "consumer");
parametersConsumer.put("timestamp", String.valueOf(System.currentTimeMillis()));
// init the object
abstractRegistry = new AbstractRegistry(url) {
@Override
public boolean isAvailable() {
return false;
}
};
// init notify listener
listener = urls -> notifySuccess = true;
// notify flag
notifySuccess = false;
}
@AfterEach
public void after() {
abstractRegistry.destroy();
}
/**
* Test method for
* {@link org.apache.dubbo.registry.support.AbstractRegistry#register(URL)}.
*
*/
@Test
void testRegister() {
// test one url
abstractRegistry.register(mockUrl);
assert abstractRegistry.getRegistered().contains(mockUrl);
// test multiple urls
for (URL url : abstractRegistry.getRegistered()) {
abstractRegistry.unregister(url);
}
List<URL> urlList = getList();
for (URL url : urlList) {
abstractRegistry.register(url);
}
MatcherAssert.assertThat(abstractRegistry.getRegistered().size(), Matchers.equalTo(urlList.size()));
}
@Test
void testRegisterIfURLNULL() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
abstractRegistry.register(null);
Assertions.fail("register url == null");
});
}
/**
* Test method for
* {@link org.apache.dubbo.registry.support.AbstractRegistry#unregister(URL)}.
*
*/
@Test
void testUnregister() {
// test one unregister
URL url = new ServiceConfigURL("dubbo", "192.168.0.1", 2200);
abstractRegistry.register(url);
abstractRegistry.unregister(url);
MatcherAssert.assertThat(
false, Matchers.equalTo(abstractRegistry.getRegistered().contains(url)));
// test multiple unregisters
for (URL u : abstractRegistry.getRegistered()) {
abstractRegistry.unregister(u);
}
List<URL> urlList = getList();
for (URL urlSub : urlList) {
abstractRegistry.register(urlSub);
}
for (URL urlSub : urlList) {
abstractRegistry.unregister(urlSub);
}
MatcherAssert.assertThat(
0, Matchers.equalTo(abstractRegistry.getRegistered().size()));
}
@Test
void testUnregisterIfUrlNull() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
abstractRegistry.unregister(null);
Assertions.fail("unregister url == null");
});
}
/**
* test subscribe and unsubscribe
*/
@Test
void testSubscribeAndUnsubscribe() {
// test subscribe
final AtomicReference<Boolean> notified = new AtomicReference<Boolean>(false);
NotifyListener listener = urls -> notified.set(Boolean.TRUE);
URL url = new ServiceConfigURL("dubbo", "192.168.0.1", 2200);
abstractRegistry.subscribe(url, listener);
Set<NotifyListener> subscribeListeners =
abstractRegistry.getSubscribed().get(url);
MatcherAssert.assertThat(true, Matchers.equalTo(subscribeListeners.contains(listener)));
// test unsubscribe
abstractRegistry.unsubscribe(url, listener);
Set<NotifyListener> unsubscribeListeners =
abstractRegistry.getSubscribed().get(url);
MatcherAssert.assertThat(false, Matchers.equalTo(unsubscribeListeners.contains(listener)));
}
@Test
void testSubscribeIfUrlNull() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
final AtomicReference<Boolean> notified = new AtomicReference<Boolean>(false);
NotifyListener listener = urls -> notified.set(Boolean.TRUE);
URL url = new ServiceConfigURL("dubbo", "192.168.0.1", 2200);
abstractRegistry.subscribe(null, listener);
Assertions.fail("subscribe url == null");
});
}
@Test
void testSubscribeIfListenerNull() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
final AtomicReference<Boolean> notified = new AtomicReference<Boolean>(false);
NotifyListener listener = urls -> notified.set(Boolean.TRUE);
URL url = new ServiceConfigURL("dubbo", "192.168.0.1", 2200);
abstractRegistry.subscribe(url, null);
Assertions.fail("listener url == null");
});
}
@Test
void testUnsubscribeIfUrlNull() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
final AtomicReference<Boolean> notified = new AtomicReference<Boolean>(false);
NotifyListener listener = urls -> notified.set(Boolean.TRUE);
abstractRegistry.unsubscribe(null, listener);
Assertions.fail("unsubscribe url == null");
});
}
@Test
void testUnsubscribeIfNotifyNull() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
final AtomicReference<Boolean> notified = new AtomicReference<Boolean>(false);
URL url = new ServiceConfigURL("dubbo", "192.168.0.1", 2200);
abstractRegistry.unsubscribe(url, null);
Assertions.fail("unsubscribe listener == null");
});
}
/**
* Test method for
* {@link org.apache.dubbo.registry.support.AbstractRegistry#subscribe(URL, NotifyListener)}.
*
*/
@Test
void testSubscribe() {
// check parameters
try {
abstractRegistry.subscribe(testUrl, null);
Assertions.fail();
} catch (Exception e) {
Assertions.assertTrue(e instanceof IllegalArgumentException);
}
// check parameters
try {
abstractRegistry.subscribe(null, null);
Assertions.fail();
} catch (Exception e) {
Assertions.assertTrue(e instanceof IllegalArgumentException);
}
// check if subscribe successfully
Assertions.assertNull(abstractRegistry.getSubscribed().get(testUrl));
abstractRegistry.subscribe(testUrl, listener);
Assertions.assertNotNull(abstractRegistry.getSubscribed().get(testUrl));
Assertions.assertTrue(abstractRegistry.getSubscribed().get(testUrl).contains(listener));
}
/**
* Test method for
* {@link org.apache.dubbo.registry.support.AbstractRegistry#unsubscribe(URL, NotifyListener)}.
*
*/
@Test
void testUnsubscribe() {
// check parameters
try {
abstractRegistry.unsubscribe(testUrl, null);
Assertions.fail();
} catch (Exception e) {
Assertions.assertTrue(e instanceof IllegalArgumentException);
}
// check parameters
try {
abstractRegistry.unsubscribe(null, null);
Assertions.fail();
} catch (Exception e) {
Assertions.assertTrue(e instanceof IllegalArgumentException);
}
Assertions.assertNull(abstractRegistry.getSubscribed().get(testUrl));
// check if unsubscribe successfully
abstractRegistry.subscribe(testUrl, listener);
abstractRegistry.unsubscribe(testUrl, listener);
// Since we have subscribed testUrl, here should return a empty set instead of null
Assertions.assertNotNull(abstractRegistry.getSubscribed().get(testUrl));
Assertions.assertFalse(abstractRegistry.getSubscribed().get(testUrl).contains(listener));
}
/**
* Test method for
* {@link org.apache.dubbo.registry.support.AbstractRegistry#recover()}.
*/
@Test
void testRecover() throws Exception {
// test recover nothing
abstractRegistry.recover();
Assertions.assertFalse(abstractRegistry.getRegistered().contains(testUrl));
Assertions.assertNull(abstractRegistry.getSubscribed().get(testUrl));
// test recover
abstractRegistry.register(testUrl);
abstractRegistry.subscribe(testUrl, listener);
abstractRegistry.recover();
// check if recover successfully
Assertions.assertTrue(abstractRegistry.getRegistered().contains(testUrl));
Assertions.assertNotNull(abstractRegistry.getSubscribed().get(testUrl));
Assertions.assertTrue(abstractRegistry.getSubscribed().get(testUrl).contains(listener));
}
@Test
void testRecover2() throws Exception {
List<URL> list = getList();
abstractRegistry.recover();
Assertions.assertEquals(0, abstractRegistry.getRegistered().size());
for (URL url : list) {
abstractRegistry.register(url);
}
Assertions.assertEquals(3, abstractRegistry.getRegistered().size());
abstractRegistry.recover();
Assertions.assertEquals(3, abstractRegistry.getRegistered().size());
}
/**
* Test method for
* {@link org.apache.dubbo.registry.support.AbstractRegistry#notify(List)}.
*/
@Test
void testNotify() {
final AtomicReference<Boolean> notified = new AtomicReference<Boolean>(false);
NotifyListener listener1 = urls -> notified.set(Boolean.TRUE);
URL url1 = new ServiceConfigURL("dubbo", "192.168.0.1", 2200, parametersConsumer);
abstractRegistry.subscribe(url1, listener1);
NotifyListener listener2 = urls -> notified.set(Boolean.TRUE);
URL url2 = new ServiceConfigURL("dubbo", "192.168.0.2", 2201, parametersConsumer);
abstractRegistry.subscribe(url2, listener2);
NotifyListener listener3 = urls -> notified.set(Boolean.TRUE);
URL url3 = new ServiceConfigURL("dubbo", "192.168.0.3", 2202, parametersConsumer);
abstractRegistry.subscribe(url3, listener3);
List<URL> urls = new ArrayList<>();
urls.add(url1);
urls.add(url2);
urls.add(url3);
abstractRegistry.notify(url1, listener1, urls);
Map<URL, Map<String, List<URL>>> map = abstractRegistry.getNotified();
MatcherAssert.assertThat(true, Matchers.equalTo(map.containsKey(url1)));
MatcherAssert.assertThat(false, Matchers.equalTo(map.containsKey(url2)));
MatcherAssert.assertThat(false, Matchers.equalTo(map.containsKey(url3)));
}
/**
* test notifyList
*/
@Test
void testNotifyList() {
final AtomicReference<Boolean> notified = new AtomicReference<Boolean>(false);
NotifyListener listener1 = urls -> notified.set(Boolean.TRUE);
URL url1 = new ServiceConfigURL("dubbo", "192.168.0.1", 2200, parametersConsumer);
abstractRegistry.subscribe(url1, listener1);
NotifyListener listener2 = urls -> notified.set(Boolean.TRUE);
URL url2 = new ServiceConfigURL("dubbo", "192.168.0.2", 2201, parametersConsumer);
abstractRegistry.subscribe(url2, listener2);
NotifyListener listener3 = urls -> notified.set(Boolean.TRUE);
URL url3 = new ServiceConfigURL("dubbo", "192.168.0.3", 2202, parametersConsumer);
abstractRegistry.subscribe(url3, listener3);
List<URL> urls = new ArrayList<>();
urls.add(url1);
urls.add(url2);
urls.add(url3);
abstractRegistry.notify(urls);
Map<URL, Map<String, List<URL>>> map = abstractRegistry.getNotified();
MatcherAssert.assertThat(true, Matchers.equalTo(map.containsKey(url1)));
MatcherAssert.assertThat(true, Matchers.equalTo(map.containsKey(url2)));
MatcherAssert.assertThat(true, Matchers.equalTo(map.containsKey(url3)));
}
@Test
void testNotifyIfURLNull() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
final AtomicReference<Boolean> notified = new AtomicReference<Boolean>(false);
NotifyListener listener1 = urls -> notified.set(Boolean.TRUE);
URL url1 = new ServiceConfigURL("dubbo", "192.168.0.1", 2200, parametersConsumer);
abstractRegistry.subscribe(url1, listener1);
NotifyListener listener2 = urls -> notified.set(Boolean.TRUE);
URL url2 = new ServiceConfigURL("dubbo", "192.168.0.2", 2201, parametersConsumer);
abstractRegistry.subscribe(url2, listener2);
NotifyListener listener3 = urls -> notified.set(Boolean.TRUE);
URL url3 = new ServiceConfigURL("dubbo", "192.168.0.3", 2202, parametersConsumer);
abstractRegistry.subscribe(url3, listener3);
List<URL> urls = new ArrayList<>();
urls.add(url1);
urls.add(url2);
urls.add(url3);
abstractRegistry.notify(null, listener1, urls);
Assertions.fail("notify url == null");
});
}
@Test
void testNotifyIfNotifyNull() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
final AtomicReference<Boolean> notified = new AtomicReference<Boolean>(false);
NotifyListener listener1 = urls -> notified.set(Boolean.TRUE);
URL url1 = new ServiceConfigURL("dubbo", "192.168.0.1", 2200, parametersConsumer);
abstractRegistry.subscribe(url1, listener1);
NotifyListener listener2 = urls -> notified.set(Boolean.TRUE);
URL url2 = new ServiceConfigURL("dubbo", "192.168.0.2", 2201, parametersConsumer);
abstractRegistry.subscribe(url2, listener2);
NotifyListener listener3 = urls -> notified.set(Boolean.TRUE);
URL url3 = new ServiceConfigURL("dubbo", "192.168.0.3", 2202, parametersConsumer);
abstractRegistry.subscribe(url3, listener3);
List<URL> urls = new ArrayList<>();
urls.add(url1);
urls.add(url2);
urls.add(url3);
abstractRegistry.notify(url1, null, urls);
Assertions.fail("notify listener == null");
});
}
/**
* Test method for
* {@link org.apache.dubbo.registry.support.AbstractRegistry#notify(URL, NotifyListener, List)}.
*
*/
@Test
void testNotifyArgs() {
// check parameters
try {
abstractRegistry.notify(null, null, null);
Assertions.fail();
} catch (Exception e) {
Assertions.assertTrue(e instanceof IllegalArgumentException);
}
// check parameters
try {
abstractRegistry.notify(testUrl, null, null);
Assertions.fail();
} catch (Exception e) {
Assertions.assertTrue(e instanceof IllegalArgumentException);
}
// check parameters
try {
abstractRegistry.notify(null, listener, null);
Assertions.fail();
} catch (Exception e) {
Assertions.assertTrue(e instanceof IllegalArgumentException);
}
Assertions.assertFalse(notifySuccess);
abstractRegistry.notify(testUrl, listener, null);
Assertions.assertFalse(notifySuccess);
List<URL> urls = new ArrayList<>();
urls.add(testUrl);
// check if notify successfully
Assertions.assertFalse(notifySuccess);
abstractRegistry.notify(testUrl, listener, urls);
Assertions.assertTrue(notifySuccess);
}
@Test
void filterEmptyTest() {
// check parameters
try {
AbstractRegistry.filterEmpty(null, null);
Assertions.fail();
} catch (Exception e) {
Assertions.assertTrue(e instanceof NullPointerException);
}
// check parameters
List<URL> urls = new ArrayList<>();
try {
AbstractRegistry.filterEmpty(null, urls);
Assertions.fail();
} catch (Exception e) {
Assertions.assertTrue(e instanceof NullPointerException);
}
// check if the output is generated by a fixed way
urls.add(testUrl.setProtocol(EMPTY_PROTOCOL));
Assertions.assertEquals(AbstractRegistry.filterEmpty(testUrl, null), urls);
List<URL> testUrls = new ArrayList<>();
Assertions.assertEquals(AbstractRegistry.filterEmpty(testUrl, testUrls), urls);
// check if the output equals the input urls
testUrls.add(testUrl);
Assertions.assertEquals(AbstractRegistry.filterEmpty(testUrl, testUrls), testUrls);
}
@Test
void lookupTest() {
// loop up before registry
try {
abstractRegistry.lookup(null);
Assertions.fail();
} catch (Exception e) {
Assertions.assertTrue(e instanceof NullPointerException);
}
List<URL> urlList1 = abstractRegistry.lookup(testUrl);
Assertions.assertFalse(urlList1.contains(testUrl));
// loop up after registry
List<URL> urls = new ArrayList<>();
urls.add(testUrl);
abstractRegistry.notify(urls);
List<URL> urlList2 = abstractRegistry.lookup(testUrl);
Assertions.assertTrue(urlList2.contains(testUrl));
}
@Test
void destroyTest() {
abstractRegistry.register(testUrl);
abstractRegistry.subscribe(testUrl, listener);
Assertions.assertEquals(1, abstractRegistry.getRegistered().size());
Assertions.assertEquals(1, abstractRegistry.getSubscribed().get(testUrl).size());
// delete listener and register
abstractRegistry.destroy();
Assertions.assertEquals(0, abstractRegistry.getRegistered().size());
Assertions.assertEquals(0, abstractRegistry.getSubscribed().get(testUrl).size());
}
@Test
void allTest() {
// test all methods
List<URL> urls = new ArrayList<>();
urls.add(testUrl);
// register, subscribe, notify, unsubscribe, unregister
abstractRegistry.register(testUrl);
Assertions.assertTrue(abstractRegistry.getRegistered().contains(testUrl));
abstractRegistry.subscribe(testUrl, listener);
Assertions.assertTrue(abstractRegistry.getSubscribed().containsKey(testUrl));
Assertions.assertFalse(notifySuccess);
abstractRegistry.notify(urls);
Assertions.assertTrue(notifySuccess);
abstractRegistry.unsubscribe(testUrl, listener);
Assertions.assertFalse(abstractRegistry.getSubscribed().containsKey(listener));
abstractRegistry.unregister(testUrl);
Assertions.assertFalse(abstractRegistry.getRegistered().contains(testUrl));
}
private List<URL> getList() {
List<URL> list = new ArrayList<>();
URL url1 = new ServiceConfigURL("dubbo", "192.168.0.1", 1000);
URL url2 = new ServiceConfigURL("dubbo", "192.168.0.2", 1001);
URL url3 = new ServiceConfigURL("dubbo", "192.168.0.3", 1002);
list.add(url1);
list.add(url2);
list.add(url3);
return list;
}
@Test
void getCacheUrlsTest() {
List<URL> urls = new ArrayList<>();
urls.add(testUrl);
// check if notify successfully
Assertions.assertFalse(notifySuccess);
abstractRegistry.notify(testUrl, listener, urls);
Assertions.assertTrue(notifySuccess);
List<URL> cacheUrl = abstractRegistry.getCacheUrls(testUrl);
Assertions.assertEquals(1, cacheUrl.size());
URL nullUrl = URL.valueOf("http://1.2.3.4:9090/registry?check=false&file=N/A&interface=com.testa");
cacheUrl = abstractRegistry.getCacheUrls(nullUrl);
Assertions.assertTrue(Objects.isNull(cacheUrl));
}
}
| 5,430 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/AbstractRegistryFactoryTest.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.registry.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.registry.NotifyListener;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Collection;
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* AbstractRegistryFactoryTest
*/
class AbstractRegistryFactoryTest {
private AbstractRegistryFactory registryFactory;
@BeforeEach
public void setup() {
registryFactory = new AbstractRegistryFactory() {
@Override
protected Registry createRegistry(final URL url) {
return new Registry() {
public URL getUrl() {
return url;
}
@Override
public boolean isAvailable() {
return false;
}
@Override
public void destroy() {}
@Override
public void register(URL url) {}
@Override
public void unregister(URL url) {}
@Override
public void subscribe(URL url, NotifyListener listener) {}
@Override
public void unsubscribe(URL url, NotifyListener listener) {}
@Override
public List<URL> lookup(URL url) {
return null;
}
};
}
};
registryFactory.setApplicationModel(ApplicationModel.defaultModel());
}
@AfterEach
public void teardown() {
ApplicationModel.defaultModel().destroy();
}
@Test
void testRegistryFactoryCache() {
URL url = URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostAddress() + ":2233");
Registry registry1 = registryFactory.getRegistry(url);
Registry registry2 = registryFactory.getRegistry(url);
Assertions.assertEquals(registry1, registry2);
}
/**
* Registration center address `dubbo` does not resolve
*/
// @Test
public void testRegistryFactoryIpCache() {
Registry registry1 = registryFactory.getRegistry(
URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostName() + ":2233"));
Registry registry2 = registryFactory.getRegistry(
URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostAddress() + ":2233"));
Assertions.assertEquals(registry1, registry2);
}
@Test
void testRegistryFactoryGroupCache() {
Registry registry1 =
registryFactory.getRegistry(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":2233?group=aaa"));
Registry registry2 =
registryFactory.getRegistry(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":2233?group=bbb"));
Assertions.assertNotSame(registry1, registry2);
}
@Test
void testDestroyAllRegistries() {
Registry registry1 =
registryFactory.getRegistry(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":8888?group=xxx"));
Registry registry2 =
registryFactory.getRegistry(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":9999?group=yyy"));
Registry registry3 =
new AbstractRegistry(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":2020?group=yyy")) {
@Override
public boolean isAvailable() {
return true;
}
};
RegistryManager registryManager =
ApplicationModel.defaultModel().getBeanFactory().getBean(RegistryManager.class);
Collection<Registry> registries = registryManager.getRegistries();
Assertions.assertTrue(registries.contains(registry1));
Assertions.assertTrue(registries.contains(registry2));
registry3.destroy();
registries = registryManager.getRegistries();
Assertions.assertFalse(registries.contains(registry3));
registryManager.destroyAll();
registries = registryManager.getRegistries();
Assertions.assertFalse(registries.contains(registry1));
Assertions.assertFalse(registries.contains(registry2));
}
}
| 5,431 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/service/DemoService2.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.registry.service;
public interface DemoService2 {
String sayHello(String str);
}
| 5,432 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/service/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.registry.service;
public interface DemoService {
String sayHello(String str);
}
| 5,433 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistryTest.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.registry.client;
import org.apache.dubbo.common.ProtocolServiceKey;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.metadata.AbstractServiceNameMapping;
import org.apache.dubbo.metadata.ServiceNameMapping;
import org.apache.dubbo.registry.NotifyListener;
import org.apache.dubbo.registry.client.event.listener.MockServiceInstancesChangedListener;
import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import static org.apache.dubbo.common.constants.CommonConstants.CHECK_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO;
import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDED_BY;
import static org.apache.dubbo.metadata.ServiceNameMapping.toStringKeys;
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.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class ServiceDiscoveryRegistryTest {
public static final String APP_NAME1 = "app1";
public static final String APP_NAME2 = "app2";
public static final String APP_NAME3 = "app3";
private static AbstractServiceNameMapping mapping = mock(AbstractServiceNameMapping.class);
private static Lock lock = new ReentrantLock();
private static URL registryURL =
URL.valueOf("zookeeper://127.0.0.1:2181/org.apache.dubbo.registry.RegistryService");
private static URL url =
URL.valueOf("consumer://127.0.0.1/TestService?interface=TestService1&check=false&protocol=dubbo");
private static NotifyListener testServiceListener = mock(NotifyListener.class);
private static List<ServiceInstance> instanceList1 = new ArrayList<>();
private static List<ServiceInstance> instanceList2 = new ArrayList<>();
private ServiceDiscoveryRegistry serviceDiscoveryRegistry;
private ServiceDiscovery serviceDiscovery;
private MockServiceInstancesChangedListener instanceListener;
private ServiceNameMapping serviceNameMapping;
@BeforeAll
public static void setUp() {
instanceList1.add(new DefaultServiceInstance());
instanceList1.add(new DefaultServiceInstance());
instanceList1.add(new DefaultServiceInstance());
instanceList2.add(new DefaultServiceInstance());
instanceList2.add(new DefaultServiceInstance());
}
@AfterEach
public void teardown() {
FrameworkModel.destroyAll();
}
@BeforeEach
public void init() {
serviceDiscovery = mock(ServiceDiscovery.class);
instanceListener = spy(new MockServiceInstancesChangedListener(Collections.emptySet(), serviceDiscovery));
doNothing().when(instanceListener).onEvent(any());
when(serviceDiscovery.createListener(any())).thenReturn(instanceListener);
when(serviceDiscovery.getInstances(any())).thenReturn(Collections.emptyList());
when(serviceDiscovery.getUrl()).thenReturn(url);
ApplicationModel applicationModel = spy(ApplicationModel.defaultModel());
when(applicationModel.getDefaultExtension(ServiceNameMapping.class)).thenReturn(mapping);
registryURL = registryURL.setScopeModel(applicationModel);
serviceDiscoveryRegistry = new ServiceDiscoveryRegistry(registryURL, serviceDiscovery, mapping);
when(mapping.getMappingLock(any())).thenReturn(lock);
when(testServiceListener.getConsumerUrl()).thenReturn(url);
}
/**
* Test subscribe
* - Normal case
* - Exceptional case
* - check=true
* - check=false
*/
@Test
void testDoSubscribe() {
ApplicationModel applicationModel = spy(ApplicationModel.defaultModel());
when(applicationModel.getDefaultExtension(ServiceNameMapping.class)).thenReturn(mapping);
// Exceptional case, no interface-app mapping found
when(mapping.getAndListen(any(), any(), any())).thenReturn(Collections.emptySet());
// when check = false
try {
registryURL = registryURL.setScopeModel(applicationModel);
serviceDiscoveryRegistry = new ServiceDiscoveryRegistry(registryURL, serviceDiscovery, mapping);
serviceDiscoveryRegistry.doSubscribe(url, testServiceListener);
} finally {
registryURL = registryURL.setScopeModel(null);
serviceDiscoveryRegistry.unsubscribe(url, testServiceListener);
}
// // when check = true
URL checkURL = url.addParameter(CHECK_KEY, true);
checkURL.setScopeModel(url.getApplicationModel());
// Exception exceptionShouldHappen = null;
// try {
// serviceDiscoveryRegistry.doSubscribe(checkURL, testServiceListener);
// } catch (IllegalStateException e) {
// exceptionShouldHappen = e;
// } finally {
// serviceDiscoveryRegistry.unsubscribe(checkURL, testServiceListener);
// }
// if (exceptionShouldHappen == null) {
// fail();
// }
// Normal case
Set<String> singleApp = new HashSet<>();
singleApp.add(APP_NAME1);
when(mapping.getAndListen(any(), any(), any())).thenReturn(singleApp);
try {
serviceDiscoveryRegistry.doSubscribe(checkURL, testServiceListener);
} finally {
serviceDiscoveryRegistry.unsubscribe(checkURL, testServiceListener);
}
// test provider case
checkURL = url.addParameter(PROVIDED_BY, APP_NAME1);
try {
serviceDiscoveryRegistry.doSubscribe(checkURL, testServiceListener);
} finally {
serviceDiscoveryRegistry.unsubscribe(checkURL, testServiceListener);
}
}
/**
* Test instance listener registration
* - one app
* - multi apps
* - repeat same multi apps, instance listener shared
* - protocol included in key
* - instance listener gets notified
* - instance listener and service listener rightly mapped
*/
@Test
void testSubscribeURLs() {
// interface to single app mapping
Set<String> singleApp = new TreeSet<>();
singleApp.add(APP_NAME1);
serviceDiscoveryRegistry.subscribeURLs(url, testServiceListener, singleApp);
assertEquals(1, serviceDiscoveryRegistry.getServiceListeners().size());
verify(testServiceListener, times(1)).addServiceListener(instanceListener);
verify(instanceListener, never()).onEvent(any());
verify(serviceDiscovery, times(1)).addServiceInstancesChangedListener(instanceListener);
// interface to multiple apps mapping
Set<String> multiApps = new TreeSet<>();
multiApps.add(APP_NAME1);
multiApps.add(APP_NAME2);
MockServiceInstancesChangedListener multiAppsInstanceListener =
spy(new MockServiceInstancesChangedListener(multiApps, serviceDiscovery));
doNothing().when(multiAppsInstanceListener).onEvent(any());
List<URL> urls = new ArrayList<>();
urls.add(URL.valueOf("dubbo://127.0.0.1:20880/TestService"));
doReturn(urls).when(multiAppsInstanceListener).getAddresses(any(), any());
when(serviceDiscovery.createListener(multiApps)).thenReturn(multiAppsInstanceListener);
when(serviceDiscovery.getInstances(APP_NAME1)).thenReturn(instanceList1);
when(serviceDiscovery.getInstances(APP_NAME2)).thenReturn(instanceList2);
serviceDiscoveryRegistry.subscribeURLs(url, testServiceListener, multiApps);
assertEquals(2, serviceDiscoveryRegistry.getServiceListeners().size());
assertEquals(
instanceListener, serviceDiscoveryRegistry.getServiceListeners().get(toStringKeys(singleApp)));
assertEquals(
multiAppsInstanceListener,
serviceDiscoveryRegistry.getServiceListeners().get(toStringKeys(multiApps)));
verify(testServiceListener, times(1)).addServiceListener(multiAppsInstanceListener);
verify(multiAppsInstanceListener, times(2)).onEvent(any());
verify(multiAppsInstanceListener, times(1)).addListenerAndNotify(any(), eq(testServiceListener));
verify(serviceDiscovery, times(1)).addServiceInstancesChangedListener(multiAppsInstanceListener);
ArgumentCaptor<List<URL>> captor = ArgumentCaptor.forClass(List.class);
verify(testServiceListener).notify(captor.capture());
assertEquals(urls, captor.getValue());
// different interface mapping to the same apps
NotifyListener testServiceListener2 = mock(NotifyListener.class);
URL url2 = URL.valueOf("tri://127.0.0.1/TestService2?interface=TestService2&check=false&protocol=tri");
when(testServiceListener2.getConsumerUrl()).thenReturn(url2);
serviceDiscoveryRegistry.subscribeURLs(url2, testServiceListener2, multiApps);
// check instance listeners not changed, methods not called
assertEquals(2, serviceDiscoveryRegistry.getServiceListeners().size());
assertEquals(
multiAppsInstanceListener,
serviceDiscoveryRegistry.getServiceListeners().get(toStringKeys(multiApps)));
verify(multiAppsInstanceListener, times(1)).addListenerAndNotify(any(), eq(testServiceListener));
// still called once, not executed this time
verify(serviceDiscovery, times(2)).addServiceInstancesChangedListener(multiAppsInstanceListener);
// check different protocol
Map<String, Set<ServiceInstancesChangedListener.NotifyListenerWithKey>> serviceListeners =
multiAppsInstanceListener.getServiceListeners();
assertEquals(2, serviceListeners.size());
assertEquals(1, serviceListeners.get(url.getServiceKey()).size());
assertEquals(1, serviceListeners.get(url2.getServiceKey()).size());
ProtocolServiceKey protocolServiceKey = new ProtocolServiceKey(
url2.getServiceInterface(), url2.getVersion(), url2.getGroup(), url2.getParameter(PROTOCOL_KEY, DUBBO));
assertTrue(serviceListeners
.get(url2.getServiceKey())
.contains(new ServiceInstancesChangedListener.NotifyListenerWithKey(
protocolServiceKey, testServiceListener2)));
}
/**
* repeat of {@link this#testSubscribeURLs()} with multi threads
*/
@Test
void testConcurrencySubscribe() {
// TODO
}
@Test
void testUnsubscribe() {
// do subscribe to prepare for unsubscribe verification
Set<String> multiApps = new TreeSet<>();
multiApps.add(APP_NAME1);
multiApps.add(APP_NAME2);
NotifyListener testServiceListener2 = mock(NotifyListener.class);
URL url2 = URL.valueOf("consumer://127.0.0.1/TestService2?interface=TestService1&check=false&protocol=tri");
when(testServiceListener2.getConsumerUrl()).thenReturn(url2);
serviceDiscoveryRegistry.subscribeURLs(url, testServiceListener, multiApps);
serviceDiscoveryRegistry.subscribeURLs(url2, testServiceListener2, multiApps);
assertEquals(1, serviceDiscoveryRegistry.getServiceListeners().size());
// do unsubscribe
when(mapping.getMapping(url2)).thenReturn(multiApps);
serviceDiscoveryRegistry.doUnsubscribe(url2, testServiceListener2);
assertEquals(1, serviceDiscoveryRegistry.getServiceListeners().size());
ServiceInstancesChangedListener instancesChangedListener = serviceDiscoveryRegistry
.getServiceListeners()
.entrySet()
.iterator()
.next()
.getValue();
assertTrue(instancesChangedListener.hasListeners());
when(mapping.getMapping(url)).thenReturn(multiApps);
serviceDiscoveryRegistry.doUnsubscribe(url, testServiceListener);
assertEquals(0, serviceDiscoveryRegistry.getServiceListeners().size());
assertFalse(instancesChangedListener.hasListeners());
}
}
| 5,434 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/InstanceAddressURLTest.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.registry.client;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.registry.ProviderFirstParams;
import org.apache.dubbo.rpc.RpcServiceContext;
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.Map;
import java.util.Set;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_APPLICATION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TAG_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.in;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
class InstanceAddressURLTest {
private static URL url = URL.valueOf(
"dubbo://30.225.21.30:20880/org.apache.dubbo.registry.service.DemoService?"
+ "REGISTRY_CLUSTER=registry1&anyhost=true&application=demo-provider2&delay=1000&deprecated=false&dubbo=2.0.2"
+ "&dynamic=true&generic=false&group=greeting&interface=org.apache.dubbo.registry.service.DemoService"
+ "&metadata-type=remote&methods=sayHello&sayHello.timeout=7000&a.timeout=7777&pid=66666&release=&revision=1.0.0&service-name-mapping=true"
+ "&side=provider&timeout=1000×tamp=1629970909999&version=1.0.0&dubbo.tag=provider¶ms-filter=-default");
private static URL url2 = URL.valueOf(
"dubbo://30.225.21.30:20880/org.apache.dubbo.registry.service.DemoService2?"
+ "REGISTRY_CLUSTER=registry1&anyhost=true&application=demo-provider2&delay=5000&deprecated=false&dubbo=2.0.2"
+ "&dynamic=true&generic=false&group=greeting&interface=org.apache.dubbo.registry.service.DemoService2"
+ "&metadata-type=remote&methods=sayHello&sayHello.timeout=7000&pid=36621&release=&revision=1.0.0&service-name-mapping=true"
+ "&side=provider&timeout=5000×tamp=1629970068002&version=1.0.0&dubbo.tag=provider2&uniqueKey=unique¶ms-filter=-default");
private static URL consumerURL = URL.valueOf("dubbo://30.225.21.30/org.apache.dubbo.registry.service.DemoService?"
+ "REGISTRY_CLUSTER=registry1&application=demo-consumer&dubbo=2.0.2"
+ "&group=greeting&interface=org.apache.dubbo.registry.service.DemoService"
+ "&version=1.0.0&timeout=9000&a.timeout=8888&dubbo.tag=consumer&protocol=dubbo");
private DefaultServiceInstance createInstance() {
DefaultServiceInstance instance =
new DefaultServiceInstance("demo-provider", "127.0.0.1", 8080, ApplicationModel.defaultModel());
Map<String, String> metadata = instance.getMetadata();
metadata.put("key1", "value1");
metadata.put("key2", "value2");
return instance;
}
private MetadataInfo createMetaDataInfo() {
MetadataInfo metadataInfo = new MetadataInfo("demo");
// export normal url again
metadataInfo.addService(url);
metadataInfo.addService(url2);
return metadataInfo;
}
private InstanceAddressURL instanceURL;
private transient volatile Set<String> providerFirstParams;
@BeforeEach
public void setUp() {
DefaultServiceInstance instance = createInstance();
MetadataInfo metadataInfo = createMetaDataInfo();
instanceURL = new InstanceAddressURL(instance, metadataInfo);
Set<ProviderFirstParams> providerFirstParams = ApplicationModel.defaultModel()
.getExtensionLoader(ProviderFirstParams.class)
.getSupportedExtensionInstances();
if (CollectionUtils.isEmpty(providerFirstParams)) {
this.providerFirstParams = null;
} else {
if (providerFirstParams.size() == 1) {
this.providerFirstParams = Collections.unmodifiableSet(
providerFirstParams.iterator().next().params());
} else {
Set<String> params = new HashSet<>();
for (ProviderFirstParams paramsFilter : providerFirstParams) {
if (paramsFilter.params() == null) {
break;
}
params.addAll(paramsFilter.params());
}
this.providerFirstParams = Collections.unmodifiableSet(params);
}
}
instanceURL.setProviderFirstParams(this.providerFirstParams);
}
@Test
void test1() {
// test reading of keys in instance and metadata work fine
assertEquals("value1", instanceURL.getParameter("key1")); // return instance key
assertNull(instanceURL.getParameter("delay")); // no service key specified
RpcServiceContext.getServiceContext().setConsumerUrl(consumerURL);
assertEquals("1000", instanceURL.getParameter("delay"));
assertEquals("1000", instanceURL.getServiceParameter(consumerURL.getProtocolServiceKey(), "delay"));
assertEquals("9000", instanceURL.getMethodParameter("sayHello", "timeout"));
assertEquals(
"9000",
instanceURL.getServiceMethodParameter(consumerURL.getProtocolServiceKey(), "sayHello", "timeout"));
assertNull(instanceURL.getParameter("uniqueKey"));
assertNull(instanceURL.getServiceParameter(consumerURL.getProtocolServiceKey(), "uniqueKey"));
assertEquals("unique", instanceURL.getServiceParameter(url2.getProtocolServiceKey(), "uniqueKey"));
// test some consumer keys have higher priority
assertEquals(
"8888", instanceURL.getServiceMethodParameter(consumerURL.getProtocolServiceKey(), "a", "timeout"));
assertEquals("9000", instanceURL.getParameter("timeout"));
// test some provider keys have higher priority
assertEquals("provider", instanceURL.getParameter(TAG_KEY));
assertEquals(instanceURL.getVersion(), instanceURL.getParameter(VERSION_KEY));
assertEquals(instanceURL.getGroup(), instanceURL.getParameter(GROUP_KEY));
assertEquals(instanceURL.getApplication(), instanceURL.getParameter(APPLICATION_KEY));
assertEquals("demo-consumer", instanceURL.getParameter(APPLICATION_KEY));
assertEquals(instanceURL.getRemoteApplication(), instanceURL.getParameter(REMOTE_APPLICATION_KEY));
assertEquals("demo-provider", instanceURL.getParameter(REMOTE_APPLICATION_KEY));
assertEquals(instanceURL.getSide(), instanceURL.getParameter(SIDE_KEY));
// assertThat(Arrays.asList("7000", "8888"), hasItem(instanceURL.getAnyMethodParameter("timeout")));
assertThat(instanceURL.getAnyMethodParameter("timeout"), in(Arrays.asList("7000", "8888")));
Map<String, String> expectedAllParams = new HashMap<>();
expectedAllParams.putAll(instanceURL.getInstance().getMetadata());
expectedAllParams.putAll(instanceURL
.getMetadataInfo()
.getServiceInfo(consumerURL.getProtocolServiceKey())
.getAllParams());
Map<String, String> consumerURLParameters = consumerURL.getParameters();
providerFirstParams.forEach(consumerURLParameters::remove);
expectedAllParams.putAll(consumerURLParameters);
assertEquals(expectedAllParams.size(), instanceURL.getParameters().size());
assertEquals(url.getParameter(TAG_KEY), instanceURL.getParameters().get(TAG_KEY));
assertEquals(
consumerURL.getParameter(TIMEOUT_KEY),
instanceURL.getParameters().get(TIMEOUT_KEY));
assertTrue(instanceURL.hasServiceMethodParameter(url.getProtocolServiceKey(), "a"));
assertTrue(instanceURL.hasServiceMethodParameter(url.getProtocolServiceKey(), "sayHello"));
assertTrue(instanceURL.hasMethodParameter("a", TIMEOUT_KEY));
assertTrue(instanceURL.hasMethodParameter(null, TIMEOUT_KEY));
assertEquals("8888", instanceURL.getMethodParameter("a", TIMEOUT_KEY));
assertTrue(instanceURL.hasMethodParameter("a", null));
assertFalse(instanceURL.hasMethodParameter("notExistMethod", null));
// keys added to instance url are shared among services.
instanceURL.addParameter("newKey", "newValue");
assertEquals("newValue", instanceURL.getParameter("newKey"));
assertEquals("newValue", instanceURL.getParameters().get("newKey"));
assertEquals(
"newValue",
instanceURL.getServiceParameters(url.getProtocolServiceKey()).get("newKey"));
}
@Test
void test2() {
RpcServiceContext.getServiceContext().setConsumerUrl(null);
Assertions.assertNull(instanceURL.getScopeModel());
ModuleModel moduleModel = Mockito.mock(ModuleModel.class);
RpcServiceContext.getServiceContext().setConsumerUrl(URL.valueOf("").setScopeModel(moduleModel));
Assertions.assertEquals(moduleModel, instanceURL.getScopeModel());
}
}
| 5,435 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryCacheTest.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.registry.client;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.registry.client.support.MockServiceDiscovery;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.apache.dubbo.common.constants.CommonConstants.METADATA_INFO_CACHE_EXPIRE_KEY;
import static org.awaitility.Awaitility.await;
class ServiceDiscoveryCacheTest {
@Test
void test() throws InterruptedException {
ApplicationModel applicationModel = FrameworkModel.defaultModel().newApplication();
applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig("Test"));
URL registryUrl = URL.valueOf("mock://127.0.0.1:12345").addParameter(METADATA_INFO_CACHE_EXPIRE_KEY, 10);
MockServiceDiscovery mockServiceDiscovery =
Mockito.spy(new MockServiceDiscovery(applicationModel, registryUrl));
mockServiceDiscovery.register(URL.valueOf("mock://127.0.0.1:12345")
.setServiceInterface("org.apache.dubbo.registry.service.DemoService"));
mockServiceDiscovery.register();
ServiceInstance localInstance = mockServiceDiscovery.getLocalInstance();
Assertions.assertEquals(
localInstance.getServiceMetadata(),
mockServiceDiscovery.getLocalMetadata(
localInstance.getServiceMetadata().getRevision()));
List<MetadataInfo> instances = new LinkedList<>();
instances.add(localInstance.getServiceMetadata().clone());
for (int i = 0; i < 15; i++) {
Thread.sleep(1);
mockServiceDiscovery.register(URL.valueOf("mock://127.0.0.1:12345")
.setServiceInterface("org.apache.dubbo.registry.service.DemoService" + i));
mockServiceDiscovery.update();
instances.add(
mockServiceDiscovery.getLocalInstance().getServiceMetadata().clone());
}
for (MetadataInfo instance : instances) {
Assertions.assertEquals(instance, mockServiceDiscovery.getLocalMetadata(instance.getRevision()));
}
for (int i = 0; i < 5; i++) {
Thread.sleep(1);
mockServiceDiscovery.register(URL.valueOf("mock://127.0.0.1:12345")
.setServiceInterface("org.apache.dubbo.registry.service.DemoService-new" + i));
mockServiceDiscovery.update();
instances.add(
mockServiceDiscovery.getLocalInstance().getServiceMetadata().clone());
}
await().until(() -> Objects.isNull(
mockServiceDiscovery.getLocalMetadata(instances.get(4).getRevision())));
for (int i = 0; i < 5; i++) {
Assertions.assertNull(
mockServiceDiscovery.getLocalMetadata(instances.get(i).getRevision()));
}
applicationModel.destroy();
}
}
| 5,436 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/AbstractServiceDiscoveryFactoryTest.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.registry.client;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* {@link AbstractServiceDiscoveryFactory}
*/
class AbstractServiceDiscoveryFactoryTest {
@Test
void testGetServiceDiscoveryWithCache() {
ApplicationModel.defaultModel()
.getApplicationConfigManager()
.setApplication(new ApplicationConfig("AbstractServiceDiscoveryFactoryTest"));
URL url = URL.valueOf("mock://127.0.0.1:8888");
ServiceDiscoveryFactory factory = ServiceDiscoveryFactory.getExtension(url);
ServiceDiscovery serviceDiscovery1 = factory.getServiceDiscovery(url);
ServiceDiscovery serviceDiscovery2 = factory.getServiceDiscovery(url);
Assertions.assertEquals(serviceDiscovery1, serviceDiscovery2);
url = url.setPath("test");
ServiceDiscovery serviceDiscovery3 = factory.getServiceDiscovery(url);
Assertions.assertNotEquals(serviceDiscovery2, serviceDiscovery3);
AbstractServiceDiscoveryFactory abstractServiceDiscoveryFactory = (AbstractServiceDiscoveryFactory) factory;
List<ServiceDiscovery> allServiceDiscoveries = abstractServiceDiscoveryFactory.getAllServiceDiscoveries();
Assertions.assertEquals(2, allServiceDiscoveries.size());
Assertions.assertTrue(allServiceDiscoveries.contains(serviceDiscovery1));
Assertions.assertTrue(allServiceDiscoveries.contains(serviceDiscovery3));
}
}
| 5,437 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/DefaultServiceInstanceTest.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.registry.client;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.EXPORTED_SERVICES_REVISION_PROPERTY_NAME;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.METADATA_STORAGE_TYPE_PROPERTY_NAME;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.getEndpoint;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.setEndpoints;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotSame;
/**
* {@link DefaultServiceInstance} Test
*
* @since 2.7.5
*/
class DefaultServiceInstanceTest {
public DefaultServiceInstance instance;
public static DefaultServiceInstance createInstance() {
DefaultServiceInstance instance =
new DefaultServiceInstance("A", "127.0.0.1", 20880, ApplicationModel.defaultModel());
Map<String, String> metadata = instance.getMetadata();
metadata.put(METADATA_STORAGE_TYPE_PROPERTY_NAME, "remote");
metadata.put(EXPORTED_SERVICES_REVISION_PROPERTY_NAME, "111");
metadata.put("site", "dubbo");
Map<String, Integer> protocolPorts = new HashMap<>();
protocolPorts.put("rest", 8080);
protocolPorts.put("dubbo", 20880);
setEndpoints(instance, protocolPorts);
return instance;
}
@BeforeEach
public void init() {
instance = createInstance();
}
@Test
void testSetAndGetValues() {
instance.setEnabled(false);
instance.setHealthy(false);
assertEquals("A", instance.getServiceName());
assertEquals("127.0.0.1", instance.getHost());
assertEquals(20880, instance.getPort());
assertFalse(instance.isEnabled());
assertFalse(instance.isHealthy());
assertFalse(instance.getMetadata().isEmpty());
}
@Test
void testInstanceOperations() {
// test multiple protocols
assertEquals(2, instance.getEndpoints().size());
DefaultServiceInstance.Endpoint endpoint = getEndpoint(instance, "rest");
DefaultServiceInstance copyInstance = instance.copyFrom(endpoint);
assertEquals(8080, endpoint.getPort());
assertEquals("rest", endpoint.getProtocol());
assertEquals(endpoint.getPort(), copyInstance.getPort());
// test all params
Map<String, String> allParams = instance.getAllParams();
assertEquals(instance.getMetadata().size(), allParams.size());
assertEquals("dubbo", allParams.get("site"));
instance.putExtendParam("key", "value");
Map<String, String> allParams2 = instance.getAllParams();
assertNotSame(allParams, allParams2);
assertEquals(instance.getMetadata().size() + instance.getExtendParams().size(), allParams2.size());
assertEquals("value", allParams2.get("key"));
// test equals
DefaultServiceInstance instance2 =
new DefaultServiceInstance("A", "127.0.0.1", 20880, ApplicationModel.defaultModel());
instance2.setMetadata(new HashMap<>(instance.getMetadata()));
instance2.getMetadata().put(EXPORTED_SERVICES_REVISION_PROPERTY_NAME, "222");
// assert instances with different revision and extend params are equal
assertEquals(instance, instance2);
}
}
| 5,438 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/support/MockServiceDiscoveryFactory.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.registry.client.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.registry.client.AbstractServiceDiscoveryFactory;
import org.apache.dubbo.registry.client.ServiceDiscovery;
public class MockServiceDiscoveryFactory extends AbstractServiceDiscoveryFactory {
@Override
protected ServiceDiscovery createDiscovery(URL registryURL) {
return new MockServiceDiscovery(applicationModel, registryURL);
}
}
| 5,439 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/support/MockServiceDiscovery.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.registry.client.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.registry.client.AbstractServiceDiscovery;
import org.apache.dubbo.registry.client.ServiceInstance;
import org.apache.dubbo.registry.client.metadata.store.MetaCacheManager;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Collections;
import java.util.List;
import java.util.Set;
public class MockServiceDiscovery extends AbstractServiceDiscovery {
public MockServiceDiscovery(ApplicationModel applicationModel, URL registryURL) {
super(applicationModel, registryURL);
}
public MockServiceDiscovery(String serviceName, URL registryURL) {
super(serviceName, registryURL);
}
@Override
public void doRegister(ServiceInstance serviceInstance) throws RuntimeException {}
@Override
public void doUnregister(ServiceInstance serviceInstance) {}
@Override
public void doDestroy() throws Exception {}
@Override
public Set<String> getServices() {
return null;
}
@Override
public List<ServiceInstance> getInstances(String serviceName) throws NullPointerException {
return Collections.emptyList();
}
public MetaCacheManager getMetaCacheManager() {
return metaCacheManager;
}
}
| 5,440 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/migration/MigrationRuleListenerTest.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.registry.client.migration;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.registry.client.migration.model.MigrationRule;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.concurrent.CountDownLatch;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import static org.awaitility.Awaitility.await;
class MigrationRuleListenerTest {
private String localRule = "key: demo-consumer\n" + "step: APPLICATION_FIRST\n"
+ "threshold: 1.0\n"
+ "proportion: 60\n"
+ "delay: 60\n"
+ "force: false\n"
+ "interfaces:\n"
+ " - serviceKey: DemoService:1.0.0\n"
+ " threshold: 0.5\n"
+ " proportion: 30\n"
+ " delay: 30\n"
+ " force: true\n"
+ " step: APPLICATION_FIRST\n"
+ " - serviceKey: GreetingService:1.0.0\n"
+ " step: FORCE_APPLICATION";
private String remoteRule = "key: demo-consumer\n" + "step: FORCE_APPLICATION\n"
+ "threshold: 1.0\n"
+ "proportion: 60\n"
+ "delay: 60\n"
+ "force: false\n"
+ "interfaces:\n"
+ " - serviceKey: DemoService:1.0.0\n"
+ " threshold: 0.5\n"
+ " proportion: 30\n"
+ " delay: 30\n"
+ " force: true\n"
+ " step: FORCE_APPLICATION\n"
+ " - serviceKey: GreetingService:1.0.0\n"
+ " step: FORCE_INTERFACE";
private String dynamicRemoteRule = "key: demo-consumer\n" + "step: APPLICATION_FIRST\n"
+ "threshold: 1.0\n"
+ "proportion: 60\n"
+ "delay: 60\n"
+ "force: false\n"
+ "interfaces:\n";
@AfterEach
public void tearDown() {
ApplicationModel.reset();
System.clearProperty("dubbo.application.migration.delay");
}
/**
* Listener started with config center and local rule, no initial remote rule.
* Check local rule take effect
*/
@Test
void test() {
DynamicConfiguration dynamicConfiguration = Mockito.mock(DynamicConfiguration.class);
ApplicationModel.reset();
ApplicationModel.defaultModel()
.getDefaultModule()
.modelEnvironment()
.setDynamicConfiguration(dynamicConfiguration);
ApplicationModel.defaultModel().getDefaultModule().modelEnvironment().setLocalMigrationRule(localRule);
ApplicationConfig applicationConfig = new ApplicationConfig();
applicationConfig.setName("demo-consumer");
ApplicationModel.defaultModel().getApplicationConfigManager().setApplication(applicationConfig);
URL consumerURL = Mockito.mock(URL.class);
Mockito.when(consumerURL.getServiceKey()).thenReturn("Test");
Mockito.when(consumerURL.getParameter("timestamp")).thenReturn("1");
System.setProperty("dubbo.application.migration.delay", "1");
MigrationRuleHandler<?> handler =
Mockito.mock(MigrationRuleHandler.class, Mockito.withSettings().verboseLogging());
CountDownLatch countDownLatch = new CountDownLatch(1);
MigrationRuleListener migrationRuleListener =
new MigrationRuleListener(ApplicationModel.defaultModel().getDefaultModule()) {
@Override
public synchronized void process(ConfigChangedEvent event) {
try {
countDownLatch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
super.process(event);
}
};
MigrationInvoker<?> migrationInvoker = Mockito.mock(MigrationInvoker.class);
migrationRuleListener.getHandlers().put(migrationInvoker, handler);
countDownLatch.countDown();
await().untilAsserted(() -> {
Mockito.verify(handler).doMigrate(Mockito.any());
});
// Mockito.verify(handler, Mockito.timeout(5000)).doMigrate(Mockito.any());
migrationRuleListener.onRefer(null, migrationInvoker, consumerURL, null);
Mockito.verify(handler, Mockito.times(2)).doMigrate(Mockito.any());
}
/**
* Test listener started without local rule and config center, INIT should be used and no scheduled task should be started.
*/
@Test
void testWithInitAndNoLocalRule() {
ApplicationModel.defaultModel().getDefaultModule().modelEnvironment().setDynamicConfiguration(null);
ApplicationModel.defaultModel().getDefaultModule().modelEnvironment().setLocalMigrationRule("");
ApplicationConfig applicationConfig = new ApplicationConfig();
applicationConfig.setName("demo-consumer");
ApplicationModel.defaultModel().getApplicationConfigManager().setApplication(applicationConfig);
URL consumerURL = Mockito.mock(URL.class);
Mockito.when(consumerURL.getServiceKey()).thenReturn("Test");
Mockito.when(consumerURL.getParameter("timestamp")).thenReturn("1");
System.setProperty("dubbo.application.migration.delay", "1000");
MigrationRuleHandler<?> handler =
Mockito.mock(MigrationRuleHandler.class, Mockito.withSettings().verboseLogging());
MigrationRuleListener migrationRuleListener =
new MigrationRuleListener(ApplicationModel.defaultModel().getDefaultModule());
MigrationInvoker<?> migrationInvoker = Mockito.mock(MigrationInvoker.class);
migrationRuleListener.getHandlers().put(migrationInvoker, handler);
migrationRuleListener.onRefer(null, migrationInvoker, consumerURL, null);
// check migration happened after invoker referred
Mockito.verify(handler, Mockito.times(1)).doMigrate(MigrationRule.getInitRule());
// check no delay tasks created for there's no local rule and no config center
Assertions.assertNull(migrationRuleListener.localRuleMigrationFuture);
Assertions.assertNull(migrationRuleListener.ruleMigrationFuture);
Assertions.assertEquals(0, migrationRuleListener.ruleQueue.size());
}
/**
* Listener with config center, initial remote rule and local rule, check
* 1. initial remote rule other than local rule take effect
* 2. remote rule change and all invokers gets notified
*/
@Test
void testWithConfigurationListenerAndLocalRule() {
DynamicConfiguration dynamicConfiguration = Mockito.mock(DynamicConfiguration.class);
Mockito.doReturn(remoteRule).when(dynamicConfiguration).getConfig(Mockito.anyString(), Mockito.anyString());
ApplicationModel.defaultModel()
.getDefaultModule()
.modelEnvironment()
.setDynamicConfiguration(dynamicConfiguration);
ApplicationModel.defaultModel().getDefaultModule().modelEnvironment().setLocalMigrationRule(localRule);
ApplicationConfig applicationConfig = new ApplicationConfig();
applicationConfig.setName("demo-consumer");
ApplicationModel.defaultModel().getApplicationConfigManager().setApplication(applicationConfig);
URL consumerURL = Mockito.mock(URL.class);
Mockito.when(consumerURL.getServiceKey()).thenReturn("Test");
Mockito.when(consumerURL.getParameter("timestamp")).thenReturn("1");
URL consumerURL2 = Mockito.mock(URL.class);
Mockito.when(consumerURL2.getServiceKey()).thenReturn("Test2");
Mockito.when(consumerURL2.getParameter("timestamp")).thenReturn("2");
System.setProperty("dubbo.application.migration.delay", "10");
MigrationRuleHandler<?> handler =
Mockito.mock(MigrationRuleHandler.class, Mockito.withSettings().verboseLogging());
MigrationRuleHandler<?> handler2 =
Mockito.mock(MigrationRuleHandler.class, Mockito.withSettings().verboseLogging());
// Both local rule and remote rule are here
// Local rule with one delayed task started to apply
MigrationRuleListener migrationRuleListener =
new MigrationRuleListener(ApplicationModel.defaultModel().getDefaultModule());
Assertions.assertNotNull(migrationRuleListener.localRuleMigrationFuture);
Assertions.assertNull(migrationRuleListener.ruleMigrationFuture);
MigrationInvoker<?> migrationInvoker = Mockito.mock(MigrationInvoker.class);
MigrationInvoker<?> migrationInvoker2 = Mockito.mock(MigrationInvoker.class);
// Remote rule will be applied when onRefer gets executed
migrationRuleListener.getHandlers().put(migrationInvoker, handler);
migrationRuleListener.onRefer(null, migrationInvoker, consumerURL, null);
MigrationRule tmpRemoteRule = migrationRuleListener.getRule();
ArgumentCaptor<MigrationRule> captor = ArgumentCaptor.forClass(MigrationRule.class);
Mockito.verify(handler, Mockito.times(1)).doMigrate(captor.capture());
Assertions.assertEquals(tmpRemoteRule, captor.getValue());
await().until(() -> migrationRuleListener.localRuleMigrationFuture.isDone());
Assertions.assertNull(migrationRuleListener.ruleMigrationFuture);
Assertions.assertEquals(tmpRemoteRule, migrationRuleListener.getRule());
Mockito.verify(handler, Mockito.times(1)).doMigrate(Mockito.any());
ArgumentCaptor<MigrationRule> captor2 = ArgumentCaptor.forClass(MigrationRule.class);
migrationRuleListener.getHandlers().put(migrationInvoker2, handler2);
migrationRuleListener.onRefer(null, migrationInvoker2, consumerURL2, null);
Mockito.verify(handler2, Mockito.times(1)).doMigrate(captor2.capture());
Assertions.assertEquals(tmpRemoteRule, captor2.getValue());
migrationRuleListener.process(new ConfigChangedEvent("key", "group", dynamicRemoteRule));
await().until(migrationRuleListener.ruleQueue::isEmpty);
await().untilAsserted(() -> {
Mockito.verify(handler, Mockito.times(2)).doMigrate(Mockito.any());
Mockito.verify(handler2, Mockito.times(2)).doMigrate(Mockito.any());
});
Assertions.assertNotNull(migrationRuleListener.ruleMigrationFuture);
ArgumentCaptor<MigrationRule> captor_event = ArgumentCaptor.forClass(MigrationRule.class);
Mockito.verify(handler, Mockito.times(2)).doMigrate(captor_event.capture());
Assertions.assertEquals(
"APPLICATION_FIRST", captor_event.getValue().getStep().toString());
Mockito.verify(handler2, Mockito.times(2)).doMigrate(captor_event.capture());
Assertions.assertEquals(
"APPLICATION_FIRST", captor_event.getValue().getStep().toString());
}
}
| 5,441 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/migration/MigrationInvokerTest.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.registry.client.migration;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.status.reporter.FrameworkStatusReportService;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.registry.client.migration.model.MigrationRule;
import org.apache.dubbo.registry.client.migration.model.MigrationStep;
import org.apache.dubbo.registry.integration.DemoService;
import org.apache.dubbo.registry.integration.DynamicDirectory;
import org.apache.dubbo.registry.integration.RegistryProtocol;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.cluster.ClusterInvoker;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.LinkedList;
import java.util.List;
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 org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
class MigrationInvokerTest {
@BeforeEach
public void before() {
FrameworkModel.destroyAll();
ApplicationConfig applicationConfig = new ApplicationConfig();
applicationConfig.setName("Test");
ApplicationModel.defaultModel().getApplicationConfigManager().setApplication(applicationConfig);
ApplicationModel.defaultModel().getBeanFactory().registerBean(FrameworkStatusReportService.class);
}
@AfterEach
public void after() {
FrameworkModel.destroyAll();
}
@SuppressWarnings("all")
@Test
void test() {
RegistryProtocol registryProtocol = Mockito.mock(RegistryProtocol.class);
ClusterInvoker invoker = Mockito.mock(ClusterInvoker.class);
ClusterInvoker serviceDiscoveryInvoker = Mockito.mock(ClusterInvoker.class);
DynamicDirectory directory = Mockito.mock(DynamicDirectory.class);
DynamicDirectory serviceDiscoveryDirectory = Mockito.mock(DynamicDirectory.class);
Mockito.when(invoker.getDirectory()).thenReturn(directory);
Mockito.when(serviceDiscoveryInvoker.getDirectory()).thenReturn(serviceDiscoveryDirectory);
Mockito.when(invoker.isAvailable()).thenReturn(true);
Mockito.when(serviceDiscoveryInvoker.isAvailable()).thenReturn(true);
Mockito.when(invoker.hasProxyInvokers()).thenReturn(true);
Mockito.when(serviceDiscoveryInvoker.hasProxyInvokers()).thenReturn(true);
List<Invoker<?>> invokers = new LinkedList<>();
invokers.add(Mockito.mock(Invoker.class));
invokers.add(Mockito.mock(Invoker.class));
List<Invoker<?>> serviceDiscoveryInvokers = new LinkedList<>();
serviceDiscoveryInvokers.add(Mockito.mock(Invoker.class));
serviceDiscoveryInvokers.add(Mockito.mock(Invoker.class));
Mockito.when(directory.getAllInvokers()).thenReturn(invokers);
Mockito.when(serviceDiscoveryDirectory.getAllInvokers()).thenReturn(serviceDiscoveryInvokers);
Mockito.when(registryProtocol.getInvoker(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()))
.thenReturn(invoker);
Mockito.when(registryProtocol.getServiceDiscoveryInvoker(
Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()))
.thenReturn(serviceDiscoveryInvoker);
URL consumerURL = Mockito.mock(URL.class);
Mockito.when(consumerURL.getServiceInterface()).thenReturn("Test");
Mockito.when(consumerURL.getGroup()).thenReturn("Group");
Mockito.when(consumerURL.getVersion()).thenReturn("0.0.0");
Mockito.when(consumerURL.getServiceKey()).thenReturn("Group/Test:0.0.0");
Mockito.when(consumerURL.getDisplayServiceKey()).thenReturn("Test:0.0.0");
Mockito.when(consumerURL.getOrDefaultApplicationModel()).thenReturn(ApplicationModel.defaultModel());
Mockito.when(invoker.getUrl()).thenReturn(consumerURL);
Mockito.when(serviceDiscoveryInvoker.getUrl()).thenReturn(consumerURL);
MigrationInvoker<?> migrationInvoker =
new MigrationInvoker<>(registryProtocol, null, null, DemoService.class, null, consumerURL);
MigrationRule migrationRule = Mockito.mock(MigrationRule.class);
Mockito.when(migrationRule.getForce(Mockito.any())).thenReturn(true);
migrationInvoker.migrateToForceInterfaceInvoker(migrationRule);
migrationInvoker.setMigrationStep(MigrationStep.FORCE_INTERFACE);
migrationInvoker.invoke(null);
Mockito.verify(invoker, Mockito.times(1)).invoke(null);
migrationInvoker.migrateToForceApplicationInvoker(migrationRule);
migrationInvoker.setMigrationStep(MigrationStep.FORCE_APPLICATION);
migrationInvoker.invoke(null);
Mockito.verify(serviceDiscoveryInvoker, Mockito.times(1)).invoke(null);
Mockito.when(migrationRule.getThreshold(Mockito.any())).thenReturn(1.0f);
migrationInvoker.migrateToApplicationFirstInvoker(migrationRule);
migrationInvoker.setMigrationStep(MigrationStep.APPLICATION_FIRST);
migrationInvoker.invoke(null);
Mockito.verify(serviceDiscoveryInvoker, Mockito.times(2)).invoke(null);
Mockito.when(migrationRule.getThreshold(Mockito.any())).thenReturn(2.0f);
migrationInvoker.migrateToApplicationFirstInvoker(migrationRule);
migrationInvoker.setMigrationStep(MigrationStep.APPLICATION_FIRST);
migrationInvoker.invoke(null);
Mockito.verify(invoker, Mockito.times(2)).invoke(null);
Mockito.when(migrationRule.getForce(Mockito.any())).thenReturn(false);
Mockito.when(migrationRule.getThreshold(Mockito.any())).thenReturn(1.0f);
migrationInvoker.migrateToForceInterfaceInvoker(migrationRule);
migrationInvoker.setMigrationStep(MigrationStep.FORCE_INTERFACE);
migrationInvoker.invoke(null);
Mockito.verify(invoker, Mockito.times(3)).invoke(null);
migrationInvoker.migrateToForceInterfaceInvoker(migrationRule);
migrationInvoker.setMigrationStep(MigrationStep.FORCE_INTERFACE);
migrationInvoker.invoke(null);
Mockito.verify(invoker, Mockito.times(4)).invoke(null);
Mockito.when(migrationRule.getThreshold(Mockito.any())).thenReturn(2.0f);
migrationInvoker.migrateToForceApplicationInvoker(migrationRule);
migrationInvoker.setMigrationStep(MigrationStep.FORCE_APPLICATION);
migrationInvoker.invoke(null);
Mockito.verify(invoker, Mockito.times(5)).invoke(null);
Mockito.when(migrationRule.getThreshold(Mockito.any())).thenReturn(1.0f);
migrationInvoker.migrateToForceApplicationInvoker(migrationRule);
migrationInvoker.setMigrationStep(MigrationStep.FORCE_APPLICATION);
migrationInvoker.invoke(null);
Mockito.verify(serviceDiscoveryInvoker, Mockito.times(3)).invoke(null);
migrationInvoker.migrateToForceApplicationInvoker(migrationRule);
migrationInvoker.setMigrationStep(MigrationStep.FORCE_APPLICATION);
migrationInvoker.invoke(null);
Mockito.verify(serviceDiscoveryInvoker, Mockito.times(4)).invoke(null);
Mockito.when(migrationRule.getThreshold(Mockito.any())).thenReturn(2.0f);
migrationInvoker.migrateToForceInterfaceInvoker(migrationRule);
migrationInvoker.setMigrationStep(MigrationStep.FORCE_INTERFACE);
migrationInvoker.invoke(null);
Mockito.verify(serviceDiscoveryInvoker, Mockito.times(5)).invoke(null);
Mockito.when(migrationRule.getThreshold(Mockito.any())).thenReturn(2.0f);
Mockito.when(migrationRule.getForce(Mockito.any())).thenReturn(true);
migrationInvoker.migrateToForceInterfaceInvoker(migrationRule);
migrationInvoker.setMigrationStep(MigrationStep.FORCE_INTERFACE);
migrationInvoker.invoke(null);
Mockito.verify(invoker, Mockito.times(6)).invoke(null);
migrationInvoker.migrateToForceApplicationInvoker(migrationRule);
migrationInvoker.setMigrationStep(MigrationStep.FORCE_APPLICATION);
migrationInvoker.invoke(null);
Mockito.verify(serviceDiscoveryInvoker, Mockito.times(6)).invoke(null);
Mockito.when(migrationRule.getForce(Mockito.any())).thenReturn(false);
migrationInvoker.migrateToForceInterfaceInvoker(migrationRule);
migrationInvoker.setMigrationStep(MigrationStep.FORCE_INTERFACE);
migrationInvoker.invoke(null);
Mockito.verify(serviceDiscoveryInvoker, Mockito.times(7)).invoke(null);
Assertions.assertNull(migrationInvoker.getInvoker());
Mockito.when(migrationRule.getForce(Mockito.any())).thenReturn(true);
migrationInvoker.migrateToForceInterfaceInvoker(migrationRule);
migrationInvoker.setMigrationStep(MigrationStep.FORCE_INTERFACE);
Mockito.when(migrationRule.getForce(Mockito.any())).thenReturn(false);
migrationInvoker.migrateToForceApplicationInvoker(migrationRule);
migrationInvoker.setMigrationStep(MigrationStep.FORCE_APPLICATION);
migrationInvoker.invoke(null);
Mockito.verify(invoker, Mockito.times(7)).invoke(null);
Assertions.assertNull(migrationInvoker.getServiceDiscoveryInvoker());
ArgumentCaptor<InvokersChangedListener> argument = ArgumentCaptor.forClass(InvokersChangedListener.class);
Mockito.verify(serviceDiscoveryDirectory, Mockito.atLeastOnce()).setInvokersChangedListener(argument.capture());
Mockito.when(migrationRule.getThreshold(Mockito.any())).thenReturn(1.0f);
migrationInvoker.migrateToApplicationFirstInvoker(migrationRule);
migrationInvoker.setMigrationStep(MigrationStep.APPLICATION_FIRST);
for (int i = 0; i < 20; i++) {
migrationInvoker.invoke(null);
}
Mockito.verify(serviceDiscoveryInvoker, Mockito.times(27)).invoke(null);
serviceDiscoveryInvokers.remove(1);
Mockito.when(serviceDiscoveryInvoker.hasProxyInvokers()).thenReturn(false);
argument.getAllValues().get(argument.getAllValues().size() - 1).onChange();
for (int i = 0; i < 20; i++) {
migrationInvoker.invoke(null);
}
Mockito.verify(invoker, Mockito.times(27)).invoke(null);
serviceDiscoveryInvokers.add(Mockito.mock(Invoker.class));
Mockito.when(serviceDiscoveryInvoker.hasProxyInvokers()).thenReturn(true);
argument.getAllValues().get(argument.getAllValues().size() - 1).onChange();
Mockito.when(migrationRule.getProportion(Mockito.any())).thenReturn(50);
migrationInvoker.setMigrationRule(migrationRule);
for (int i = 0; i < 1000; i++) {
migrationInvoker.invoke(null);
}
Mockito.verify(serviceDiscoveryInvoker, Mockito.atMost(1026)).invoke(null);
Mockito.verify(invoker, Mockito.atLeast(28)).invoke(null);
Mockito.when(migrationRule.getDelay(Mockito.any())).thenReturn(1);
long currentTimeMillis = System.currentTimeMillis();
migrationInvoker.migrateToForceApplicationInvoker(migrationRule);
Assertions.assertTrue(System.currentTimeMillis() - currentTimeMillis >= 2000);
}
@SuppressWarnings("all")
@Test
void testDecide() {
RegistryProtocol registryProtocol = Mockito.mock(RegistryProtocol.class);
ClusterInvoker invoker = Mockito.mock(ClusterInvoker.class);
ClusterInvoker serviceDiscoveryInvoker = Mockito.mock(ClusterInvoker.class);
DynamicDirectory directory = Mockito.mock(DynamicDirectory.class);
DynamicDirectory serviceDiscoveryDirectory = Mockito.mock(DynamicDirectory.class);
Mockito.when(invoker.getDirectory()).thenReturn(directory);
Mockito.when(serviceDiscoveryInvoker.getDirectory()).thenReturn(serviceDiscoveryDirectory);
Mockito.when(invoker.isAvailable()).thenReturn(true);
Mockito.when(serviceDiscoveryInvoker.isAvailable()).thenReturn(true);
Mockito.when(invoker.hasProxyInvokers()).thenReturn(true);
Mockito.when(serviceDiscoveryInvoker.hasProxyInvokers()).thenReturn(true);
List<Invoker<?>> invokers = new LinkedList<>();
invokers.add(Mockito.mock(Invoker.class));
invokers.add(Mockito.mock(Invoker.class));
List<Invoker<?>> serviceDiscoveryInvokers = new LinkedList<>();
serviceDiscoveryInvokers.add(Mockito.mock(Invoker.class));
serviceDiscoveryInvokers.add(Mockito.mock(Invoker.class));
Mockito.when(directory.getAllInvokers()).thenReturn(invokers);
Mockito.when(serviceDiscoveryDirectory.getAllInvokers()).thenReturn(serviceDiscoveryInvokers);
Mockito.when(registryProtocol.getInvoker(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()))
.thenReturn(invoker);
Mockito.when(registryProtocol.getServiceDiscoveryInvoker(
Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()))
.thenReturn(serviceDiscoveryInvoker);
URL consumerURL = Mockito.mock(URL.class);
Mockito.when(consumerURL.getServiceInterface()).thenReturn("Test");
Mockito.when(consumerURL.getGroup()).thenReturn("Group");
Mockito.when(consumerURL.getVersion()).thenReturn("0.0.0");
Mockito.when(consumerURL.getServiceKey()).thenReturn("Group/Test:0.0.0");
Mockito.when(consumerURL.getDisplayServiceKey()).thenReturn("Test:0.0.0");
Mockito.when(consumerURL.getOrDefaultApplicationModel()).thenReturn(ApplicationModel.defaultModel());
Mockito.when(invoker.getUrl()).thenReturn(consumerURL);
Mockito.when(serviceDiscoveryInvoker.getUrl()).thenReturn(consumerURL);
MigrationInvoker<?> migrationInvoker =
new MigrationInvoker<>(registryProtocol, null, null, DemoService.class, null, consumerURL);
MigrationRule migrationRule = Mockito.mock(MigrationRule.class);
Mockito.when(migrationRule.getForce(Mockito.any())).thenReturn(true);
migrationInvoker.migrateToApplicationFirstInvoker(migrationRule);
migrationInvoker.setMigrationStep(MigrationStep.APPLICATION_FIRST);
migrationInvoker.invoke(null);
Mockito.verify(serviceDiscoveryInvoker, Mockito.times(1)).invoke(null);
Mockito.when(serviceDiscoveryInvoker.isAvailable()).thenReturn(false);
migrationInvoker.invoke(null);
Mockito.verify(invoker, Mockito.times(1)).invoke(null);
Mockito.when(serviceDiscoveryInvoker.isAvailable()).thenReturn(true);
migrationInvoker.invoke(null);
Mockito.verify(serviceDiscoveryInvoker, Mockito.times(2)).invoke(null);
}
@Test
void testConcurrency() {
// 独立线程
// 独立线程invoker状态切换
}
}
| 5,442 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/migration/MigrationRuleHandlerTest.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.registry.client.migration;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.registry.client.migration.model.MigrationRule;
import org.apache.dubbo.registry.client.migration.model.MigrationStep;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
class MigrationRuleHandlerTest {
@Test
void test() {
MigrationClusterInvoker<?> invoker = Mockito.mock(MigrationClusterInvoker.class);
URL url = Mockito.mock(URL.class);
Mockito.when(url.getDisplayServiceKey()).thenReturn("test");
Mockito.when(url.getParameter(Mockito.any(), (String) Mockito.any())).thenAnswer(i -> i.getArgument(1));
Mockito.when(url.getOrDefaultApplicationModel()).thenReturn(ApplicationModel.defaultModel());
MigrationRuleHandler<?> handler = new MigrationRuleHandler<>(invoker, url);
Mockito.when(invoker.migrateToForceApplicationInvoker(Mockito.any())).thenReturn(true);
Mockito.when(invoker.migrateToForceInterfaceInvoker(Mockito.any())).thenReturn(true);
MigrationRule initRule = MigrationRule.getInitRule();
handler.doMigrate(initRule);
Mockito.verify(invoker, Mockito.times(1)).migrateToApplicationFirstInvoker(initRule);
MigrationRule rule = Mockito.mock(MigrationRule.class);
Mockito.when(rule.getStep(url)).thenReturn(MigrationStep.FORCE_APPLICATION);
handler.doMigrate(rule);
Mockito.verify(invoker, Mockito.times(1)).migrateToForceApplicationInvoker(rule);
Mockito.when(rule.getStep(url)).thenReturn(MigrationStep.APPLICATION_FIRST);
handler.doMigrate(rule);
Mockito.verify(invoker, Mockito.times(1)).migrateToApplicationFirstInvoker(rule);
Mockito.when(rule.getStep(url)).thenReturn(MigrationStep.FORCE_INTERFACE);
handler.doMigrate(rule);
Mockito.verify(invoker, Mockito.times(1)).migrateToForceInterfaceInvoker(rule);
// migration failed, current rule not changed
testMigrationFailed(rule, url, handler, invoker);
// rule not changed, check migration not actually executed
testMigrationWithStepUnchanged(rule, url, handler, invoker);
}
private void testMigrationFailed(
MigrationRule rule, URL url, MigrationRuleHandler<?> handler, MigrationClusterInvoker<?> invoker) {
Assertions.assertEquals(MigrationStep.FORCE_INTERFACE, handler.getMigrationStep());
Mockito.when(invoker.migrateToForceApplicationInvoker(Mockito.any())).thenReturn(false);
Mockito.when(rule.getStep(url)).thenReturn(MigrationStep.FORCE_APPLICATION);
handler.doMigrate(rule);
Mockito.verify(invoker, Mockito.times(2)).migrateToForceApplicationInvoker(rule);
Assertions.assertEquals(MigrationStep.FORCE_INTERFACE, handler.getMigrationStep());
}
private void testMigrationWithStepUnchanged(
MigrationRule rule, URL url, MigrationRuleHandler<?> handler, MigrationClusterInvoker<?> invoker) {
// set the same as
Mockito.when(rule.getStep(url)).thenReturn(handler.getMigrationStep());
handler.doMigrate(rule);
// no interaction
Mockito.verify(invoker, Mockito.times(1)).migrateToForceInterfaceInvoker(rule);
}
}
| 5,443 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/migration/DefaultMigrationAddressComparatorTest.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.registry.client.migration;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.registry.client.migration.model.MigrationRule;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.cluster.ClusterInvoker;
import org.apache.dubbo.rpc.cluster.Directory;
import java.util.Collections;
import java.util.LinkedList;
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.registry.client.migration.DefaultMigrationAddressComparator.NEW_ADDRESS_SIZE;
import static org.apache.dubbo.registry.client.migration.DefaultMigrationAddressComparator.OLD_ADDRESS_SIZE;
class DefaultMigrationAddressComparatorTest {
@SuppressWarnings("all")
@Test
void test() {
DefaultMigrationAddressComparator comparator = new DefaultMigrationAddressComparator();
ClusterInvoker newInvoker = Mockito.mock(ClusterInvoker.class);
ClusterInvoker oldInvoker = Mockito.mock(ClusterInvoker.class);
Directory newDirectory = Mockito.mock(Directory.class);
Directory oldDirectory = Mockito.mock(Directory.class);
MigrationRule rule = Mockito.mock(MigrationRule.class);
URL url = Mockito.mock(URL.class);
Mockito.when(url.getDisplayServiceKey()).thenReturn("test");
Mockito.when(newInvoker.getDirectory()).thenReturn(newDirectory);
Mockito.when(oldInvoker.getDirectory()).thenReturn(oldDirectory);
Mockito.when(newInvoker.getUrl()).thenReturn(url);
Mockito.when(oldInvoker.getUrl()).thenReturn(url);
Mockito.when(newInvoker.hasProxyInvokers()).thenReturn(false);
Mockito.when(newDirectory.getAllInvokers()).thenReturn(Collections.emptyList());
Assertions.assertFalse(comparator.shouldMigrate(newInvoker, oldInvoker, rule));
Assertions.assertEquals(-1, comparator.getAddressSize("test").get(NEW_ADDRESS_SIZE));
Assertions.assertEquals(0, comparator.getAddressSize("test").get(OLD_ADDRESS_SIZE));
Mockito.when(newInvoker.hasProxyInvokers()).thenReturn(true);
Mockito.when(oldInvoker.hasProxyInvokers()).thenReturn(false);
Mockito.when(oldDirectory.getAllInvokers()).thenReturn(Collections.emptyList());
Assertions.assertTrue(comparator.shouldMigrate(newInvoker, oldInvoker, rule));
Assertions.assertEquals(0, comparator.getAddressSize("test").get(NEW_ADDRESS_SIZE));
Assertions.assertEquals(-1, comparator.getAddressSize("test").get(OLD_ADDRESS_SIZE));
Mockito.when(oldInvoker.hasProxyInvokers()).thenReturn(true);
List<Invoker<?>> newInvokerList = new LinkedList<>();
newInvokerList.add(Mockito.mock(Invoker.class));
newInvokerList.add(Mockito.mock(Invoker.class));
newInvokerList.add(Mockito.mock(Invoker.class));
Mockito.when(newDirectory.getAllInvokers()).thenReturn(newInvokerList);
List<Invoker<?>> oldInvokerList = new LinkedList<>();
oldInvokerList.add(Mockito.mock(Invoker.class));
oldInvokerList.add(Mockito.mock(Invoker.class));
Mockito.when(oldDirectory.getAllInvokers()).thenReturn(oldInvokerList);
Assertions.assertTrue(comparator.shouldMigrate(newInvoker, oldInvoker, null));
Mockito.when(rule.getThreshold(url)).thenReturn(0.5f);
newInvokerList.clear();
newInvokerList.add(Mockito.mock(Invoker.class));
Assertions.assertTrue(comparator.shouldMigrate(newInvoker, oldInvoker, rule));
newInvokerList.clear();
// hasProxyInvokers will check if invokers list is empty
// if hasProxyInvokers return true, comparator will directly because default threshold is 0.0
Assertions.assertTrue(comparator.shouldMigrate(newInvoker, oldInvoker, null));
Assertions.assertFalse(comparator.shouldMigrate(newInvoker, oldInvoker, rule));
Assertions.assertEquals(0, comparator.getAddressSize("test").get(NEW_ADDRESS_SIZE));
Assertions.assertEquals(2, comparator.getAddressSize("test").get(OLD_ADDRESS_SIZE));
}
}
| 5,444 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/migration | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/migration/model/MigrationRuleTest.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.registry.client.migration.model;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.metadata.ServiceNameMapping;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentMatchers;
import org.mockito.Mockito;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_CLUSTER_TYPE_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.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class MigrationRuleTest {
private static final ServiceNameMapping mapping = mock(ServiceNameMapping.class);
@Test
void test_parse() {
when(mapping.getMapping(any(URL.class))).thenReturn(Collections.emptySet());
String rule = "key: demo-consumer\n" + "step: APPLICATION_FIRST\n"
+ "threshold: 1.0\n"
+ "proportion: 60\n"
+ "delay: 60\n"
+ "force: false\n"
+ "interfaces:\n"
+ " - serviceKey: DemoService:1.0.0\n"
+ " threshold: 0.5\n"
+ " proportion: 30\n"
+ " delay: 30\n"
+ " force: true\n"
+ " step: APPLICATION_FIRST\n"
+ " - serviceKey: GreetingService:1.0.0\n"
+ " step: FORCE_APPLICATION\n"
+ "applications:\n"
+ " - serviceKey: TestApplication\n"
+ " threshold: 0.3\n"
+ " proportion: 20\n"
+ " delay: 10\n"
+ " force: false\n"
+ " step: FORCE_INTERFACE\n";
MigrationRule migrationRule = MigrationRule.parse(rule);
assertEquals("demo-consumer", migrationRule.getKey());
assertEquals(MigrationStep.APPLICATION_FIRST, migrationRule.getStep());
assertEquals(1.0f, migrationRule.getThreshold());
assertEquals(60, migrationRule.getProportion());
assertEquals(60, migrationRule.getDelay());
assertEquals(false, migrationRule.getForce());
URL url = Mockito.mock(URL.class);
ApplicationModel defaultModel = Mockito.spy(ApplicationModel.defaultModel());
Mockito.when(defaultModel.getDefaultExtension(ServiceNameMapping.class)).thenReturn(mapping);
Mockito.when(url.getScopeModel()).thenReturn(defaultModel);
Mockito.when(url.getDisplayServiceKey()).thenReturn("DemoService:1.0.0");
Mockito.when(url.getParameter(ArgumentMatchers.eq(REGISTRY_CLUSTER_TYPE_KEY), anyString()))
.thenReturn("default");
Mockito.when(url.getParameter(ArgumentMatchers.eq(REGISTRY_CLUSTER_TYPE_KEY), anyString()))
.thenReturn("default");
assertEquals(2, migrationRule.getInterfaces().size());
assertEquals(0.5f, migrationRule.getThreshold(url));
assertEquals(30, migrationRule.getProportion(url));
assertEquals(30, migrationRule.getDelay(url));
assertTrue(migrationRule.getForce(url));
assertEquals(MigrationStep.APPLICATION_FIRST, migrationRule.getStep(url));
Mockito.when(url.getDisplayServiceKey()).thenReturn("GreetingService:1.0.0");
assertEquals(1.0f, migrationRule.getThreshold(url));
assertEquals(60, migrationRule.getProportion(url));
assertEquals(60, migrationRule.getDelay(url));
assertFalse(migrationRule.getForce(url));
assertEquals(MigrationStep.FORCE_APPLICATION, migrationRule.getStep(url));
Mockito.when(url.getDisplayServiceKey()).thenReturn("GreetingService:1.0.1");
Mockito.when(url.getServiceInterface()).thenReturn("GreetingService");
when(mapping.getRemoteMapping(any(URL.class))).thenReturn(Collections.singleton("TestApplication"));
Set<String> services = new HashSet<>();
services.add("TestApplication");
when(mapping.getMapping(any(URL.class))).thenReturn(services);
assertEquals(0.3f, migrationRule.getThreshold(url));
assertEquals(20, migrationRule.getProportion(url));
assertEquals(10, migrationRule.getDelay(url));
assertFalse(migrationRule.getForce(url));
assertEquals(MigrationStep.FORCE_INTERFACE, migrationRule.getStep(url));
when(mapping.getMapping(any(URL.class))).thenReturn(Collections.emptySet());
ApplicationModel.defaultModel().destroy();
}
}
| 5,445 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/event | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/event/listener/ServiceInstancesChangedListenerWithoutEmptyProtectTest.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.registry.client.event.listener;
import org.apache.dubbo.common.ProtocolServiceKey;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.common.utils.LRUCache;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.metadata.MetadataService;
import org.apache.dubbo.registry.NotifyListener;
import org.apache.dubbo.registry.client.DefaultServiceInstance;
import org.apache.dubbo.registry.client.InstanceAddressURL;
import org.apache.dubbo.registry.client.ServiceDiscovery;
import org.apache.dubbo.registry.client.ServiceInstance;
import org.apache.dubbo.registry.client.event.ServiceInstancesChangedEvent;
import org.apache.dubbo.registry.client.metadata.store.MetaCacheManager;
import org.apache.dubbo.registry.client.support.MockServiceDiscovery;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.hamcrest.Matchers;
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.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import static org.apache.dubbo.common.constants.CommonConstants.REVISION_KEY;
import static org.apache.dubbo.common.utils.CollectionUtils.isEmpty;
import static org.apache.dubbo.common.utils.CollectionUtils.isNotEmpty;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.EXPORTED_SERVICES_REVISION_PROPERTY_NAME;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
/**
* {@link ServiceInstancesChangedListener} Test
*
* @since 2.7.5
*/
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class ServiceInstancesChangedListenerWithoutEmptyProtectTest {
static List<ServiceInstance> app1Instances;
static List<ServiceInstance> app2Instances;
static List<ServiceInstance> app1FailedInstances;
static List<ServiceInstance> app1FailedInstances2;
static List<ServiceInstance> app1InstancesWithNoRevision;
static List<ServiceInstance> app1InstancesMultipleProtocols;
static String metadata_111 = "{\"app\":\"app1\",\"revision\":\"111\",\"services\":{"
+ "\"org.apache.dubbo.demo.DemoService:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app1\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}"
+ "}}";
static String metadata_222 = "{\"app\":\"app2\",\"revision\":\"222\",\"services\":{"
+ "\"org.apache.dubbo.demo.DemoService:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}},"
+ "\"org.apache.dubbo.demo.DemoService2:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService2\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService2\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService2\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}"
+ "}}";
static String metadata_333 = "{\"app\":\"app2\",\"revision\":\"333\",\"services\":{"
+ "\"org.apache.dubbo.demo.DemoService:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}},"
+ "\"org.apache.dubbo.demo.DemoService2:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService2\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService2\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService2\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}},"
+ "\"org.apache.dubbo.demo.DemoService3:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService3\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService3\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService3\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}"
+ "}}";
// failed
static String metadata_444 = "{\"app\":\"app1\",\"revision\":\"444\",\"services\":{"
+ "\"org.apache.dubbo.demo.DemoService:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}"
+ "}}";
// only triple protocol enabled
static String metadata_555_triple = "{\"app\":\"app1\",\"revision\":\"555\",\"services\":{"
+ "\"org.apache.dubbo.demo.DemoService:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService\",\"protocol\":\"tri\",\"path\":\"org.apache.dubbo.demo.DemoService\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}"
+ "}}";
static String service1 = "org.apache.dubbo.demo.DemoService";
static String service2 = "org.apache.dubbo.demo.DemoService2";
static String service3 = "org.apache.dubbo.demo.DemoService3";
static URL consumerURL = URL.valueOf(
"dubbo://127.0.0.1/org.apache.dubbo.demo.DemoService?interface=org.apache.dubbo.demo.DemoService&protocol=dubbo®istry_cluster=default");
static URL consumerURL2 = URL.valueOf(
"dubbo://127.0.0.1/org.apache.dubbo.demo.DemoService2?interface=org.apache.dubbo.demo.DemoService2&protocol=dubbo®istry_cluster=default");
static URL consumerURL3 = URL.valueOf(
"dubbo://127.0.0.1/org.apache.dubbo.demo.DemoService3?interface=org.apache.dubbo.demo.DemoService3&protocol=dubbo®istry_cluster=default");
static URL multipleProtocolsConsumerURL = URL.valueOf(
"dubbo,tri://127.0.0.1/org.apache.dubbo.demo.DemoService?interface=org.apache.dubbo.demo.DemoService&protocol=dubbo,tri®istry_cluster=default");
static URL noProtocolConsumerURL = URL.valueOf(
"consumer://127.0.0.1/org.apache.dubbo.demo.DemoService?interface=org.apache.dubbo.demo.DemoService®istry_cluster=default");
static URL singleProtocolsConsumerURL = URL.valueOf(
"tri://127.0.0.1/org.apache.dubbo.demo.DemoService?interface=org.apache.dubbo.demo.DemoService&protocol=tri®istry_cluster=default");
static URL registryURL = URL.valueOf("dubbo://127.0.0.1:2181/org.apache.dubbo.demo.RegistryService");
static MetadataInfo metadataInfo_111;
static MetadataInfo metadataInfo_222;
static MetadataInfo metadataInfo_333;
static MetadataInfo metadataInfo_444;
static MetadataInfo metadataInfo_555_tri;
static MetadataService metadataService;
static ServiceDiscovery serviceDiscovery;
static ServiceInstancesChangedListener listener = null;
@BeforeAll
public static void setUp() {
metadataService = Mockito.mock(MetadataService.class);
List<Object> urlsSameRevision = new ArrayList<>();
urlsSameRevision.add("127.0.0.1:20880?revision=111");
urlsSameRevision.add("127.0.0.2:20880?revision=111");
urlsSameRevision.add("127.0.0.3:20880?revision=111");
List<Object> urlsDifferentRevision = new ArrayList<>();
urlsDifferentRevision.add("30.10.0.1:20880?revision=222");
urlsDifferentRevision.add("30.10.0.2:20880?revision=222");
urlsDifferentRevision.add("30.10.0.3:20880?revision=333");
urlsDifferentRevision.add("30.10.0.4:20880?revision=333");
List<Object> urlsFailedRevision = new ArrayList<>();
urlsFailedRevision.add("30.10.0.5:20880?revision=222");
urlsFailedRevision.add("30.10.0.6:20880?revision=222");
urlsFailedRevision.add("30.10.0.7:20880?revision=444"); // revision will fail
urlsFailedRevision.add("30.10.0.8:20880?revision=444"); // revision will fail
List<Object> urlsFailedRevision2 = new ArrayList<>();
urlsFailedRevision2.add("30.10.0.1:20880?revision=222");
urlsFailedRevision2.add("30.10.0.2:20880?revision=222");
List<Object> urlsWithoutRevision = new ArrayList<>();
urlsWithoutRevision.add("30.10.0.1:20880");
List<Object> urlsMultipleProtocols = new ArrayList<>();
urlsMultipleProtocols.add("30.10.0.1:20880?revision=555"); // triple
urlsMultipleProtocols.addAll(urlsSameRevision); // dubbo
app1Instances = buildInstances(urlsSameRevision);
app2Instances = buildInstances(urlsDifferentRevision);
app1FailedInstances = buildInstances(urlsFailedRevision);
app1FailedInstances2 = buildInstances(urlsFailedRevision2);
app1InstancesWithNoRevision = buildInstances(urlsWithoutRevision);
app1InstancesMultipleProtocols = buildInstances(urlsMultipleProtocols);
metadataInfo_111 = JsonUtils.toJavaObject(metadata_111, MetadataInfo.class);
metadataInfo_222 = JsonUtils.toJavaObject(metadata_222, MetadataInfo.class);
metadataInfo_333 = JsonUtils.toJavaObject(metadata_333, MetadataInfo.class);
metadataInfo_444 = JsonUtils.toJavaObject(metadata_444, MetadataInfo.class);
metadataInfo_555_tri = JsonUtils.toJavaObject(metadata_555_triple, MetadataInfo.class);
serviceDiscovery = Mockito.mock(ServiceDiscovery.class);
when(serviceDiscovery.getUrl()).thenReturn(registryURL);
when(serviceDiscovery.getRemoteMetadata(eq("111"), anyList())).thenReturn(metadataInfo_111);
when(serviceDiscovery.getRemoteMetadata(eq("222"), anyList())).thenReturn(metadataInfo_222);
when(serviceDiscovery.getRemoteMetadata(eq("333"), anyList())).thenReturn(metadataInfo_333);
when(serviceDiscovery.getRemoteMetadata(eq("444"), anyList())).thenReturn(MetadataInfo.EMPTY);
when(serviceDiscovery.getRemoteMetadata(eq("555"), anyList())).thenReturn(metadataInfo_555_tri);
}
@BeforeEach
public void init() {
// Because all tests use the same ServiceDiscovery, the previous metadataCache should be cleared before next
// unit test
// to avoid contaminating next unit test.
clearMetadataCache();
}
@AfterEach
public void tearDown() throws Exception {
if (listener != null) {
listener.destroy();
listener = null;
}
}
@AfterAll
public static void destroy() throws Exception {
serviceDiscovery.destroy();
}
// 正常场景。单应用app1 通知地址基本流程,只做instance-metadata关联,没有metadata内容的解析
@Test
@Order(1)
public void testInstanceNotification() {
Set<String> serviceNames = new HashSet<>();
serviceNames.add("app1");
listener = new ServiceInstancesChangedListener(serviceNames, serviceDiscovery);
ServiceInstancesChangedEvent event = new ServiceInstancesChangedEvent("app1", app1Instances);
listener.onEvent(event);
Map<String, List<ServiceInstance>> allInstances = listener.getAllInstances();
Assertions.assertEquals(1, allInstances.size());
Assertions.assertEquals(3, allInstances.get("app1").size());
ProtocolServiceKey protocolServiceKey = new ProtocolServiceKey(service1, null, null, "dubbo");
List<URL> serviceUrls = listener.getAddresses(protocolServiceKey, consumerURL);
Assertions.assertEquals(3, serviceUrls.size());
assertTrue(serviceUrls.get(0) instanceof InstanceAddressURL);
}
// 正常场景。单应用app1,进一步检查 metadata service 是否正确映射
@Test
@Order(2)
public void testInstanceNotificationAndMetadataParse() {
Set<String> serviceNames = new HashSet<>();
serviceNames.add("app1");
listener = new ServiceInstancesChangedListener(serviceNames, serviceDiscovery);
// notify instance change
ServiceInstancesChangedEvent event = new ServiceInstancesChangedEvent("app1", app1Instances);
listener.onEvent(event);
Map<String, List<ServiceInstance>> allInstances = listener.getAllInstances();
Assertions.assertEquals(1, allInstances.size());
Assertions.assertEquals(3, allInstances.get("app1").size());
ProtocolServiceKey protocolServiceKey = new ProtocolServiceKey(service1, null, null, "dubbo");
List<URL> serviceUrls = listener.getAddresses(protocolServiceKey, consumerURL);
Assertions.assertEquals(3, serviceUrls.size());
assertTrue(serviceUrls.get(0) instanceof InstanceAddressURL);
assertThat(serviceUrls, Matchers.hasItem(Matchers.hasProperty("instance", Matchers.notNullValue())));
assertThat(serviceUrls, Matchers.hasItem(Matchers.hasProperty("metadataInfo", Matchers.notNullValue())));
}
// 正常场景。多应用,app1 app2 分别通知地址
@Test
@Order(3)
public void testMultipleAppNotification() {
Set<String> serviceNames = new HashSet<>();
serviceNames.add("app1");
serviceNames.add("app2");
listener = new ServiceInstancesChangedListener(serviceNames, serviceDiscovery);
// notify app1 instance change
ServiceInstancesChangedEvent app1_event = new ServiceInstancesChangedEvent("app1", app1Instances);
listener.onEvent(app1_event);
// notify app2 instance change
ServiceInstancesChangedEvent app2_event = new ServiceInstancesChangedEvent("app2", app2Instances);
listener.onEvent(app2_event);
// check
Map<String, List<ServiceInstance>> allInstances = listener.getAllInstances();
Assertions.assertEquals(2, allInstances.size());
Assertions.assertEquals(3, allInstances.get("app1").size());
Assertions.assertEquals(4, allInstances.get("app2").size());
ProtocolServiceKey protocolServiceKey1 = new ProtocolServiceKey(service1, null, null, "dubbo");
ProtocolServiceKey protocolServiceKey2 = new ProtocolServiceKey(service2, null, null, "dubbo");
ProtocolServiceKey protocolServiceKey3 = new ProtocolServiceKey(service3, null, null, "dubbo");
List<URL> serviceUrls = listener.getAddresses(protocolServiceKey1, consumerURL);
Assertions.assertEquals(7, serviceUrls.size());
List<URL> serviceUrls2 = listener.getAddresses(protocolServiceKey2, consumerURL);
Assertions.assertEquals(4, serviceUrls2.size());
assertTrue(serviceUrls2.get(0).getIp().contains("30.10."));
List<URL> serviceUrls3 = listener.getAddresses(protocolServiceKey3, consumerURL);
Assertions.assertEquals(2, serviceUrls3.size());
assertTrue(serviceUrls3.get(0).getIp().contains("30.10."));
}
// 正常场景。多应用,app1 app2,空地址通知(边界条件)能否解析出正确的空地址列表
@Test
@Order(4)
public void testMultipleAppEmptyNotification() {
Set<String> serviceNames = new HashSet<>();
serviceNames.add("app1");
serviceNames.add("app2");
listener = new ServiceInstancesChangedListener(serviceNames, serviceDiscovery);
// notify app1 instance change
ServiceInstancesChangedEvent app1_event = new ServiceInstancesChangedEvent("app1", app1Instances);
listener.onEvent(app1_event);
// notify app2 instance change
ServiceInstancesChangedEvent app2_event = new ServiceInstancesChangedEvent("app2", app2Instances);
listener.onEvent(app2_event);
// empty notification
ServiceInstancesChangedEvent app1_event_again =
new ServiceInstancesChangedEvent("app1", Collections.EMPTY_LIST);
listener.onEvent(app1_event_again);
// check app1 cleared
Map<String, List<ServiceInstance>> allInstances = listener.getAllInstances();
Assertions.assertEquals(2, allInstances.size());
Assertions.assertEquals(0, allInstances.get("app1").size());
Assertions.assertEquals(4, allInstances.get("app2").size());
ProtocolServiceKey protocolServiceKey1 = new ProtocolServiceKey(service1, null, null, "dubbo");
ProtocolServiceKey protocolServiceKey2 = new ProtocolServiceKey(service2, null, null, "dubbo");
ProtocolServiceKey protocolServiceKey3 = new ProtocolServiceKey(service3, null, null, "dubbo");
List<URL> serviceUrls = listener.getAddresses(protocolServiceKey1, consumerURL);
Assertions.assertEquals(4, serviceUrls.size());
assertTrue(serviceUrls.get(0).getIp().contains("30.10."));
List<URL> serviceUrls2 = listener.getAddresses(protocolServiceKey2, consumerURL);
Assertions.assertEquals(4, serviceUrls2.size());
assertTrue(serviceUrls2.get(0).getIp().contains("30.10."));
List<URL> serviceUrls3 = listener.getAddresses(protocolServiceKey3, consumerURL);
Assertions.assertEquals(2, serviceUrls3.size());
assertTrue(serviceUrls3.get(0).getIp().contains("30.10."));
// app2 empty notification
ServiceInstancesChangedEvent app2_event_again =
new ServiceInstancesChangedEvent("app2", Collections.EMPTY_LIST);
listener.onEvent(app2_event_again);
// check app2 cleared
Map<String, List<ServiceInstance>> allInstances_app2 = listener.getAllInstances();
Assertions.assertEquals(2, allInstances_app2.size());
Assertions.assertEquals(0, allInstances_app2.get("app1").size());
Assertions.assertEquals(0, allInstances_app2.get("app2").size());
assertTrue(isEmpty(listener.getAddresses(protocolServiceKey1, consumerURL)));
assertTrue(isEmpty(listener.getAddresses(protocolServiceKey2, consumerURL)));
assertTrue(isEmpty(listener.getAddresses(protocolServiceKey3, consumerURL)));
}
// 正常场景。检查instance listener -> service listener(Directory)地址推送流程
@Test
@Order(5)
public void testServiceListenerNotification() {
Set<String> serviceNames = new HashSet<>();
serviceNames.add("app1");
serviceNames.add("app2");
listener = new ServiceInstancesChangedListener(serviceNames, serviceDiscovery);
NotifyListener demoServiceListener = Mockito.mock(NotifyListener.class);
when(demoServiceListener.getConsumerUrl()).thenReturn(consumerURL);
NotifyListener demoService2Listener = Mockito.mock(NotifyListener.class);
when(demoService2Listener.getConsumerUrl()).thenReturn(consumerURL2);
listener.addListenerAndNotify(consumerURL, demoServiceListener);
listener.addListenerAndNotify(consumerURL2, demoService2Listener);
// notify app1 instance change
ServiceInstancesChangedEvent app1_event = new ServiceInstancesChangedEvent("app1", app1Instances);
listener.onEvent(app1_event);
// check
ArgumentCaptor<List<URL>> captor = ArgumentCaptor.forClass(List.class);
Mockito.verify(demoServiceListener, Mockito.times(1)).notify(captor.capture());
List<URL> notifiedUrls = captor.getValue();
Assertions.assertEquals(3, notifiedUrls.size());
ArgumentCaptor<List<URL>> captor2 = ArgumentCaptor.forClass(List.class);
Mockito.verify(demoService2Listener, Mockito.times(1)).notify(captor2.capture());
List<URL> notifiedUrls2 = captor2.getValue();
Assertions.assertEquals(1, notifiedUrls2.size());
// notify app2 instance change
ServiceInstancesChangedEvent app2_event = new ServiceInstancesChangedEvent("app2", app2Instances);
listener.onEvent(app2_event);
// check
ArgumentCaptor<List<URL>> app2_captor = ArgumentCaptor.forClass(List.class);
Mockito.verify(demoServiceListener, Mockito.times(2)).notify(app2_captor.capture());
List<URL> app2_notifiedUrls = app2_captor.getValue();
Assertions.assertEquals(7, app2_notifiedUrls.size());
ArgumentCaptor<List<URL>> app2_captor2 = ArgumentCaptor.forClass(List.class);
Mockito.verify(demoService2Listener, Mockito.times(2)).notify(app2_captor2.capture());
List<URL> app2_notifiedUrls2 = app2_captor2.getValue();
Assertions.assertEquals(4, app2_notifiedUrls2.size());
// test service listener still get notified when added after instance notification.
NotifyListener demoService3Listener = Mockito.mock(NotifyListener.class);
when(demoService3Listener.getConsumerUrl()).thenReturn(consumerURL3);
listener.addListenerAndNotify(consumerURL3, demoService3Listener);
Mockito.verify(demoService3Listener, Mockito.times(1)).notify(Mockito.anyList());
}
@Test
@Order(6)
public void testMultiServiceListenerNotification() {
Set<String> serviceNames = new HashSet<>();
serviceNames.add("app1");
serviceNames.add("app2");
listener = new ServiceInstancesChangedListener(serviceNames, serviceDiscovery);
NotifyListener demoServiceListener1 = Mockito.mock(NotifyListener.class);
when(demoServiceListener1.getConsumerUrl()).thenReturn(consumerURL);
NotifyListener demoServiceListener2 = Mockito.mock(NotifyListener.class);
when(demoServiceListener2.getConsumerUrl()).thenReturn(consumerURL);
NotifyListener demoService2Listener1 = Mockito.mock(NotifyListener.class);
when(demoService2Listener1.getConsumerUrl()).thenReturn(consumerURL2);
NotifyListener demoService2Listener2 = Mockito.mock(NotifyListener.class);
when(demoService2Listener2.getConsumerUrl()).thenReturn(consumerURL2);
listener.addListenerAndNotify(consumerURL, demoServiceListener1);
listener.addListenerAndNotify(consumerURL, demoServiceListener2);
listener.addListenerAndNotify(consumerURL2, demoService2Listener1);
listener.addListenerAndNotify(consumerURL2, demoService2Listener2);
// notify app1 instance change
ServiceInstancesChangedEvent app1_event = new ServiceInstancesChangedEvent("app1", app1Instances);
listener.onEvent(app1_event);
// check
ArgumentCaptor<List<URL>> captor = ArgumentCaptor.forClass(List.class);
Mockito.verify(demoServiceListener1, Mockito.times(1)).notify(captor.capture());
List<URL> notifiedUrls = captor.getValue();
Assertions.assertEquals(3, notifiedUrls.size());
ArgumentCaptor<List<URL>> captor2 = ArgumentCaptor.forClass(List.class);
Mockito.verify(demoService2Listener1, Mockito.times(1)).notify(captor2.capture());
List<URL> notifiedUrls2 = captor2.getValue();
Assertions.assertEquals(1, notifiedUrls2.size());
// notify app2 instance change
ServiceInstancesChangedEvent app2_event = new ServiceInstancesChangedEvent("app2", app2Instances);
listener.onEvent(app2_event);
// check
ArgumentCaptor<List<URL>> app2_captor = ArgumentCaptor.forClass(List.class);
Mockito.verify(demoServiceListener1, Mockito.times(2)).notify(app2_captor.capture());
List<URL> app2_notifiedUrls = app2_captor.getValue();
Assertions.assertEquals(7, app2_notifiedUrls.size());
ArgumentCaptor<List<URL>> app2_captor2 = ArgumentCaptor.forClass(List.class);
Mockito.verify(demoService2Listener1, Mockito.times(2)).notify(app2_captor2.capture());
List<URL> app2_notifiedUrls2 = app2_captor2.getValue();
Assertions.assertEquals(4, app2_notifiedUrls2.size());
// test service listener still get notified when added after instance notification.
NotifyListener demoService3Listener = Mockito.mock(NotifyListener.class);
when(demoService3Listener.getConsumerUrl()).thenReturn(consumerURL3);
listener.addListenerAndNotify(consumerURL3, demoService3Listener);
Mockito.verify(demoService3Listener, Mockito.times(1)).notify(Mockito.anyList());
}
/**
* Test subscribe multiple protocols
*/
@Test
@Order(7)
public void testSubscribeMultipleProtocols() {
Set<String> serviceNames = new HashSet<>();
serviceNames.add("app1");
listener = new ServiceInstancesChangedListener(serviceNames, serviceDiscovery);
// no protocol specified, consume all instances
NotifyListener demoServiceListener1 = Mockito.mock(NotifyListener.class);
when(demoServiceListener1.getConsumerUrl()).thenReturn(noProtocolConsumerURL);
listener.addListenerAndNotify(noProtocolConsumerURL, demoServiceListener1);
// multiple protocols specified
NotifyListener demoServiceListener2 = Mockito.mock(NotifyListener.class);
when(demoServiceListener2.getConsumerUrl()).thenReturn(multipleProtocolsConsumerURL);
listener.addListenerAndNotify(multipleProtocolsConsumerURL, demoServiceListener2);
// one protocol specified
NotifyListener demoServiceListener3 = Mockito.mock(NotifyListener.class);
when(demoServiceListener3.getConsumerUrl()).thenReturn(singleProtocolsConsumerURL);
listener.addListenerAndNotify(singleProtocolsConsumerURL, demoServiceListener3);
// notify app1 instance change
ServiceInstancesChangedEvent app1_event =
new ServiceInstancesChangedEvent("app1", app1InstancesMultipleProtocols);
listener.onEvent(app1_event);
// check instances expose framework supported default protocols(currently dubbo, triple and rest) are notified
ArgumentCaptor<List<URL>> default_protocol_captor = ArgumentCaptor.forClass(List.class);
Mockito.verify(demoServiceListener1, Mockito.times(1)).notify(default_protocol_captor.capture());
List<URL> default_protocol_notifiedUrls = default_protocol_captor.getValue();
Assertions.assertEquals(4, default_protocol_notifiedUrls.size());
// check instances expose protocols in consuming list(dubbo and triple) are notified
ArgumentCaptor<List<URL>> multi_protocols_captor = ArgumentCaptor.forClass(List.class);
Mockito.verify(demoServiceListener2, Mockito.times(1)).notify(multi_protocols_captor.capture());
List<URL> multi_protocol_notifiedUrls = multi_protocols_captor.getValue();
Assertions.assertEquals(4, multi_protocol_notifiedUrls.size());
// check instances expose protocols in consuming list(only triple) are notified
ArgumentCaptor<List<URL>> single_protocols_captor = ArgumentCaptor.forClass(List.class);
Mockito.verify(demoServiceListener3, Mockito.times(1)).notify(single_protocols_captor.capture());
List<URL> single_protocol_notifiedUrls = single_protocols_captor.getValue();
Assertions.assertEquals(1, single_protocol_notifiedUrls.size());
}
/**
* Test subscribe multiple groups
*/
@Test
@Order(8)
public void testSubscribeMultipleGroups() {
Set<String> serviceNames = new HashSet<>();
serviceNames.add("app1");
listener = new ServiceInstancesChangedListener(serviceNames, serviceDiscovery);
// notify instance change
ServiceInstancesChangedEvent event = new ServiceInstancesChangedEvent("app1", app1Instances);
listener.onEvent(event);
Map<String, List<ServiceInstance>> allInstances = listener.getAllInstances();
Assertions.assertEquals(1, allInstances.size());
Assertions.assertEquals(3, allInstances.get("app1").size());
ProtocolServiceKey protocolServiceKey = new ProtocolServiceKey(service1, null, null, "dubbo");
List<URL> serviceUrls = listener.getAddresses(protocolServiceKey, consumerURL);
Assertions.assertEquals(3, serviceUrls.size());
assertTrue(serviceUrls.get(0) instanceof InstanceAddressURL);
protocolServiceKey = new ProtocolServiceKey(service1, null, "", "dubbo");
serviceUrls = listener.getAddresses(protocolServiceKey, consumerURL);
Assertions.assertEquals(3, serviceUrls.size());
assertTrue(serviceUrls.get(0) instanceof InstanceAddressURL);
protocolServiceKey = new ProtocolServiceKey(service1, null, ",group1", "dubbo");
serviceUrls = listener.getAddresses(protocolServiceKey, consumerURL);
Assertions.assertEquals(3, serviceUrls.size());
assertTrue(serviceUrls.get(0) instanceof InstanceAddressURL);
protocolServiceKey = new ProtocolServiceKey(service1, null, "group1,", "dubbo");
serviceUrls = listener.getAddresses(protocolServiceKey, consumerURL);
Assertions.assertEquals(3, serviceUrls.size());
assertTrue(serviceUrls.get(0) instanceof InstanceAddressURL);
protocolServiceKey = new ProtocolServiceKey(service1, null, "*", "dubbo");
serviceUrls = listener.getAddresses(protocolServiceKey, consumerURL);
Assertions.assertEquals(3, serviceUrls.size());
assertTrue(serviceUrls.get(0) instanceof InstanceAddressURL);
protocolServiceKey = new ProtocolServiceKey(service1, null, "group1", "dubbo");
serviceUrls = listener.getAddresses(protocolServiceKey, consumerURL);
Assertions.assertEquals(0, serviceUrls.size());
protocolServiceKey = new ProtocolServiceKey(service1, null, "group1,group2", "dubbo");
serviceUrls = listener.getAddresses(protocolServiceKey, consumerURL);
Assertions.assertEquals(0, serviceUrls.size());
protocolServiceKey = new ProtocolServiceKey(service1, null, "group1,,group2", "dubbo");
serviceUrls = listener.getAddresses(protocolServiceKey, consumerURL);
Assertions.assertEquals(3, serviceUrls.size());
assertTrue(serviceUrls.get(0) instanceof InstanceAddressURL);
}
/**
* Test subscribe multiple versions
*/
@Test
@Order(9)
public void testSubscribeMultipleVersions() {
Set<String> serviceNames = new HashSet<>();
serviceNames.add("app1");
listener = new ServiceInstancesChangedListener(serviceNames, serviceDiscovery);
// notify instance change
ServiceInstancesChangedEvent event = new ServiceInstancesChangedEvent("app1", app1Instances);
listener.onEvent(event);
Map<String, List<ServiceInstance>> allInstances = listener.getAllInstances();
Assertions.assertEquals(1, allInstances.size());
Assertions.assertEquals(3, allInstances.get("app1").size());
ProtocolServiceKey protocolServiceKey = new ProtocolServiceKey(service1, null, null, "dubbo");
List<URL> serviceUrls = listener.getAddresses(protocolServiceKey, consumerURL);
Assertions.assertEquals(3, serviceUrls.size());
assertTrue(serviceUrls.get(0) instanceof InstanceAddressURL);
protocolServiceKey = new ProtocolServiceKey(service1, "", null, "dubbo");
serviceUrls = listener.getAddresses(protocolServiceKey, consumerURL);
Assertions.assertEquals(3, serviceUrls.size());
assertTrue(serviceUrls.get(0) instanceof InstanceAddressURL);
protocolServiceKey = new ProtocolServiceKey(service1, "*", null, "dubbo");
serviceUrls = listener.getAddresses(protocolServiceKey, consumerURL);
Assertions.assertEquals(3, serviceUrls.size());
assertTrue(serviceUrls.get(0) instanceof InstanceAddressURL);
protocolServiceKey = new ProtocolServiceKey(service1, ",1.0.0", null, "dubbo");
serviceUrls = listener.getAddresses(protocolServiceKey, consumerURL);
Assertions.assertEquals(3, serviceUrls.size());
assertTrue(serviceUrls.get(0) instanceof InstanceAddressURL);
protocolServiceKey = new ProtocolServiceKey(service1, "1.0.0,", null, "dubbo");
serviceUrls = listener.getAddresses(protocolServiceKey, consumerURL);
Assertions.assertEquals(3, serviceUrls.size());
assertTrue(serviceUrls.get(0) instanceof InstanceAddressURL);
protocolServiceKey = new ProtocolServiceKey(service1, "1.0.0,,1.0.1", null, "dubbo");
serviceUrls = listener.getAddresses(protocolServiceKey, consumerURL);
Assertions.assertEquals(3, serviceUrls.size());
assertTrue(serviceUrls.get(0) instanceof InstanceAddressURL);
protocolServiceKey = new ProtocolServiceKey(service1, "1.0.1,1.0.0", null, "dubbo");
serviceUrls = listener.getAddresses(protocolServiceKey, consumerURL);
Assertions.assertEquals(0, serviceUrls.size());
}
// revision 异常场景。第一次启动,完全拿不到metadata,只能通知部分地址
@Test
@Order(10)
public void testRevisionFailureOnStartup() {
Set<String> serviceNames = new HashSet<>();
serviceNames.add("app1");
listener = new ServiceInstancesChangedListener(serviceNames, serviceDiscovery);
// notify app1 instance change
ServiceInstancesChangedEvent failed_revision_event =
new ServiceInstancesChangedEvent("app1", app1FailedInstances);
listener.onEvent(failed_revision_event);
ProtocolServiceKey protocolServiceKey1 = new ProtocolServiceKey(service1, null, null, "dubbo");
ProtocolServiceKey protocolServiceKey2 = new ProtocolServiceKey(service2, null, null, "dubbo");
List<URL> serviceUrls = listener.getAddresses(protocolServiceKey1, consumerURL);
List<URL> serviceUrls2 = listener.getAddresses(protocolServiceKey2, consumerURL);
assertTrue(isNotEmpty(serviceUrls));
assertTrue(isNotEmpty(serviceUrls2));
}
// revision 异常场景。运行中地址通知,拿不到revision就用老版本revision
@Test
@Order(11)
public void testRevisionFailureOnNotification() {
Set<String> serviceNames = new HashSet<>();
serviceNames.add("app1");
serviceNames.add("app2");
listener = new ServiceInstancesChangedListener(serviceNames, serviceDiscovery);
// notify app1 instance change
ServiceInstancesChangedEvent event = new ServiceInstancesChangedEvent("app1", app1Instances);
listener.onEvent(event);
when(serviceDiscovery.getRemoteMetadata(eq("222"), anyList())).thenAnswer(new Answer<MetadataInfo>() {
@Override
public MetadataInfo answer(InvocationOnMock invocationOnMock) throws Throwable {
if (Thread.currentThread().getName().contains("Dubbo-framework-metadata-retry")) {
return metadataInfo_222;
}
return MetadataInfo.EMPTY;
}
});
ServiceInstancesChangedEvent event2 = new ServiceInstancesChangedEvent("app2", app1FailedInstances2);
listener.onEvent(event2);
// event2 did not really take effect
ProtocolServiceKey protocolServiceKey1 = new ProtocolServiceKey(service1, null, null, "dubbo");
ProtocolServiceKey protocolServiceKey2 = new ProtocolServiceKey(service2, null, null, "dubbo");
Assertions.assertEquals(
3, listener.getAddresses(protocolServiceKey1, consumerURL).size());
assertTrue(isEmpty(listener.getAddresses(protocolServiceKey2, consumerURL)));
//
init();
try {
Thread.sleep(15000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// check recovered after retry.
List<URL> serviceUrls_after_retry = listener.getAddresses(protocolServiceKey1, consumerURL);
Assertions.assertEquals(5, serviceUrls_after_retry.size());
List<URL> serviceUrls2_after_retry = listener.getAddresses(protocolServiceKey2, consumerURL);
Assertions.assertEquals(2, serviceUrls2_after_retry.size());
}
// Abnormal case. Instance does not have revision
@Test
@Order(12)
public void testInstanceWithoutRevision() {
Set<String> serviceNames = new HashSet<>();
serviceNames.add("app1");
ServiceDiscovery serviceDiscovery = Mockito.mock(ServiceDiscovery.class);
listener = new ServiceInstancesChangedListener(serviceNames, serviceDiscovery);
ServiceInstancesChangedListener spyListener = Mockito.spy(listener);
Mockito.doReturn(null).when(metadataService).getMetadataInfo(eq(null));
ServiceInstancesChangedEvent event = new ServiceInstancesChangedEvent("app1", app1InstancesWithNoRevision);
spyListener.onEvent(event);
// notification succeeded
assertTrue(true);
}
Set<String> getExpectedSet(List<String> list) {
return new HashSet<>(list);
}
static List<ServiceInstance> buildInstances(List<Object> rawURls) {
List<ServiceInstance> instances = new ArrayList<>();
for (Object obj : rawURls) {
String rawURL = (String) obj;
DefaultServiceInstance instance = new DefaultServiceInstance();
final URL dubboUrl = URL.valueOf(rawURL);
instance.setRawAddress(rawURL);
instance.setHost(dubboUrl.getHost());
instance.setEnabled(true);
instance.setHealthy(true);
instance.setPort(dubboUrl.getPort());
instance.setRegistryCluster("default");
instance.setApplicationModel(ApplicationModel.defaultModel());
Map<String, String> metadata = new HashMap<>();
if (StringUtils.isNotEmpty(dubboUrl.getParameter(REVISION_KEY))) {
metadata.put(EXPORTED_SERVICES_REVISION_PROPERTY_NAME, dubboUrl.getParameter(REVISION_KEY));
}
instance.setMetadata(metadata);
instances.add(instance);
}
return instances;
}
private void clearMetadataCache() {
try {
MockServiceDiscovery mockServiceDiscovery =
(MockServiceDiscovery) ServiceInstancesChangedListenerWithoutEmptyProtectTest.serviceDiscovery;
MetaCacheManager metaCacheManager = mockServiceDiscovery.getMetaCacheManager();
Field cacheField = metaCacheManager.getClass().getDeclaredField("cache");
cacheField.setAccessible(true);
LRUCache<String, MetadataInfo> cache = (LRUCache<String, MetadataInfo>) cacheField.get(metaCacheManager);
cache.clear();
cacheField.setAccessible(false);
} catch (Exception e) {
// ignore
}
}
}
| 5,446 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/event | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/event/listener/MockServiceInstancesChangedListener.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.registry.client.event.listener;
import org.apache.dubbo.common.ProtocolServiceKey;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.registry.client.ServiceDiscovery;
import org.apache.dubbo.registry.client.event.ServiceInstancesChangedEvent;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class MockServiceInstancesChangedListener extends ServiceInstancesChangedListener {
public MockServiceInstancesChangedListener(Set<String> serviceNames, ServiceDiscovery serviceDiscovery) {
super(serviceNames, serviceDiscovery);
}
@Override
public synchronized void onEvent(ServiceInstancesChangedEvent event) {
// do nothing
}
@Override
public List<URL> getAddresses(ProtocolServiceKey protocolServiceKey, URL consumerURL) {
return super.getAddresses(protocolServiceKey, consumerURL);
}
public Map<String, Set<NotifyListenerWithKey>> getServiceListeners() {
return listeners;
}
}
| 5,447 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/event | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/event/listener/ServiceInstancesChangedListenerTest.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.registry.client.event.listener;
import org.apache.dubbo.common.ProtocolServiceKey;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.common.utils.LRUCache;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.metadata.MetadataService;
import org.apache.dubbo.registry.NotifyListener;
import org.apache.dubbo.registry.client.DefaultServiceInstance;
import org.apache.dubbo.registry.client.InstanceAddressURL;
import org.apache.dubbo.registry.client.ServiceDiscovery;
import org.apache.dubbo.registry.client.ServiceInstance;
import org.apache.dubbo.registry.client.event.ServiceInstancesChangedEvent;
import org.apache.dubbo.registry.client.metadata.store.MetaCacheManager;
import org.apache.dubbo.registry.client.support.MockServiceDiscovery;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.hamcrest.Matchers;
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.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import static org.apache.dubbo.common.constants.CommonConstants.REVISION_KEY;
import static org.apache.dubbo.common.utils.CollectionUtils.isEmpty;
import static org.apache.dubbo.common.utils.CollectionUtils.isNotEmpty;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.EXPORTED_SERVICES_REVISION_PROPERTY_NAME;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
/**
* {@link ServiceInstancesChangedListener} Test
*
* @since 2.7.5
*/
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class ServiceInstancesChangedListenerTest {
static List<ServiceInstance> app1Instances;
static List<ServiceInstance> app2Instances;
static List<ServiceInstance> app1FailedInstances;
static List<ServiceInstance> app1FailedInstances2;
static List<ServiceInstance> app1InstancesWithNoRevision;
static List<ServiceInstance> app1InstancesMultipleProtocols;
static String metadata_111 = "{\"app\":\"app1\",\"revision\":\"111\",\"services\":{"
+ "\"org.apache.dubbo.demo.DemoService:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app1\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}"
+ "}}";
static String metadata_222 = "{\"app\":\"app2\",\"revision\":\"222\",\"services\":{"
+ "\"org.apache.dubbo.demo.DemoService:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}},"
+ "\"org.apache.dubbo.demo.DemoService2:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService2\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService2\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService2\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}"
+ "}}";
static String metadata_333 = "{\"app\":\"app2\",\"revision\":\"333\",\"services\":{"
+ "\"org.apache.dubbo.demo.DemoService:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}},"
+ "\"org.apache.dubbo.demo.DemoService2:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService2\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService2\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService2\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}},"
+ "\"org.apache.dubbo.demo.DemoService3:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService3\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService3\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService3\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}"
+ "}}";
// failed
static String metadata_444 = "{\"app\":\"app1\",\"revision\":\"444\",\"services\":{"
+ "\"org.apache.dubbo.demo.DemoService:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}"
+ "}}";
// only triple protocol enabled
static String metadata_555_triple = "{\"app\":\"app1\",\"revision\":\"555\",\"services\":{"
+ "\"org.apache.dubbo.demo.DemoService:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService\",\"protocol\":\"tri\",\"path\":\"org.apache.dubbo.demo.DemoService\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}"
+ "}}";
static String service1 = "org.apache.dubbo.demo.DemoService";
static String service2 = "org.apache.dubbo.demo.DemoService2";
static String service3 = "org.apache.dubbo.demo.DemoService3";
static URL consumerURL = URL.valueOf(
"dubbo://127.0.0.1/org.apache.dubbo.demo.DemoService?interface=org.apache.dubbo.demo.DemoService&protocol=dubbo®istry_cluster=default");
static URL consumerURL2 = URL.valueOf(
"dubbo://127.0.0.1/org.apache.dubbo.demo.DemoService2?interface=org.apache.dubbo.demo.DemoService2&protocol=dubbo®istry_cluster=default");
static URL consumerURL3 = URL.valueOf(
"dubbo://127.0.0.1/org.apache.dubbo.demo.DemoService3?interface=org.apache.dubbo.demo.DemoService3&protocol=dubbo®istry_cluster=default");
static URL multipleProtocolsConsumerURL = URL.valueOf(
"dubbo,tri://127.0.0.1/org.apache.dubbo.demo.DemoService?interface=org.apache.dubbo.demo.DemoService&protocol=dubbo,tri®istry_cluster=default");
static URL noProtocolConsumerURL = URL.valueOf(
"consumer://127.0.0.1/org.apache.dubbo.demo.DemoService?interface=org.apache.dubbo.demo.DemoService®istry_cluster=default");
static URL singleProtocolsConsumerURL = URL.valueOf(
"tri://127.0.0.1/org.apache.dubbo.demo.DemoService?interface=org.apache.dubbo.demo.DemoService&protocol=tri®istry_cluster=default");
static URL registryURL =
URL.valueOf("dubbo://127.0.0.1:2181/org.apache.dubbo.demo.RegistryService?enable-empty-protection=true");
static MetadataInfo metadataInfo_111;
static MetadataInfo metadataInfo_222;
static MetadataInfo metadataInfo_333;
static MetadataInfo metadataInfo_444;
static MetadataInfo metadataInfo_555_tri;
static MetadataService metadataService;
static ServiceDiscovery serviceDiscovery;
static ServiceInstancesChangedListener listener = null;
@BeforeAll
public static void setUp() {
metadataService = Mockito.mock(MetadataService.class);
List<Object> urlsSameRevision = new ArrayList<>();
urlsSameRevision.add("127.0.0.1:20880?revision=111");
urlsSameRevision.add("127.0.0.2:20880?revision=111");
urlsSameRevision.add("127.0.0.3:20880?revision=111");
List<Object> urlsDifferentRevision = new ArrayList<>();
urlsDifferentRevision.add("30.10.0.1:20880?revision=222");
urlsDifferentRevision.add("30.10.0.2:20880?revision=222");
urlsDifferentRevision.add("30.10.0.3:20880?revision=333");
urlsDifferentRevision.add("30.10.0.4:20880?revision=333");
List<Object> urlsFailedRevision = new ArrayList<>();
urlsFailedRevision.add("30.10.0.5:20880?revision=222");
urlsFailedRevision.add("30.10.0.6:20880?revision=222");
urlsFailedRevision.add("30.10.0.7:20880?revision=444"); // revision will fail
urlsFailedRevision.add("30.10.0.8:20880?revision=444"); // revision will fail
List<Object> urlsFailedRevision2 = new ArrayList<>();
urlsFailedRevision2.add("30.10.0.1:20880?revision=222");
urlsFailedRevision2.add("30.10.0.2:20880?revision=222");
List<Object> urlsWithoutRevision = new ArrayList<>();
urlsWithoutRevision.add("30.10.0.1:20880");
List<Object> urlsMultipleProtocols = new ArrayList<>();
urlsMultipleProtocols.add("30.10.0.1:20880?revision=555"); // triple
urlsMultipleProtocols.addAll(urlsSameRevision); // dubbo
app1Instances = buildInstances(urlsSameRevision);
app2Instances = buildInstances(urlsDifferentRevision);
app1FailedInstances = buildInstances(urlsFailedRevision);
app1FailedInstances2 = buildInstances(urlsFailedRevision2);
app1InstancesWithNoRevision = buildInstances(urlsWithoutRevision);
app1InstancesMultipleProtocols = buildInstances(urlsMultipleProtocols);
metadataInfo_111 = JsonUtils.toJavaObject(metadata_111, MetadataInfo.class);
metadataInfo_222 = JsonUtils.toJavaObject(metadata_222, MetadataInfo.class);
metadataInfo_333 = JsonUtils.toJavaObject(metadata_333, MetadataInfo.class);
metadataInfo_444 = JsonUtils.toJavaObject(metadata_444, MetadataInfo.class);
metadataInfo_555_tri = JsonUtils.toJavaObject(metadata_555_triple, MetadataInfo.class);
serviceDiscovery = Mockito.mock(ServiceDiscovery.class);
when(serviceDiscovery.getUrl()).thenReturn(registryURL);
when(serviceDiscovery.getRemoteMetadata(eq("111"), anyList())).thenReturn(metadataInfo_111);
when(serviceDiscovery.getRemoteMetadata(eq("222"), anyList())).thenReturn(metadataInfo_222);
when(serviceDiscovery.getRemoteMetadata(eq("333"), anyList())).thenReturn(metadataInfo_333);
when(serviceDiscovery.getRemoteMetadata(eq("444"), anyList())).thenReturn(MetadataInfo.EMPTY);
when(serviceDiscovery.getRemoteMetadata(eq("555"), anyList())).thenReturn(metadataInfo_555_tri);
}
@BeforeEach
public void init() {
// Because all tests use the same ServiceDiscovery, the previous metadataCache should be cleared before next
// unit test
// to avoid contaminating next unit test.
clearMetadataCache();
}
@AfterEach
public void tearDown() throws Exception {
if (listener != null) {
listener.destroy();
listener = null;
}
}
@AfterAll
public static void destroy() throws Exception {
serviceDiscovery.destroy();
}
// 正常场景。单应用app1 通知地址基本流程,只做instance-metadata关联,没有metadata内容的解析
@Test
@Order(1)
public void testInstanceNotification() {
Set<String> serviceNames = new HashSet<>();
serviceNames.add("app1");
listener = new ServiceInstancesChangedListener(serviceNames, serviceDiscovery);
ServiceInstancesChangedEvent event = new ServiceInstancesChangedEvent("app1", app1Instances);
listener.onEvent(event);
Map<String, List<ServiceInstance>> allInstances = listener.getAllInstances();
Assertions.assertEquals(1, allInstances.size());
Assertions.assertEquals(3, allInstances.get("app1").size());
ProtocolServiceKey protocolServiceKey = new ProtocolServiceKey(service1, null, null, "dubbo");
List<URL> serviceUrls = listener.getAddresses(protocolServiceKey, consumerURL);
Assertions.assertEquals(3, serviceUrls.size());
assertTrue(serviceUrls.get(0) instanceof InstanceAddressURL);
}
// 正常场景。单应用app1,进一步检查 metadata service 是否正确映射
@Test
@Order(2)
public void testInstanceNotificationAndMetadataParse() {
Set<String> serviceNames = new HashSet<>();
serviceNames.add("app1");
listener = new ServiceInstancesChangedListener(serviceNames, serviceDiscovery);
// notify instance change
ServiceInstancesChangedEvent event = new ServiceInstancesChangedEvent("app1", app1Instances);
listener.onEvent(event);
Map<String, List<ServiceInstance>> allInstances = listener.getAllInstances();
Assertions.assertEquals(1, allInstances.size());
Assertions.assertEquals(3, allInstances.get("app1").size());
ProtocolServiceKey protocolServiceKey = new ProtocolServiceKey(service1, null, null, "dubbo");
List<URL> serviceUrls = listener.getAddresses(protocolServiceKey, consumerURL);
Assertions.assertEquals(3, serviceUrls.size());
assertTrue(serviceUrls.get(0) instanceof InstanceAddressURL);
assertThat(serviceUrls, Matchers.hasItem(Matchers.hasProperty("instance", Matchers.notNullValue())));
assertThat(serviceUrls, Matchers.hasItem(Matchers.hasProperty("metadataInfo", Matchers.notNullValue())));
}
// 正常场景。多应用,app1 app2 分别通知地址
@Test
@Order(3)
public void testMultipleAppNotification() {
Set<String> serviceNames = new HashSet<>();
serviceNames.add("app1");
serviceNames.add("app2");
listener = new ServiceInstancesChangedListener(serviceNames, serviceDiscovery);
// notify app1 instance change
ServiceInstancesChangedEvent app1_event = new ServiceInstancesChangedEvent("app1", app1Instances);
listener.onEvent(app1_event);
// notify app2 instance change
ServiceInstancesChangedEvent app2_event = new ServiceInstancesChangedEvent("app2", app2Instances);
listener.onEvent(app2_event);
// check
Map<String, List<ServiceInstance>> allInstances = listener.getAllInstances();
Assertions.assertEquals(2, allInstances.size());
Assertions.assertEquals(3, allInstances.get("app1").size());
Assertions.assertEquals(4, allInstances.get("app2").size());
ProtocolServiceKey protocolServiceKey1 = new ProtocolServiceKey(service1, null, null, "dubbo");
ProtocolServiceKey protocolServiceKey2 = new ProtocolServiceKey(service2, null, null, "dubbo");
ProtocolServiceKey protocolServiceKey3 = new ProtocolServiceKey(service3, null, null, "dubbo");
List<URL> serviceUrls = listener.getAddresses(protocolServiceKey1, consumerURL);
Assertions.assertEquals(7, serviceUrls.size());
List<URL> serviceUrls2 = listener.getAddresses(protocolServiceKey2, consumerURL);
Assertions.assertEquals(4, serviceUrls2.size());
assertTrue(serviceUrls2.get(0).getIp().contains("30.10."));
List<URL> serviceUrls3 = listener.getAddresses(protocolServiceKey3, consumerURL);
Assertions.assertEquals(2, serviceUrls3.size());
assertTrue(serviceUrls3.get(0).getIp().contains("30.10."));
}
// 正常场景。多应用,app1 app2,空地址通知(边界条件)能否解析出正确的空地址列表
@Test
@Order(4)
public void testMultipleAppEmptyNotification() {
Set<String> serviceNames = new HashSet<>();
serviceNames.add("app1");
serviceNames.add("app2");
listener = new ServiceInstancesChangedListener(serviceNames, serviceDiscovery);
// notify app1 instance change
ServiceInstancesChangedEvent app1_event = new ServiceInstancesChangedEvent("app1", app1Instances);
listener.onEvent(app1_event);
// notify app2 instance change
ServiceInstancesChangedEvent app2_event = new ServiceInstancesChangedEvent("app2", app2Instances);
listener.onEvent(app2_event);
// empty notification
ServiceInstancesChangedEvent app1_event_again =
new ServiceInstancesChangedEvent("app1", Collections.EMPTY_LIST);
listener.onEvent(app1_event_again);
// check app1 cleared
Map<String, List<ServiceInstance>> allInstances = listener.getAllInstances();
Assertions.assertEquals(2, allInstances.size());
Assertions.assertEquals(0, allInstances.get("app1").size());
Assertions.assertEquals(4, allInstances.get("app2").size());
ProtocolServiceKey protocolServiceKey1 = new ProtocolServiceKey(service1, null, null, "dubbo");
ProtocolServiceKey protocolServiceKey2 = new ProtocolServiceKey(service2, null, null, "dubbo");
ProtocolServiceKey protocolServiceKey3 = new ProtocolServiceKey(service3, null, null, "dubbo");
List<URL> serviceUrls = listener.getAddresses(protocolServiceKey1, consumerURL);
Assertions.assertEquals(4, serviceUrls.size());
assertTrue(serviceUrls.get(0).getIp().contains("30.10."));
List<URL> serviceUrls2 = listener.getAddresses(protocolServiceKey2, consumerURL);
Assertions.assertEquals(4, serviceUrls2.size());
assertTrue(serviceUrls2.get(0).getIp().contains("30.10."));
List<URL> serviceUrls3 = listener.getAddresses(protocolServiceKey3, consumerURL);
Assertions.assertEquals(2, serviceUrls3.size());
assertTrue(serviceUrls3.get(0).getIp().contains("30.10."));
// app2 empty notification
ServiceInstancesChangedEvent app2_event_again =
new ServiceInstancesChangedEvent("app2", Collections.EMPTY_LIST);
listener.onEvent(app2_event_again);
// check app2 cleared
Map<String, List<ServiceInstance>> allInstances_app2 = listener.getAllInstances();
Assertions.assertEquals(2, allInstances_app2.size());
Assertions.assertEquals(0, allInstances_app2.get("app1").size());
Assertions.assertEquals(0, allInstances_app2.get("app2").size());
assertTrue(isEmpty(listener.getAddresses(protocolServiceKey1, consumerURL)));
assertTrue(isEmpty(listener.getAddresses(protocolServiceKey2, consumerURL)));
assertTrue(isEmpty(listener.getAddresses(protocolServiceKey3, consumerURL)));
}
// 正常场景。检查instance listener -> service listener(Directory)地址推送流程
@Test
@Order(5)
public void testServiceListenerNotification() {
Set<String> serviceNames = new HashSet<>();
serviceNames.add("app1");
serviceNames.add("app2");
listener = new ServiceInstancesChangedListener(serviceNames, serviceDiscovery);
NotifyListener demoServiceListener = Mockito.mock(NotifyListener.class);
when(demoServiceListener.getConsumerUrl()).thenReturn(consumerURL);
NotifyListener demoService2Listener = Mockito.mock(NotifyListener.class);
when(demoService2Listener.getConsumerUrl()).thenReturn(consumerURL2);
listener.addListenerAndNotify(consumerURL, demoServiceListener);
listener.addListenerAndNotify(consumerURL2, demoService2Listener);
// notify app1 instance change
ServiceInstancesChangedEvent app1_event = new ServiceInstancesChangedEvent("app1", app1Instances);
listener.onEvent(app1_event);
// check
ArgumentCaptor<List<URL>> captor = ArgumentCaptor.forClass(List.class);
Mockito.verify(demoServiceListener, Mockito.times(1)).notify(captor.capture());
List<URL> notifiedUrls = captor.getValue();
Assertions.assertEquals(3, notifiedUrls.size());
ArgumentCaptor<List<URL>> captor2 = ArgumentCaptor.forClass(List.class);
Mockito.verify(demoService2Listener, Mockito.times(1)).notify(captor2.capture());
List<URL> notifiedUrls2 = captor2.getValue();
Assertions.assertEquals(0, notifiedUrls2.size());
// notify app2 instance change
ServiceInstancesChangedEvent app2_event = new ServiceInstancesChangedEvent("app2", app2Instances);
listener.onEvent(app2_event);
// check
ArgumentCaptor<List<URL>> app2_captor = ArgumentCaptor.forClass(List.class);
Mockito.verify(demoServiceListener, Mockito.times(2)).notify(app2_captor.capture());
List<URL> app2_notifiedUrls = app2_captor.getValue();
Assertions.assertEquals(7, app2_notifiedUrls.size());
ArgumentCaptor<List<URL>> app2_captor2 = ArgumentCaptor.forClass(List.class);
Mockito.verify(demoService2Listener, Mockito.times(2)).notify(app2_captor2.capture());
List<URL> app2_notifiedUrls2 = app2_captor2.getValue();
Assertions.assertEquals(4, app2_notifiedUrls2.size());
// test service listener still get notified when added after instance notification.
NotifyListener demoService3Listener = Mockito.mock(NotifyListener.class);
when(demoService3Listener.getConsumerUrl()).thenReturn(consumerURL3);
listener.addListenerAndNotify(consumerURL3, demoService3Listener);
Mockito.verify(demoService3Listener, Mockito.times(1)).notify(Mockito.anyList());
}
@Test
@Order(6)
public void testMultiServiceListenerNotification() {
Set<String> serviceNames = new HashSet<>();
serviceNames.add("app1");
serviceNames.add("app2");
listener = new ServiceInstancesChangedListener(serviceNames, serviceDiscovery);
NotifyListener demoServiceListener1 = Mockito.mock(NotifyListener.class);
when(demoServiceListener1.getConsumerUrl()).thenReturn(consumerURL);
NotifyListener demoServiceListener2 = Mockito.mock(NotifyListener.class);
when(demoServiceListener2.getConsumerUrl()).thenReturn(consumerURL);
NotifyListener demoService2Listener1 = Mockito.mock(NotifyListener.class);
when(demoService2Listener1.getConsumerUrl()).thenReturn(consumerURL2);
NotifyListener demoService2Listener2 = Mockito.mock(NotifyListener.class);
when(demoService2Listener2.getConsumerUrl()).thenReturn(consumerURL2);
listener.addListenerAndNotify(consumerURL, demoServiceListener1);
listener.addListenerAndNotify(consumerURL, demoServiceListener2);
listener.addListenerAndNotify(consumerURL2, demoService2Listener1);
listener.addListenerAndNotify(consumerURL2, demoService2Listener2);
// notify app1 instance change
ServiceInstancesChangedEvent app1_event = new ServiceInstancesChangedEvent("app1", app1Instances);
listener.onEvent(app1_event);
// check
ArgumentCaptor<List<URL>> captor = ArgumentCaptor.forClass(List.class);
Mockito.verify(demoServiceListener1, Mockito.times(1)).notify(captor.capture());
List<URL> notifiedUrls = captor.getValue();
Assertions.assertEquals(3, notifiedUrls.size());
ArgumentCaptor<List<URL>> captor2 = ArgumentCaptor.forClass(List.class);
Mockito.verify(demoService2Listener1, Mockito.times(1)).notify(captor2.capture());
List<URL> notifiedUrls2 = captor2.getValue();
Assertions.assertEquals(0, notifiedUrls2.size());
// notify app2 instance change
ServiceInstancesChangedEvent app2_event = new ServiceInstancesChangedEvent("app2", app2Instances);
listener.onEvent(app2_event);
// check
ArgumentCaptor<List<URL>> app2_captor = ArgumentCaptor.forClass(List.class);
Mockito.verify(demoServiceListener1, Mockito.times(2)).notify(app2_captor.capture());
List<URL> app2_notifiedUrls = app2_captor.getValue();
Assertions.assertEquals(7, app2_notifiedUrls.size());
ArgumentCaptor<List<URL>> app2_captor2 = ArgumentCaptor.forClass(List.class);
Mockito.verify(demoService2Listener1, Mockito.times(2)).notify(app2_captor2.capture());
List<URL> app2_notifiedUrls2 = app2_captor2.getValue();
Assertions.assertEquals(4, app2_notifiedUrls2.size());
// test service listener still get notified when added after instance notification.
NotifyListener demoService3Listener = Mockito.mock(NotifyListener.class);
when(demoService3Listener.getConsumerUrl()).thenReturn(consumerURL3);
listener.addListenerAndNotify(consumerURL3, demoService3Listener);
Mockito.verify(demoService3Listener, Mockito.times(1)).notify(Mockito.anyList());
}
/**
* Test subscribe multiple protocols
*/
@Test
@Order(7)
public void testSubscribeMultipleProtocols() {
Set<String> serviceNames = new HashSet<>();
serviceNames.add("app1");
listener = new ServiceInstancesChangedListener(serviceNames, serviceDiscovery);
// no protocol specified, consume all instances
NotifyListener demoServiceListener1 = Mockito.mock(NotifyListener.class);
when(demoServiceListener1.getConsumerUrl()).thenReturn(noProtocolConsumerURL);
listener.addListenerAndNotify(noProtocolConsumerURL, demoServiceListener1);
// multiple protocols specified
NotifyListener demoServiceListener2 = Mockito.mock(NotifyListener.class);
when(demoServiceListener2.getConsumerUrl()).thenReturn(multipleProtocolsConsumerURL);
listener.addListenerAndNotify(multipleProtocolsConsumerURL, demoServiceListener2);
// one protocol specified
NotifyListener demoServiceListener3 = Mockito.mock(NotifyListener.class);
when(demoServiceListener3.getConsumerUrl()).thenReturn(singleProtocolsConsumerURL);
listener.addListenerAndNotify(singleProtocolsConsumerURL, demoServiceListener3);
// notify app1 instance change
ServiceInstancesChangedEvent app1_event =
new ServiceInstancesChangedEvent("app1", app1InstancesMultipleProtocols);
listener.onEvent(app1_event);
// check instances expose framework supported default protocols(currently dubbo, triple and rest) are notified
ArgumentCaptor<List<URL>> default_protocol_captor = ArgumentCaptor.forClass(List.class);
Mockito.verify(demoServiceListener1, Mockito.times(1)).notify(default_protocol_captor.capture());
List<URL> default_protocol_notifiedUrls = default_protocol_captor.getValue();
Assertions.assertEquals(4, default_protocol_notifiedUrls.size());
// check instances expose protocols in consuming list(dubbo and triple) are notified
ArgumentCaptor<List<URL>> multi_protocols_captor = ArgumentCaptor.forClass(List.class);
Mockito.verify(demoServiceListener2, Mockito.times(1)).notify(multi_protocols_captor.capture());
List<URL> multi_protocol_notifiedUrls = multi_protocols_captor.getValue();
Assertions.assertEquals(4, multi_protocol_notifiedUrls.size());
// check instances expose protocols in consuming list(only triple) are notified
ArgumentCaptor<List<URL>> single_protocols_captor = ArgumentCaptor.forClass(List.class);
Mockito.verify(demoServiceListener3, Mockito.times(1)).notify(single_protocols_captor.capture());
List<URL> single_protocol_notifiedUrls = single_protocols_captor.getValue();
Assertions.assertEquals(1, single_protocol_notifiedUrls.size());
}
/**
* Test subscribe multiple groups
*/
@Test
@Order(8)
public void testSubscribeMultipleGroups() {
Set<String> serviceNames = new HashSet<>();
serviceNames.add("app1");
listener = new ServiceInstancesChangedListener(serviceNames, serviceDiscovery);
// notify instance change
ServiceInstancesChangedEvent event = new ServiceInstancesChangedEvent("app1", app1Instances);
listener.onEvent(event);
Map<String, List<ServiceInstance>> allInstances = listener.getAllInstances();
Assertions.assertEquals(1, allInstances.size());
Assertions.assertEquals(3, allInstances.get("app1").size());
ProtocolServiceKey protocolServiceKey = new ProtocolServiceKey(service1, null, null, "dubbo");
List<URL> serviceUrls = listener.getAddresses(protocolServiceKey, consumerURL);
Assertions.assertEquals(3, serviceUrls.size());
assertTrue(serviceUrls.get(0) instanceof InstanceAddressURL);
protocolServiceKey = new ProtocolServiceKey(service1, null, "", "dubbo");
serviceUrls = listener.getAddresses(protocolServiceKey, consumerURL);
Assertions.assertEquals(3, serviceUrls.size());
assertTrue(serviceUrls.get(0) instanceof InstanceAddressURL);
protocolServiceKey = new ProtocolServiceKey(service1, null, ",group1", "dubbo");
serviceUrls = listener.getAddresses(protocolServiceKey, consumerURL);
Assertions.assertEquals(3, serviceUrls.size());
assertTrue(serviceUrls.get(0) instanceof InstanceAddressURL);
protocolServiceKey = new ProtocolServiceKey(service1, null, "group1,", "dubbo");
serviceUrls = listener.getAddresses(protocolServiceKey, consumerURL);
Assertions.assertEquals(3, serviceUrls.size());
assertTrue(serviceUrls.get(0) instanceof InstanceAddressURL);
protocolServiceKey = new ProtocolServiceKey(service1, null, "*", "dubbo");
serviceUrls = listener.getAddresses(protocolServiceKey, consumerURL);
Assertions.assertEquals(3, serviceUrls.size());
assertTrue(serviceUrls.get(0) instanceof InstanceAddressURL);
protocolServiceKey = new ProtocolServiceKey(service1, null, "group1", "dubbo");
serviceUrls = listener.getAddresses(protocolServiceKey, consumerURL);
Assertions.assertEquals(0, serviceUrls.size());
protocolServiceKey = new ProtocolServiceKey(service1, null, "group1,group2", "dubbo");
serviceUrls = listener.getAddresses(protocolServiceKey, consumerURL);
Assertions.assertEquals(0, serviceUrls.size());
protocolServiceKey = new ProtocolServiceKey(service1, null, "group1,,group2", "dubbo");
serviceUrls = listener.getAddresses(protocolServiceKey, consumerURL);
Assertions.assertEquals(3, serviceUrls.size());
assertTrue(serviceUrls.get(0) instanceof InstanceAddressURL);
}
/**
* Test subscribe multiple versions
*/
@Test
@Order(9)
public void testSubscribeMultipleVersions() {
Set<String> serviceNames = new HashSet<>();
serviceNames.add("app1");
listener = new ServiceInstancesChangedListener(serviceNames, serviceDiscovery);
// notify instance change
ServiceInstancesChangedEvent event = new ServiceInstancesChangedEvent("app1", app1Instances);
listener.onEvent(event);
Map<String, List<ServiceInstance>> allInstances = listener.getAllInstances();
Assertions.assertEquals(1, allInstances.size());
Assertions.assertEquals(3, allInstances.get("app1").size());
ProtocolServiceKey protocolServiceKey = new ProtocolServiceKey(service1, null, null, "dubbo");
List<URL> serviceUrls = listener.getAddresses(protocolServiceKey, consumerURL);
Assertions.assertEquals(3, serviceUrls.size());
assertTrue(serviceUrls.get(0) instanceof InstanceAddressURL);
protocolServiceKey = new ProtocolServiceKey(service1, "", null, "dubbo");
serviceUrls = listener.getAddresses(protocolServiceKey, consumerURL);
Assertions.assertEquals(3, serviceUrls.size());
assertTrue(serviceUrls.get(0) instanceof InstanceAddressURL);
protocolServiceKey = new ProtocolServiceKey(service1, "*", null, "dubbo");
serviceUrls = listener.getAddresses(protocolServiceKey, consumerURL);
Assertions.assertEquals(3, serviceUrls.size());
assertTrue(serviceUrls.get(0) instanceof InstanceAddressURL);
protocolServiceKey = new ProtocolServiceKey(service1, ",1.0.0", null, "dubbo");
serviceUrls = listener.getAddresses(protocolServiceKey, consumerURL);
Assertions.assertEquals(3, serviceUrls.size());
assertTrue(serviceUrls.get(0) instanceof InstanceAddressURL);
protocolServiceKey = new ProtocolServiceKey(service1, "1.0.0,", null, "dubbo");
serviceUrls = listener.getAddresses(protocolServiceKey, consumerURL);
Assertions.assertEquals(3, serviceUrls.size());
assertTrue(serviceUrls.get(0) instanceof InstanceAddressURL);
protocolServiceKey = new ProtocolServiceKey(service1, "1.0.0,,1.0.1", null, "dubbo");
serviceUrls = listener.getAddresses(protocolServiceKey, consumerURL);
Assertions.assertEquals(3, serviceUrls.size());
assertTrue(serviceUrls.get(0) instanceof InstanceAddressURL);
protocolServiceKey = new ProtocolServiceKey(service1, "1.0.1,1.0.0", null, "dubbo");
serviceUrls = listener.getAddresses(protocolServiceKey, consumerURL);
Assertions.assertEquals(0, serviceUrls.size());
}
// revision 异常场景。第一次启动,完全拿不到metadata,只能通知部分地址
@Test
@Order(10)
public void testRevisionFailureOnStartup() {
Set<String> serviceNames = new HashSet<>();
serviceNames.add("app1");
listener = new ServiceInstancesChangedListener(serviceNames, serviceDiscovery);
// notify app1 instance change
ServiceInstancesChangedEvent failed_revision_event =
new ServiceInstancesChangedEvent("app1", app1FailedInstances);
listener.onEvent(failed_revision_event);
ProtocolServiceKey protocolServiceKey1 = new ProtocolServiceKey(service1, null, null, "dubbo");
ProtocolServiceKey protocolServiceKey2 = new ProtocolServiceKey(service2, null, null, "dubbo");
List<URL> serviceUrls = listener.getAddresses(protocolServiceKey1, consumerURL);
List<URL> serviceUrls2 = listener.getAddresses(protocolServiceKey2, consumerURL);
assertTrue(isNotEmpty(serviceUrls));
assertTrue(isNotEmpty(serviceUrls2));
}
// revision 异常场景。运行中地址通知,拿不到revision就用老版本revision
@Test
@Order(11)
public void testRevisionFailureOnNotification() {
Set<String> serviceNames = new HashSet<>();
serviceNames.add("app1");
serviceNames.add("app2");
listener = new ServiceInstancesChangedListener(serviceNames, serviceDiscovery);
// notify app1 instance change
ServiceInstancesChangedEvent event = new ServiceInstancesChangedEvent("app1", app1Instances);
listener.onEvent(event);
when(serviceDiscovery.getRemoteMetadata(eq("222"), anyList())).thenAnswer(new Answer<MetadataInfo>() {
@Override
public MetadataInfo answer(InvocationOnMock invocationOnMock) throws Throwable {
if (Thread.currentThread().getName().contains("Dubbo-framework-metadata-retry")) {
return metadataInfo_222;
}
return MetadataInfo.EMPTY;
}
});
ServiceInstancesChangedEvent event2 = new ServiceInstancesChangedEvent("app2", app1FailedInstances2);
listener.onEvent(event2);
// event2 did not really take effect
ProtocolServiceKey protocolServiceKey1 = new ProtocolServiceKey(service1, null, null, "dubbo");
ProtocolServiceKey protocolServiceKey2 = new ProtocolServiceKey(service2, null, null, "dubbo");
Assertions.assertEquals(
3, listener.getAddresses(protocolServiceKey1, consumerURL).size());
assertTrue(isEmpty(listener.getAddresses(protocolServiceKey2, consumerURL)));
//
init();
try {
Thread.sleep(15000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// check recovered after retry.
List<URL> serviceUrls_after_retry = listener.getAddresses(protocolServiceKey1, consumerURL);
Assertions.assertEquals(5, serviceUrls_after_retry.size());
List<URL> serviceUrls2_after_retry = listener.getAddresses(protocolServiceKey2, consumerURL);
Assertions.assertEquals(2, serviceUrls2_after_retry.size());
}
// Abnormal case. Instance does not have revision
@Test
@Order(12)
public void testInstanceWithoutRevision() {
Set<String> serviceNames = new HashSet<>();
serviceNames.add("app1");
ServiceDiscovery serviceDiscovery = Mockito.mock(ServiceDiscovery.class);
listener = new ServiceInstancesChangedListener(serviceNames, serviceDiscovery);
ServiceInstancesChangedListener spyListener = Mockito.spy(listener);
Mockito.doReturn(null).when(metadataService).getMetadataInfo(eq(null));
ServiceInstancesChangedEvent event = new ServiceInstancesChangedEvent("app1", app1InstancesWithNoRevision);
spyListener.onEvent(event);
// notification succeeded
assertTrue(true);
}
Set<String> getExpectedSet(List<String> list) {
return new HashSet<>(list);
}
static List<ServiceInstance> buildInstances(List<Object> rawURls) {
List<ServiceInstance> instances = new ArrayList<>();
for (Object obj : rawURls) {
String rawURL = (String) obj;
DefaultServiceInstance instance = new DefaultServiceInstance();
final URL dubboUrl = URL.valueOf(rawURL);
instance.setRawAddress(rawURL);
instance.setHost(dubboUrl.getHost());
instance.setEnabled(true);
instance.setHealthy(true);
instance.setPort(dubboUrl.getPort());
instance.setRegistryCluster("default");
instance.setApplicationModel(ApplicationModel.defaultModel());
Map<String, String> metadata = new HashMap<>();
if (StringUtils.isNotEmpty(dubboUrl.getParameter(REVISION_KEY))) {
metadata.put(EXPORTED_SERVICES_REVISION_PROPERTY_NAME, dubboUrl.getParameter(REVISION_KEY));
}
instance.setMetadata(metadata);
instances.add(instance);
}
return instances;
}
private void clearMetadataCache() {
try {
MockServiceDiscovery mockServiceDiscovery =
(MockServiceDiscovery) ServiceInstancesChangedListenerTest.serviceDiscovery;
MetaCacheManager metaCacheManager = mockServiceDiscovery.getMetaCacheManager();
Field cacheField = metaCacheManager.getClass().getDeclaredField("cache");
cacheField.setAccessible(true);
LRUCache<String, MetadataInfo> cache = (LRUCache<String, MetadataInfo>) cacheField.get(metaCacheManager);
cache.clear();
cacheField.setAccessible(false);
} catch (Exception e) {
// ignore
}
}
}
| 5,448 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/ProtocolPortsMetadataCustomizerTest.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.registry.client.metadata;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.beans.factory.ScopeBeanFactory;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.metadata.MetadataService;
import org.apache.dubbo.registry.client.DefaultServiceInstance;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.io.IOException;
import java.util.List;
import org.hamcrest.MatcherAssert;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.ENDPOINTS;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasProperty;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
class ProtocolPortsMetadataCustomizerTest {
public DefaultServiceInstance instance;
private MetadataService mockedMetadataService;
private ApplicationModel mockedApplicationModel;
private ScopeBeanFactory mockedBeanFactory;
public static DefaultServiceInstance createInstance() {
return new DefaultServiceInstance("A", "127.0.0.1", 20880, ApplicationModel.defaultModel());
}
@AfterAll
public static void clearUp() {
ApplicationModel.reset();
}
@BeforeEach
public void init() {
instance = createInstance();
URL dubboUrl = URL.valueOf(
"dubbo://30.10.104.63:20880/org.apache.dubbo.demo.GreetingService?"
+ "REGISTRY_CLUSTER=registry1&anyhost=true&application=demo-provider2&delay=5000&deprecated=false&dubbo=2.0.2&dynamic=true&generic=false&group=greeting&interface=org.apache.dubbo.demo.GreetingService&metadata-type=remote&methods=hello&pid=55805&release=&revision=1.0.0&service-name-mapping=true&side=provider&timeout=5000×tamp=1630229110058&version=1.0.0");
URL triURL = URL.valueOf(
"tri://30.10.104.63:50332/org.apache.dubbo.demo.GreetingService?"
+ "REGISTRY_CLUSTER=registry1&anyhost=true&application=demo-provider2&delay=5000&deprecated=false&dubbo=2.0.2&dynamic=true&generic=false&group=greeting&interface=org.apache.dubbo.demo.GreetingService&metadata-type=remote&methods=hello&pid=55805&release=&revision=1.0.0&service-name-mapping=true&side=provider&timeout=5000×tamp=1630229110058&version=1.0.0");
MetadataInfo metadataInfo = new MetadataInfo();
metadataInfo.addService(dubboUrl);
metadataInfo.addService(triURL);
instance.setServiceMetadata(metadataInfo);
mockedMetadataService = Mockito.mock(MetadataService.class);
}
@AfterEach
public void tearDown() throws IOException {
Mockito.framework().clearInlineMocks();
}
@Test
void test() {
ProtocolPortsMetadataCustomizer customizer = new ProtocolPortsMetadataCustomizer();
customizer.customize(instance, ApplicationModel.defaultModel());
String endpoints = instance.getMetadata().get(ENDPOINTS);
assertNotNull(endpoints);
List<DefaultServiceInstance.Endpoint> endpointList =
JsonUtils.toJavaList(endpoints, DefaultServiceInstance.Endpoint.class);
assertEquals(2, endpointList.size());
MatcherAssert.assertThat(endpointList, hasItem(hasProperty("protocol", equalTo("dubbo"))));
MatcherAssert.assertThat(endpointList, hasItem(hasProperty("port", equalTo(20880))));
MatcherAssert.assertThat(endpointList, hasItem(hasProperty("protocol", equalTo("tri"))));
MatcherAssert.assertThat(endpointList, hasItem(hasProperty("port", equalTo(50332))));
}
}
| 5,449 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataCustomizerTest.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.registry.client.metadata;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.registry.client.DefaultServiceInstance;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
class ServiceInstanceMetadataCustomizerTest {
private static ServiceInstanceMetadataCustomizer serviceInstanceMetadataCustomizer;
@BeforeAll
public static void setUp() {
serviceInstanceMetadataCustomizer = new ServiceInstanceMetadataCustomizer();
}
@AfterAll
public static void clearUp() {
ApplicationModel.reset();
}
/**
* Only 'include' policy spicified in Customized Filter will take effect
*/
@Test
void testCustomizeWithIncludeFilters() {
ApplicationModel applicationModel = spy(ApplicationModel.defaultModel());
ApplicationConfig applicationConfig = new ApplicationConfig("aa");
doReturn(applicationConfig).when(applicationModel).getCurrentConfig();
DefaultServiceInstance serviceInstance1 =
new DefaultServiceInstance("ServiceInstanceMetadataCustomizerTest", applicationModel);
MetadataInfo metadataInfo = new MetadataInfo();
metadataInfo.addService(
URL.valueOf(
"tri://127.1.1.1:50052/org.apache.dubbo.demo.GreetingService?application=ServiceInstanceMetadataCustomizerTest&env=test&side=provider&group=test"));
serviceInstance1.setServiceMetadata(metadataInfo);
serviceInstanceMetadataCustomizer.customize(serviceInstance1, applicationModel);
Assertions.assertEquals(1, serviceInstance1.getMetadata().size());
Assertions.assertEquals("provider", serviceInstance1.getMetadata(SIDE_KEY));
Assertions.assertNull(serviceInstance1.getMetadata("env"));
Assertions.assertNull(serviceInstance1.getMetadata("application"));
}
/**
* Only 'exclude' policies specified in Exclude Filters will take effect
*/
@Test
void testCustomizeWithExcludeFilters() {
ApplicationModel applicationModel = spy(ApplicationModel.defaultModel());
ApplicationConfig applicationConfig = new ApplicationConfig("aa");
doReturn(applicationConfig).when(applicationModel).getCurrentConfig();
DefaultServiceInstance serviceInstance1 =
new DefaultServiceInstance("ServiceInstanceMetadataCustomizerTest", applicationModel);
MetadataInfo metadataInfo = new MetadataInfo();
metadataInfo.addService(
URL.valueOf(
"tri://127.1.1.1:50052/org.apache.dubbo.demo.GreetingService?application=ServiceInstanceMetadataCustomizerTest&env=test&side=provider&group=test¶ms-filter=-customized,-dubbo"));
serviceInstance1.setServiceMetadata(metadataInfo);
serviceInstanceMetadataCustomizer.customize(serviceInstance1, applicationModel);
Assertions.assertEquals(2, serviceInstance1.getMetadata().size());
Assertions.assertEquals("ServiceInstanceMetadataCustomizerTest", serviceInstance1.getMetadata("application"));
Assertions.assertEquals("test", serviceInstance1.getMetadata("env"));
Assertions.assertNull(serviceInstance1.getMetadata("side"));
Assertions.assertNull(serviceInstance1.getMetadata("group"));
}
}
| 5,450 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/StandardMetadataServiceURLBuilderTest.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.registry.client.metadata;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.metadata.MetadataService;
import org.apache.dubbo.registry.client.DefaultServiceInstance;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.List;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.registry.client.metadata.MetadataServiceURLBuilderTest.serviceInstance;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* {@link StandardMetadataServiceURLBuilder} Test
*/
class StandardMetadataServiceURLBuilderTest {
@BeforeAll
public static void setUp() {
ApplicationConfig applicationConfig = new ApplicationConfig("demo");
applicationConfig.setMetadataServicePort(7001);
ApplicationModel.defaultModel().getApplicationConfigManager().setApplication(applicationConfig);
}
@AfterAll
public static void clearUp() {
ApplicationModel.reset();
}
@Test
void testBuild() {
ExtensionLoader<MetadataServiceURLBuilder> loader =
ApplicationModel.defaultModel().getExtensionLoader(MetadataServiceURLBuilder.class);
MetadataServiceURLBuilder builder = loader.getExtension(StandardMetadataServiceURLBuilder.NAME);
// test generateUrlWithoutMetadata
List<URL> urls =
builder.build(new DefaultServiceInstance("test", "127.0.0.1", 8080, ApplicationModel.defaultModel()));
assertEquals(1, urls.size());
URL url = urls.get(0);
assertEquals("dubbo", url.getProtocol());
assertEquals("127.0.0.1", url.getHost());
assertEquals(7001, url.getPort());
assertEquals(MetadataService.class.getName(), url.getServiceInterface());
assertEquals("test", url.getGroup());
assertEquals("consumer", url.getSide());
assertEquals("1.0.0", url.getVersion());
// assertEquals(url.getParameters().get("getAndListenInstanceMetadata.1.callback"), "true");
assertEquals("false", url.getParameters().get("reconnect"));
assertEquals("5000", url.getParameters().get("timeout"));
assertEquals(ApplicationModel.defaultModel(), url.getApplicationModel());
// test generateWithMetadata
urls = builder.build(serviceInstance);
assertEquals(1, urls.size());
url = urls.get(0);
assertEquals("rest", url.getProtocol());
assertEquals("127.0.0.1", url.getHost());
assertEquals(20880, url.getPort());
assertEquals(MetadataService.class.getName(), url.getServiceInterface());
assertEquals("test", url.getGroup());
assertEquals("consumer", url.getSide());
assertEquals("1.0.0", url.getVersion());
assertEquals("dubbo-provider-demo", url.getApplication());
assertEquals("5000", url.getParameters().get("timeout"));
}
}
| 5,451 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/MetadataServiceURLBuilderTest.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.registry.client.metadata;
import org.apache.dubbo.registry.client.DefaultServiceInstance;
import org.apache.dubbo.registry.client.ServiceInstance;
import org.apache.dubbo.rpc.model.ApplicationModel;
/**
* {@link MetadataServiceURLBuilder} Test
*
* @since 2.7.5
*/
class MetadataServiceURLBuilderTest {
static ServiceInstance serviceInstance =
new DefaultServiceInstance("test", "127.0.0.1", 8080, ApplicationModel.defaultModel());
static {
serviceInstance
.getMetadata()
.put(
"dubbo.metadata-service.urls",
"[ \"dubbo://192.168.0.102:20881/com.alibaba.cloud.dubbo.service.DubboMetadataService?anyhost=true&application=spring-cloud-alibaba-dubbo-provider&bind.ip=192.168.0.102&bind.port=20881&deprecated=false&dubbo=2.0.2&dynamic=true&generic=false&group=spring-cloud-alibaba-dubbo-provider&interface=com.alibaba.cloud.dubbo.service.DubboMetadataService&methods=getAllServiceKeys,getServiceRestMetadata,getExportedURLs,getAllExportedURLs&pid=17134&qos.enable=false®ister=true&release=2.7.3&revision=1.0.0&side=provider×tamp=1564826098503&version=1.0.0\" ]");
serviceInstance
.getMetadata()
.put(
"dubbo.metadata-service.url-params",
"{\"application\":\"dubbo-provider-demo\",\"protocol\":\"rest\",\"group\":\"dubbo-provider-demo\",\"version\":\"1.0.0\",\"timestamp\":\"1564845042651\",\"dubbo\":\"2.0.2\",\"host\":\"192.168.0.102\",\"port\":\"20880\"}");
}
}
| 5,452 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/SpringCloudMetadataServiceURLBuilderTest.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.registry.client.metadata;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.registry.client.DefaultServiceInstance;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.List;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.registry.client.metadata.MetadataServiceURLBuilderTest.serviceInstance;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* {@link SpringCloudMetadataServiceURLBuilder} Test
*
* @since 2.7.5
*/
class SpringCloudMetadataServiceURLBuilderTest {
private SpringCloudMetadataServiceURLBuilder builder = new SpringCloudMetadataServiceURLBuilder();
@Test
void testBuild() {
List<URL> urls =
builder.build(new DefaultServiceInstance("127.0.0.1", "test", 8080, ApplicationModel.defaultModel()));
assertEquals(0, urls.size());
urls = builder.build(serviceInstance);
assertEquals(1, urls.size());
URL url = urls.get(0);
assertEquals("192.168.0.102", url.getHost());
assertEquals(20881, url.getPort());
assertEquals("com.alibaba.cloud.dubbo.service.DubboMetadataService", url.getServiceInterface());
}
}
| 5,453 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/MetadataServiceNameMappingTest.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.registry.client.metadata;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.ConfigItem;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.MetadataReportConfig;
import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.metadata.report.MetadataReport;
import org.apache.dubbo.metadata.report.MetadataReportInstance;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
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.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
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.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
class MetadataServiceNameMappingTest {
private MetadataServiceNameMapping mapping;
private URL url;
private ConfigManager configManager;
private MetadataReport metadataReport;
private ApplicationModel applicationModel;
private Map<String, MetadataReport> metadataReportList = new HashMap<>();
@BeforeEach
public void setUp() {
applicationModel = ApplicationModel.defaultModel();
configManager = mock(ConfigManager.class);
metadataReport = mock(MetadataReport.class);
metadataReportList.put("default", metadataReport);
mapping = new MetadataServiceNameMapping(applicationModel);
mapping.setApplicationModel(applicationModel);
url = URL.valueOf("dubbo://127.0.0.1:20880/TestService?version=1.0.0");
}
@AfterEach
public void teardown() {
applicationModel.destroy();
}
@Test
void testMap() {
ApplicationModel mockedApplicationModel = spy(applicationModel);
when(configManager.getMetadataConfigs()).thenReturn(Collections.emptyList());
Mockito.when(mockedApplicationModel.getApplicationConfigManager()).thenReturn(configManager);
Mockito.when(mockedApplicationModel.getCurrentConfig()).thenReturn(new ApplicationConfig("test"));
// metadata report config not found
mapping.setApplicationModel(mockedApplicationModel);
boolean result = mapping.map(url);
assertFalse(result);
when(configManager.getMetadataConfigs()).thenReturn(Arrays.asList(new MetadataReportConfig()));
MetadataReportInstance reportInstance = mock(MetadataReportInstance.class);
Mockito.when(reportInstance.getMetadataReports(true)).thenReturn(metadataReportList);
mapping.metadataReportInstance = reportInstance;
when(metadataReport.registerServiceAppMapping(any(), any(), any())).thenReturn(true);
// metadata report directly
result = mapping.map(url);
assertTrue(result);
// metadata report using cas and retry, succeeded after retried 10 times
when(metadataReport.registerServiceAppMapping(any(), any(), any())).thenReturn(false);
when(metadataReport.getConfigItem(any(), any())).thenReturn(new ConfigItem());
when(metadataReport.registerServiceAppMapping(any(), any(), any(), any()))
.thenAnswer(new Answer<Boolean>() {
private int counter = 0;
@Override
public Boolean answer(InvocationOnMock invocationOnMock) {
if (++counter == 10) {
return true;
}
return false;
}
});
assertTrue(mapping.map(url));
// metadata report using cas and retry, failed after 11 times retry
when(metadataReport.registerServiceAppMapping(any(), any(), any(), any()))
.thenReturn(false);
Exception exceptionExpected = null;
assertFalse(mapping.map(url));
}
/**
* This test currently doesn't make any sense
*/
@Test
void testGet() {
Set<String> set = new HashSet<>();
set.add("app1");
MetadataReportInstance reportInstance = mock(MetadataReportInstance.class);
Mockito.when(reportInstance.getMetadataReport(any())).thenReturn(metadataReport);
when(metadataReport.getServiceAppMapping(any(), any())).thenReturn(set);
mapping.metadataReportInstance = reportInstance;
Set<String> result = mapping.get(url);
assertEquals(set, result);
}
/**
* Same situation as testGet, so left empty.
*/
@Test
void testGetAndListen() {
// TODO
}
}
| 5,454 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceHostPortCustomizerTest.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.registry.client.metadata;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.beans.factory.ScopeBeanFactory;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.metadata.MetadataService;
import org.apache.dubbo.registry.client.DefaultServiceInstance;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.concurrent.ExecutionException;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
/**
* Test for https://github.com/apache/dubbo/issues/8698
*/
class ServiceInstanceHostPortCustomizerTest {
private static ServiceInstanceHostPortCustomizer serviceInstanceHostPortCustomizer;
@BeforeAll
public static void setUp() {
serviceInstanceHostPortCustomizer = new ServiceInstanceHostPortCustomizer();
}
@AfterAll
public static void clearUp() {
ApplicationModel.reset();
}
@Test
void customizePreferredProtocol() throws ExecutionException, InterruptedException {
ScopeBeanFactory beanFactory = mock(ScopeBeanFactory.class);
MetadataService metadataService = mock(MetadataService.class);
when(beanFactory.getBean(MetadataService.class)).thenReturn(metadataService);
ApplicationModel applicationModel = spy(ApplicationModel.defaultModel());
when(applicationModel.getBeanFactory()).thenReturn(beanFactory);
// test protocol set
ApplicationConfig applicationConfig = new ApplicationConfig("aa");
// when(applicationModel.getCurrentConfig()).thenReturn(applicationConfig);
doReturn(applicationConfig).when(applicationModel).getCurrentConfig();
DefaultServiceInstance serviceInstance1 =
new DefaultServiceInstance("without-preferredProtocol", applicationModel);
MetadataInfo metadataInfo = new MetadataInfo();
metadataInfo.addService(URL.valueOf("tri://127.1.1.1:50052/org.apache.dubbo.demo.GreetingService"));
serviceInstance1.setServiceMetadata(metadataInfo);
serviceInstanceHostPortCustomizer.customize(serviceInstance1, applicationModel);
Assertions.assertEquals("127.1.1.1", serviceInstance1.getHost());
Assertions.assertEquals(50052, serviceInstance1.getPort());
// pick the preferredProtocol
applicationConfig.setProtocol("tri");
metadataInfo.addService(URL.valueOf("dubbo://127.1.2.3:20889/org.apache.dubbo.demo.HelloService"));
serviceInstanceHostPortCustomizer.customize(serviceInstance1, applicationModel);
Assertions.assertEquals("127.1.1.1", serviceInstance1.getHost());
Assertions.assertEquals(50052, serviceInstance1.getPort());
}
}
| 5,455 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/store/ExcludedParamsFilter2.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.registry.client.metadata.store;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.metadata.MetadataParamsFilter;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
@Activate
public class ExcludedParamsFilter2 implements MetadataParamsFilter {
@Override
public String[] serviceParamsIncluded() {
return new String[0];
}
@Override
public String[] serviceParamsExcluded() {
return new String[0];
}
/**
* Not included in this test
*/
@Override
public String[] instanceParamsIncluded() {
return new String[0];
}
@Override
public String[] instanceParamsExcluded() {
return new String[] {GROUP_KEY, "params-filter"};
}
}
| 5,456 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/store/MetaCacheManagerTest.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.registry.client.metadata.store;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.metadata.MetadataInfo;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.AfterEach;
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.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.fail;
class MetaCacheManagerTest {
@BeforeEach
public void setup() throws URISyntaxException {
String directory = getDirectoryOfClassPath();
System.setProperty("dubbo.meta.cache.filePath", directory);
System.setProperty("dubbo.meta.cache.fileName", "test-metadata.dubbo.cache");
}
@AfterEach
public void clear() throws URISyntaxException {
System.clearProperty("dubbo.meta.cache.filePath");
System.clearProperty("dubbo.meta.cache.fileName");
}
@Test
void testCache() {
// ScheduledExecutorService cacheRefreshExecutor = Executors.newSingleThreadScheduledExecutor(new
// NamedThreadFactory("Dubbo-cache-refresh"));
// ExecutorRepository executorRepository = Mockito.mock(ExecutorRepository.class);
// when(executorRepository.getCacheRefreshExecutor()).thenReturn(cacheRefreshExecutor);
// ExtensionAccessor extensionAccessor = Mockito.mock(ExtensionAccessor.class);
// when(extensionAccessor.getDefaultExtension(ExecutorRepository.class)).thenReturn(executorRepository);
MetaCacheManager cacheManager = new MetaCacheManager();
try {
// cacheManager.setExtensionAccessor(extensionAccessor);
MetadataInfo metadataInfo = cacheManager.get("1");
assertNotNull(metadataInfo);
assertEquals("demo", metadataInfo.getApp());
metadataInfo = cacheManager.get("2");
assertNull(metadataInfo);
Map<String, MetadataInfo> newMetadatas = new HashMap<>();
MetadataInfo metadataInfo2 = JsonUtils.toJavaObject(
"{\"app\":\"demo2\",\"services\":{\"greeting/org.apache.dubbo.registry.service.DemoService2:1.0.0:dubbo\":{\"name\":\"org.apache.dubbo.registry.service.DemoService2\",\"group\":\"greeting\",\"version\":\"1.0.0\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.registry.service.DemoService2\",\"params\":{\"application\":\"demo-provider2\",\"sayHello.timeout\":\"7000\",\"version\":\"1.0.0\",\"timeout\":\"5000\",\"group\":\"greeting\"}},\"greeting/org.apache.dubbo.registry.service.DemoService:1.0.0:dubbo\":{\"name\":\"org.apache.dubbo.registry.service.DemoService\",\"group\":\"greeting\",\"version\":\"1.0.0\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.registry.service.DemoService\",\"params\":{\"application\":\"demo-provider2\",\"version\":\"1.0.0\",\"timeout\":\"5000\",\"group\":\"greeting\"}}}}\n",
MetadataInfo.class);
newMetadatas.put("2", metadataInfo2);
cacheManager.update(newMetadatas);
metadataInfo = cacheManager.get("1");
assertNotNull(metadataInfo);
assertEquals("demo", metadataInfo.getApp());
metadataInfo = cacheManager.get("2");
assertNotNull(metadataInfo);
assertEquals("demo2", metadataInfo.getApp());
} finally {
cacheManager.destroy();
}
}
@Test
void testCacheDump() {
System.setProperty("dubbo.meta.cache.fileName", "not-exist.dubbo.cache");
MetadataInfo metadataInfo3 = JsonUtils.toJavaObject(
"{\"app\":\"demo3\",\"services\":{\"greeting/org.apache.dubbo.registry.service.DemoService2:1.0.0:dubbo\":{\"name\":\"org.apache.dubbo.registry.service.DemoService2\",\"group\":\"greeting\",\"version\":\"1.0.0\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.registry.service.DemoService2\",\"params\":{\"application\":\"demo-provider2\",\"sayHello.timeout\":\"7000\",\"version\":\"1.0.0\",\"timeout\":\"5000\",\"group\":\"greeting\"}},\"greeting/org.apache.dubbo.registry.service.DemoService:1.0.0:dubbo\":{\"name\":\"org.apache.dubbo.registry.service.DemoService\",\"group\":\"greeting\",\"version\":\"1.0.0\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.registry.service.DemoService\",\"params\":{\"application\":\"demo-provider2\",\"version\":\"1.0.0\",\"timeout\":\"5000\",\"group\":\"greeting\"}}}}\n",
MetadataInfo.class);
MetaCacheManager cacheManager = new MetaCacheManager();
try {
cacheManager.put("3", metadataInfo3);
try {
MetaCacheManager.CacheRefreshTask<MetadataInfo> task = new MetaCacheManager.CacheRefreshTask<>(
cacheManager.getCacheStore(), cacheManager.getCache(), cacheManager, 0);
task.run();
} catch (Exception e) {
fail();
} finally {
cacheManager.destroy();
}
MetaCacheManager newCacheManager = null;
try {
newCacheManager = new MetaCacheManager();
MetadataInfo metadataInfo = newCacheManager.get("3");
assertNotNull(metadataInfo);
assertEquals("demo3", metadataInfo.getApp());
} finally {
newCacheManager.destroy();
}
} finally {
cacheManager.destroy();
}
}
private String getDirectoryOfClassPath() throws URISyntaxException {
URL resource = this.getClass().getResource("/log4j.xml");
String path = Paths.get(resource.toURI()).toFile().getAbsolutePath();
int index = path.indexOf("log4j.xml");
String directoryPath = path.substring(0, index);
return directoryPath;
}
}
| 5,457 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/store/CustomizedParamsFilter.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.registry.client.metadata.store;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.metadata.MetadataParamsFilter;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
@Activate
public class CustomizedParamsFilter implements MetadataParamsFilter {
@Override
public String[] serviceParamsIncluded() {
return new String[] {APPLICATION_KEY, TIMEOUT_KEY, GROUP_KEY, VERSION_KEY};
}
@Override
public String[] serviceParamsExcluded() {
return new String[0];
}
/**
* Not included in this test
*/
@Override
public String[] instanceParamsIncluded() {
return new String[] {SIDE_KEY};
}
@Override
public String[] instanceParamsExcluded() {
return new String[0];
}
}
| 5,458 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/store/ExcludedParamsFilter.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.registry.client.metadata.store;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.metadata.MetadataParamsFilter;
import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY;
@Activate
public class ExcludedParamsFilter implements MetadataParamsFilter {
@Override
public String[] serviceParamsIncluded() {
return new String[0];
}
@Override
public String[] serviceParamsExcluded() {
return new String[0];
}
/**
* Not included in this test
*/
@Override
public String[] instanceParamsIncluded() {
return new String[0];
}
@Override
public String[] instanceParamsExcluded() {
return new String[] {SIDE_KEY};
}
}
| 5,459 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryScopeModelInitializer.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.registry;
import org.apache.dubbo.common.beans.factory.ScopeBeanFactory;
import org.apache.dubbo.registry.integration.ExporterFactory;
import org.apache.dubbo.registry.support.RegistryManager;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.apache.dubbo.rpc.model.ScopeModelInitializer;
public class RegistryScopeModelInitializer implements ScopeModelInitializer {
@Override
public void initializeFrameworkModel(FrameworkModel frameworkModel) {
ScopeBeanFactory beanFactory = frameworkModel.getBeanFactory();
beanFactory.registerBean(ExporterFactory.class);
}
@Override
public void initializeApplicationModel(ApplicationModel applicationModel) {
ScopeBeanFactory beanFactory = applicationModel.getBeanFactory();
beanFactory.registerBean(RegistryManager.class);
}
@Override
public void initializeModuleModel(ModuleModel moduleModel) {}
}
| 5,460 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryServiceListener.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.registry;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.SPI;
@SPI
public interface RegistryServiceListener {
default void onRegister(URL url, Registry registry) {}
default void onUnregister(URL url, Registry registry) {}
default void onSubscribe(URL url, Registry registry) {}
default void onUnsubscribe(URL url, Registry registry) {}
}
| 5,461 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryService.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.registry;
import org.apache.dubbo.common.URL;
import java.util.List;
/**
* RegistryService. (SPI, Prototype, ThreadSafe)
*
* @see org.apache.dubbo.registry.Registry
* @see org.apache.dubbo.registry.RegistryFactory#getRegistry(URL)
*/
public interface RegistryService {
/**
* Register data, such as : provider service, consumer address, route rule, override rule and other data.
* <p>
* Registering is required to support the contract:<br>
* 1. When the URL sets the check=false parameter. When the registration fails, the exception is not thrown and retried in the background. Otherwise, the exception will be thrown.<br>
* 2. When URL sets the dynamic=false parameter, it needs to be stored persistently, otherwise, it should be deleted automatically when the registrant has an abnormal exit.<br>
* 3. When the URL sets category=routers, it means classified storage, the default category is providers, and the data can be notified by the classified section. <br>
* 4. When the registry is restarted, network jitter, data can not be lost, including automatically deleting data from the broken line.<br>
* 5. Allow URLs which have the same URL but different parameters to coexist,they can't cover each other.<br>
*
* @param url Registration information , is not allowed to be empty, e.g: dubbo://10.20.153.10/org.apache.dubbo.foo.BarService?version=1.0.0&application=kylin
*/
void register(URL url);
/**
* Unregister
* <p>
* Unregistering is required to support the contract:<br>
* 1. If it is the persistent stored data of dynamic=false, the registration data can not be found, then the IllegalStateException is thrown, otherwise it is ignored.<br>
* 2. Unregister according to the full url match.<br>
*
* @param url Registration information , is not allowed to be empty, e.g: dubbo://10.20.153.10/org.apache.dubbo.foo.BarService?version=1.0.0&application=kylin
*/
void unregister(URL url);
/**
* Subscribe to eligible registered data and automatically push when the registered data is changed.
* <p>
* Subscribing need to support contracts:<br>
* 1. When the URL sets the check=false parameter. When the registration fails, the exception is not thrown and retried in the background. <br>
* 2. When URL sets category=routers, it only notifies the specified classification data. Multiple classifications are separated by commas, and allows asterisk to match, which indicates that all categorical data are subscribed.<br>
* 3. Allow interface, group, version, and classifier as a conditional query, e.g.: interface=org.apache.dubbo.foo.BarService&version=1.0.0<br>
* 4. And the query conditions allow the asterisk to be matched, subscribe to all versions of all the packets of all interfaces, e.g. :interface=*&group=*&version=*&classifier=*<br>
* 5. When the registry is restarted and network jitter, it is necessary to automatically restore the subscription request.<br>
* 6. Allow URLs which have the same URL but different parameters to coexist,they can't cover each other.<br>
* 7. The subscription process must be blocked, when the first notice is finished and then returned.<br>
*
* @param url Subscription condition, not allowed to be empty, e.g. consumer://10.20.153.10/org.apache.dubbo.foo.BarService?version=1.0.0&application=kylin
* @param listener A listener of the change event, not allowed to be empty
*/
void subscribe(URL url, NotifyListener listener);
/**
* Unsubscribe
* <p>
* Unsubscribing is required to support the contract:<br>
* 1. If you don't subscribe, ignore it directly.<br>
* 2. Unsubscribe by full URL match.<br>
*
* @param url Subscription condition, not allowed to be empty, e.g. consumer://10.20.153.10/org.apache.dubbo.foo.BarService?version=1.0.0&application=kylin
* @param listener A listener of the change event, not allowed to be empty
*/
void unsubscribe(URL url, NotifyListener listener);
/**
* Query the registered data that matches the conditions. Corresponding to the push mode of the subscription, this is the pull mode and returns only one result.
*
* @param url Query condition, is not allowed to be empty, e.g. consumer://10.20.153.10/org.apache.dubbo.foo.BarService?version=1.0.0&application=kylin
* @return The registered information list, which may be empty, the meaning is the same as the parameters of {@link org.apache.dubbo.registry.NotifyListener#notify(List<URL>)}.
* @see org.apache.dubbo.registry.NotifyListener#notify(List)
*/
List<URL> lookup(URL url);
}
| 5,462 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/ListenerRegistryWrapper.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.registry;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.UrlUtils;
import java.util.List;
import java.util.function.Consumer;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR;
public class ListenerRegistryWrapper implements Registry {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(ListenerRegistryWrapper.class);
private final Registry registry;
private final List<RegistryServiceListener> listeners;
public ListenerRegistryWrapper(Registry registry, List<RegistryServiceListener> listeners) {
this.registry = registry;
this.listeners = listeners;
}
@Override
public URL getUrl() {
return registry.getUrl();
}
@Override
public boolean isAvailable() {
return registry.isAvailable();
}
@Override
public void destroy() {
registry.destroy();
}
@Override
public void register(URL url) {
try {
if (registry != null) {
registry.register(url);
}
} finally {
if (!UrlUtils.isConsumer(url)) {
listenerEvent(serviceListener -> serviceListener.onRegister(url, registry));
}
}
}
@Override
public void unregister(URL url) {
try {
if (registry != null) {
registry.unregister(url);
}
} finally {
if (!UrlUtils.isConsumer(url)) {
listenerEvent(serviceListener -> serviceListener.onUnregister(url, registry));
}
}
}
@Override
public void subscribe(URL url, NotifyListener listener) {
try {
if (registry != null) {
registry.subscribe(url, listener);
}
} finally {
listenerEvent(serviceListener -> serviceListener.onSubscribe(url, registry));
}
}
@Override
public void unsubscribe(URL url, NotifyListener listener) {
try {
registry.unsubscribe(url, listener);
} finally {
listenerEvent(serviceListener -> serviceListener.onUnsubscribe(url, registry));
}
}
@Override
public boolean isServiceDiscovery() {
return registry.isServiceDiscovery();
}
@Override
public List<URL> lookup(URL url) {
return registry.lookup(url);
}
public Registry getRegistry() {
return registry;
}
private void listenerEvent(Consumer<RegistryServiceListener> consumer) {
if (CollectionUtils.isNotEmpty(listeners)) {
RuntimeException exception = null;
for (RegistryServiceListener listener : listeners) {
if (listener != null) {
try {
consumer.accept(listener);
} catch (RuntimeException t) {
logger.error(INTERNAL_ERROR, "unknown error in registry module", "", t.getMessage(), t);
exception = t;
}
}
}
if (exception != null) {
throw exception;
}
}
}
}
| 5,463 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryFactory.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.registry;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Adaptive;
import org.apache.dubbo.common.extension.SPI;
import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY;
import static org.apache.dubbo.common.extension.ExtensionScope.APPLICATION;
/**
* RegistryFactory. (SPI, Singleton, ThreadSafe)
*
* @see org.apache.dubbo.registry.support.AbstractRegistryFactory
*/
@SPI(scope = APPLICATION)
public interface RegistryFactory {
/**
* Connect to the registry
* <p>
* Connecting the registry needs to support the contract: <br>
* 1. When the check=false is set, the connection is not checked, otherwise the exception is thrown when disconnection <br>
* 2. Support username:password authority authentication on URL.<br>
* 3. Support the backup=10.20.153.10 candidate registry cluster address.<br>
* 4. Support file=registry.cache local disk file cache.<br>
* 5. Support the timeout=1000 request timeout setting.<br>
* 6. Support session=60000 session timeout or expiration settings.<br>
*
* @param url Registry address, is not allowed to be empty
* @return Registry reference, never return empty value
*/
@Adaptive({PROTOCOL_KEY})
Registry getRegistry(URL url);
}
| 5,464 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryNotifier.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.registry;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_DELAY_EXECUTE_TIMES;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_FAILED_NOTIFY_EVENT;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_NOTIFY_EVENT;
public abstract class RegistryNotifier {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(RegistryNotifier.class);
private volatile long lastExecuteTime;
private volatile long lastEventTime;
private final URL url;
private Object rawAddresses;
private long delayTime;
// should delay notify or not
private final AtomicBoolean shouldDelay = new AtomicBoolean(false);
// for the first 10 notification will be notified immediately
private final AtomicInteger executeTime = new AtomicInteger(0);
private ScheduledExecutorService scheduler;
public RegistryNotifier(URL registryUrl, long delayTime) {
this(registryUrl, delayTime, null);
}
public RegistryNotifier(URL registryUrl, long delayTime, ScheduledExecutorService scheduler) {
this.url = registryUrl;
this.delayTime = delayTime;
if (scheduler == null) {
this.scheduler = registryUrl
.getOrDefaultFrameworkModel()
.getBeanFactory()
.getBean(FrameworkExecutorRepository.class)
.getRegistryNotificationExecutor();
} else {
this.scheduler = scheduler;
}
}
public synchronized void notify(Object rawAddresses) {
this.rawAddresses = rawAddresses;
long notifyTime = System.currentTimeMillis();
this.lastEventTime = notifyTime;
long delta = (System.currentTimeMillis() - lastExecuteTime) - delayTime;
// more than 10 calls && next execute time is in the future
boolean delay = shouldDelay.get() && delta < 0;
// when the scheduler is shutdown, no notification is sent
if (scheduler.isShutdown()) {
if (logger.isWarnEnabled()) {
logger.warn(
COMMON_FAILED_NOTIFY_EVENT,
"",
"",
"Notification scheduler is off, no notifications are sent. Registry URL: " + url);
}
return;
} else if (delay) {
scheduler.schedule(new NotificationTask(this, notifyTime), -delta, TimeUnit.MILLISECONDS);
} else {
// check if more than 10 calls
if (!shouldDelay.get() && executeTime.incrementAndGet() > DEFAULT_DELAY_EXECUTE_TIMES) {
shouldDelay.set(true);
}
scheduler.submit(new NotificationTask(this, notifyTime));
}
try {
while (this.lastEventTime == System.currentTimeMillis()) {
// wait to let event time refresh
Thread.sleep(1);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public long getDelayTime() {
return delayTime;
}
/**
* notification of instance addresses (aka providers).
*
* @param rawAddresses data.
*/
protected abstract void doNotify(Object rawAddresses);
public static class NotificationTask implements Runnable {
private final RegistryNotifier listener;
private final long time;
public NotificationTask(RegistryNotifier listener, long time) {
this.listener = listener;
this.time = time;
}
@Override
public void run() {
try {
if (this.time == listener.lastEventTime) {
listener.doNotify(listener.rawAddresses);
listener.lastExecuteTime = System.currentTimeMillis();
synchronized (listener) {
if (this.time == listener.lastEventTime) {
listener.rawAddresses = null;
}
}
}
} catch (Throwable t) {
logger.error(REGISTRY_FAILED_NOTIFY_EVENT, "", "", "Error occurred when notify directory. ", t);
}
}
}
}
| 5,465 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/NotifyListener.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.registry;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener;
import java.util.List;
/**
* NotifyListener. (API, Prototype, ThreadSafe)
*
* @see org.apache.dubbo.registry.RegistryService#subscribe(URL, NotifyListener)
*/
public interface NotifyListener {
/**
* Triggered when a service change notification is received.
* <p>
* Notify needs to support the contract: <br>
* 1. Always notifications on the service interface and the dimension of the data type. that is, won't notify part of the same type data belonging to one service. Users do not need to compare the results of the previous notification.<br>
* 2. The first notification at a subscription must be a full notification of all types of data of a service.<br>
* 3. At the time of change, different types of data are allowed to be notified separately, e.g.: providers, consumers, routers, overrides. It allows only one of these types to be notified, but the data of this type must be full, not incremental.<br>
* 4. If a data type is empty, need to notify a empty protocol with category parameter identification of url data.<br>
* 5. The order of notifications to be guaranteed by the notifications(That is, the implementation of the registry). Such as: single thread push, queue serialization, and version comparison.<br>
*
* @param urls The list of registered information , is always not empty. The meaning is the same as the return value of {@link org.apache.dubbo.registry.RegistryService#lookup(URL)}.
*/
void notify(List<URL> urls);
default void addServiceListener(ServiceInstancesChangedListener instanceListener) {}
default ServiceInstancesChangedListener getServiceListener() {
return null;
}
default URL getConsumerUrl() {
return null;
}
}
| 5,466 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryFactoryWrapper.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.registry;
import org.apache.dubbo.common.URL;
import java.util.Collections;
public class RegistryFactoryWrapper implements RegistryFactory {
private RegistryFactory registryFactory;
public RegistryFactoryWrapper(RegistryFactory registryFactory) {
this.registryFactory = registryFactory;
}
@Override
public Registry getRegistry(URL url) {
return new ListenerRegistryWrapper(
registryFactory.getRegistry(url),
Collections.unmodifiableList(url.getOrDefaultApplicationModel()
.getExtensionLoader(RegistryServiceListener.class)
.getActivateExtension(url, "registry.listeners")));
}
}
| 5,467 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/ProviderFirstParams.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.registry;
import org.apache.dubbo.common.extension.SPI;
import java.util.Set;
@SPI
public interface ProviderFirstParams {
Set<String> params();
}
| 5,468 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/Registry.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.registry;
import org.apache.dubbo.common.Node;
import org.apache.dubbo.common.URL;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_DELAY_NOTIFICATION_TIME;
import static org.apache.dubbo.common.constants.CommonConstants.REGISTRY_DELAY_NOTIFICATION_KEY;
/**
* Registry. (SPI, Prototype, ThreadSafe)
*
* @see org.apache.dubbo.registry.RegistryFactory#getRegistry(URL)
* @see org.apache.dubbo.registry.support.AbstractRegistry
*/
public interface Registry extends Node, RegistryService {
default int getDelay() {
return getUrl().getParameter(REGISTRY_DELAY_NOTIFICATION_KEY, DEFAULT_DELAY_NOTIFICATION_TIME);
}
default boolean isServiceDiscovery() {
return false;
}
default void reExportRegister(URL url) {
register(url);
}
default void reExportUnregister(URL url) {
unregister(url);
}
}
| 5,469 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/Constants.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.registry;
public interface Constants {
String REGISTER_IP_KEY = "register.ip";
String REGISTER_KEY = "register";
String SUBSCRIBE_KEY = "subscribe";
String DEFAULT_REGISTRY = "dubbo";
String REGISTER = "register";
String UNREGISTER = "unregister";
String SUBSCRIBE = "subscribe";
String UNSUBSCRIBE = "unsubscribe";
String CONFIGURATORS_SUFFIX = ".configurators";
String ADMIN_PROTOCOL = "admin";
String PROVIDER_PROTOCOL = "provider";
String CONSUMER_PROTOCOL = "consumer";
String SCRIPT_PROTOCOL = "script";
String CONDITION_PROTOCOL = "condition";
String TRACE_PROTOCOL = "trace";
/**
* simple the registry for provider.
*
* @since 2.7.0
*/
String SIMPLIFIED_KEY = "simplified";
/**
* To decide whether register center saves file synchronously, the default value is asynchronously
*/
String REGISTRY_FILESAVE_SYNC_KEY = "save.file";
/**
* Reconnection period in milliseconds for register center
*/
String REGISTRY_RECONNECT_PERIOD_KEY = "reconnect.period";
int DEFAULT_SESSION_TIMEOUT = 60 * 1000;
/**
* Default value for the times of retry: -1 (forever)
*/
int DEFAULT_REGISTRY_RETRY_TIMES = -1;
int DEFAULT_REGISTRY_RECONNECT_PERIOD = 3 * 1000;
/**
* Default value for the period of retry interval in milliseconds: 5000
*/
int DEFAULT_REGISTRY_RETRY_PERIOD = 5 * 1000;
/**
* Most retry times
*/
String REGISTRY_RETRY_TIMES_KEY = "retry.times";
/**
* Period of registry center's retry interval
*/
String REGISTRY_RETRY_PERIOD_KEY = "retry.period";
String SESSION_TIMEOUT_KEY = "session";
/**
* To decide the frequency of checking Distributed Service Discovery Registry callback hook (in ms)
*/
String ECHO_POLLING_CYCLE_KEY = "echoPollingCycle";
/**
* Default value for check frequency: 60000 (ms)
*/
int DEFAULT_ECHO_POLLING_CYCLE = 60000;
String MIGRATION_STEP_KEY = "migration.step";
String MIGRATION_DELAY_KEY = "migration.delay";
String MIGRATION_FORCE_KEY = "migration.force";
String MIGRATION_PROMOTION_KEY = "migration.promotion";
String MIGRATION_THRESHOLD_KEY = "migration.threshold";
String ENABLE_26X_CONFIGURATION_LISTEN = "enable-26x-configuration-listen";
String ENABLE_CONFIGURATION_LISTEN = "enable-configuration-listen";
/**
* MIGRATION_RULE_XXX from remote configuration
*/
String MIGRATION_RULE_KEY = "key";
String MIGRATION_RULE_STEP_KEY = "step";
String MIGRATION_RULE_THRESHOLD_KEY = "threshold";
String MIGRATION_RULE_PROPORTION_KEY = "proportion";
String MIGRATION_RULE_DELAY_KEY = "delay";
String MIGRATION_RULE_FORCE_KEY = "force";
String MIGRATION_RULE_INTERFACES_KEY = "interfaces";
String MIGRATION_RULE_APPLICATIONS_KEY = "applications";
String USER_HOME = "user.home";
String DUBBO_REGISTRY = "/.dubbo/dubbo-registry-";
String CACHE = ".cache";
int DEFAULT_CAS_RETRY_TIMES = 10;
String CAS_RETRY_TIMES_KEY = "dubbo.metadata-report.cas-retry-times";
int DEFAULT_CAS_RETRY_WAIT_TIME = 100;
String CAS_RETRY_WAIT_TIME_KEY = "dubbo.metadata-report.cas-retry-wait-time";
}
| 5,470 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/FailedSubscribedTask.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.registry.retry;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.timer.Timeout;
import org.apache.dubbo.registry.NotifyListener;
import org.apache.dubbo.registry.support.FailbackRegistry;
/**
* FailedSubscribedTask
*/
public final class FailedSubscribedTask extends AbstractRetryTask {
private static final String NAME = "retry subscribe";
private final NotifyListener listener;
public FailedSubscribedTask(URL url, FailbackRegistry registry, NotifyListener listener) {
super(url, registry, NAME);
if (listener == null) {
throw new IllegalArgumentException();
}
this.listener = listener;
}
@Override
protected void doRetry(URL url, FailbackRegistry registry, Timeout timeout) {
registry.doSubscribe(url, listener);
registry.removeFailedSubscribedTask(url, listener);
}
}
| 5,471 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/FailedRegisteredTask.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.registry.retry;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.timer.Timeout;
import org.apache.dubbo.registry.support.FailbackRegistry;
/**
* FailedRegisteredTask
*/
public final class FailedRegisteredTask extends AbstractRetryTask {
private static final String NAME = "retry register";
public FailedRegisteredTask(URL url, FailbackRegistry registry) {
super(url, registry, NAME);
}
@Override
protected void doRetry(URL url, FailbackRegistry registry, Timeout timeout) {
registry.doRegister(url);
registry.removeFailedRegisteredTask(url);
}
}
| 5,472 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/ReExportTask.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.registry.retry;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.timer.Timeout;
import org.apache.dubbo.registry.support.FailbackRegistry;
/**
* ReExportTask
*/
public class ReExportTask extends AbstractRetryTask {
private static final String NAME = "retry re-export";
private Runnable runnable;
public ReExportTask(Runnable runnable, URL oldUrl, FailbackRegistry registry) {
super(oldUrl, registry, NAME);
this.runnable = runnable;
}
@Override
protected void doRetry(URL oldUrl, FailbackRegistry registry, Timeout timeout) {
runnable.run();
}
}
| 5,473 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/FailedUnregisteredTask.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.registry.retry;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.timer.Timeout;
import org.apache.dubbo.registry.support.FailbackRegistry;
/**
* FailedUnregisteredTask
*/
public final class FailedUnregisteredTask extends AbstractRetryTask {
private static final String NAME = "retry unregister";
public FailedUnregisteredTask(URL url, FailbackRegistry registry) {
super(url, registry, NAME);
}
@Override
protected void doRetry(URL url, FailbackRegistry registry, Timeout timeout) {
registry.doUnregister(url);
registry.removeFailedUnregisteredTask(url);
}
}
| 5,474 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/AbstractRetryTask.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.registry.retry;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.timer.Timeout;
import org.apache.dubbo.common.timer.Timer;
import org.apache.dubbo.common.timer.TimerTask;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.registry.support.FailbackRegistry;
import java.util.concurrent.TimeUnit;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_EXECUTE_RETRYING_TASK;
import static org.apache.dubbo.registry.Constants.DEFAULT_REGISTRY_RETRY_PERIOD;
import static org.apache.dubbo.registry.Constants.DEFAULT_REGISTRY_RETRY_TIMES;
import static org.apache.dubbo.registry.Constants.REGISTRY_RETRY_PERIOD_KEY;
import static org.apache.dubbo.registry.Constants.REGISTRY_RETRY_TIMES_KEY;
/**
* AbstractRetryTask
*/
public abstract class AbstractRetryTask implements TimerTask {
protected final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
/**
* url for retry task
*/
protected final URL url;
/**
* registry for this task
*/
protected final FailbackRegistry registry;
/**
* retry period
*/
private final long retryPeriod;
/**
* define the most retry times
*/
private final int retryTimes;
/**
* task name for this task
*/
private final String taskName;
/**
* times of retry.
* retry task is execute in single thread so that the times is not need volatile.
*/
private int times = 1;
private volatile boolean cancel;
AbstractRetryTask(URL url, FailbackRegistry registry, String taskName) {
if (url == null || StringUtils.isBlank(taskName)) {
throw new IllegalArgumentException();
}
this.url = url;
this.registry = registry;
this.taskName = taskName;
this.cancel = false;
this.retryPeriod = url.getParameter(REGISTRY_RETRY_PERIOD_KEY, DEFAULT_REGISTRY_RETRY_PERIOD);
this.retryTimes = url.getParameter(REGISTRY_RETRY_TIMES_KEY, DEFAULT_REGISTRY_RETRY_TIMES);
}
public void cancel() {
cancel = true;
}
public boolean isCancel() {
return cancel;
}
protected void reput(Timeout timeout, long tick) {
if (timeout == null) {
throw new IllegalArgumentException();
}
Timer timer = timeout.timer();
if (timer.isStop() || timeout.isCancelled() || isCancel()) {
return;
}
times++;
timer.newTimeout(timeout.task(), tick, TimeUnit.MILLISECONDS);
}
@Override
public void run(Timeout timeout) throws Exception {
if (timeout.isCancelled() || timeout.timer().isStop() || isCancel()) {
// other thread cancel this timeout or stop the timer.
return;
}
if (retryTimes > 0 && times > retryTimes) {
// 1-13 - failed to execute the retrying task.
logger.warn(
REGISTRY_EXECUTE_RETRYING_TASK,
"registry center offline",
"Check the registry server.",
"Final failed to execute task " + taskName + ", url: " + url + ", retry " + retryTimes + " times.");
return;
}
if (logger.isInfoEnabled()) {
logger.info(taskName + " : " + url);
}
try {
doRetry(url, registry, timeout);
} catch (Throwable t) { // Ignore all the exceptions and wait for the next retry
// 1-13 - failed to execute the retrying task.
logger.warn(
REGISTRY_EXECUTE_RETRYING_TASK,
"registry center offline",
"Check the registry server.",
"Failed to execute task " + taskName + ", url: " + url + ", waiting for again, cause:"
+ t.getMessage(),
t);
// reput this task when catch exception.
reput(timeout, retryPeriod);
}
}
protected abstract void doRetry(URL url, FailbackRegistry registry, Timeout timeout);
}
| 5,475 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/FailedUnsubscribedTask.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.registry.retry;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.timer.Timeout;
import org.apache.dubbo.registry.NotifyListener;
import org.apache.dubbo.registry.support.FailbackRegistry;
/**
* FailedUnsubscribedTask
*/
public final class FailedUnsubscribedTask extends AbstractRetryTask {
private static final String NAME = "retry unsubscribe";
private final NotifyListener listener;
public FailedUnsubscribedTask(URL url, FailbackRegistry registry, NotifyListener listener) {
super(url, registry, NAME);
if (listener == null) {
throw new IllegalArgumentException();
}
this.listener = listener;
}
@Override
protected void doRetry(URL url, FailbackRegistry registry, Timeout timeout) {
registry.doUnsubscribe(url, listener);
registry.removeFailedUnsubscribedTask(url, listener);
}
}
| 5,476 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/ExporterFactory.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.registry.integration;
import org.apache.dubbo.rpc.Exporter;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
public class ExporterFactory {
private final Map<String, ReferenceCountExporter<?>> exporters = new ConcurrentHashMap<>();
protected ReferenceCountExporter<?> createExporter(String providerKey, Callable<Exporter<?>> exporterProducer) {
return exporters.computeIfAbsent(providerKey, key -> {
try {
return new ReferenceCountExporter<>(exporterProducer.call(), key, this);
} catch (Exception e) {
throw new RuntimeException(e);
}
});
}
protected void remove(String key, ReferenceCountExporter<?> exporter) {
exporters.remove(key, exporter);
}
}
| 5,477 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/InterfaceCompatibleRegistryProtocol.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.registry.integration;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.URLBuilder;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.client.ServiceDiscoveryRegistryDirectory;
import org.apache.dubbo.registry.client.migration.MigrationInvoker;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.cluster.Cluster;
import org.apache.dubbo.rpc.cluster.ClusterInvoker;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL;
import static org.apache.dubbo.registry.Constants.DEFAULT_REGISTRY;
/**
* RegistryProtocol
*/
public class InterfaceCompatibleRegistryProtocol extends RegistryProtocol {
@Override
protected URL getRegistryUrl(Invoker<?> originInvoker) {
URL registryUrl = originInvoker.getUrl();
if (REGISTRY_PROTOCOL.equals(registryUrl.getProtocol())) {
String protocol = registryUrl.getParameter(REGISTRY_KEY, DEFAULT_REGISTRY);
registryUrl = registryUrl.setProtocol(protocol).removeParameter(REGISTRY_KEY);
}
return registryUrl;
}
@Override
protected URL getRegistryUrl(URL url) {
return URLBuilder.from(url)
.setProtocol(url.getParameter(REGISTRY_KEY, DEFAULT_REGISTRY))
.removeParameter(REGISTRY_KEY)
.build();
}
@Override
public <T> ClusterInvoker<T> getInvoker(Cluster cluster, Registry registry, Class<T> type, URL url) {
DynamicDirectory<T> directory = new RegistryDirectory<>(type, url);
return doCreateInvoker(directory, cluster, registry, type);
}
@Override
public <T> ClusterInvoker<T> getServiceDiscoveryInvoker(
Cluster cluster, Registry registry, Class<T> type, URL url) {
registry = getRegistry(super.getRegistryUrl(url));
DynamicDirectory<T> directory = new ServiceDiscoveryRegistryDirectory<>(type, url);
return doCreateInvoker(directory, cluster, registry, type);
}
@Override
protected <T> ClusterInvoker<T> getMigrationInvoker(
RegistryProtocol registryProtocol,
Cluster cluster,
Registry registry,
Class<T> type,
URL url,
URL consumerUrl) {
// ClusterInvoker<T> invoker = getInvoker(cluster, registry, type, url);
return new MigrationInvoker<T>(registryProtocol, cluster, registry, type, url, consumerUrl);
}
}
| 5,478 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.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.registry.integration;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.common.constants.RegistryConstants;
import org.apache.dubbo.common.deploy.ApplicationDeployer;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository;
import org.apache.dubbo.common.timer.HashedWheelTimer;
import org.apache.dubbo.common.url.component.ServiceConfigURL;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.ConcurrentHashSet;
import org.apache.dubbo.common.utils.NamedThreadFactory;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.common.utils.UrlUtils;
import org.apache.dubbo.metrics.event.MetricsEventBus;
import org.apache.dubbo.metrics.registry.event.RegistryEvent;
import org.apache.dubbo.registry.NotifyListener;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.RegistryFactory;
import org.apache.dubbo.registry.RegistryService;
import org.apache.dubbo.registry.client.ServiceDiscoveryRegistryDirectory;
import org.apache.dubbo.registry.client.migration.MigrationClusterInvoker;
import org.apache.dubbo.registry.client.migration.ServiceDiscoveryMigrationInvoker;
import org.apache.dubbo.registry.retry.ReExportTask;
import org.apache.dubbo.registry.support.SkipFailbackWrapperException;
import org.apache.dubbo.rpc.Exporter;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.ProtocolServer;
import org.apache.dubbo.rpc.ProxyFactory;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.Cluster;
import org.apache.dubbo.rpc.cluster.ClusterInvoker;
import org.apache.dubbo.rpc.cluster.Configurator;
import org.apache.dubbo.rpc.cluster.Constants;
import org.apache.dubbo.rpc.cluster.governance.GovernanceRuleRepository;
import org.apache.dubbo.rpc.cluster.support.MergeableCluster;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.apache.dubbo.rpc.model.ProviderModel;
import org.apache.dubbo.rpc.model.ScopeModel;
import org.apache.dubbo.rpc.model.ScopeModelAware;
import org.apache.dubbo.rpc.model.ScopeModelUtil;
import org.apache.dubbo.rpc.protocol.InvokerWrapper;
import org.apache.dubbo.rpc.support.ProtocolUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.BACKGROUND_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.CLUSTER_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.ENABLED_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE;
import static org.apache.dubbo.common.constants.CommonConstants.EXTRA_KEYS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.HIDE_KEY_PREFIX;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.IPV6_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.MONITOR_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PACKABLE_METHOD_FACTORY_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PID_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.REGISTRY_LOCAL_FILE_CACHE_ENABLED;
import static org.apache.dubbo.common.constants.CommonConstants.REGISTRY_PROTOCOL_LISTENER_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.RELEASE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.SIDE_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.common.constants.FilterConstants.VALIDATION_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_UNSUPPORTED_CATEGORY;
import static org.apache.dubbo.common.constants.QosConstants.ACCEPT_FOREIGN_IP;
import static org.apache.dubbo.common.constants.QosConstants.QOS_ENABLE;
import static org.apache.dubbo.common.constants.QosConstants.QOS_HOST;
import static org.apache.dubbo.common.constants.QosConstants.QOS_PORT;
import static org.apache.dubbo.common.constants.RegistryConstants.ALL_CATEGORIES;
import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_CATEGORY;
import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.OVERRIDE_PROTOCOL;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTER_MODE_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.SERVICE_REGISTRY_PROTOCOL;
import static org.apache.dubbo.common.utils.StringUtils.isEmpty;
import static org.apache.dubbo.common.utils.UrlUtils.classifyUrls;
import static org.apache.dubbo.registry.Constants.CONFIGURATORS_SUFFIX;
import static org.apache.dubbo.registry.Constants.DEFAULT_REGISTRY_RETRY_PERIOD;
import static org.apache.dubbo.registry.Constants.ENABLE_26X_CONFIGURATION_LISTEN;
import static org.apache.dubbo.registry.Constants.ENABLE_CONFIGURATION_LISTEN;
import static org.apache.dubbo.registry.Constants.PROVIDER_PROTOCOL;
import static org.apache.dubbo.registry.Constants.REGISTER_IP_KEY;
import static org.apache.dubbo.registry.Constants.REGISTER_KEY;
import static org.apache.dubbo.registry.Constants.REGISTRY_RETRY_PERIOD_KEY;
import static org.apache.dubbo.registry.Constants.SIMPLIFIED_KEY;
import static org.apache.dubbo.remoting.Constants.BIND_IP_KEY;
import static org.apache.dubbo.remoting.Constants.BIND_PORT_KEY;
import static org.apache.dubbo.remoting.Constants.CHECK_KEY;
import static org.apache.dubbo.remoting.Constants.CODEC_KEY;
import static org.apache.dubbo.remoting.Constants.CONNECTIONS_KEY;
import static org.apache.dubbo.remoting.Constants.EXCHANGER_KEY;
import static org.apache.dubbo.remoting.Constants.PREFER_SERIALIZATION_KEY;
import static org.apache.dubbo.remoting.Constants.SERIALIZATION_KEY;
import static org.apache.dubbo.rpc.Constants.DEPRECATED_KEY;
import static org.apache.dubbo.rpc.Constants.GENERIC_KEY;
import static org.apache.dubbo.rpc.Constants.INTERFACES;
import static org.apache.dubbo.rpc.Constants.MOCK_KEY;
import static org.apache.dubbo.rpc.Constants.TOKEN_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.CONSUMER_URL_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.EXPORT_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.WARMUP_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.WEIGHT_KEY;
import static org.apache.dubbo.rpc.model.ScopeModelUtil.getApplicationModel;
/**
* TODO, replace RegistryProtocol completely in the future.
*/
public class RegistryProtocol implements Protocol, ScopeModelAware {
public static final String[] DEFAULT_REGISTER_PROVIDER_KEYS = {
APPLICATION_KEY, CODEC_KEY, EXCHANGER_KEY, SERIALIZATION_KEY, PREFER_SERIALIZATION_KEY, CLUSTER_KEY,
CONNECTIONS_KEY, DEPRECATED_KEY,
GROUP_KEY, LOADBALANCE_KEY, MOCK_KEY, PATH_KEY, TIMEOUT_KEY, TOKEN_KEY, VERSION_KEY, WARMUP_KEY,
WEIGHT_KEY, DUBBO_VERSION_KEY, RELEASE_KEY, SIDE_KEY, IPV6_KEY, PACKABLE_METHOD_FACTORY_KEY
};
public static final String[] DEFAULT_REGISTER_CONSUMER_KEYS = {
APPLICATION_KEY, VERSION_KEY, GROUP_KEY, DUBBO_VERSION_KEY, RELEASE_KEY
};
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(RegistryProtocol.class);
private final Map<String, ServiceConfigurationListener> serviceConfigurationListeners = new ConcurrentHashMap<>();
// To solve the problem of RMI repeated exposure port conflicts, the services that have been exposed are no longer
// exposed.
// provider url <--> registry url <--> exporter
private final Map<String, Map<String, ExporterChangeableWrapper<?>>> bounds = new ConcurrentHashMap<>();
protected Protocol protocol;
protected ProxyFactory proxyFactory;
private ConcurrentMap<URL, ReExportTask> reExportFailedTasks = new ConcurrentHashMap<>();
private HashedWheelTimer retryTimer = new HashedWheelTimer(
new NamedThreadFactory("DubboReexportTimer", true),
DEFAULT_REGISTRY_RETRY_PERIOD,
TimeUnit.MILLISECONDS,
128);
private FrameworkModel frameworkModel;
private ExporterFactory exporterFactory;
// Filter the parameters that do not need to be output in url(Starting with .)
private static String[] getFilteredKeys(URL url) {
Map<String, String> params = url.getParameters();
if (CollectionUtils.isNotEmptyMap(params)) {
return params.keySet().stream()
.filter(k -> k.startsWith(HIDE_KEY_PREFIX))
.toArray(String[]::new);
} else {
return new String[0];
}
}
public RegistryProtocol() {}
@Override
public void setFrameworkModel(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
this.exporterFactory = frameworkModel.getBeanFactory().getBean(ExporterFactory.class);
}
public void setProtocol(Protocol protocol) {
this.protocol = protocol;
}
public void setProxyFactory(ProxyFactory proxyFactory) {
this.proxyFactory = proxyFactory;
}
@Override
public int getDefaultPort() {
return 9090;
}
public Map<URL, Set<NotifyListener>> getOverrideListeners() {
Map<URL, Set<NotifyListener>> map = new HashMap<>();
List<ApplicationModel> applicationModels = frameworkModel.getApplicationModels();
if (applicationModels.size() == 1) {
return applicationModels
.get(0)
.getBeanFactory()
.getBean(ProviderConfigurationListener.class)
.getOverrideListeners();
} else {
for (ApplicationModel applicationModel : applicationModels) {
map.putAll(applicationModel
.getBeanFactory()
.getBean(ProviderConfigurationListener.class)
.getOverrideListeners());
}
}
return map;
}
private static void register(Registry registry, URL registeredProviderUrl) {
ApplicationDeployer deployer =
registeredProviderUrl.getOrDefaultApplicationModel().getDeployer();
try {
deployer.increaseServiceRefreshCount();
String registryName = Optional.ofNullable(registry.getUrl())
.map(u -> u.getParameter(
RegistryConstants.REGISTRY_CLUSTER_KEY,
UrlUtils.isServiceDiscoveryURL(u) ? u.getParameter(REGISTRY_KEY) : u.getProtocol()))
.filter(StringUtils::isNotEmpty)
.orElse("unknown");
MetricsEventBus.post(
RegistryEvent.toRsEvent(
registeredProviderUrl.getApplicationModel(),
registeredProviderUrl.getServiceKey(),
1,
Collections.singletonList(registryName)),
() -> {
registry.register(registeredProviderUrl);
return null;
});
} finally {
deployer.decreaseServiceRefreshCount();
}
}
private void registerStatedUrl(URL registryUrl, URL registeredProviderUrl, boolean registered) {
ProviderModel model = (ProviderModel) registeredProviderUrl.getServiceModel();
model.addStatedUrl(new ProviderModel.RegisterStatedURL(registeredProviderUrl, registryUrl, registered));
}
@Override
public <T> Exporter<T> export(final Invoker<T> originInvoker) throws RpcException {
URL registryUrl = getRegistryUrl(originInvoker);
// url to export locally
URL providerUrl = getProviderUrl(originInvoker);
// Subscribe the override data
// FIXME When the provider subscribes, it will affect the scene : a certain JVM exposes the service and call
// the same service. Because the subscribed is cached key with the name of the service, it causes the
// subscription information to cover.
final URL overrideSubscribeUrl = getSubscribedOverrideUrl(providerUrl);
final OverrideListener overrideSubscribeListener = new OverrideListener(overrideSubscribeUrl, originInvoker);
Map<URL, Set<NotifyListener>> overrideListeners =
getProviderConfigurationListener(overrideSubscribeUrl).getOverrideListeners();
overrideListeners
.computeIfAbsent(overrideSubscribeUrl, k -> new ConcurrentHashSet<>())
.add(overrideSubscribeListener);
providerUrl = overrideUrlWithConfig(providerUrl, overrideSubscribeListener);
// export invoker
final ExporterChangeableWrapper<T> exporter = doLocalExport(originInvoker, providerUrl);
// url to registry
final Registry registry = getRegistry(registryUrl);
final URL registeredProviderUrl = getUrlToRegistry(providerUrl, registryUrl);
// decide if we need to delay publish (provider itself and registry should both need to register)
boolean register = providerUrl.getParameter(REGISTER_KEY, true) && registryUrl.getParameter(REGISTER_KEY, true);
if (register) {
register(registry, registeredProviderUrl);
}
// register stated url on provider model
registerStatedUrl(registryUrl, registeredProviderUrl, register);
exporter.setRegisterUrl(registeredProviderUrl);
exporter.setSubscribeUrl(overrideSubscribeUrl);
exporter.setNotifyListener(overrideSubscribeListener);
exporter.setRegistered(register);
ApplicationModel applicationModel = getApplicationModel(providerUrl.getScopeModel());
if (applicationModel
.modelEnvironment()
.getConfiguration()
.convert(Boolean.class, ENABLE_26X_CONFIGURATION_LISTEN, true)) {
if (!registry.isServiceDiscovery()) {
// Deprecated! Subscribe to override rules in 2.6.x or before.
registry.subscribe(overrideSubscribeUrl, overrideSubscribeListener);
}
}
notifyExport(exporter);
// Ensure that a new exporter instance is returned every time export
return new DestroyableExporter<>(exporter);
}
private <T> void notifyExport(ExporterChangeableWrapper<T> exporter) {
ScopeModel scopeModel = exporter.getRegisterUrl().getScopeModel();
List<RegistryProtocolListener> listeners = ScopeModelUtil.getExtensionLoader(
RegistryProtocolListener.class, scopeModel)
.getActivateExtension(exporter.getOriginInvoker().getUrl(), REGISTRY_PROTOCOL_LISTENER_KEY);
if (CollectionUtils.isNotEmpty(listeners)) {
for (RegistryProtocolListener listener : listeners) {
listener.onExport(this, exporter);
}
}
}
private URL overrideUrlWithConfig(URL providerUrl, OverrideListener listener) {
ProviderConfigurationListener providerConfigurationListener = getProviderConfigurationListener(providerUrl);
providerUrl = providerConfigurationListener.overrideUrl(providerUrl);
ServiceConfigurationListener serviceConfigurationListener =
new ServiceConfigurationListener(providerUrl.getOrDefaultModuleModel(), providerUrl, listener);
serviceConfigurationListeners.put(providerUrl.getServiceKey(), serviceConfigurationListener);
return serviceConfigurationListener.overrideUrl(providerUrl);
}
@SuppressWarnings("unchecked")
private <T> ExporterChangeableWrapper<T> doLocalExport(final Invoker<T> originInvoker, URL providerUrl) {
String providerUrlKey = getProviderUrlKey(originInvoker);
String registryUrlKey = getRegistryUrlKey(originInvoker);
Invoker<?> invokerDelegate = new InvokerDelegate<>(originInvoker, providerUrl);
ReferenceCountExporter<?> exporter =
exporterFactory.createExporter(providerUrlKey, () -> protocol.export(invokerDelegate));
return (ExporterChangeableWrapper<T>) bounds.computeIfAbsent(providerUrlKey, _k -> new ConcurrentHashMap<>())
.computeIfAbsent(registryUrlKey, s -> {
return new ExporterChangeableWrapper<>((ReferenceCountExporter<T>) exporter, originInvoker);
});
}
public <T> void reExport(Exporter<T> exporter, URL newInvokerUrl) {
if (exporter instanceof ExporterChangeableWrapper) {
ExporterChangeableWrapper<T> exporterWrapper = (ExporterChangeableWrapper<T>) exporter;
Invoker<T> originInvoker = exporterWrapper.getOriginInvoker();
reExport(originInvoker, newInvokerUrl);
}
}
/**
* Reexport the invoker of the modified url
*
* @param originInvoker
* @param newInvokerUrl
* @param <T>
*/
@SuppressWarnings("unchecked")
public <T> void reExport(final Invoker<T> originInvoker, URL newInvokerUrl) {
String providerUrlKey = getProviderUrlKey(originInvoker);
String registryUrlKey = getRegistryUrlKey(originInvoker);
Map<String, ExporterChangeableWrapper<?>> registryMap = bounds.get(providerUrlKey);
if (registryMap == null) {
logger.warn(
INTERNAL_ERROR,
"error state, exporterMap can not be null",
"",
"error state, exporterMap can not be null",
new IllegalStateException("error state, exporterMap can not be null"));
return;
}
ExporterChangeableWrapper<T> exporter = (ExporterChangeableWrapper<T>) registryMap.get(registryUrlKey);
if (exporter == null) {
logger.warn(
INTERNAL_ERROR,
"error state, exporterMap can not be null",
"",
"error state, exporterMap can not be null",
new IllegalStateException("error state, exporterMap can not be null"));
return;
}
URL registeredUrl = exporter.getRegisterUrl();
URL registryUrl = getRegistryUrl(originInvoker);
URL newProviderUrl = getUrlToRegistry(newInvokerUrl, registryUrl);
// update local exporter
Invoker<T> invokerDelegate = new InvokerDelegate<T>(originInvoker, newInvokerUrl);
exporter.setExporter(protocol.export(invokerDelegate));
// update registry
if (!newProviderUrl.equals(registeredUrl)) {
try {
doReExport(originInvoker, exporter, registryUrl, registeredUrl, newProviderUrl);
} catch (Exception e) {
ReExportTask oldTask = reExportFailedTasks.get(registeredUrl);
if (oldTask != null) {
return;
}
ReExportTask task = new ReExportTask(
() -> doReExport(originInvoker, exporter, registryUrl, registeredUrl, newProviderUrl),
registeredUrl,
null);
oldTask = reExportFailedTasks.putIfAbsent(registeredUrl, task);
if (oldTask == null) {
// never has a retry task. then start a new task for retry.
retryTimer.newTimeout(
task,
registryUrl.getParameter(REGISTRY_RETRY_PERIOD_KEY, DEFAULT_REGISTRY_RETRY_PERIOD),
TimeUnit.MILLISECONDS);
}
}
}
}
private <T> void doReExport(
final Invoker<T> originInvoker,
ExporterChangeableWrapper<T> exporter,
URL registryUrl,
URL oldProviderUrl,
URL newProviderUrl) {
if (exporter.isRegistered()) {
Registry registry;
try {
registry = getRegistry(getRegistryUrl(originInvoker));
} catch (Exception e) {
throw new SkipFailbackWrapperException(e);
}
logger.info("Try to unregister old url: " + oldProviderUrl);
registry.reExportUnregister(oldProviderUrl);
logger.info("Try to register new url: " + newProviderUrl);
registry.reExportRegister(newProviderUrl);
}
try {
ProviderModel.RegisterStatedURL statedUrl = getStatedUrl(registryUrl, newProviderUrl);
statedUrl.setProviderUrl(newProviderUrl);
exporter.setRegisterUrl(newProviderUrl);
} catch (Exception e) {
throw new SkipFailbackWrapperException(e);
}
}
private ProviderModel.RegisterStatedURL getStatedUrl(URL registryUrl, URL providerUrl) {
ProviderModel providerModel =
frameworkModel.getServiceRepository().lookupExportedService(providerUrl.getServiceKey());
List<ProviderModel.RegisterStatedURL> statedUrls = providerModel.getStatedUrl();
return statedUrls.stream()
.filter(u -> u.getRegistryUrl().equals(registryUrl)
&& u.getProviderUrl().getProtocol().equals(providerUrl.getProtocol()))
.findFirst()
.orElseThrow(() -> new IllegalStateException("There should have at least one registered url."));
}
/**
* Get an instance of registry based on the address of invoker
*
* @param registryUrl
* @return
*/
protected Registry getRegistry(final URL registryUrl) {
RegistryFactory registryFactory = ScopeModelUtil.getExtensionLoader(
RegistryFactory.class, registryUrl.getScopeModel())
.getAdaptiveExtension();
return registryFactory.getRegistry(registryUrl);
}
protected URL getRegistryUrl(Invoker<?> originInvoker) {
return originInvoker.getUrl();
}
protected URL getRegistryUrl(URL url) {
if (SERVICE_REGISTRY_PROTOCOL.equals(url.getProtocol())) {
return url;
}
return url.addParameter(REGISTRY_KEY, url.getProtocol()).setProtocol(SERVICE_REGISTRY_PROTOCOL);
}
/**
* Return the url that is registered to the registry and filter the url parameter once
*
* @param providerUrl
* @return url to registry.
*/
private URL getUrlToRegistry(final URL providerUrl, final URL registryUrl) {
// The address you see at the registry
if (!registryUrl.getParameter(SIMPLIFIED_KEY, false)) {
return providerUrl
.removeParameters(getFilteredKeys(providerUrl))
.removeParameters(
MONITOR_KEY,
BIND_IP_KEY,
BIND_PORT_KEY,
QOS_ENABLE,
QOS_HOST,
QOS_PORT,
ACCEPT_FOREIGN_IP,
VALIDATION_KEY,
INTERFACES,
REGISTER_MODE_KEY,
PID_KEY,
REGISTRY_LOCAL_FILE_CACHE_ENABLED,
EXECUTOR_MANAGEMENT_MODE,
BACKGROUND_KEY,
ANYHOST_KEY);
} else {
String extraKeys = registryUrl.getParameter(EXTRA_KEYS_KEY, "");
// if path is not the same as interface name then we should keep INTERFACE_KEY,
// otherwise, the registry structure of zookeeper would be '/dubbo/path/providers',
// but what we expect is '/dubbo/interface/providers'
if (!providerUrl.getPath().equals(providerUrl.getParameter(INTERFACE_KEY))) {
if (StringUtils.isNotEmpty(extraKeys)) {
extraKeys += ",";
}
extraKeys += INTERFACE_KEY;
}
String[] paramsToRegistry =
getParamsToRegistry(DEFAULT_REGISTER_PROVIDER_KEYS, COMMA_SPLIT_PATTERN.split(extraKeys));
return URL.valueOf(providerUrl, paramsToRegistry, providerUrl.getParameter(METHODS_KEY, (String[]) null));
}
}
private URL getSubscribedOverrideUrl(URL registeredProviderUrl) {
return registeredProviderUrl
.setProtocol(PROVIDER_PROTOCOL)
.addParameters(CATEGORY_KEY, CONFIGURATORS_CATEGORY, CHECK_KEY, String.valueOf(false));
}
/**
* Get the address of the providerUrl through the url of the invoker
*
* @param originInvoker
* @return
*/
private URL getProviderUrl(final Invoker<?> originInvoker) {
Object providerURL = originInvoker.getUrl().getAttribute(EXPORT_KEY);
if (!(providerURL instanceof URL)) {
throw new IllegalArgumentException("The registry export url is null! registry: "
+ originInvoker.getUrl().getAddress());
}
return (URL) providerURL;
}
/**
* Get the key cached in bounds by invoker
*
* @param originInvoker
* @return
*/
private String getProviderUrlKey(final Invoker<?> originInvoker) {
URL providerUrl = getProviderUrl(originInvoker);
String key = providerUrl.removeParameters(DYNAMIC_KEY, ENABLED_KEY).toFullString();
return key;
}
private String getRegistryUrlKey(final Invoker<?> originInvoker) {
URL registryUrl = getRegistryUrl(originInvoker);
String key = registryUrl.removeParameters(DYNAMIC_KEY, ENABLED_KEY).toFullString();
return key;
}
@Override
@SuppressWarnings("unchecked")
public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException {
url = getRegistryUrl(url);
Registry registry = getRegistry(url);
if (RegistryService.class.equals(type)) {
return proxyFactory.getInvoker((T) registry, type, url);
}
// group="a,b" or group="*"
Map<String, String> qs = (Map<String, String>) url.getAttribute(REFER_KEY);
String group = qs.get(GROUP_KEY);
if (StringUtils.isNotEmpty(group)) {
if ((COMMA_SPLIT_PATTERN.split(group)).length > 1 || "*".equals(group)) {
return doRefer(Cluster.getCluster(url.getScopeModel(), MergeableCluster.NAME), registry, type, url, qs);
}
}
Cluster cluster = Cluster.getCluster(url.getScopeModel(), qs.get(CLUSTER_KEY));
return doRefer(cluster, registry, type, url, qs);
}
protected <T> Invoker<T> doRefer(
Cluster cluster, Registry registry, Class<T> type, URL url, Map<String, String> parameters) {
Map<String, Object> consumerAttribute = new HashMap<>(url.getAttributes());
consumerAttribute.remove(REFER_KEY);
String p = isEmpty(parameters.get(PROTOCOL_KEY)) ? CONSUMER : parameters.get(PROTOCOL_KEY);
URL consumerUrl = new ServiceConfigURL(
p,
null,
null,
parameters.get(REGISTER_IP_KEY),
0,
getPath(parameters, type),
parameters,
consumerAttribute);
url = url.putAttribute(CONSUMER_URL_KEY, consumerUrl);
ClusterInvoker<T> migrationInvoker = getMigrationInvoker(this, cluster, registry, type, url, consumerUrl);
return interceptInvoker(migrationInvoker, url, consumerUrl);
}
private String getPath(Map<String, String> parameters, Class<?> type) {
return !ProtocolUtils.isGeneric(parameters.get(GENERIC_KEY)) ? type.getName() : parameters.get(INTERFACE_KEY);
}
protected <T> ClusterInvoker<T> getMigrationInvoker(
RegistryProtocol registryProtocol,
Cluster cluster,
Registry registry,
Class<T> type,
URL url,
URL consumerUrl) {
return new ServiceDiscoveryMigrationInvoker<T>(registryProtocol, cluster, registry, type, url, consumerUrl);
}
/**
* This method tries to load all RegistryProtocolListener definitions, which are used to control the behaviour of invoker by interacting with defined, then uses those listeners to
* change the status and behaviour of the MigrationInvoker.
* <p>
* Currently available Listener is MigrationRuleListener, one used to control the Migration behaviour with dynamically changing rules.
*
* @param invoker MigrationInvoker that determines which type of invoker list to use
* @param url The original url generated during refer, more like a registry:// style url
* @param consumerUrl Consumer url representing current interface and its config
* @param <T> The service definition
* @return The @param MigrationInvoker passed in
*/
protected <T> Invoker<T> interceptInvoker(ClusterInvoker<T> invoker, URL url, URL consumerUrl) {
List<RegistryProtocolListener> listeners = findRegistryProtocolListeners(url);
if (CollectionUtils.isEmpty(listeners)) {
return invoker;
}
for (RegistryProtocolListener listener : listeners) {
listener.onRefer(this, invoker, consumerUrl, url);
}
return invoker;
}
public <T> ClusterInvoker<T> getServiceDiscoveryInvoker(
Cluster cluster, Registry registry, Class<T> type, URL url) {
DynamicDirectory<T> directory = new ServiceDiscoveryRegistryDirectory<>(type, url);
return doCreateInvoker(directory, cluster, registry, type);
}
public <T> ClusterInvoker<T> getInvoker(Cluster cluster, Registry registry, Class<T> type, URL url) {
// FIXME, this method is currently not used, create the right registry before enable.
DynamicDirectory<T> directory = new RegistryDirectory<>(type, url);
return doCreateInvoker(directory, cluster, registry, type);
}
protected <T> ClusterInvoker<T> doCreateInvoker(
DynamicDirectory<T> directory, Cluster cluster, Registry registry, Class<T> type) {
directory.setRegistry(registry);
directory.setProtocol(protocol);
// all attributes of REFER_KEY
Map<String, String> parameters =
new HashMap<>(directory.getConsumerUrl().getParameters());
URL urlToRegistry = new ServiceConfigURL(
parameters.get(PROTOCOL_KEY) == null ? CONSUMER : parameters.get(PROTOCOL_KEY),
parameters.remove(REGISTER_IP_KEY),
0,
getPath(parameters, type),
parameters);
urlToRegistry = urlToRegistry.setScopeModel(directory.getConsumerUrl().getScopeModel());
urlToRegistry = urlToRegistry.setServiceModel(directory.getConsumerUrl().getServiceModel());
if (directory.isShouldRegister()) {
directory.setRegisteredConsumerUrl(urlToRegistry);
registry.register(directory.getRegisteredConsumerUrl());
}
directory.buildRouterChain(urlToRegistry);
directory.subscribe(toSubscribeUrl(urlToRegistry));
return (ClusterInvoker<T>) cluster.join(directory, true);
}
public <T> void reRefer(ClusterInvoker<?> invoker, URL newSubscribeUrl) {
if (!(invoker instanceof MigrationClusterInvoker)) {
logger.error(
REGISTRY_UNSUPPORTED_CATEGORY,
"",
"",
"Only invoker type of MigrationClusterInvoker supports reRefer, current invoker is "
+ invoker.getClass());
return;
}
MigrationClusterInvoker<?> migrationClusterInvoker = (MigrationClusterInvoker<?>) invoker;
migrationClusterInvoker.reRefer(newSubscribeUrl);
}
public static URL toSubscribeUrl(URL url) {
return url.addParameter(CATEGORY_KEY, ALL_CATEGORIES);
}
protected List<RegistryProtocolListener> findRegistryProtocolListeners(URL url) {
return ScopeModelUtil.getExtensionLoader(RegistryProtocolListener.class, url.getScopeModel())
.getActivateExtension(url, REGISTRY_PROTOCOL_LISTENER_KEY);
}
// available to test
public String[] getParamsToRegistry(String[] defaultKeys, String[] additionalParameterKeys) {
int additionalLen = additionalParameterKeys.length;
String[] registryParams = new String[defaultKeys.length + additionalLen];
System.arraycopy(defaultKeys, 0, registryParams, 0, defaultKeys.length);
System.arraycopy(additionalParameterKeys, 0, registryParams, defaultKeys.length, additionalLen);
return registryParams;
}
@Override
public void destroy() {
// FIXME all application models in framework are removed at this moment
for (ApplicationModel applicationModel : frameworkModel.getApplicationModels()) {
for (ModuleModel moduleModel : applicationModel.getModuleModels()) {
List<RegistryProtocolListener> listeners = moduleModel
.getExtensionLoader(RegistryProtocolListener.class)
.getLoadedExtensionInstances();
if (CollectionUtils.isNotEmpty(listeners)) {
for (RegistryProtocolListener listener : listeners) {
listener.onDestroy();
}
}
}
}
for (ApplicationModel applicationModel : frameworkModel.getApplicationModels()) {
if (applicationModel
.modelEnvironment()
.getConfiguration()
.convert(Boolean.class, org.apache.dubbo.registry.Constants.ENABLE_CONFIGURATION_LISTEN, true)) {
for (ModuleModel moduleModel : applicationModel.getPubModuleModels()) {
String applicationName = applicationModel.tryGetApplicationName();
if (applicationName == null) {
// already removed
continue;
}
if (moduleModel.getServiceRepository().getExportedServices().size() > 0) {
moduleModel
.getExtensionLoader(GovernanceRuleRepository.class)
.getDefaultExtension()
.removeListener(
applicationName + CONFIGURATORS_SUFFIX,
getProviderConfigurationListener(moduleModel));
}
}
}
}
List<Exporter<?>> exporters =
bounds.values().stream().flatMap(e -> e.values().stream()).collect(Collectors.toList());
for (Exporter<?> exporter : exporters) {
exporter.unexport();
}
bounds.clear();
}
@Override
public List<ProtocolServer> getServers() {
return protocol.getServers();
}
// Merge the urls of configurators
private static URL getConfiguredInvokerUrl(List<Configurator> configurators, URL url) {
if (CollectionUtils.isNotEmpty(configurators)) {
for (Configurator configurator : configurators) {
url = configurator.configure(url);
}
}
return url;
}
public static class InvokerDelegate<T> extends InvokerWrapper<T> {
/**
* @param invoker
* @param url invoker.getUrl return this value
*/
public InvokerDelegate(Invoker<T> invoker, URL url) {
super(invoker, url);
}
public Invoker<T> getInvoker() {
if (invoker instanceof InvokerDelegate) {
return ((InvokerDelegate<T>) invoker).getInvoker();
} else {
return invoker;
}
}
}
private static class DestroyableExporter<T> implements Exporter<T> {
private Exporter<T> exporter;
public DestroyableExporter(Exporter<T> exporter) {
this.exporter = exporter;
}
@Override
public Invoker<T> getInvoker() {
return exporter.getInvoker();
}
@Override
public void unexport() {
exporter.unexport();
}
@Override
public void register() {
exporter.register();
}
@Override
public void unregister() {
exporter.unregister();
}
}
/**
* Reexport: the exporter destroy problem in protocol
* 1.Ensure that the exporter returned by registry protocol can be normal destroyed
* 2.No need to re-register to the registry after notify
* 3.The invoker passed by the export method , would better to be the invoker of exporter
*/
private class OverrideListener implements NotifyListener {
private final URL subscribeUrl;
private final Invoker originInvoker;
private List<Configurator> configurators;
public OverrideListener(URL subscribeUrl, Invoker originalInvoker) {
this.subscribeUrl = subscribeUrl;
this.originInvoker = originalInvoker;
}
/**
* @param urls The list of registered information, is always not empty, The meaning is the same as the
* return value of {@link org.apache.dubbo.registry.RegistryService#lookup(URL)}.
*/
@Override
public synchronized void notify(List<URL> urls) {
if (logger.isDebugEnabled()) {
logger.debug("original override urls: " + urls);
}
List<URL> matchedUrls = getMatchedUrls(urls, subscribeUrl);
if (logger.isDebugEnabled()) {
logger.debug("subscribe url: " + subscribeUrl + ", override urls: " + matchedUrls);
}
// No matching results
if (matchedUrls.isEmpty()) {
return;
}
this.configurators = Configurator.toConfigurators(classifyUrls(matchedUrls, UrlUtils::isConfigurator))
.orElse(configurators);
ApplicationDeployer deployer =
subscribeUrl.getOrDefaultApplicationModel().getDeployer();
try {
deployer.increaseServiceRefreshCount();
doOverrideIfNecessary();
} finally {
deployer.decreaseServiceRefreshCount();
}
}
public synchronized void doOverrideIfNecessary() {
final Invoker<?> invoker;
if (originInvoker instanceof InvokerDelegate) {
invoker = ((InvokerDelegate<?>) originInvoker).getInvoker();
} else {
invoker = originInvoker;
}
// The origin invoker
URL originUrl = RegistryProtocol.this.getProviderUrl(invoker);
String providerUrlKey = getProviderUrlKey(originInvoker);
String registryUrlKey = getRegistryUrlKey(originInvoker);
Map<String, ExporterChangeableWrapper<?>> exporterMap = bounds.get(providerUrlKey);
if (exporterMap == null) {
logger.warn(
INTERNAL_ERROR,
"error state, exporterMap can not be null",
"",
"error state, exporterMap can not be null",
new IllegalStateException("error state, exporterMap can not be null"));
return;
}
ExporterChangeableWrapper<?> exporter = exporterMap.get(registryUrlKey);
if (exporter == null) {
logger.warn(
INTERNAL_ERROR,
"unknown error in registry module",
"",
"error state, exporter should not be null",
new IllegalStateException("error state, exporter should not be null"));
return;
}
// The current, may have been merged many times
Invoker<?> exporterInvoker = exporter.getInvoker();
URL currentUrl = exporterInvoker == null ? null : exporterInvoker.getUrl();
// Merged with this configuration
URL newUrl = getConfiguredInvokerUrl(configurators, originUrl);
newUrl = getConfiguredInvokerUrl(
getProviderConfigurationListener(originUrl).getConfigurators(), newUrl);
newUrl = getConfiguredInvokerUrl(
serviceConfigurationListeners.get(originUrl.getServiceKey()).getConfigurators(), newUrl);
if (!newUrl.equals(currentUrl)) {
if (newUrl.getParameter(Constants.NEED_REEXPORT, true)) {
RegistryProtocol.this.reExport(originInvoker, newUrl);
}
logger.info("exported provider url changed, origin url: " + originUrl + ", old export url: "
+ currentUrl + ", new export url: " + newUrl);
}
}
private List<URL> getMatchedUrls(List<URL> configuratorUrls, URL currentSubscribe) {
List<URL> result = new ArrayList<>();
for (URL url : configuratorUrls) {
URL overrideUrl = url;
// Compatible with the old version
if (url.getCategory() == null && OVERRIDE_PROTOCOL.equals(url.getProtocol())) {
overrideUrl = url.addParameter(CATEGORY_KEY, CONFIGURATORS_CATEGORY);
}
// Check whether url is to be applied to the current service
if (UrlUtils.isMatch(currentSubscribe, overrideUrl)) {
result.add(url);
}
}
return result;
}
}
private ProviderConfigurationListener getProviderConfigurationListener(URL url) {
return getProviderConfigurationListener(url.getOrDefaultModuleModel());
}
private ProviderConfigurationListener getProviderConfigurationListener(ModuleModel moduleModel) {
return moduleModel
.getBeanFactory()
.getOrRegisterBean(
ProviderConfigurationListener.class, type -> new ProviderConfigurationListener(moduleModel));
}
private class ServiceConfigurationListener extends AbstractConfiguratorListener {
private URL providerUrl;
private OverrideListener notifyListener;
private final ModuleModel moduleModel;
public ServiceConfigurationListener(ModuleModel moduleModel, URL providerUrl, OverrideListener notifyListener) {
super(moduleModel);
this.providerUrl = providerUrl;
this.notifyListener = notifyListener;
this.moduleModel = moduleModel;
if (moduleModel
.modelEnvironment()
.getConfiguration()
.convert(Boolean.class, ENABLE_CONFIGURATION_LISTEN, true)) {
this.initWith(DynamicConfiguration.getRuleKey(providerUrl) + CONFIGURATORS_SUFFIX);
}
}
private <T> URL overrideUrl(URL providerUrl) {
return RegistryProtocol.getConfiguredInvokerUrl(configurators, providerUrl);
}
@Override
protected void notifyOverrides() {
ApplicationDeployer deployer =
this.moduleModel.getApplicationModel().getDeployer();
try {
deployer.increaseServiceRefreshCount();
notifyListener.doOverrideIfNecessary();
} finally {
deployer.decreaseServiceRefreshCount();
}
}
}
private class ProviderConfigurationListener extends AbstractConfiguratorListener {
private final Map<URL, Set<NotifyListener>> overrideListeners = new ConcurrentHashMap<>();
private final ModuleModel moduleModel;
public ProviderConfigurationListener(ModuleModel moduleModel) {
super(moduleModel);
this.moduleModel = moduleModel;
if (moduleModel
.modelEnvironment()
.getConfiguration()
.convert(Boolean.class, ENABLE_CONFIGURATION_LISTEN, true)) {
this.initWith(moduleModel.getApplicationModel().getApplicationName() + CONFIGURATORS_SUFFIX);
}
}
/**
* Get existing configuration rule and override provider url before exporting.
*
* @param providerUrl
* @param <T>
* @return
*/
private <T> URL overrideUrl(URL providerUrl) {
return RegistryProtocol.getConfiguredInvokerUrl(configurators, providerUrl);
}
@Override
protected void notifyOverrides() {
ApplicationDeployer deployer =
this.moduleModel.getApplicationModel().getDeployer();
try {
deployer.increaseServiceRefreshCount();
overrideListeners.values().forEach(listeners -> {
for (NotifyListener listener : listeners) {
((OverrideListener) listener).doOverrideIfNecessary();
}
});
} finally {
deployer.decreaseServiceRefreshCount();
}
}
public Map<URL, Set<NotifyListener>> getOverrideListeners() {
return overrideListeners;
}
}
/**
* exporter proxy, establish the corresponding relationship between the returned exporter and the exporter
* exported by the protocol, and can modify the relationship at the time of override.
*
* @param <T>
*/
private class ExporterChangeableWrapper<T> implements Exporter<T> {
private final ScheduledExecutorService executor;
private final Invoker<T> originInvoker;
private Exporter<T> exporter;
private URL subscribeUrl;
private URL registerUrl;
private NotifyListener notifyListener;
private final AtomicBoolean registered = new AtomicBoolean(false);
public ExporterChangeableWrapper(ReferenceCountExporter<T> exporter, Invoker<T> originInvoker) {
this.exporter = exporter;
exporter.increaseCount();
this.originInvoker = originInvoker;
FrameworkExecutorRepository frameworkExecutorRepository = originInvoker
.getUrl()
.getOrDefaultFrameworkModel()
.getBeanFactory()
.getBean(FrameworkExecutorRepository.class);
this.executor = frameworkExecutorRepository.getSharedScheduledExecutor();
}
public Invoker<T> getOriginInvoker() {
return originInvoker;
}
@Override
public Invoker<T> getInvoker() {
return exporter.getInvoker();
}
public void setExporter(Exporter<T> exporter) {
this.exporter = exporter;
}
@Override
public void register() {
if (registered.compareAndSet(false, true)) {
URL registryUrl = getRegistryUrl(originInvoker);
Registry registry = getRegistry(registryUrl);
RegistryProtocol.register(registry, getRegisterUrl());
ProviderModel providerModel = frameworkModel
.getServiceRepository()
.lookupExportedService(getRegisterUrl().getServiceKey());
List<ProviderModel.RegisterStatedURL> statedUrls = providerModel.getStatedUrl();
statedUrls.stream()
.filter(u -> u.getRegistryUrl().equals(registryUrl)
&& u.getProviderUrl()
.getProtocol()
.equals(getRegisterUrl().getProtocol()))
.forEach(u -> u.setRegistered(true));
logger.info("Registered dubbo service " + getRegisterUrl().getServiceKey() + " url " + getRegisterUrl()
+ " to registry " + registryUrl);
}
}
@Override
public synchronized void unregister() {
if (registered.compareAndSet(true, false)) {
URL registryUrl = getRegistryUrl(originInvoker);
Registry registry = RegistryProtocol.this.getRegistry(registryUrl);
ProviderModel providerModel = frameworkModel
.getServiceRepository()
.lookupExportedService(getRegisterUrl().getServiceKey());
List<ProviderModel.RegisterStatedURL> statedURLs = providerModel.getStatedUrl().stream()
.filter(u -> u.getRegistryUrl().equals(registryUrl)
&& u.getProviderUrl()
.getProtocol()
.equals(getRegisterUrl().getProtocol()))
.collect(Collectors.toList());
if (statedURLs.isEmpty()
|| statedURLs.stream().anyMatch(ProviderModel.RegisterStatedURL::isRegistered)) {
try {
registry.unregister(registerUrl);
} catch (Throwable t) {
logger.warn(INTERNAL_ERROR, "unknown error in registry module", "", t.getMessage(), t);
}
}
try {
if (subscribeUrl != null) {
Map<URL, Set<NotifyListener>> overrideListeners =
getProviderConfigurationListener(subscribeUrl).getOverrideListeners();
Set<NotifyListener> listeners = overrideListeners.get(subscribeUrl);
if (listeners != null) {
if (listeners.remove(notifyListener)) {
ApplicationModel applicationModel = getApplicationModel(registerUrl.getScopeModel());
if (applicationModel
.modelEnvironment()
.getConfiguration()
.convert(Boolean.class, ENABLE_26X_CONFIGURATION_LISTEN, true)) {
if (!registry.isServiceDiscovery()) {
registry.unsubscribe(subscribeUrl, notifyListener);
}
}
if (applicationModel
.modelEnvironment()
.getConfiguration()
.convert(Boolean.class, ENABLE_CONFIGURATION_LISTEN, true)) {
for (ModuleModel moduleModel : applicationModel.getPubModuleModels()) {
if (moduleModel
.getServiceRepository()
.getExportedServices()
.size()
> 0) {
moduleModel
.getExtensionLoader(GovernanceRuleRepository.class)
.getDefaultExtension()
.removeListener(
subscribeUrl.getServiceKey() + CONFIGURATORS_SUFFIX,
serviceConfigurationListeners.remove(
subscribeUrl.getServiceKey()));
}
}
}
}
if (listeners.isEmpty()) {
overrideListeners.remove(subscribeUrl);
}
}
}
} catch (Throwable t) {
logger.warn(INTERNAL_ERROR, "unknown error in registry module", "", t.getMessage(), t);
}
}
}
@Override
public synchronized void unexport() {
String providerUrlKey = getProviderUrlKey(this.originInvoker);
String registryUrlKey = getRegistryUrlKey(this.originInvoker);
Map<String, ExporterChangeableWrapper<?>> exporterMap = bounds.remove(providerUrlKey);
if (exporterMap != null) {
exporterMap.remove(registryUrlKey);
}
unregister();
doUnExport();
}
public void setRegistered(boolean registered) {
this.registered.set(registered);
}
public boolean isRegistered() {
return registered.get();
}
private void doUnExport() {
try {
exporter.unexport();
} catch (Throwable t) {
logger.warn(INTERNAL_ERROR, "unknown error in registry module", "", t.getMessage(), t);
}
}
public void setSubscribeUrl(URL subscribeUrl) {
this.subscribeUrl = subscribeUrl;
}
public void setRegisterUrl(URL registerUrl) {
this.registerUrl = registerUrl;
}
public void setNotifyListener(NotifyListener notifyListener) {
this.notifyListener = notifyListener;
}
public URL getRegisterUrl() {
return registerUrl;
}
}
}
| 5,479 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocolListener.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.registry.integration;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.rpc.Exporter;
import org.apache.dubbo.rpc.cluster.ClusterInvoker;
import static org.apache.dubbo.common.extension.ExtensionScope.MODULE;
/**
* RegistryProtocol listener is introduced to provide a chance to user to customize or change export and refer behavior
* of RegistryProtocol. For example: re-export or re-refer on the fly when certain condition meets.
*/
@SPI(scope = MODULE)
public interface RegistryProtocolListener {
/**
* Notify RegistryProtocol's listeners when a service is registered
*
* @param registryProtocol RegistryProtocol instance
* @param exporter exporter
* @see RegistryProtocol#export(org.apache.dubbo.rpc.Invoker)
*/
void onExport(RegistryProtocol registryProtocol, Exporter<?> exporter);
/**
* Notify RegistryProtocol's listeners when a service is subscribed
*
* @param registryProtocol RegistryProtocol instance
* @param invoker invoker
* @param url
* @see RegistryProtocol#refer(Class, URL)
*/
void onRefer(RegistryProtocol registryProtocol, ClusterInvoker<?> invoker, URL url, URL registryURL);
/**
* Notify RegistryProtocol's listeners when the protocol is destroyed
*/
void onDestroy();
}
| 5,480 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/ReferenceCountExporter.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.registry.integration;
import org.apache.dubbo.rpc.Exporter;
import org.apache.dubbo.rpc.Invoker;
import java.util.concurrent.atomic.AtomicInteger;
public class ReferenceCountExporter<T> implements Exporter<T> {
private final Exporter<T> exporter;
private final String providerKey;
private final ExporterFactory exporterFactory;
private final AtomicInteger count = new AtomicInteger(0);
public ReferenceCountExporter(Exporter<T> exporter, String providerKey, ExporterFactory exporterFactory) {
this.exporter = exporter;
this.providerKey = providerKey;
this.exporterFactory = exporterFactory;
}
@Override
public Invoker<T> getInvoker() {
return exporter.getInvoker();
}
public void increaseCount() {
count.incrementAndGet();
}
@Override
public void unexport() {
if (count.decrementAndGet() == 0) {
exporter.unexport();
}
exporterFactory.remove(providerKey, this);
}
@Override
public void register() {}
@Override
public void unregister() {}
}
| 5,481 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/DynamicDirectory.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.registry.integration;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.Version;
import org.apache.dubbo.common.config.ConfigurationUtils;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.registry.AddressListener;
import org.apache.dubbo.registry.NotifyListener;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener;
import org.apache.dubbo.registry.client.migration.InvokersChangedListener;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.Cluster;
import org.apache.dubbo.rpc.cluster.Configurator;
import org.apache.dubbo.rpc.cluster.Constants;
import org.apache.dubbo.rpc.cluster.RouterChain;
import org.apache.dubbo.rpc.cluster.RouterFactory;
import org.apache.dubbo.rpc.cluster.SingleRouterChain;
import org.apache.dubbo.rpc.cluster.directory.AbstractDirectory;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.List;
import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_FAILED_SITE_SELECTION;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_DESTROY_SERVICE;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_DESTROY_UNREGISTER_URL;
import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMERS_CATEGORY;
import static org.apache.dubbo.registry.Constants.REGISTER_KEY;
import static org.apache.dubbo.registry.Constants.SIMPLIFIED_KEY;
import static org.apache.dubbo.registry.integration.InterfaceCompatibleRegistryProtocol.DEFAULT_REGISTER_CONSUMER_KEYS;
import static org.apache.dubbo.remoting.Constants.CHECK_KEY;
/**
* DynamicDirectory
*/
public abstract class DynamicDirectory<T> extends AbstractDirectory<T> implements NotifyListener {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DynamicDirectory.class);
protected final Cluster cluster;
protected final RouterFactory routerFactory;
/**
* Initialization at construction time, assertion not null
*/
protected final String serviceKey;
/**
* Initialization at construction time, assertion not null
*/
protected final Class<T> serviceType;
/**
* Initialization at construction time, assertion not null, and always assign non-null value
*/
protected volatile URL directoryUrl;
protected final boolean multiGroup;
/**
* Initialization at the time of injection, the assertion is not null
*/
protected Protocol protocol;
/**
* Initialization at the time of injection, the assertion is not null
*/
protected Registry registry;
protected volatile boolean forbidden = false;
protected boolean shouldRegister;
protected boolean shouldSimplified;
/**
* Initialization at construction time, assertion not null, and always assign not null value
*/
protected volatile URL subscribeUrl;
protected volatile URL registeredConsumerUrl;
/**
* The initial value is null and the midway may be assigned to null, please use the local variable reference
* override rules
* Priority: override>-D>consumer>provider
* Rule one: for a certain provider <ip:port,timeout=100>
* Rule two: for all providers <* ,timeout=5000>
*/
protected volatile List<Configurator> configurators;
protected ServiceInstancesChangedListener serviceListener;
/**
* Should continue route if directory is empty
*/
private final boolean shouldFailFast;
private volatile InvokersChangedListener invokersChangedListener;
private volatile boolean invokersChanged;
public DynamicDirectory(Class<T> serviceType, URL url) {
super(url, true);
ModuleModel moduleModel = url.getOrDefaultModuleModel();
this.cluster = moduleModel.getExtensionLoader(Cluster.class).getAdaptiveExtension();
this.routerFactory = moduleModel.getExtensionLoader(RouterFactory.class).getAdaptiveExtension();
if (serviceType == null) {
throw new IllegalArgumentException("service type is null.");
}
if (StringUtils.isEmpty(url.getServiceKey())) {
throw new IllegalArgumentException("registry serviceKey is null.");
}
this.shouldRegister = !ANY_VALUE.equals(url.getServiceInterface()) && url.getParameter(REGISTER_KEY, true);
this.shouldSimplified = url.getParameter(SIMPLIFIED_KEY, false);
this.serviceType = serviceType;
this.serviceKey = super.getConsumerUrl().getServiceKey();
this.directoryUrl = consumerUrl;
String group = directoryUrl.getGroup("");
this.multiGroup = group != null && (ANY_VALUE.equals(group) || group.contains(","));
this.shouldFailFast = Boolean.parseBoolean(
ConfigurationUtils.getProperty(moduleModel, Constants.SHOULD_FAIL_FAST_KEY, "true"));
}
@Override
public void addServiceListener(ServiceInstancesChangedListener instanceListener) {
this.serviceListener = instanceListener;
}
@Override
public ServiceInstancesChangedListener getServiceListener() {
return this.serviceListener;
}
public void setProtocol(Protocol protocol) {
this.protocol = protocol;
}
public void setRegistry(Registry registry) {
this.registry = registry;
}
public Registry getRegistry() {
return registry;
}
public boolean isShouldRegister() {
return shouldRegister;
}
public void subscribe(URL url) {
setSubscribeUrl(url);
registry.subscribe(url, this);
}
public void unSubscribe(URL url) {
setSubscribeUrl(null);
registry.unsubscribe(url, this);
}
@Override
public List<Invoker<T>> doList(
SingleRouterChain<T> singleRouterChain, BitList<Invoker<T>> invokers, Invocation invocation) {
if (forbidden && shouldFailFast) {
// 1. No service provider 2. Service providers are disabled
throw new RpcException(
RpcException.FORBIDDEN_EXCEPTION,
"No provider available from registry " + this
+ " for service " + getConsumerUrl().getServiceKey() + " on consumer "
+ NetUtils.getLocalHost()
+ " use dubbo version " + Version.getVersion()
+ ", please check status of providers(disabled, not registered or in blacklist).");
}
if (multiGroup) {
return this.getInvokers();
}
try {
// Get invokers from cache, only runtime routers will be executed.
List<Invoker<T>> result = singleRouterChain.route(getConsumerUrl(), invokers, invocation);
return result == null ? BitList.emptyList() : result;
} catch (Throwable t) {
// 2-1 - Failed to execute routing.
logger.error(
CLUSTER_FAILED_SITE_SELECTION,
"",
"",
"Failed to execute router: " + getUrl() + ", cause: " + t.getMessage(),
t);
return BitList.emptyList();
}
}
@Override
public Class<T> getInterface() {
return serviceType;
}
@Override
public List<Invoker<T>> getAllInvokers() {
return this.getInvokers();
}
/**
* The currently effective consumer url
*
* @return URL
*/
@Override
public URL getConsumerUrl() {
return this.directoryUrl;
}
/**
* The original consumer url
*
* @return URL
*/
public URL getOriginalConsumerUrl() {
return this.consumerUrl;
}
/**
* The url registered to registry or metadata center
*
* @return URL
*/
public URL getRegisteredConsumerUrl() {
return registeredConsumerUrl;
}
/**
* The url used to subscribe from registry
*
* @return URL
*/
public URL getSubscribeUrl() {
return subscribeUrl;
}
public void setSubscribeUrl(URL subscribeUrl) {
this.subscribeUrl = subscribeUrl;
}
public void setRegisteredConsumerUrl(URL url) {
if (!shouldSimplified) {
this.registeredConsumerUrl =
url.addParameters(CATEGORY_KEY, CONSUMERS_CATEGORY, CHECK_KEY, String.valueOf(false));
} else {
this.registeredConsumerUrl = URL.valueOf(url, DEFAULT_REGISTER_CONSUMER_KEYS, null)
.addParameters(CATEGORY_KEY, CONSUMERS_CATEGORY, CHECK_KEY, String.valueOf(false));
}
}
public void buildRouterChain(URL url) {
this.setRouterChain(RouterChain.buildChain(getInterface(), url));
}
@Override
public boolean isAvailable() {
if (isDestroyed() || this.forbidden) {
return false;
}
for (Invoker<T> validInvoker : getValidInvokers()) {
if (validInvoker.isAvailable()) {
return true;
} else {
addInvalidateInvoker(validInvoker);
}
}
return false;
}
@Override
public void destroy() {
if (isDestroyed()) {
return;
}
// unregister.
try {
if (getRegisteredConsumerUrl() != null && registry != null && registry.isAvailable()) {
registry.unregister(getRegisteredConsumerUrl());
}
} catch (Throwable t) {
// 1-8: Failed to unregister / unsubscribe url on destroy.
logger.warn(
REGISTRY_FAILED_DESTROY_UNREGISTER_URL,
"",
"",
"unexpected error when unregister service " + serviceKey + " from registry: " + registry.getUrl(),
t);
}
// unsubscribe.
try {
if (getSubscribeUrl() != null && registry != null && registry.isAvailable()) {
registry.unsubscribe(getSubscribeUrl(), this);
}
} catch (Throwable t) {
// 1-8: Failed to unregister / unsubscribe url on destroy.
logger.warn(
REGISTRY_FAILED_DESTROY_UNREGISTER_URL,
"",
"",
"unexpected error when unsubscribe service " + serviceKey + " from registry: " + registry.getUrl(),
t);
}
ExtensionLoader<AddressListener> addressListenerExtensionLoader =
getUrl().getOrDefaultModuleModel().getExtensionLoader(AddressListener.class);
List<AddressListener> supportedListeners =
addressListenerExtensionLoader.getActivateExtension(getUrl(), (String[]) null);
if (CollectionUtils.isNotEmpty(supportedListeners)) {
for (AddressListener addressListener : supportedListeners) {
addressListener.destroy(getConsumerUrl(), this);
}
}
synchronized (this) {
try {
destroyAllInvokers();
} catch (Throwable t) {
// 1-15 - Failed to destroy service.
logger.warn(REGISTRY_FAILED_DESTROY_SERVICE, "", "", "Failed to destroy service " + serviceKey, t);
}
routerChain.destroy();
invokersChangedListener = null;
serviceListener = null;
super.destroy(); // must be executed after unsubscribing
}
}
@Override
public void discordAddresses() {
try {
destroyAllInvokers();
} catch (Throwable t) {
// 1-15 - Failed to destroy service.
logger.warn(REGISTRY_FAILED_DESTROY_SERVICE, "", "", "Failed to destroy service " + serviceKey, t);
}
}
public synchronized void setInvokersChangedListener(InvokersChangedListener listener) {
this.invokersChangedListener = listener;
if (invokersChangedListener != null && invokersChanged) {
invokersChangedListener.onChange();
}
}
protected synchronized void invokersChanged() {
refreshInvoker();
invokersChanged = true;
if (invokersChangedListener != null) {
invokersChangedListener.onChange();
invokersChanged = false;
}
}
@Override
public boolean isNotificationReceived() {
return invokersChanged;
}
protected abstract void destroyAllInvokers();
protected abstract void refreshOverrideAndInvoker(List<URL> urls);
}
| 5,482 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.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.registry.integration;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.URLBuilder;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.common.constants.RegistryConstants;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.url.component.DubboServiceAddressURL;
import org.apache.dubbo.common.url.component.ServiceAddressURL;
import org.apache.dubbo.common.url.component.ServiceConfigURL;
import org.apache.dubbo.common.utils.Assert;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.common.utils.UrlUtils;
import org.apache.dubbo.metrics.event.MetricsEventBus;
import org.apache.dubbo.metrics.registry.event.RegistryEvent;
import org.apache.dubbo.registry.AddressListener;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.Configurator;
import org.apache.dubbo.rpc.cluster.Router;
import org.apache.dubbo.rpc.cluster.directory.StaticDirectory;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import org.apache.dubbo.rpc.cluster.support.ClusterUtils;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.DISABLED_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PROTOCOL;
import static org.apache.dubbo.common.constants.CommonConstants.ENABLED_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_REGISTER_MODE;
import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_INIT_SERIALIZATION_OPTIMIZER;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_REFER_INVOKER;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_UNSUPPORTED;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_FAILED_CONVERT_URL;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_EMPTY_ADDRESS;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_DESTROY_SERVICE;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_UNSUPPORTED_CATEGORY;
import static org.apache.dubbo.common.constants.RegistryConstants.APP_DYNAMIC_CONFIGURATORS_CATEGORY;
import static org.apache.dubbo.common.constants.RegistryConstants.COMPATIBLE_CONFIG_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_CATEGORY;
import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_CATEGORY;
import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_HASHMAP_LOAD_FACTOR;
import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_CONFIGURATORS_CATEGORY;
import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL;
import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDERS_CATEGORY;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTER_MODE_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.ROUTERS_CATEGORY;
import static org.apache.dubbo.common.constants.RegistryConstants.ROUTE_PROTOCOL;
import static org.apache.dubbo.registry.Constants.CONFIGURATORS_SUFFIX;
import static org.apache.dubbo.registry.Constants.ENABLE_26X_CONFIGURATION_LISTEN;
import static org.apache.dubbo.rpc.Constants.MOCK_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.ROUTER_KEY;
import static org.apache.dubbo.rpc.model.ScopeModelUtil.getModuleModel;
/**
* RegistryDirectory
*/
public class RegistryDirectory<T> extends DynamicDirectory<T> {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(RegistryDirectory.class);
private final ConsumerConfigurationListener consumerConfigurationListener;
private ReferenceConfigurationListener referenceConfigurationListener;
/**
* Map<url, Invoker> cache service url to invoker mapping.
* The initial value is null and the midway may be assigned to null, please use the local variable reference
*/
protected volatile Map<URL, Invoker<T>> urlInvokerMap;
/**
* The initial value is null and the midway may be assigned to null, please use the local variable reference
*/
protected volatile Set<URL> cachedInvokerUrls;
private final ModuleModel moduleModel;
public RegistryDirectory(Class<T> serviceType, URL url) {
super(serviceType, url);
moduleModel = getModuleModel(url.getScopeModel());
consumerConfigurationListener = getConsumerConfigurationListener(moduleModel);
}
@Override
public void subscribe(URL url) {
// Fail-fast detection protocol spi
String queryProtocols = this.queryMap.get(PROTOCOL_KEY);
if (StringUtils.isNotBlank(queryProtocols)) {
String[] acceptProtocols = queryProtocols.split(",");
for (String acceptProtocol : acceptProtocols) {
if (!moduleModel
.getApplicationModel()
.getExtensionLoader(Protocol.class)
.hasExtension(acceptProtocol)) {
throw new IllegalStateException("No such extension org.apache.dubbo.rpc.Protocol by name "
+ acceptProtocol + ", please check whether related SPI module is missing");
}
}
}
ApplicationModel applicationModel = url.getApplicationModel();
String registryClusterName = registry.getUrl()
.getParameter(
RegistryConstants.REGISTRY_CLUSTER_KEY,
registry.getUrl().getParameter(PROTOCOL_KEY));
MetricsEventBus.post(RegistryEvent.toSubscribeEvent(applicationModel, registryClusterName), () -> {
super.subscribe(url);
return null;
});
if (moduleModel
.modelEnvironment()
.getConfiguration()
.convert(Boolean.class, org.apache.dubbo.registry.Constants.ENABLE_CONFIGURATION_LISTEN, true)) {
consumerConfigurationListener.addNotifyListener(this);
referenceConfigurationListener = new ReferenceConfigurationListener(moduleModel, this, url);
}
}
private ConsumerConfigurationListener getConsumerConfigurationListener(ModuleModel moduleModel) {
return moduleModel
.getBeanFactory()
.getOrRegisterBean(
ConsumerConfigurationListener.class, type -> new ConsumerConfigurationListener(moduleModel));
}
@Override
public void unSubscribe(URL url) {
super.unSubscribe(url);
if (moduleModel
.modelEnvironment()
.getConfiguration()
.convert(Boolean.class, org.apache.dubbo.registry.Constants.ENABLE_CONFIGURATION_LISTEN, true)) {
consumerConfigurationListener.removeNotifyListener(this);
if (referenceConfigurationListener != null) {
referenceConfigurationListener.stop();
}
}
}
@Override
public void destroy() {
super.destroy();
if (moduleModel
.modelEnvironment()
.getConfiguration()
.convert(Boolean.class, org.apache.dubbo.registry.Constants.ENABLE_CONFIGURATION_LISTEN, true)) {
consumerConfigurationListener.removeNotifyListener(this);
if (referenceConfigurationListener != null) {
referenceConfigurationListener.stop();
}
}
}
@Override
public synchronized void notify(List<URL> urls) {
if (isDestroyed()) {
return;
}
Map<String, List<URL>> categoryUrls = urls.stream()
.filter(Objects::nonNull)
.filter(this::isValidCategory)
.filter(this::isNotCompatibleFor26x)
.collect(Collectors.groupingBy(this::judgeCategory));
if (moduleModel
.modelEnvironment()
.getConfiguration()
.convert(Boolean.class, ENABLE_26X_CONFIGURATION_LISTEN, true)) {
List<URL> configuratorURLs = categoryUrls.getOrDefault(CONFIGURATORS_CATEGORY, Collections.emptyList());
this.configurators = Configurator.toConfigurators(configuratorURLs).orElse(this.configurators);
List<URL> routerURLs = categoryUrls.getOrDefault(ROUTERS_CATEGORY, Collections.emptyList());
toRouters(routerURLs).ifPresent(this::addRouters);
}
// providers
List<URL> providerURLs = categoryUrls.getOrDefault(PROVIDERS_CATEGORY, Collections.emptyList());
// 3.x added for extend URL address
ExtensionLoader<AddressListener> addressListenerExtensionLoader =
getUrl().getOrDefaultModuleModel().getExtensionLoader(AddressListener.class);
List<AddressListener> supportedListeners =
addressListenerExtensionLoader.getActivateExtension(getUrl(), (String[]) null);
if (supportedListeners != null && !supportedListeners.isEmpty()) {
for (AddressListener addressListener : supportedListeners) {
providerURLs = addressListener.notify(providerURLs, getConsumerUrl(), this);
}
}
refreshOverrideAndInvoker(providerURLs);
}
@Override
public boolean isServiceDiscovery() {
return false;
}
private String judgeCategory(URL url) {
if (UrlUtils.isConfigurator(url)) {
return CONFIGURATORS_CATEGORY;
} else if (UrlUtils.isRoute(url)) {
return ROUTERS_CATEGORY;
} else if (UrlUtils.isProvider(url)) {
return PROVIDERS_CATEGORY;
}
return "";
}
// RefreshOverrideAndInvoker will be executed by registryCenter and configCenter, so it should be synchronized.
@Override
protected synchronized void refreshOverrideAndInvoker(List<URL> urls) {
// mock zookeeper://xxx?mock=return null
this.directoryUrl = overrideWithConfigurator(getOriginalConsumerUrl());
refreshInvoker(urls);
}
/**
* Convert the invokerURL list to the Invoker Map. The rules of the conversion are as follows:
* <ol>
* <li> If URL has been converted to invoker, it is no longer re-referenced and obtained directly from the cache,
* and notice that any parameter changes in the URL will be re-referenced.</li>
* <li>If the incoming invoker list is not empty, it means that it is the latest invoker list.</li>
* <li>If the list of incoming invokerUrl is empty, It means that the rule is only a override rule or a route
* rule, which needs to be re-contrasted to decide whether to re-reference.</li>
* </ol>
*
* @param invokerUrls this parameter can't be null
*/
private void refreshInvoker(List<URL> invokerUrls) {
Assert.notNull(invokerUrls, "invokerUrls should not be null");
if (invokerUrls.size() == 1
&& invokerUrls.get(0) != null
&& EMPTY_PROTOCOL.equals(invokerUrls.get(0).getProtocol())) {
refreshRouter(
BitList.emptyList(), () -> this.forbidden = true // Forbid to access
);
destroyAllInvokers(); // Close all invokers
} else {
this.forbidden = false; // Allow to access
if (invokerUrls == Collections.<URL>emptyList()) {
invokerUrls = new ArrayList<>();
}
// use local reference to avoid NPE as this.cachedInvokerUrls will be set null by destroyAllInvokers().
Set<URL> localCachedInvokerUrls = this.cachedInvokerUrls;
if (invokerUrls.isEmpty()) {
if (CollectionUtils.isNotEmpty(localCachedInvokerUrls)) {
// 1-4 Empty address.
logger.warn(
REGISTRY_EMPTY_ADDRESS,
"configuration ",
"",
"Service" + serviceKey
+ " received empty address list with no EMPTY protocol set, trigger empty protection.");
invokerUrls.addAll(localCachedInvokerUrls);
}
} else {
localCachedInvokerUrls = new HashSet<>();
localCachedInvokerUrls.addAll(invokerUrls); // Cached invoker urls, convenient for comparison
this.cachedInvokerUrls = localCachedInvokerUrls;
}
if (invokerUrls.isEmpty()) {
return;
}
// use local reference to avoid NPE as this.urlInvokerMap will be set null concurrently at
// destroyAllInvokers().
Map<URL, Invoker<T>> localUrlInvokerMap = this.urlInvokerMap;
// can't use local reference as oldUrlInvokerMap's mappings might be removed directly at toInvokers().
Map<URL, Invoker<T>> oldUrlInvokerMap = null;
if (localUrlInvokerMap != null) {
// the initial capacity should be set greater than the maximum number of entries divided by the load
// factor to avoid resizing.
oldUrlInvokerMap =
new LinkedHashMap<>(Math.round(1 + localUrlInvokerMap.size() / DEFAULT_HASHMAP_LOAD_FACTOR));
localUrlInvokerMap.forEach(oldUrlInvokerMap::put);
}
Map<URL, Invoker<T>> newUrlInvokerMap =
toInvokers(oldUrlInvokerMap, invokerUrls); // Translate url list to Invoker map
/*
* If the calculation is wrong, it is not processed.
*
* 1. The protocol configured by the client is inconsistent with the protocol of the server.
* eg: consumer protocol = dubbo, provider only has other protocol services(rest).
* 2. The registration center is not robust and pushes illegal specification data.
*
*/
if (CollectionUtils.isEmptyMap(newUrlInvokerMap)) {
// 3-1 - Failed to convert the URL address into Invokers.
logger.error(
PROXY_FAILED_CONVERT_URL,
"inconsistency between the client protocol and the protocol of the server",
"",
"urls to invokers error",
new IllegalStateException("urls to invokers error. invokerUrls.size :" + invokerUrls.size()
+ ", invoker.size :0. urls :" + invokerUrls.toString()));
return;
}
List<Invoker<T>> newInvokers = Collections.unmodifiableList(new ArrayList<>(newUrlInvokerMap.values()));
BitList<Invoker<T>> finalInvokers =
multiGroup ? new BitList<>(toMergeInvokerList(newInvokers)) : new BitList<>(newInvokers);
// pre-route and build cache
refreshRouter(finalInvokers.clone(), () -> this.setInvokers(finalInvokers));
this.urlInvokerMap = newUrlInvokerMap;
try {
destroyUnusedInvokers(oldUrlInvokerMap, newUrlInvokerMap); // Close the unused Invoker
} catch (Exception e) {
logger.warn(REGISTRY_FAILED_DESTROY_SERVICE, "", "", "destroyUnusedInvokers error. ", e);
}
// notify invokers refreshed
this.invokersChanged();
}
logger.info("Received invokers changed event from registry. " + "Registry type: interface. "
+ "Service Key: "
+ getConsumerUrl().getServiceKey() + ". " + "Urls Size : "
+ invokerUrls.size() + ". " + "Invokers Size : "
+ getInvokers().size() + ". " + "Available Size: "
+ getValidInvokers().size() + ". " + "Available Invokers : "
+ joinValidInvokerAddresses());
}
private List<Invoker<T>> toMergeInvokerList(List<Invoker<T>> invokers) {
List<Invoker<T>> mergedInvokers = new ArrayList<>();
Map<String, List<Invoker<T>>> groupMap = new HashMap<>();
for (Invoker<T> invoker : invokers) {
String group = invoker.getUrl().getGroup("");
groupMap.computeIfAbsent(group, k -> new ArrayList<>());
groupMap.get(group).add(invoker);
}
if (groupMap.size() == 1) {
mergedInvokers.addAll(groupMap.values().iterator().next());
} else if (groupMap.size() > 1) {
for (List<Invoker<T>> groupList : groupMap.values()) {
StaticDirectory<T> staticDirectory = new StaticDirectory<>(groupList);
staticDirectory.buildRouterChain();
mergedInvokers.add(cluster.join(staticDirectory, false));
}
} else {
mergedInvokers = invokers;
}
return mergedInvokers;
}
/**
* @param urls
* @return null : no routers ,do nothing
* else :routers list
*/
private Optional<List<Router>> toRouters(List<URL> urls) {
if (urls == null || urls.isEmpty()) {
return Optional.empty();
}
List<Router> routers = new ArrayList<>();
for (URL url : urls) {
if (EMPTY_PROTOCOL.equals(url.getProtocol())) {
continue;
}
String routerType = url.getParameter(ROUTER_KEY);
if (routerType != null && routerType.length() > 0) {
url = url.setProtocol(routerType);
}
try {
Router router = routerFactory.getRouter(url);
if (!routers.contains(router)) {
routers.add(router);
}
} catch (Throwable t) {
logger.error(PROXY_FAILED_CONVERT_URL, "", "", "convert router url to router error, url:" + url, t);
}
}
return Optional.of(routers);
}
/**
* Turn urls into invokers, and if url has been referred, will not re-reference.
* the items that will be put into newUrlInvokeMap will be removed from oldUrlInvokerMap.
*
* @param oldUrlInvokerMap it might be modified during the process.
* @param urls
* @return invokers
*/
private Map<URL, Invoker<T>> toInvokers(Map<URL, Invoker<T>> oldUrlInvokerMap, List<URL> urls) {
Map<URL, Invoker<T>> newUrlInvokerMap =
new ConcurrentHashMap<>(urls == null ? 1 : (int) (urls.size() / 0.75f + 1));
if (urls == null || urls.isEmpty()) {
return newUrlInvokerMap;
}
String queryProtocols = this.queryMap.get(PROTOCOL_KEY);
for (URL providerUrl : urls) {
if (!checkProtocolValid(queryProtocols, providerUrl)) {
continue;
}
URL url = mergeUrl(providerUrl);
// Cache key is url that does not merge with consumer side parameters,
// regardless of how the consumer combines parameters,
// if the server url changes, then refer again
Invoker<T> invoker = oldUrlInvokerMap == null ? null : oldUrlInvokerMap.remove(url);
if (invoker == null) { // Not in the cache, refer again
try {
boolean enabled = true;
if (url.hasParameter(DISABLED_KEY)) {
enabled = !url.getParameter(DISABLED_KEY, false);
} else {
enabled = url.getParameter(ENABLED_KEY, true);
}
if (enabled) {
invoker = protocol.refer(serviceType, url);
}
} catch (Throwable t) {
// Thrown by AbstractProtocol.optimizeSerialization()
if (t instanceof RpcException && t.getMessage().contains("serialization optimizer")) {
// 4-2 - serialization optimizer class initialization failed.
logger.error(
PROTOCOL_FAILED_INIT_SERIALIZATION_OPTIMIZER,
"typo in optimizer class",
"",
"Failed to refer invoker for interface:" + serviceType + ",url:(" + url + ")"
+ t.getMessage(),
t);
} else {
// 4-3 - Failed to refer invoker by other reason.
logger.error(
PROTOCOL_FAILED_REFER_INVOKER,
"",
"",
"Failed to refer invoker for interface:" + serviceType + ",url:(" + url + ")"
+ t.getMessage(),
t);
}
}
if (invoker != null) { // Put new invoker in cache
newUrlInvokerMap.put(url, invoker);
}
} else {
newUrlInvokerMap.put(url, invoker);
}
}
return newUrlInvokerMap;
}
private boolean checkProtocolValid(String queryProtocols, URL providerUrl) {
// If protocol is configured at the reference side, only the matching protocol is selected
if (queryProtocols != null && queryProtocols.length() > 0) {
boolean accept = false;
String[] acceptProtocols = queryProtocols.split(",");
for (String acceptProtocol : acceptProtocols) {
if (providerUrl.getProtocol().equals(acceptProtocol)) {
accept = true;
break;
}
}
if (!accept) {
return false;
}
}
if (EMPTY_PROTOCOL.equals(providerUrl.getProtocol())) {
return false;
}
if (!getUrl().getOrDefaultFrameworkModel()
.getExtensionLoader(Protocol.class)
.hasExtension(providerUrl.getProtocol())) {
// 4-1 - Unsupported protocol
logger.error(
PROTOCOL_UNSUPPORTED,
"protocol extension does not installed",
"",
"Unsupported protocol.",
new IllegalStateException("Unsupported protocol " + providerUrl.getProtocol() + " in notified url: "
+ providerUrl + " from registry " + getUrl().getAddress() + " to consumer "
+ NetUtils.getLocalHost() + ", supported protocol: "
+ getUrl().getOrDefaultFrameworkModel()
.getExtensionLoader(Protocol.class)
.getSupportedExtensions()));
return false;
}
return true;
}
/**
* Merge url parameters. the order is: override > -D >Consumer > Provider
*
* @param providerUrl
* @return
*/
private URL mergeUrl(URL providerUrl) {
if (providerUrl instanceof ServiceAddressURL) {
providerUrl = overrideWithConfigurator(providerUrl);
} else {
providerUrl = moduleModel
.getApplicationModel()
.getBeanFactory()
.getBean(ClusterUtils.class)
.mergeUrl(providerUrl, queryMap); // Merge the consumer side parameters
providerUrl = overrideWithConfigurator(providerUrl);
providerUrl = providerUrl.addParameter(
Constants.CHECK_KEY,
String.valueOf(
false)); // Do not check whether the connection is successful or not, always create Invoker!
}
// FIXME, kept for mock
if (providerUrl.hasParameter(MOCK_KEY) || providerUrl.getAnyMethodParameter(MOCK_KEY) != null) {
providerUrl = providerUrl.removeParameter(MOCK_KEY);
}
if ((providerUrl.getPath() == null || providerUrl.getPath().length() == 0)
&& DUBBO_PROTOCOL.equals(providerUrl.getProtocol())) { // Compatible version 1.0
// fix by tony.chenl DUBBO-44
String path = directoryUrl.getServiceInterface();
if (path != null) {
int i = path.indexOf('/');
if (i >= 0) {
path = path.substring(i + 1);
}
i = path.lastIndexOf(':');
if (i >= 0) {
path = path.substring(0, i);
}
providerUrl = providerUrl.setPath(path);
}
}
return providerUrl;
}
protected URL overrideWithConfigurator(URL providerUrl) {
// override url with configurator from "override://" URL for dubbo 2.6 and before
providerUrl = overrideWithConfigurators(this.configurators, providerUrl);
// override url with configurator from "app-name.configurators"
providerUrl = overrideWithConfigurators(consumerConfigurationListener.getConfigurators(), providerUrl);
// override url with configurator from configurators from "service-name.configurators"
if (referenceConfigurationListener != null) {
providerUrl = overrideWithConfigurators(referenceConfigurationListener.getConfigurators(), providerUrl);
}
return providerUrl;
}
private URL overrideWithConfigurators(List<Configurator> configurators, URL url) {
if (CollectionUtils.isNotEmpty(configurators)) {
if (url instanceof DubboServiceAddressURL) {
DubboServiceAddressURL interfaceAddressURL = (DubboServiceAddressURL) url;
URL overriddenURL = interfaceAddressURL.getOverrideURL();
if (overriddenURL == null) {
String appName = interfaceAddressURL.getApplication();
String side = interfaceAddressURL.getSide();
overriddenURL = URLBuilder.from(interfaceAddressURL)
.clearParameters()
.addParameter(APPLICATION_KEY, appName)
.addParameter(SIDE_KEY, side)
.build();
}
for (Configurator configurator : configurators) {
overriddenURL = configurator.configure(overriddenURL);
}
url = new DubboServiceAddressURL(
interfaceAddressURL.getUrlAddress(),
interfaceAddressURL.getUrlParam(),
interfaceAddressURL.getConsumerURL(),
(ServiceConfigURL) overriddenURL);
} else {
for (Configurator configurator : configurators) {
url = configurator.configure(url);
}
}
}
return url;
}
/**
* Close all invokers
*/
@Override
protected void destroyAllInvokers() {
Map<URL, Invoker<T>> localUrlInvokerMap = this.urlInvokerMap; // local reference
if (!CollectionUtils.isEmptyMap(localUrlInvokerMap)) {
for (Invoker<T> invoker : new ArrayList<>(localUrlInvokerMap.values())) {
try {
invoker.destroy();
} catch (Throwable t) {
// 1-15 - Failed to destroy service
logger.warn(
REGISTRY_FAILED_DESTROY_SERVICE,
"",
"",
"Failed to destroy service " + serviceKey + " to provider " + invoker.getUrl(),
t);
}
}
localUrlInvokerMap.clear();
}
this.urlInvokerMap = null;
this.cachedInvokerUrls = null;
destroyInvokers();
}
private void destroyUnusedInvokers(Map<URL, Invoker<T>> oldUrlInvokerMap, Map<URL, Invoker<T>> newUrlInvokerMap) {
if (CollectionUtils.isEmptyMap(newUrlInvokerMap)) {
destroyAllInvokers();
return;
}
if (CollectionUtils.isEmptyMap(oldUrlInvokerMap)) {
return;
}
for (Map.Entry<URL, Invoker<T>> entry : oldUrlInvokerMap.entrySet()) {
Invoker<T> invoker = entry.getValue();
if (invoker != null) {
try {
invoker.destroy();
if (logger.isDebugEnabled()) {
logger.debug("destroy invoker[" + invoker.getUrl() + "] success. ");
}
} catch (Exception e) {
logger.warn(
REGISTRY_FAILED_DESTROY_SERVICE,
"",
"",
"destroy invoker[" + invoker.getUrl() + "] failed. " + e.getMessage(),
e);
}
}
}
logger.info(
"New url total size, " + newUrlInvokerMap.size() + ", destroyed total size " + oldUrlInvokerMap.size());
}
/**
* Haomin: added for test purpose
*/
public Map<URL, Invoker<T>> getUrlInvokerMap() {
return urlInvokerMap;
}
private boolean isValidCategory(URL url) {
String category = url.getCategory(DEFAULT_CATEGORY);
if ((ROUTERS_CATEGORY.equals(category) || ROUTE_PROTOCOL.equals(url.getProtocol()))
|| PROVIDERS_CATEGORY.equals(category)
|| CONFIGURATORS_CATEGORY.equals(category)
|| DYNAMIC_CONFIGURATORS_CATEGORY.equals(category)
|| APP_DYNAMIC_CONFIGURATORS_CATEGORY.equals(category)) {
return true;
}
// 1-16 - Unsupported category in NotifyListener
logger.warn(
REGISTRY_UNSUPPORTED_CATEGORY,
"",
"",
"Unsupported category " + category + " in notified url: " + url + " from registry "
+ getUrl().getAddress() + " to consumer " + NetUtils.getLocalHost());
return false;
}
@Override
protected Map<String, String> getDirectoryMeta() {
String registryKey = Optional.ofNullable(getRegistry())
.map(Registry::getUrl)
.map(url -> url.getParameter(RegistryConstants.REGISTRY_CLUSTER_KEY, url.getProtocol()))
.orElse("unknown");
Map<String, String> metas = new HashMap<>();
metas.put(REGISTRY_KEY, registryKey);
metas.put(REGISTER_MODE_KEY, INTERFACE_REGISTER_MODE);
return metas;
}
private boolean isNotCompatibleFor26x(URL url) {
return StringUtils.isEmpty(url.getParameter(COMPATIBLE_CONFIG_KEY));
}
private static class ReferenceConfigurationListener extends AbstractConfiguratorListener {
private RegistryDirectory directory;
private URL url;
ReferenceConfigurationListener(ModuleModel moduleModel, RegistryDirectory directory, URL url) {
super(moduleModel);
this.directory = directory;
this.url = url;
this.initWith(DynamicConfiguration.getRuleKey(url) + CONFIGURATORS_SUFFIX);
}
void stop() {
this.stopListen(DynamicConfiguration.getRuleKey(url) + CONFIGURATORS_SUFFIX);
}
@Override
protected void notifyOverrides() {
// to notify configurator/router changes
directory.refreshOverrideAndInvoker(Collections.emptyList());
}
}
private static class ConsumerConfigurationListener extends AbstractConfiguratorListener {
List<RegistryDirectory> listeners = new ArrayList<>();
ConsumerConfigurationListener(ModuleModel moduleModel) {
super(moduleModel);
this.initWith(moduleModel.getApplicationModel().getApplicationName() + CONFIGURATORS_SUFFIX);
}
void addNotifyListener(RegistryDirectory listener) {
this.listeners.add(listener);
}
void removeNotifyListener(RegistryDirectory listener) {
this.listeners.remove(listener);
}
@Override
protected void notifyOverrides() {
listeners.forEach(listener -> listener.refreshOverrideAndInvoker(Collections.emptyList()));
}
}
@Override
public String toString() {
return "RegistryDirectory(" + "registry: " + getUrl().getAddress() + ")-" + super.toString();
}
}
| 5,483 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/AbstractConfiguratorListener.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.registry.integration;
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.ConfigurationListener;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.cluster.Configurator;
import org.apache.dubbo.rpc.cluster.configurator.parser.ConfigParser;
import org.apache.dubbo.rpc.cluster.governance.GovernanceRuleRepository;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_PARSE_DYNAMIC_CONFIG;
import static org.apache.dubbo.rpc.Constants.ACCESS_LOG_FIXED_PATH_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.ROUTER_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.RULE_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.RUNTIME_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.TYPE_KEY;
/**
* AbstractConfiguratorListener
*/
public abstract class AbstractConfiguratorListener implements ConfigurationListener {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(AbstractConfiguratorListener.class);
protected List<Configurator> configurators = Collections.emptyList();
protected GovernanceRuleRepository ruleRepository;
protected Set<String> securityKey = new HashSet<>();
protected ModuleModel moduleModel;
public AbstractConfiguratorListener(ModuleModel moduleModel) {
this.moduleModel = moduleModel;
ruleRepository =
moduleModel.getExtensionLoader(GovernanceRuleRepository.class).getDefaultExtension();
initSecurityKey();
}
private void initSecurityKey() {
// FileRouterFactory key
securityKey.add(ACCESS_LOG_FIXED_PATH_KEY);
securityKey.add(ROUTER_KEY);
securityKey.add(RULE_KEY);
securityKey.add(RUNTIME_KEY);
securityKey.add(TYPE_KEY);
}
protected final void initWith(String key) {
ruleRepository.addListener(key, this);
String rawConfig = ruleRepository.getRule(key, DynamicConfiguration.DEFAULT_GROUP);
if (!StringUtils.isEmpty(rawConfig)) {
genConfiguratorsFromRawRule(rawConfig);
}
}
protected final void stopListen(String key) {
ruleRepository.removeListener(key, this);
}
@Override
public void process(ConfigChangedEvent event) {
if (logger.isInfoEnabled()) {
logger.info("Notification of overriding rule, change type is: " + event.getChangeType()
+ ", raw config content is:\n " + event.getContent());
}
if (event.getChangeType().equals(ConfigChangeType.DELETED)) {
configurators.clear();
} else {
// ADDED or MODIFIED
if (!genConfiguratorsFromRawRule(event.getContent())) {
return;
}
}
notifyOverrides();
}
private boolean genConfiguratorsFromRawRule(String rawConfig) {
List<URL> urls;
try {
// parseConfigurators will recognize app/service config automatically.
urls = ConfigParser.parseConfigurators(rawConfig);
} catch (Exception e) {
// 1-14 - Failed to parse raw dynamic config.
logger.warn(
REGISTRY_FAILED_PARSE_DYNAMIC_CONFIG,
"",
"",
"Failed to parse raw dynamic config and it will not take effect, the raw config is: " + rawConfig
+ ", cause: " + e.getMessage());
return false;
}
List<URL> safeUrls = urls.stream()
.map(url -> url.removeParameters(securityKey))
.map(url -> url.setScopeModel(moduleModel))
.collect(Collectors.toList());
configurators = Configurator.toConfigurators(safeUrls).orElse(configurators);
return true;
}
protected abstract void notifyOverrides();
public List<Configurator> getConfigurators() {
return configurators;
}
public void setConfigurators(List<Configurator> configurators) {
this.configurators = configurators;
}
}
| 5,484 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/status/RegistryStatusChecker.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.registry.status;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.status.Status;
import org.apache.dubbo.common.status.StatusChecker;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.support.RegistryManager;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Collection;
/**
* RegistryStatusChecker
*
*/
@Activate
public class RegistryStatusChecker implements StatusChecker {
private ApplicationModel applicationModel;
public RegistryStatusChecker(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
}
@Override
public Status check() {
RegistryManager registryManager = applicationModel.getBeanFactory().getBean(RegistryManager.class);
Collection<Registry> registries = registryManager.getRegistries();
if (registries.isEmpty()) {
return new Status(Status.Level.UNKNOWN);
}
Status.Level level = Status.Level.OK;
StringBuilder buf = new StringBuilder();
for (Registry registry : registries) {
if (buf.length() > 0) {
buf.append(',');
}
buf.append(registry.getUrl().getAddress());
if (!registry.isAvailable()) {
level = Status.Level.ERROR;
buf.append("(disconnected)");
} else {
buf.append("(connected)");
}
}
return new Status(level, buf.toString());
}
}
| 5,485 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/SkipFailbackWrapperException.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.registry.support;
/**
* Wrapper Exception, it is used to indicate that {@link FailbackRegistry} skips Failback.
* <p>
* NOTE: Expect to find other more conventional ways of instruction.
*
* @see FailbackRegistry
*/
public class SkipFailbackWrapperException extends RuntimeException {
public SkipFailbackWrapperException(Throwable cause) {
super(cause);
}
@Override
public synchronized Throwable fillInStackTrace() {
// do nothing
return null;
}
}
| 5,486 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/CacheableFailbackRegistry.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.registry.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.URLBuilder;
import org.apache.dubbo.common.URLStrParser;
import org.apache.dubbo.common.config.ConfigurationUtils;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository;
import org.apache.dubbo.common.url.component.DubboServiceAddressURL;
import org.apache.dubbo.common.url.component.ServiceAddressURL;
import org.apache.dubbo.common.url.component.URLAddress;
import org.apache.dubbo.common.url.component.URLParam;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.common.utils.UrlUtils;
import org.apache.dubbo.registry.NotifyListener;
import org.apache.dubbo.registry.ProviderFirstParams;
import org.apache.dubbo.rpc.model.ScopeModel;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import static org.apache.dubbo.common.URLStrParser.ENCODED_AND_MARK;
import static org.apache.dubbo.common.URLStrParser.ENCODED_PID_KEY;
import static org.apache.dubbo.common.URLStrParser.ENCODED_QUESTION_MARK;
import static org.apache.dubbo.common.URLStrParser.ENCODED_TIMESTAMP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.CACHE_CLEAR_TASK_INTERVAL;
import static org.apache.dubbo.common.constants.CommonConstants.CACHE_CLEAR_WAITING_THRESHOLD;
import static org.apache.dubbo.common.constants.CommonConstants.CHECK_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO;
import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR;
import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_SEPARATOR_ENCODED;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_PROPERTY_TYPE_MISMATCH;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_EMPTY_ADDRESS;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_CLEAR_CACHED_URLS;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_URL_EVICTING;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_NO_PARAMETERS_URL;
import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_ENABLE_EMPTY_PROTECTION;
import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL;
import static org.apache.dubbo.common.constants.RegistryConstants.ENABLE_EMPTY_PROTECTION_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDERS_CATEGORY;
/**
* <p>
* Based on FailbackRegistry, it adds a URLAddress and URLParam cache to save RAM space.
*
* <p>
* It's useful for registries whose sdk returns raw string as provider instance. For example, Zookeeper and etcd.
*
* @see org.apache.dubbo.registry.support.FailbackRegistry
* @see org.apache.dubbo.registry.support.AbstractRegistry
*/
public abstract class CacheableFailbackRegistry extends FailbackRegistry {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(CacheableFailbackRegistry.class);
private static String[] VARIABLE_KEYS = new String[] {ENCODED_TIMESTAMP_KEY, ENCODED_PID_KEY};
protected ConcurrentMap<String, URLAddress> stringAddress = new ConcurrentHashMap<>();
protected ConcurrentMap<String, URLParam> stringParam = new ConcurrentHashMap<>();
private ScheduledExecutorService cacheRemovalScheduler;
private int cacheRemovalTaskIntervalInMillis;
private int cacheClearWaitingThresholdInMillis;
private Map<ServiceAddressURL, Long> waitForRemove = new ConcurrentHashMap<>();
private Semaphore semaphore = new Semaphore(1);
private final Map<String, String> extraParameters;
protected final Map<URL, Map<String, ServiceAddressURL>> stringUrls = new ConcurrentHashMap<>();
protected CacheableFailbackRegistry(URL url) {
super(url);
extraParameters = new HashMap<>(8);
extraParameters.put(CHECK_KEY, String.valueOf(false));
cacheRemovalScheduler = url.getOrDefaultFrameworkModel()
.getBeanFactory()
.getBean(FrameworkExecutorRepository.class)
.nextScheduledExecutor();
cacheRemovalTaskIntervalInMillis = getIntConfig(url.getScopeModel(), CACHE_CLEAR_TASK_INTERVAL, 2 * 60 * 1000);
cacheClearWaitingThresholdInMillis =
getIntConfig(url.getScopeModel(), CACHE_CLEAR_WAITING_THRESHOLD, 5 * 60 * 1000);
}
protected static int getIntConfig(ScopeModel scopeModel, String key, int def) {
String str = ConfigurationUtils.getProperty(scopeModel, key);
int result = def;
if (StringUtils.isNotEmpty(str)) {
try {
result = Integer.parseInt(str);
} catch (NumberFormatException e) {
// 0-2 Property type mismatch.
logger.warn(
COMMON_PROPERTY_TYPE_MISMATCH,
"typo in property value",
"This property requires an integer value.",
"Invalid registry properties configuration key " + key + ", value " + str);
}
}
return result;
}
@Override
public void doUnsubscribe(URL url, NotifyListener listener) {
this.evictURLCache(url);
}
protected void evictURLCache(URL url) {
Map<String, ServiceAddressURL> oldURLs = stringUrls.remove(url);
try {
if (CollectionUtils.isNotEmptyMap(oldURLs)) {
logger.info("Evicting urls for service " + url.getServiceKey() + ", size " + oldURLs.size());
Long currentTimestamp = System.currentTimeMillis();
for (Map.Entry<String, ServiceAddressURL> entry : oldURLs.entrySet()) {
waitForRemove.put(entry.getValue(), currentTimestamp);
}
if (CollectionUtils.isNotEmptyMap(waitForRemove)) {
if (semaphore.tryAcquire()) {
cacheRemovalScheduler.schedule(
new RemovalTask(), cacheRemovalTaskIntervalInMillis, TimeUnit.MILLISECONDS);
}
}
}
} catch (Exception e) {
// It seems that the most possible statement that causes exception is the 'schedule()' method.
// The executor that FrameworkExecutorRepository.nextScheduledExecutor() method returns
// is made by Executors.newSingleThreadScheduledExecutor().
// After observing the code of ScheduledThreadPoolExecutor.delayedExecute,
// it seems that it only throws RejectedExecutionException when the thread pool is shutdown.
// When? FrameworkExecutorRepository gets destroyed.
// 1-3: URL evicting failed.
logger.warn(
REGISTRY_FAILED_URL_EVICTING,
"thread pool getting destroyed",
"",
"Failed to evict url for " + url.getServiceKey(),
e);
}
}
protected List<URL> toUrlsWithoutEmpty(URL consumer, Collection<String> providers) {
// keep old urls
Map<String, ServiceAddressURL> oldURLs = stringUrls.get(consumer);
// create new urls
Map<String, ServiceAddressURL> newURLs = new HashMap<>((int) (providers.size() / 0.75f + 1));
// remove 'release', 'dubbo', 'methods', timestamp, 'dubbo.tag' parameter
// in consumer URL.
URL copyOfConsumer = removeParamsFromConsumer(consumer);
if (oldURLs == null) {
for (String rawProvider : providers) {
// remove VARIABLE_KEYS(timestamp,pid..) in provider url.
rawProvider = stripOffVariableKeys(rawProvider);
// create DubboServiceAddress object using provider url, consumer url, and extra parameters.
ServiceAddressURL cachedURL = createURL(rawProvider, copyOfConsumer, getExtraParameters());
if (cachedURL == null) {
continue;
}
newURLs.put(rawProvider, cachedURL);
}
} else {
// maybe only default, or "env" + default
for (String rawProvider : providers) {
rawProvider = stripOffVariableKeys(rawProvider);
ServiceAddressURL cachedURL = oldURLs.remove(rawProvider);
if (cachedURL == null) {
cachedURL = createURL(rawProvider, copyOfConsumer, getExtraParameters());
if (cachedURL == null) {
continue;
}
}
newURLs.put(rawProvider, cachedURL);
}
}
evictURLCache(consumer);
stringUrls.put(consumer, newURLs);
return new ArrayList<>(newURLs.values());
}
protected List<URL> toUrlsWithEmpty(URL consumer, String path, Collection<String> providers) {
List<URL> urls = new ArrayList<>(1);
boolean isProviderPath = path.endsWith(PROVIDERS_CATEGORY);
if (isProviderPath) {
if (CollectionUtils.isNotEmpty(providers)) {
urls = toUrlsWithoutEmpty(consumer, providers);
} else {
// clear cache on empty notification: unsubscribe or provider offline
evictURLCache(consumer);
}
} else {
if (CollectionUtils.isNotEmpty(providers)) {
urls = toConfiguratorsWithoutEmpty(consumer, providers);
}
}
if (urls.isEmpty()) {
int i = path.lastIndexOf(PATH_SEPARATOR);
String category = i < 0 ? path : path.substring(i + 1);
if (!PROVIDERS_CATEGORY.equals(category)
|| !getUrl().getParameter(ENABLE_EMPTY_PROTECTION_KEY, DEFAULT_ENABLE_EMPTY_PROTECTION)) {
if (PROVIDERS_CATEGORY.equals(category)) {
logger.warn(
REGISTRY_EMPTY_ADDRESS,
"",
"",
"Service " + consumer.getServiceKey()
+ " received empty address list and empty protection is disabled, will clear current available addresses");
}
URL empty = URLBuilder.from(consumer)
.setProtocol(EMPTY_PROTOCOL)
.addParameter(CATEGORY_KEY, category)
.build();
urls.add(empty);
}
}
return urls;
}
/**
* Create DubboServiceAddress object using provider url, consumer url, and extra parameters.
*
* @param rawProvider provider url string
* @param consumerURL URL object of consumer
* @param extraParameters extra parameters
* @return created DubboServiceAddressURL object
*/
protected ServiceAddressURL createURL(String rawProvider, URL consumerURL, Map<String, String> extraParameters) {
boolean encoded = true;
// use encoded value directly to avoid URLDecoder.decode allocation.
int paramStartIdx = rawProvider.indexOf(ENCODED_QUESTION_MARK);
if (paramStartIdx == -1) {
// if ENCODED_QUESTION_MARK does not show, mark as not encoded.
encoded = false;
}
// split by (encoded) question mark.
// part[0] => protocol + ip address + interface.
// part[1] => parameters (metadata).
String[] parts = URLStrParser.parseRawURLToArrays(rawProvider, paramStartIdx);
if (parts.length <= 1) {
// 1-5 Received URL without any parameters.
logger.warn(REGISTRY_NO_PARAMETERS_URL, "", "", "Received url without any parameters " + rawProvider);
return DubboServiceAddressURL.valueOf(rawProvider, consumerURL);
}
String rawAddress = parts[0];
String rawParams = parts[1];
// Workaround for 'effectively final': duplicate the encoded variable.
boolean isEncoded = encoded;
// PathURLAddress if it's using dubbo protocol.
URLAddress address = ConcurrentHashMapUtils.computeIfAbsent(
stringAddress, rawAddress, k -> URLAddress.parse(k, getDefaultURLProtocol(), isEncoded));
address.setTimestamp(System.currentTimeMillis());
URLParam param = ConcurrentHashMapUtils.computeIfAbsent(
stringParam, rawParams, k -> URLParam.parse(k, isEncoded, extraParameters));
param.setTimestamp(System.currentTimeMillis());
// create service URL using cached address, param, and consumer URL.
ServiceAddressURL cachedServiceAddressURL = createServiceURL(address, param, consumerURL);
if (isMatch(consumerURL, cachedServiceAddressURL)) {
return cachedServiceAddressURL;
}
return null;
}
protected ServiceAddressURL createServiceURL(URLAddress address, URLParam param, URL consumerURL) {
return new DubboServiceAddressURL(address, param, consumerURL, null);
}
protected URL removeParamsFromConsumer(URL consumer) {
Set<ProviderFirstParams> providerFirstParams = consumer.getOrDefaultApplicationModel()
.getExtensionLoader(ProviderFirstParams.class)
.getSupportedExtensionInstances();
if (CollectionUtils.isEmpty(providerFirstParams)) {
return consumer;
}
for (ProviderFirstParams paramsFilter : providerFirstParams) {
consumer = consumer.removeParameters(paramsFilter.params());
}
return consumer;
}
private String stripOffVariableKeys(String rawProvider) {
String[] keys = getVariableKeys();
if (keys == null || keys.length == 0) {
return rawProvider;
}
for (String key : keys) {
int idxStart = rawProvider.indexOf(key);
if (idxStart == -1) {
continue;
}
int idxEnd = rawProvider.indexOf(ENCODED_AND_MARK, idxStart);
String part1 = rawProvider.substring(0, idxStart);
if (idxEnd == -1) {
rawProvider = part1;
} else {
String part2 = rawProvider.substring(idxEnd + ENCODED_AND_MARK.length());
rawProvider = part1 + part2;
}
}
if (rawProvider.endsWith(ENCODED_AND_MARK)) {
rawProvider = rawProvider.substring(0, rawProvider.length() - ENCODED_AND_MARK.length());
}
if (rawProvider.endsWith(ENCODED_QUESTION_MARK)) {
rawProvider = rawProvider.substring(0, rawProvider.length() - ENCODED_QUESTION_MARK.length());
}
return rawProvider;
}
private List<URL> toConfiguratorsWithoutEmpty(URL consumer, Collection<String> configurators) {
List<URL> urls = new ArrayList<>();
if (CollectionUtils.isNotEmpty(configurators)) {
for (String provider : configurators) {
if (provider.contains(PROTOCOL_SEPARATOR_ENCODED)) {
URL url = URLStrParser.parseEncodedStr(provider);
if (UrlUtils.isMatch(consumer, url)) {
urls.add(url);
}
}
}
}
return urls;
}
protected Map<String, String> getExtraParameters() {
return extraParameters;
}
protected String[] getVariableKeys() {
return VARIABLE_KEYS;
}
protected String getDefaultURLProtocol() {
return DUBBO;
}
/**
* This method is for unit test to see if the RemovalTask has completed or not.<br />
* <strong>Please do not call this method in other places.</strong>
*/
@Deprecated
protected Semaphore getSemaphore() {
return semaphore;
}
protected abstract boolean isMatch(URL subscribeUrl, URL providerUrl);
/**
* The cached URL removal task, which will be run on a scheduled thread pool. (It will be run after a delay.)
*/
private class RemovalTask implements Runnable {
@Override
public void run() {
logger.info("Clearing cached URLs, waiting to clear size " + waitForRemove.size());
int clearCount = 0;
try {
Iterator<Map.Entry<ServiceAddressURL, Long>> it =
waitForRemove.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<ServiceAddressURL, Long> entry = it.next();
ServiceAddressURL removeURL = entry.getKey();
long removeTime = entry.getValue();
long current = System.currentTimeMillis();
if (current - removeTime >= cacheClearWaitingThresholdInMillis) {
URLAddress urlAddress = removeURL.getUrlAddress();
URLParam urlParam = removeURL.getUrlParam();
if (current - urlAddress.getTimestamp() >= cacheClearWaitingThresholdInMillis) {
stringAddress.remove(urlAddress.getRawAddress());
}
if (current - urlParam.getTimestamp() >= cacheClearWaitingThresholdInMillis) {
stringParam.remove(urlParam.getRawParam());
}
it.remove();
clearCount++;
}
}
} catch (Throwable t) {
// 1-6 Error when clearing cached URLs.
logger.error(REGISTRY_FAILED_CLEAR_CACHED_URLS, "", "", "Error occurred when clearing cached URLs", t);
} finally {
semaphore.release();
}
logger.info("Clear cached URLs, size " + clearCount);
if (CollectionUtils.isNotEmptyMap(waitForRemove)) {
// move to next schedule
if (semaphore.tryAcquire()) {
cacheRemovalScheduler.schedule(
new RemovalTask(), cacheRemovalTaskIntervalInMillis, TimeUnit.MILLISECONDS);
}
}
}
}
}
| 5,487 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistryFactory.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.registry.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.URLBuilder;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.RegistryFactory;
import org.apache.dubbo.registry.RegistryService;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ScopeModelAware;
import static org.apache.dubbo.common.constants.CommonConstants.CHECK_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_CREATE_INSTANCE;
import static org.apache.dubbo.rpc.cluster.Constants.EXPORT_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY;
/**
* AbstractRegistryFactory. (SPI, Singleton, ThreadSafe)
*
* @see org.apache.dubbo.registry.RegistryFactory
*/
public abstract class AbstractRegistryFactory implements RegistryFactory, ScopeModelAware {
private static final ErrorTypeAwareLogger LOGGER =
LoggerFactory.getErrorTypeAwareLogger(AbstractRegistryFactory.class);
private RegistryManager registryManager;
protected ApplicationModel applicationModel;
@Override
public void setApplicationModel(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
this.registryManager = applicationModel.getBeanFactory().getBean(RegistryManager.class);
}
@Override
public Registry getRegistry(URL url) {
if (registryManager == null) {
throw new IllegalStateException("Unable to fetch RegistryManager from ApplicationModel BeanFactory. "
+ "Please check if `setApplicationModel` has been override.");
}
Registry defaultNopRegistry = registryManager.getDefaultNopRegistryIfDestroyed();
if (null != defaultNopRegistry) {
return defaultNopRegistry;
}
url = URLBuilder.from(url)
.setPath(RegistryService.class.getName())
.addParameter(INTERFACE_KEY, RegistryService.class.getName())
.removeParameter(TIMESTAMP_KEY)
.removeAttribute(EXPORT_KEY)
.removeAttribute(REFER_KEY)
.build();
String key = createRegistryCacheKey(url);
Registry registry = null;
boolean check = url.getParameter(CHECK_KEY, true) && url.getPort() != 0;
// Lock the registry access process to ensure a single instance of the registry
registryManager.getRegistryLock().lock();
try {
// double check
// fix https://github.com/apache/dubbo/issues/7265.
defaultNopRegistry = registryManager.getDefaultNopRegistryIfDestroyed();
if (null != defaultNopRegistry) {
return defaultNopRegistry;
}
registry = registryManager.getRegistry(key);
if (registry != null) {
return registry;
}
// create registry by spi/ioc
registry = createRegistry(url);
if (check && registry == null) {
throw new IllegalStateException("Can not create registry " + url);
}
if (registry != null) {
registryManager.putRegistry(key, registry);
}
} catch (Exception e) {
if (check) {
throw new RuntimeException("Can not create registry " + url, e);
} else {
// 1-11 Failed to obtain or create registry (service) object.
LOGGER.warn(REGISTRY_FAILED_CREATE_INSTANCE, "", "", "Failed to obtain or create registry ", e);
}
} finally {
// Release the lock
registryManager.getRegistryLock().unlock();
}
return registry;
}
/**
* Create the key for the registries cache.
* This method may be overridden by the sub-class.
*
* @param url the registration {@link URL url}
* @return non-null
*/
protected String createRegistryCacheKey(URL url) {
return url.toServiceStringWithoutResolving();
}
protected abstract Registry createRegistry(URL url);
}
| 5,488 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/FailbackRegistry.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.registry.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.timer.HashedWheelTimer;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.NamedThreadFactory;
import org.apache.dubbo.registry.NotifyListener;
import org.apache.dubbo.registry.retry.FailedRegisteredTask;
import org.apache.dubbo.registry.retry.FailedSubscribedTask;
import org.apache.dubbo.registry.retry.FailedUnregisteredTask;
import org.apache.dubbo.registry.retry.FailedUnsubscribedTask;
import org.apache.dubbo.remoting.Constants;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_NOTIFY_EVENT;
import static org.apache.dubbo.registry.Constants.DEFAULT_REGISTRY_RETRY_PERIOD;
import static org.apache.dubbo.registry.Constants.REGISTRY_RETRY_PERIOD_KEY;
/**
* A template implementation of registry service that provides auto-retry ability.
* (SPI, Prototype, ThreadSafe)
*/
public abstract class FailbackRegistry extends AbstractRegistry {
/* retry task map */
private final ConcurrentMap<URL, FailedRegisteredTask> failedRegistered = new ConcurrentHashMap<>();
private final ConcurrentMap<URL, FailedUnregisteredTask> failedUnregistered = new ConcurrentHashMap<>();
private final ConcurrentMap<Holder, FailedSubscribedTask> failedSubscribed = new ConcurrentHashMap<>();
private final ConcurrentMap<Holder, FailedUnsubscribedTask> failedUnsubscribed = new ConcurrentHashMap<>();
/**
* The time in milliseconds the retryExecutor will wait
*/
private final int retryPeriod;
// Timer for failure retry, regular check if there is a request for failure, and if there is, an unlimited retry
private final HashedWheelTimer retryTimer;
public FailbackRegistry(URL url) {
super(url);
this.retryPeriod = url.getParameter(REGISTRY_RETRY_PERIOD_KEY, DEFAULT_REGISTRY_RETRY_PERIOD);
// since the retry task will not be very much. 128 ticks is enough.
retryTimer = new HashedWheelTimer(
new NamedThreadFactory("DubboRegistryRetryTimer", true), retryPeriod, TimeUnit.MILLISECONDS, 128);
}
public void removeFailedRegisteredTask(URL url) {
failedRegistered.remove(url);
}
public void removeFailedUnregisteredTask(URL url) {
failedUnregistered.remove(url);
}
public void removeFailedSubscribedTask(URL url, NotifyListener listener) {
Holder h = new Holder(url, listener);
failedSubscribed.remove(h);
}
public void removeFailedUnsubscribedTask(URL url, NotifyListener listener) {
Holder h = new Holder(url, listener);
failedUnsubscribed.remove(h);
}
private void addFailedRegistered(URL url) {
FailedRegisteredTask oldOne = failedRegistered.get(url);
if (oldOne != null) {
return;
}
FailedRegisteredTask newTask = new FailedRegisteredTask(url, this);
oldOne = failedRegistered.putIfAbsent(url, newTask);
if (oldOne == null) {
// never has a retry task. then start a new task for retry.
retryTimer.newTimeout(newTask, retryPeriod, TimeUnit.MILLISECONDS);
}
}
private void removeFailedRegistered(URL url) {
FailedRegisteredTask f = failedRegistered.remove(url);
if (f != null) {
f.cancel();
}
}
private void addFailedUnregistered(URL url) {
FailedUnregisteredTask oldOne = failedUnregistered.get(url);
if (oldOne != null) {
return;
}
FailedUnregisteredTask newTask = new FailedUnregisteredTask(url, this);
oldOne = failedUnregistered.putIfAbsent(url, newTask);
if (oldOne == null) {
// never has a retry task. then start a new task for retry.
retryTimer.newTimeout(newTask, retryPeriod, TimeUnit.MILLISECONDS);
}
}
private void removeFailedUnregistered(URL url) {
FailedUnregisteredTask f = failedUnregistered.remove(url);
if (f != null) {
f.cancel();
}
}
protected void addFailedSubscribed(URL url, NotifyListener listener) {
Holder h = new Holder(url, listener);
FailedSubscribedTask oldOne = failedSubscribed.get(h);
if (oldOne != null) {
return;
}
FailedSubscribedTask newTask = new FailedSubscribedTask(url, this, listener);
oldOne = failedSubscribed.putIfAbsent(h, newTask);
if (oldOne == null) {
// never has a retry task. then start a new task for retry.
retryTimer.newTimeout(newTask, retryPeriod, TimeUnit.MILLISECONDS);
}
}
public void removeFailedSubscribed(URL url, NotifyListener listener) {
Holder h = new Holder(url, listener);
FailedSubscribedTask f = failedSubscribed.remove(h);
if (f != null) {
f.cancel();
}
removeFailedUnsubscribed(url, listener);
}
private void addFailedUnsubscribed(URL url, NotifyListener listener) {
Holder h = new Holder(url, listener);
FailedUnsubscribedTask oldOne = failedUnsubscribed.get(h);
if (oldOne != null) {
return;
}
FailedUnsubscribedTask newTask = new FailedUnsubscribedTask(url, this, listener);
oldOne = failedUnsubscribed.putIfAbsent(h, newTask);
if (oldOne == null) {
// never has a retry task. then start a new task for retry.
retryTimer.newTimeout(newTask, retryPeriod, TimeUnit.MILLISECONDS);
}
}
private void removeFailedUnsubscribed(URL url, NotifyListener listener) {
Holder h = new Holder(url, listener);
FailedUnsubscribedTask f = failedUnsubscribed.remove(h);
if (f != null) {
f.cancel();
}
}
ConcurrentMap<URL, FailedRegisteredTask> getFailedRegistered() {
return failedRegistered;
}
ConcurrentMap<URL, FailedUnregisteredTask> getFailedUnregistered() {
return failedUnregistered;
}
ConcurrentMap<Holder, FailedSubscribedTask> getFailedSubscribed() {
return failedSubscribed;
}
ConcurrentMap<Holder, FailedUnsubscribedTask> getFailedUnsubscribed() {
return failedUnsubscribed;
}
@Override
public void register(URL url) {
if (!acceptable(url)) {
logger.info("URL " + url + " will not be registered to Registry. Registry " + this.getUrl()
+ " does not accept service of this protocol type.");
return;
}
super.register(url);
removeFailedRegistered(url);
removeFailedUnregistered(url);
try {
// Sending a registration request to the server side
doRegister(url);
} catch (Exception e) {
Throwable t = e;
// If the startup detection is opened, the Exception is thrown directly.
boolean check = getUrl().getParameter(Constants.CHECK_KEY, true)
&& url.getParameter(Constants.CHECK_KEY, true)
&& (url.getPort() != 0);
boolean skipFailback = t instanceof SkipFailbackWrapperException;
if (check || skipFailback) {
if (skipFailback) {
t = t.getCause();
}
throw new IllegalStateException(
"Failed to register " + url + " to registry " + getUrl().getAddress() + ", cause: "
+ t.getMessage(),
t);
} else {
logger.error(
INTERNAL_ERROR,
"unknown error in registry module",
"",
"Failed to register " + url + ", waiting for retry, cause: " + t.getMessage(),
t);
}
// Record a failed registration request to a failed list, retry regularly
addFailedRegistered(url);
}
}
@Override
public void reExportRegister(URL url) {
if (!acceptable(url)) {
logger.info("URL " + url + " will not be registered to Registry. Registry " + url
+ " does not accept service of this protocol type.");
return;
}
super.register(url);
removeFailedRegistered(url);
removeFailedUnregistered(url);
try {
// Sending a registration request to the server side
doRegister(url);
} catch (Exception e) {
if (!(e instanceof SkipFailbackWrapperException)) {
throw new IllegalStateException(
"Failed to register (re-export) " + url + " to registry " + getUrl().getAddress() + ", cause: "
+ e.getMessage(),
e);
}
}
}
@Override
public void unregister(URL url) {
super.unregister(url);
removeFailedRegistered(url);
removeFailedUnregistered(url);
try {
// Sending a cancellation request to the server side
doUnregister(url);
} catch (Exception e) {
Throwable t = e;
// If the startup detection is opened, the Exception is thrown directly.
boolean check = getUrl().getParameter(Constants.CHECK_KEY, true)
&& url.getParameter(Constants.CHECK_KEY, true)
&& (url.getPort() != 0);
boolean skipFailback = t instanceof SkipFailbackWrapperException;
if (check || skipFailback) {
if (skipFailback) {
t = t.getCause();
}
throw new IllegalStateException(
"Failed to unregister " + url + " to registry " + getUrl().getAddress() + ", cause: "
+ t.getMessage(),
t);
} else {
logger.error(
INTERNAL_ERROR,
"unknown error in registry module",
"",
"Failed to unregister " + url + ", waiting for retry, cause: " + t.getMessage(),
t);
}
// Record a failed registration request to a failed list, retry regularly
addFailedUnregistered(url);
}
}
@Override
public void reExportUnregister(URL url) {
super.unregister(url);
removeFailedRegistered(url);
removeFailedUnregistered(url);
try {
// Sending a cancellation request to the server side
doUnregister(url);
} catch (Exception e) {
if (!(e instanceof SkipFailbackWrapperException)) {
throw new IllegalStateException(
"Failed to unregister(re-export) " + url + " to registry " + getUrl().getAddress() + ", cause: "
+ e.getMessage(),
e);
}
}
}
@Override
public void subscribe(URL url, NotifyListener listener) {
super.subscribe(url, listener);
removeFailedSubscribed(url, listener);
try {
// Sending a subscription request to the server side
doSubscribe(url, listener);
} catch (Exception e) {
Throwable t = e;
List<URL> urls = getCacheUrls(url);
if (CollectionUtils.isNotEmpty(urls)) {
notify(url, listener, urls);
logger.error(
REGISTRY_FAILED_NOTIFY_EVENT,
"",
"",
"Failed to subscribe " + url + ", Using cached list: " + urls + " from cache file: "
+ getCacheFile().getName() + ", cause: " + t.getMessage(),
t);
} else {
// If the startup detection is opened, the Exception is thrown directly.
boolean check =
getUrl().getParameter(Constants.CHECK_KEY, true) && url.getParameter(Constants.CHECK_KEY, true);
boolean skipFailback = t instanceof SkipFailbackWrapperException;
if (check || skipFailback) {
if (skipFailback) {
t = t.getCause();
}
throw new IllegalStateException("Failed to subscribe " + url + ", cause: " + t.getMessage(), t);
} else {
logger.error(
REGISTRY_FAILED_NOTIFY_EVENT,
"",
"",
"Failed to subscribe " + url + ", waiting for retry, cause: " + t.getMessage(),
t);
}
}
// Record a failed registration request to a failed list, retry regularly
addFailedSubscribed(url, listener);
}
}
@Override
public void unsubscribe(URL url, NotifyListener listener) {
super.unsubscribe(url, listener);
removeFailedSubscribed(url, listener);
try {
// Sending a canceling subscription request to the server side
doUnsubscribe(url, listener);
} catch (Exception e) {
Throwable t = e;
// If the startup detection is opened, the Exception is thrown directly.
boolean check =
getUrl().getParameter(Constants.CHECK_KEY, true) && url.getParameter(Constants.CHECK_KEY, true);
boolean skipFailback = t instanceof SkipFailbackWrapperException;
if (check || skipFailback) {
if (skipFailback) {
t = t.getCause();
}
throw new IllegalStateException(
"Failed to unsubscribe " + url + " to registry " + getUrl().getAddress() + ", cause: "
+ t.getMessage(),
t);
} else {
logger.error(
REGISTRY_FAILED_NOTIFY_EVENT,
"",
"",
"Failed to unsubscribe " + url + ", waiting for retry, cause: " + t.getMessage(),
t);
}
// Record a failed registration request to a failed list, retry regularly
addFailedUnsubscribed(url, listener);
}
}
@Override
protected void notify(URL url, NotifyListener listener, List<URL> urls) {
if (url == null) {
throw new IllegalArgumentException("notify url == null");
}
if (listener == null) {
throw new IllegalArgumentException("notify listener == null");
}
try {
doNotify(url, listener, urls);
} catch (Exception t) {
// Record a failed registration request to a failed list
logger.error(
REGISTRY_FAILED_NOTIFY_EVENT,
"",
"",
"Failed to notify addresses for subscribe " + url + ", cause: " + t.getMessage(),
t);
}
}
protected void doNotify(URL url, NotifyListener listener, List<URL> urls) {
super.notify(url, listener, urls);
}
@Override
protected void recover() throws Exception {
// register
Set<URL> recoverRegistered = new HashSet<>(getRegistered());
if (!recoverRegistered.isEmpty()) {
if (logger.isInfoEnabled()) {
logger.info("Recover register url " + recoverRegistered);
}
for (URL url : recoverRegistered) {
// remove fail registry or unRegistry task first.
removeFailedRegistered(url);
removeFailedUnregistered(url);
addFailedRegistered(url);
}
}
// subscribe
Map<URL, Set<NotifyListener>> recoverSubscribed = new HashMap<>(getSubscribed());
if (!recoverSubscribed.isEmpty()) {
if (logger.isInfoEnabled()) {
logger.info("Recover subscribe url " + recoverSubscribed.keySet());
}
for (Map.Entry<URL, Set<NotifyListener>> entry : recoverSubscribed.entrySet()) {
URL url = entry.getKey();
for (NotifyListener listener : entry.getValue()) {
// First remove other tasks to ensure that addFailedSubscribed can succeed.
removeFailedSubscribed(url, listener);
addFailedSubscribed(url, listener);
}
}
}
}
@Override
public void destroy() {
super.destroy();
retryTimer.stop();
}
// ==== Template method ====
public abstract void doRegister(URL url);
public abstract void doUnregister(URL url);
public abstract void doSubscribe(URL url, NotifyListener listener);
public abstract void doUnsubscribe(URL url, NotifyListener listener);
static class Holder {
private final URL url;
private final NotifyListener notifyListener;
Holder(URL url, NotifyListener notifyListener) {
if (url == null || notifyListener == null) {
throw new IllegalArgumentException();
}
this.url = url;
this.notifyListener = notifyListener;
}
@Override
public int hashCode() {
return url.hashCode() + notifyListener.hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Holder) {
Holder h = (Holder) obj;
return this.url.equals(h.url) && this.notifyListener.equals(h.notifyListener);
} else {
return false;
}
}
}
}
| 5,489 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistry.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.registry.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.ConcurrentHashSet;
import org.apache.dubbo.common.utils.ConfigUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.common.utils.UrlUtils;
import org.apache.dubbo.registry.NotifyListener;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE;
import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN;
import static org.apache.dubbo.common.constants.CommonConstants.FILE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.REGISTRY_LOCAL_FILE_CACHE_ENABLED;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_EMPTY_ADDRESS;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_DELETE_LOCKFILE;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_DESTROY_UNREGISTER_URL;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_NOTIFY_EVENT;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_READ_WRITE_CACHE_FILE;
import static org.apache.dubbo.common.constants.RegistryConstants.ACCEPTS_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_CATEGORY;
import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL;
import static org.apache.dubbo.registry.Constants.CACHE;
import static org.apache.dubbo.registry.Constants.DUBBO_REGISTRY;
import static org.apache.dubbo.registry.Constants.REGISTRY_FILESAVE_SYNC_KEY;
import static org.apache.dubbo.registry.Constants.USER_HOME;
/**
* <p>
* Provides a fail-safe registry service backed by cache file. The consumer/provider can still find each other when registry center crashed.
* <p>
* (SPI, Prototype, ThreadSafe)
*/
public abstract class AbstractRegistry implements Registry {
// URL address separator, used in file cache, service provider URL separation
private static final char URL_SEPARATOR = ' ';
// URL address separated regular expression for parsing the service provider URL list in the file cache
private static final String URL_SPLIT = "\\s+";
// Max times to retry to save properties to local cache file
private static final int MAX_RETRY_TIMES_SAVE_PROPERTIES = 3;
// Default interval in millisecond for saving properties to local cache file
private static final long DEFAULT_INTERVAL_SAVE_PROPERTIES = 500L;
// Log output
protected final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
// Local disk cache, where the special key value.registries records the list of registry centers, and the others are
// the list of notified service providers
private final Properties properties = new Properties();
// File cache timing writing
private final ScheduledExecutorService registryCacheExecutor;
private final AtomicLong lastCacheChanged = new AtomicLong();
private final AtomicInteger savePropertiesRetryTimes = new AtomicInteger();
private final Set<URL> registered = new ConcurrentHashSet<>();
private final ConcurrentMap<URL, Set<NotifyListener>> subscribed = new ConcurrentHashMap<>();
private final ConcurrentMap<URL, Map<String, List<URL>>> notified = new ConcurrentHashMap<>();
// Is it synchronized to save the file
private boolean syncSaveFile;
private URL registryUrl;
// Local disk cache file
private File file;
private final boolean localCacheEnabled;
protected RegistryManager registryManager;
protected ApplicationModel applicationModel;
private static final String CAUSE_MULTI_DUBBO_USING_SAME_FILE = "multiple Dubbo instance are using the same file";
protected AbstractRegistry(URL url) {
setUrl(url);
registryManager = url.getOrDefaultApplicationModel().getBeanFactory().getBean(RegistryManager.class);
localCacheEnabled = url.getParameter(REGISTRY_LOCAL_FILE_CACHE_ENABLED, true);
registryCacheExecutor = url.getOrDefaultFrameworkModel()
.getBeanFactory()
.getBean(FrameworkExecutorRepository.class)
.getSharedScheduledExecutor();
if (localCacheEnabled) {
// Start file save timer
syncSaveFile = url.getParameter(REGISTRY_FILESAVE_SYNC_KEY, false);
String defaultFilename = System.getProperty(USER_HOME) + DUBBO_REGISTRY + url.getApplication() + "-"
+ url.getAddress().replaceAll(":", "-") + CACHE;
String filename = url.getParameter(FILE_KEY, defaultFilename);
File file = null;
if (ConfigUtils.isNotEmpty(filename)) {
file = new File(filename);
if (!file.exists()
&& file.getParentFile() != null
&& !file.getParentFile().exists()) {
if (!file.getParentFile().mkdirs()) {
IllegalArgumentException illegalArgumentException =
new IllegalArgumentException("Invalid registry cache file " + file
+ ", cause: Failed to create directory " + file.getParentFile() + "!");
if (logger != null) {
// 1-9 failed to read / save registry cache file.
logger.error(
REGISTRY_FAILED_READ_WRITE_CACHE_FILE,
"cache directory inaccessible",
"Try adjusting permission of the directory.",
"failed to create directory",
illegalArgumentException);
}
throw illegalArgumentException;
}
}
}
this.file = file;
// When starting the subscription center,
// we need to read the local cache file for future Registry fault tolerance processing.
loadProperties();
notify(url.getBackupUrls());
}
}
protected static List<URL> filterEmpty(URL url, List<URL> urls) {
if (CollectionUtils.isEmpty(urls)) {
List<URL> result = new ArrayList<>(1);
result.add(url.setProtocol(EMPTY_PROTOCOL));
return result;
}
return urls;
}
@Override
public URL getUrl() {
return registryUrl;
}
protected void setUrl(URL url) {
if (url == null) {
throw new IllegalArgumentException("registry url == null");
}
this.registryUrl = url;
}
public Set<URL> getRegistered() {
return Collections.unmodifiableSet(registered);
}
public Map<URL, Set<NotifyListener>> getSubscribed() {
return Collections.unmodifiableMap(subscribed);
}
public Map<URL, Map<String, List<URL>>> getNotified() {
return Collections.unmodifiableMap(notified);
}
public File getCacheFile() {
return file;
}
public Properties getCacheProperties() {
return properties;
}
public AtomicLong getLastCacheChanged() {
return lastCacheChanged;
}
public void doSaveProperties(long version) {
if (version < lastCacheChanged.get()) {
return;
}
if (file == null) {
return;
}
// Save
File lockfile = null;
try {
lockfile = new File(file.getAbsolutePath() + ".lock");
if (!lockfile.exists()) {
lockfile.createNewFile();
}
try (RandomAccessFile raf = new RandomAccessFile(lockfile, "rw");
FileChannel channel = raf.getChannel()) {
FileLock lock = channel.tryLock();
if (lock == null) {
IOException ioException = new IOException(
"Can not lock the registry cache file " + file.getAbsolutePath() + ", "
+ "ignore and retry later, maybe multi java process use the file, please config: dubbo.registry.file=xxx.properties");
// 1-9 failed to read / save registry cache file.
logger.warn(
REGISTRY_FAILED_READ_WRITE_CACHE_FILE,
CAUSE_MULTI_DUBBO_USING_SAME_FILE,
"",
"Adjust dubbo.registry.file.",
ioException);
throw ioException;
}
// Save
try {
if (!file.exists()) {
file.createNewFile();
}
Properties tmpProperties;
if (syncSaveFile) {
// When syncReport = true, properties.setProperty and properties.store are called from the same
// thread(reportCacheExecutor), so deep copy is not required
tmpProperties = properties;
} else {
// Using properties.setProperty and properties.store method will cause lock contention
// under multi-threading, so deep copy a new container
tmpProperties = new Properties();
Set<Map.Entry<Object, Object>> entries = properties.entrySet();
for (Map.Entry<Object, Object> entry : entries) {
tmpProperties.setProperty((String) entry.getKey(), (String) entry.getValue());
}
}
try (FileOutputStream outputFile = new FileOutputStream(file)) {
tmpProperties.store(outputFile, "Dubbo Registry Cache");
}
} finally {
lock.release();
}
}
} catch (Throwable e) {
savePropertiesRetryTimes.incrementAndGet();
if (savePropertiesRetryTimes.get() >= MAX_RETRY_TIMES_SAVE_PROPERTIES) {
if (e instanceof OverlappingFileLockException) {
// fix #9341, ignore OverlappingFileLockException
logger.info("Failed to save registry cache file for file overlapping lock exception, file name "
+ file.getName());
} else {
// 1-9 failed to read / save registry cache file.
logger.warn(
REGISTRY_FAILED_READ_WRITE_CACHE_FILE,
CAUSE_MULTI_DUBBO_USING_SAME_FILE,
"",
"Failed to save registry cache file after retrying " + MAX_RETRY_TIMES_SAVE_PROPERTIES
+ " times, cause: " + e.getMessage(),
e);
}
savePropertiesRetryTimes.set(0);
return;
}
if (version < lastCacheChanged.get()) {
savePropertiesRetryTimes.set(0);
return;
} else {
registryCacheExecutor.schedule(
() -> doSaveProperties(lastCacheChanged.incrementAndGet()),
DEFAULT_INTERVAL_SAVE_PROPERTIES,
TimeUnit.MILLISECONDS);
}
if (!(e instanceof OverlappingFileLockException)) {
logger.warn(
REGISTRY_FAILED_READ_WRITE_CACHE_FILE,
CAUSE_MULTI_DUBBO_USING_SAME_FILE,
"However, the retrying count limit is not exceeded. Dubbo will still try.",
"Failed to save registry cache file, will retry, cause: " + e.getMessage(),
e);
}
} finally {
if (lockfile != null) {
if (!lockfile.delete()) {
// 1-10 Failed to delete lock file.
logger.warn(
REGISTRY_FAILED_DELETE_LOCKFILE,
"",
"",
String.format("Failed to delete lock file [%s]", lockfile.getName()));
}
}
}
}
private void loadProperties() {
if (file == null || !file.exists()) {
return;
}
try (InputStream in = Files.newInputStream(file.toPath())) {
properties.load(in);
if (logger.isInfoEnabled()) {
logger.info("Loaded registry cache file " + file);
}
} catch (IOException e) {
// 1-9 failed to read / save registry cache file.
logger.warn(
REGISTRY_FAILED_READ_WRITE_CACHE_FILE, CAUSE_MULTI_DUBBO_USING_SAME_FILE, "", e.getMessage(), e);
} catch (Throwable e) {
// 1-9 failed to read / save registry cache file.
logger.warn(
REGISTRY_FAILED_READ_WRITE_CACHE_FILE,
CAUSE_MULTI_DUBBO_USING_SAME_FILE,
"",
"Failed to load registry cache file " + file,
e);
}
}
public List<URL> getCacheUrls(URL url) {
Map<String, List<URL>> categoryNotified = notified.get(url);
if (CollectionUtils.isNotEmptyMap(categoryNotified)) {
List<URL> urls = categoryNotified.values().stream()
.flatMap(Collection::stream)
.collect(Collectors.toList());
return urls;
}
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
String key = (String) entry.getKey();
String value = (String) entry.getValue();
if (StringUtils.isNotEmpty(key)
&& key.equals(url.getServiceKey())
&& (Character.isLetter(key.charAt(0)) || key.charAt(0) == '_')
&& StringUtils.isNotEmpty(value)) {
String[] arr = value.trim().split(URL_SPLIT);
List<URL> urls = new ArrayList<>();
for (String u : arr) {
urls.add(URL.valueOf(u));
}
return urls;
}
}
return null;
}
@Override
public List<URL> lookup(URL url) {
List<URL> result = new ArrayList<>();
Map<String, List<URL>> notifiedUrls = getNotified().get(url);
if (CollectionUtils.isNotEmptyMap(notifiedUrls)) {
for (List<URL> urls : notifiedUrls.values()) {
for (URL u : urls) {
if (!EMPTY_PROTOCOL.equals(u.getProtocol())) {
result.add(u);
}
}
}
} else {
final AtomicReference<List<URL>> reference = new AtomicReference<>();
NotifyListener listener = reference::set;
subscribe(url, listener); // Subscribe logic guarantees the first notify to return
List<URL> urls = reference.get();
if (CollectionUtils.isNotEmpty(urls)) {
for (URL u : urls) {
if (!EMPTY_PROTOCOL.equals(u.getProtocol())) {
result.add(u);
}
}
}
}
return result;
}
@Override
public void register(URL url) {
if (url == null) {
throw new IllegalArgumentException("register url == null");
}
if (url.getPort() != 0) {
if (logger.isInfoEnabled()) {
logger.info("Register: " + url);
}
}
registered.add(url);
}
@Override
public void unregister(URL url) {
if (url == null) {
throw new IllegalArgumentException("unregister url == null");
}
if (url.getPort() != 0) {
if (logger.isInfoEnabled()) {
logger.info("Unregister: " + url);
}
}
registered.remove(url);
}
@Override
public void subscribe(URL url, NotifyListener listener) {
if (url == null) {
throw new IllegalArgumentException("subscribe url == null");
}
if (listener == null) {
throw new IllegalArgumentException("subscribe listener == null");
}
if (logger.isInfoEnabled()) {
logger.info("Subscribe: " + url);
}
Set<NotifyListener> listeners = subscribed.computeIfAbsent(url, n -> new ConcurrentHashSet<>());
listeners.add(listener);
}
@Override
public void unsubscribe(URL url, NotifyListener listener) {
if (url == null) {
throw new IllegalArgumentException("unsubscribe url == null");
}
if (listener == null) {
throw new IllegalArgumentException("unsubscribe listener == null");
}
if (logger.isInfoEnabled()) {
logger.info("Unsubscribe: " + url);
}
Set<NotifyListener> listeners = subscribed.get(url);
if (listeners != null) {
listeners.remove(listener);
}
// do not forget remove notified
notified.remove(url);
}
protected void recover() throws Exception {
// register
Set<URL> recoverRegistered = new HashSet<>(getRegistered());
if (!recoverRegistered.isEmpty()) {
if (logger.isInfoEnabled()) {
logger.info("Recover register url " + recoverRegistered);
}
for (URL url : recoverRegistered) {
register(url);
}
}
// subscribe
Map<URL, Set<NotifyListener>> recoverSubscribed = new HashMap<>(getSubscribed());
if (!recoverSubscribed.isEmpty()) {
if (logger.isInfoEnabled()) {
logger.info("Recover subscribe url " + recoverSubscribed.keySet());
}
for (Map.Entry<URL, Set<NotifyListener>> entry : recoverSubscribed.entrySet()) {
URL url = entry.getKey();
for (NotifyListener listener : entry.getValue()) {
subscribe(url, listener);
}
}
}
}
protected void notify(List<URL> urls) {
if (CollectionUtils.isEmpty(urls)) {
return;
}
for (Map.Entry<URL, Set<NotifyListener>> entry : getSubscribed().entrySet()) {
URL url = entry.getKey();
if (!UrlUtils.isMatch(url, urls.get(0))) {
continue;
}
Set<NotifyListener> listeners = entry.getValue();
if (listeners != null) {
for (NotifyListener listener : listeners) {
try {
notify(url, listener, filterEmpty(url, urls));
} catch (Throwable t) {
// 1-7: Failed to notify registry event.
logger.error(
REGISTRY_FAILED_NOTIFY_EVENT,
"consumer is offline",
"",
"Failed to notify registry event, urls: " + urls + ", cause: " + t.getMessage(),
t);
}
}
}
}
}
/**
* Notify changes from the provider side.
*
* @param url consumer side url
* @param listener listener
* @param urls provider latest urls
*/
protected void notify(URL url, NotifyListener listener, List<URL> urls) {
if (url == null) {
throw new IllegalArgumentException("notify url == null");
}
if (listener == null) {
throw new IllegalArgumentException("notify listener == null");
}
if ((CollectionUtils.isEmpty(urls)) && !ANY_VALUE.equals(url.getServiceInterface())) {
// 1-4 Empty address.
logger.warn(REGISTRY_EMPTY_ADDRESS, "", "", "Ignore empty notify urls for subscribe url " + url);
return;
}
if (logger.isInfoEnabled()) {
logger.info("Notify urls for subscribe url " + url + ", url size: " + urls.size());
}
// keep every provider's category.
Map<String, List<URL>> result = new HashMap<>();
for (URL u : urls) {
if (UrlUtils.isMatch(url, u)) {
String category = u.getCategory(DEFAULT_CATEGORY);
List<URL> categoryList = result.computeIfAbsent(category, k -> new ArrayList<>());
categoryList.add(u);
}
}
if (result.size() == 0) {
return;
}
Map<String, List<URL>> categoryNotified = notified.computeIfAbsent(url, u -> new ConcurrentHashMap<>());
for (Map.Entry<String, List<URL>> entry : result.entrySet()) {
String category = entry.getKey();
List<URL> categoryList = entry.getValue();
categoryNotified.put(category, categoryList);
listener.notify(categoryList);
// We will update our cache file after each notification.
// When our Registry has a subscribed failure due to network jitter, we can return at least the existing
// cache URL.
if (localCacheEnabled) {
saveProperties(url);
}
}
}
private void saveProperties(URL url) {
if (file == null) {
return;
}
try {
StringBuilder buf = new StringBuilder();
Map<String, List<URL>> categoryNotified = notified.get(url);
if (categoryNotified != null) {
for (List<URL> us : categoryNotified.values()) {
for (URL u : us) {
if (buf.length() > 0) {
buf.append(URL_SEPARATOR);
}
buf.append(u.toFullString());
}
}
}
properties.setProperty(url.getServiceKey(), buf.toString());
long version = lastCacheChanged.incrementAndGet();
if (syncSaveFile) {
doSaveProperties(version);
} else {
registryCacheExecutor.schedule(
() -> doSaveProperties(version), DEFAULT_INTERVAL_SAVE_PROPERTIES, TimeUnit.MILLISECONDS);
}
} catch (Throwable t) {
logger.warn(INTERNAL_ERROR, "unknown error in registry module", "", t.getMessage(), t);
}
}
@Override
public void destroy() {
if (logger.isInfoEnabled()) {
logger.info("Destroy registry:" + getUrl());
}
Set<URL> destroyRegistered = new HashSet<>(getRegistered());
if (!destroyRegistered.isEmpty()) {
for (URL url : new HashSet<>(destroyRegistered)) {
if (url.getParameter(DYNAMIC_KEY, true)) {
try {
unregister(url);
if (logger.isInfoEnabled()) {
logger.info("Destroy unregister url " + url);
}
} catch (Throwable t) {
// 1-8: Failed to unregister / unsubscribe url on destroy.
logger.warn(
REGISTRY_FAILED_DESTROY_UNREGISTER_URL,
"",
"",
"Failed to unregister url " + url + " to registry " + getUrl() + " on destroy, cause: "
+ t.getMessage(),
t);
}
}
}
}
Map<URL, Set<NotifyListener>> destroySubscribed = new HashMap<>(getSubscribed());
if (!destroySubscribed.isEmpty()) {
for (Map.Entry<URL, Set<NotifyListener>> entry : destroySubscribed.entrySet()) {
URL url = entry.getKey();
for (NotifyListener listener : entry.getValue()) {
try {
unsubscribe(url, listener);
if (logger.isInfoEnabled()) {
logger.info("Destroy unsubscribe url " + url);
}
} catch (Throwable t) {
// 1-8: Failed to unregister / unsubscribe url on destroy.
logger.warn(
REGISTRY_FAILED_DESTROY_UNREGISTER_URL,
"",
"",
"Failed to unsubscribe url " + url + " to registry " + getUrl() + " on destroy, cause: "
+ t.getMessage(),
t);
}
}
}
}
registryManager.removeDestroyedRegistry(this);
}
protected boolean acceptable(URL urlToRegistry) {
String pattern = registryUrl.getParameter(ACCEPTS_KEY);
if (StringUtils.isEmpty(pattern)) {
return true;
}
String[] accepts = COMMA_SPLIT_PATTERN.split(pattern);
Set<String> allow =
Arrays.stream(accepts).filter(p -> !p.startsWith("-")).collect(Collectors.toSet());
Set<String> disAllow = Arrays.stream(accepts)
.filter(p -> p.startsWith("-"))
.map(p -> p.substring(1))
.collect(Collectors.toSet());
if (CollectionUtils.isNotEmpty(allow)) {
// allow first
return allow.contains(urlToRegistry.getProtocol());
} else if (CollectionUtils.isNotEmpty(disAllow)) {
// contains disAllow, deny
return !disAllow.contains(urlToRegistry.getProtocol());
} else {
// default allow
return true;
}
}
@Override
public String toString() {
return getUrl().toString();
}
}
| 5,490 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/DefaultProviderFirstParams.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.registry.support;
import org.apache.dubbo.registry.ProviderFirstParams;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.METHODS_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.TIMESTAMP_KEY;
public class DefaultProviderFirstParams implements ProviderFirstParams {
private static final Set<String> PARAMS = Collections.unmodifiableSet(new HashSet<String>() {
{
addAll(Arrays.asList(RELEASE_KEY, DUBBO_VERSION_KEY, METHODS_KEY, TIMESTAMP_KEY, TAG_KEY));
}
});
@Override
public Set<String> params() {
return PARAMS;
}
}
| 5,491 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/RegistryManager.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.registry.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.registry.NotifyListener;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.client.ServiceDiscovery;
import org.apache.dubbo.registry.client.ServiceDiscoveryRegistry;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_FETCH_INSTANCE;
/**
* Application Level, used to collect Registries
*/
public class RegistryManager {
private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(RegistryManager.class);
private ApplicationModel applicationModel;
/**
* Registry Collection Map<RegistryAddress, Registry>
*/
private final Map<String, Registry> registries = new ConcurrentHashMap<>();
/**
* The lock for the acquisition process of the registry
*/
protected final ReentrantLock lock = new ReentrantLock();
private final AtomicBoolean destroyed = new AtomicBoolean(false);
public RegistryManager(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
}
/**
* Get all registries
*
* @return all registries
*/
public Collection<Registry> getRegistries() {
return Collections.unmodifiableCollection(new LinkedList<>(registries.values()));
}
public Registry getRegistry(String key) {
return registries.get(key);
}
public void putRegistry(String key, Registry registry) {
registries.put(key, registry);
}
public List<ServiceDiscovery> getServiceDiscoveries() {
return getRegistries().stream()
.filter(registry -> registry instanceof ServiceDiscoveryRegistry)
.map(registry -> (ServiceDiscoveryRegistry) registry)
.map(ServiceDiscoveryRegistry::getServiceDiscovery)
.collect(Collectors.toList());
}
/**
* Close all created registries
*/
public void destroyAll() {
if (!destroyed.compareAndSet(false, true)) {
return;
}
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Close all registries " + getRegistries());
}
// Lock up the registry shutdown process
lock.lock();
try {
for (Registry registry : getRegistries()) {
try {
registry.destroy();
} catch (Throwable e) {
LOGGER.warn(INTERNAL_ERROR, "unknown error in registry module", "", e.getMessage(), e);
}
}
registries.clear();
} finally {
// Release the lock
lock.unlock();
}
}
/**
* Reset state of AbstractRegistryFactory
*/
public void reset() {
destroyed.set(false);
registries.clear();
}
protected Registry getDefaultNopRegistryIfDestroyed() {
if (destroyed.get()) {
// 1-12 Failed to fetch (server) instance since the registry instances have been destroyed.
LOGGER.warn(
REGISTRY_FAILED_FETCH_INSTANCE,
"misuse of the methods",
"",
"All registry instances have been destroyed, failed to fetch any instance. "
+ "Usually, this means no need to try to do unnecessary redundant resource clearance, all registries has been taken care of.");
return DEFAULT_NOP_REGISTRY;
}
return null;
}
protected Lock getRegistryLock() {
return lock;
}
public void removeDestroyedRegistry(Registry toRm) {
lock.lock();
try {
registries.entrySet().removeIf(entry -> entry.getValue().equals(toRm));
} finally {
lock.unlock();
}
}
// for unit test
public void clearRegistryNotDestroy() {
registries.clear();
}
public static RegistryManager getInstance(ApplicationModel applicationModel) {
return applicationModel.getBeanFactory().getBean(RegistryManager.class);
}
private static final Registry DEFAULT_NOP_REGISTRY = new Registry() {
@Override
public URL getUrl() {
return null;
}
@Override
public boolean isAvailable() {
return false;
}
@Override
public void destroy() {}
@Override
public void register(URL url) {}
@Override
public void unregister(URL url) {}
@Override
public void subscribe(URL url, NotifyListener listener) {}
@Override
public void unsubscribe(URL url, NotifyListener listener) {}
@Override
public List<URL> lookup(URL url) {
return null;
}
};
}
| 5,492 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/RegistryClusterIdentifier.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.registry.client;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.rpc.model.ScopeModelUtil;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_CLUSTER_TYPE_KEY;
@SPI
public interface RegistryClusterIdentifier {
String providerKey(URL url);
String consumerKey(URL url);
static RegistryClusterIdentifier getExtension(URL url) {
ExtensionLoader<RegistryClusterIdentifier> loader =
ScopeModelUtil.getExtensionLoader(RegistryClusterIdentifier.class, url.getScopeModel());
return loader.getExtension(url.getParameter(REGISTRY_CLUSTER_TYPE_KEY, "default"));
}
}
| 5,493 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryFactory.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.registry.client;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.extension.SPI;
import static org.apache.dubbo.common.extension.ExtensionScope.APPLICATION;
/**
* The factory to create {@link ServiceDiscovery}
*
* @see ServiceDiscovery
* @since 2.7.5
*/
@SPI(value = "default", scope = APPLICATION)
public interface ServiceDiscoveryFactory {
/**
* Get the instance of {@link ServiceDiscovery}
*
* @param registryURL the {@link URL} to connect the registry
* @return non-null
*/
ServiceDiscovery getServiceDiscovery(URL registryURL);
/**
* Get the extension instance of {@link ServiceDiscoveryFactory} by {@link URL#getProtocol() the protocol}
*
* @param registryURL the {@link URL} to connect the registry
* @return non-null
*/
static ServiceDiscoveryFactory getExtension(URL registryURL) {
String protocol = registryURL.getProtocol();
ExtensionLoader<ServiceDiscoveryFactory> loader =
registryURL.getOrDefaultApplicationModel().getExtensionLoader(ServiceDiscoveryFactory.class);
return loader.getOrDefaultExtension(protocol);
}
}
| 5,494 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstance.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.registry.client;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ScopeModelUtil;
import java.beans.Transient;
import java.io.Serializable;
import java.util.Map;
import java.util.SortedMap;
/**
* The model class of an instance of a service, which is used for service registration and discovery.
* <p>
*
* @since 2.7.5
*/
public interface ServiceInstance extends Serializable {
/**
* The name of service that current instance belongs to.
*
* @return non-null
*/
String getServiceName();
/**
* The hostname of the registered service instance.
*
* @return non-null
*/
String getHost();
/**
* The port of the registered service instance.
*
* @return the positive integer if present
*/
int getPort();
String getAddress();
/**
* The enabled status of the registered service instance.
*
* @return if <code>true</code>, indicates current instance is enabled, or disable, the client should remove this one.
* The default value is <code>true</code>
*/
default boolean isEnabled() {
return true;
}
/**
* The registered service instance is health or not.
*
* @return if <code>true</code>, indicates current instance is healthy, or unhealthy, the client may ignore this one.
* The default value is <code>true</code>
*/
default boolean isHealthy() {
return true;
}
/**
* The key / value pair metadata associated with the service instance.
*
* @return non-null, mutable and unsorted {@link Map}
*/
Map<String, String> getMetadata();
SortedMap<String, String> getSortedMetadata();
String getRegistryCluster();
void setRegistryCluster(String registryCluster);
Map<String, String> getExtendParams();
String getExtendParam(String key);
String putExtendParam(String key, String value);
String putExtendParamIfAbsent(String key, String value);
String removeExtendParam(String key);
Map<String, String> getAllParams();
void setApplicationModel(ApplicationModel applicationModel);
@Transient
ApplicationModel getApplicationModel();
@Transient
default ApplicationModel getOrDefaultApplicationModel() {
return ScopeModelUtil.getApplicationModel(getApplicationModel());
}
/**
* Get the value of metadata by the specified name
*
* @param name the specified name
* @return the value of metadata if found, or <code>null</code>
* @since 2.7.8
*/
default String getMetadata(String name) {
return getMetadata(name, null);
}
/**
* Get the value of metadata by the specified name
*
* @param name the specified name
* @return the value of metadata if found, or <code>defaultValue</code>
* @since 2.7.8
*/
default String getMetadata(String name, String defaultValue) {
return getMetadata().getOrDefault(name, defaultValue);
}
MetadataInfo getServiceMetadata();
void setServiceMetadata(MetadataInfo serviceMetadata);
InstanceAddressURL toURL(String protocol);
}
| 5,495 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistry.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.registry.client;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.RegistryConstants;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.common.utils.ConcurrentHashSet;
import org.apache.dubbo.metadata.AbstractServiceNameMapping;
import org.apache.dubbo.metadata.MappingChangedEvent;
import org.apache.dubbo.metadata.MappingListener;
import org.apache.dubbo.metadata.ServiceNameMapping;
import org.apache.dubbo.metrics.event.MetricsEventBus;
import org.apache.dubbo.metrics.registry.event.RegistryEvent;
import org.apache.dubbo.registry.NotifyListener;
import org.apache.dubbo.registry.client.event.ServiceInstancesChangedEvent;
import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener;
import org.apache.dubbo.registry.support.FailbackRegistry;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_CLUSTER_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_TYPE_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.SERVICE_REGISTRY_TYPE;
import static org.apache.dubbo.common.function.ThrowableAction.execute;
import static org.apache.dubbo.common.utils.CollectionUtils.toTreeSet;
import static org.apache.dubbo.metadata.ServiceNameMapping.toStringKeys;
import static org.apache.dubbo.registry.client.ServiceDiscoveryFactory.getExtension;
/**
* TODO, this bridge implementation is not necessary now, protocol can interact with service discovery directly.
* <p>
* ServiceDiscoveryRegistry is a very special Registry implementation, which is used to bridge the old interface-level service discovery model
* with the new service discovery model introduced in 3.0 in a compatible manner.
* <p>
* It fully complies with the extension specification of the Registry SPI, but is different from the specific implementation of zookeeper and Nacos,
* because it does not interact with any real third-party registry, but only with the relevant components of ServiceDiscovery in the process.
* In short, it bridges the old interface model and the new service discovery model:
* <p>
* - register() aggregates interface level data into MetadataInfo by mainly interacting with MetadataService.
* - subscribe() triggers the whole subscribe process of the application level service discovery model.
* - Maps interface to applications depending on ServiceNameMapping.
* - Starts the new service discovery listener (InstanceListener) and makes NotifierListeners part of the InstanceListener.
*/
public class ServiceDiscoveryRegistry extends FailbackRegistry {
protected final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
private final ServiceDiscovery serviceDiscovery;
private final AbstractServiceNameMapping serviceNameMapping;
/* apps - listener */
private final Map<String, ServiceInstancesChangedListener> serviceListeners = new ConcurrentHashMap<>();
private final Map<String, Set<MappingListener>> mappingListeners = new ConcurrentHashMap<>();
/* This lock has the same scope and lifecycle as its corresponding instance listener.
It's used to make sure that only one interface mapping to the same app list can do subscribe or unsubscribe at the same moment.
And the lock should be destroyed when listener destroying its corresponding instance listener.
* */
private final ConcurrentMap<String, Lock> appSubscriptionLocks = new ConcurrentHashMap<>();
public ServiceDiscoveryRegistry(URL registryURL, ApplicationModel applicationModel) {
super(registryURL);
this.serviceDiscovery = createServiceDiscovery(registryURL);
this.serviceNameMapping =
(AbstractServiceNameMapping) ServiceNameMapping.getDefaultExtension(registryURL.getScopeModel());
super.applicationModel = applicationModel;
}
// Currently, for test purpose
protected ServiceDiscoveryRegistry(
URL registryURL, ServiceDiscovery serviceDiscovery, ServiceNameMapping serviceNameMapping) {
super(registryURL);
this.serviceDiscovery = serviceDiscovery;
this.serviceNameMapping = (AbstractServiceNameMapping) serviceNameMapping;
}
public ServiceDiscovery getServiceDiscovery() {
return serviceDiscovery;
}
/**
* Create the {@link ServiceDiscovery} from the registry {@link URL}
*
* @param registryURL the {@link URL} to connect the registry
* @return non-null
*/
protected ServiceDiscovery createServiceDiscovery(URL registryURL) {
return getServiceDiscovery(registryURL
.addParameter(INTERFACE_KEY, ServiceDiscovery.class.getName())
.removeParameter(REGISTRY_TYPE_KEY));
}
/**
* Get the instance {@link ServiceDiscovery} from the registry {@link URL} using
* {@link ServiceDiscoveryFactory} SPI
*
* @param registryURL the {@link URL} to connect the registry
* @return
*/
private ServiceDiscovery getServiceDiscovery(URL registryURL) {
ServiceDiscoveryFactory factory = getExtension(registryURL);
return factory.getServiceDiscovery(registryURL);
}
protected boolean shouldRegister(URL providerURL) {
String side = providerURL.getSide();
boolean should = PROVIDER_SIDE.equals(side); // Only register the Provider.
if (!should && logger.isDebugEnabled()) {
logger.debug(String.format("The URL[%s] should not be registered.", providerURL));
}
if (!acceptable(providerURL)) {
logger.info("URL " + providerURL + " will not be registered to Registry. Registry " + this.getUrl()
+ " does not accept service of this protocol type.");
return false;
}
return should;
}
protected boolean shouldSubscribe(URL subscribedURL) {
return !shouldRegister(subscribedURL);
}
@Override
public final void register(URL url) {
if (!shouldRegister(url)) { // Should Not Register
return;
}
doRegister(url);
}
@Override
public void doRegister(URL url) {
// fixme, add registry-cluster is not necessary anymore
url = addRegistryClusterKey(url);
serviceDiscovery.register(url);
}
@Override
public final void unregister(URL url) {
if (!shouldRegister(url)) {
return;
}
doUnregister(url);
}
@Override
public void doUnregister(URL url) {
// fixme, add registry-cluster is not necessary anymore
url = addRegistryClusterKey(url);
serviceDiscovery.unregister(url);
}
@Override
public final void subscribe(URL url, NotifyListener listener) {
if (!shouldSubscribe(url)) { // Should Not Subscribe
return;
}
doSubscribe(url, listener);
}
@Override
public void doSubscribe(URL url, NotifyListener listener) {
url = addRegistryClusterKey(url);
serviceDiscovery.subscribe(url, listener);
Set<String> mappingByUrl = ServiceNameMapping.getMappingByUrl(url);
String key = ServiceNameMapping.buildMappingKey(url);
if (mappingByUrl == null) {
Lock mappingLock = serviceNameMapping.getMappingLock(key);
try {
mappingLock.lock();
mappingByUrl = serviceNameMapping.getMapping(url);
try {
MappingListener mappingListener = new DefaultMappingListener(url, mappingByUrl, listener);
mappingByUrl = serviceNameMapping.getAndListen(this.getUrl(), url, mappingListener);
synchronized (mappingListeners) {
mappingListeners
.computeIfAbsent(url.getProtocolServiceKey(), (k) -> new ConcurrentHashSet<>())
.add(mappingListener);
}
} catch (Exception e) {
logger.warn(
INTERNAL_ERROR,
"",
"",
"Cannot find app mapping for service " + url.getServiceInterface() + ", will not migrate.",
e);
}
if (CollectionUtils.isEmpty(mappingByUrl)) {
logger.info(
"No interface-apps mapping found in local cache, stop subscribing, will automatically wait for mapping listener callback: "
+ url);
// if (check) {
// throw new IllegalStateException("Should has at least one way to know which
// services this interface belongs to, subscription url: " + url);
// }
return;
}
} finally {
mappingLock.unlock();
}
}
subscribeURLs(url, listener, mappingByUrl);
}
@Override
public final void unsubscribe(URL url, NotifyListener listener) {
if (!shouldSubscribe(url)) { // Should Not Subscribe
return;
}
url = addRegistryClusterKey(url);
doUnsubscribe(url, listener);
}
private URL addRegistryClusterKey(URL url) {
String registryCluster = serviceDiscovery.getUrl().getParameter(REGISTRY_CLUSTER_KEY);
if (registryCluster != null && url.getParameter(REGISTRY_CLUSTER_KEY) == null) {
url = url.addParameter(REGISTRY_CLUSTER_KEY, registryCluster);
}
return url;
}
@Override
public void doUnsubscribe(URL url, NotifyListener listener) {
// TODO: remove service name mapping listener
serviceDiscovery.unsubscribe(url, listener);
String protocolServiceKey = url.getProtocolServiceKey();
Set<String> serviceNames = serviceNameMapping.getMapping(url);
synchronized (mappingListeners) {
Set<MappingListener> keyedListeners = mappingListeners.get(protocolServiceKey);
if (keyedListeners != null) {
List<MappingListener> matched = keyedListeners.stream()
.filter(mappingListener -> mappingListener instanceof DefaultMappingListener
&& (Objects.equals(((DefaultMappingListener) mappingListener).getListener(), listener)))
.collect(Collectors.toList());
for (MappingListener mappingListener : matched) {
serviceNameMapping.stopListen(url, mappingListener);
keyedListeners.remove(mappingListener);
}
if (keyedListeners.isEmpty()) {
mappingListeners.remove(protocolServiceKey, Collections.emptySet());
}
}
}
if (CollectionUtils.isNotEmpty(serviceNames)) {
String serviceNamesKey = toStringKeys(serviceNames);
Lock appSubscriptionLock = getAppSubscription(serviceNamesKey);
try {
appSubscriptionLock.lock();
ServiceInstancesChangedListener instancesChangedListener = serviceListeners.get(serviceNamesKey);
if (instancesChangedListener != null) {
instancesChangedListener.removeListener(url.getServiceKey(), listener);
if (!instancesChangedListener.hasListeners()) {
instancesChangedListener.destroy();
serviceListeners.remove(serviceNamesKey);
removeAppSubscriptionLock(serviceNamesKey);
}
}
} finally {
appSubscriptionLock.unlock();
}
}
}
@Override
public List<URL> lookup(URL url) {
throw new UnsupportedOperationException("");
}
@Override
public boolean isAvailable() {
// serviceDiscovery isAvailable has a default method, which can be used as a reference when implementing
return serviceDiscovery.isAvailable();
}
@Override
public void destroy() {
registryManager.removeDestroyedRegistry(this);
// stop ServiceDiscovery
execute(serviceDiscovery::destroy);
// destroy all event listener
for (ServiceInstancesChangedListener listener : serviceListeners.values()) {
listener.destroy();
}
appSubscriptionLocks.clear();
serviceListeners.clear();
mappingListeners.clear();
}
@Override
public boolean isServiceDiscovery() {
return true;
}
protected void subscribeURLs(URL url, NotifyListener listener, Set<String> serviceNames) {
serviceNames = toTreeSet(serviceNames);
String serviceNamesKey = toStringKeys(serviceNames);
String serviceKey = url.getServiceKey();
logger.info(
String.format("Trying to subscribe from apps %s for service key %s, ", serviceNamesKey, serviceKey));
// register ServiceInstancesChangedListener
Lock appSubscriptionLock = getAppSubscription(serviceNamesKey);
try {
appSubscriptionLock.lock();
ServiceInstancesChangedListener serviceInstancesChangedListener = serviceListeners.get(serviceNamesKey);
if (serviceInstancesChangedListener == null) {
serviceInstancesChangedListener = serviceDiscovery.createListener(serviceNames);
for (String serviceName : serviceNames) {
List<ServiceInstance> serviceInstances = serviceDiscovery.getInstances(serviceName);
if (CollectionUtils.isNotEmpty(serviceInstances)) {
serviceInstancesChangedListener.onEvent(
new ServiceInstancesChangedEvent(serviceName, serviceInstances));
}
}
serviceListeners.put(serviceNamesKey, serviceInstancesChangedListener);
}
if (!serviceInstancesChangedListener.isDestroyed()) {
listener.addServiceListener(serviceInstancesChangedListener);
serviceInstancesChangedListener.addListenerAndNotify(url, listener);
ServiceInstancesChangedListener finalServiceInstancesChangedListener = serviceInstancesChangedListener;
String serviceDiscoveryName =
url.getParameter(RegistryConstants.REGISTRY_CLUSTER_KEY, url.getProtocol());
MetricsEventBus.post(
RegistryEvent.toSsEvent(
url.getApplicationModel(), serviceKey, Collections.singletonList(serviceDiscoveryName)),
() -> {
serviceDiscovery.addServiceInstancesChangedListener(finalServiceInstancesChangedListener);
return null;
});
} else {
logger.info(String.format("Listener of %s has been destroyed by another thread.", serviceNamesKey));
serviceListeners.remove(serviceNamesKey);
}
} finally {
appSubscriptionLock.unlock();
}
}
/**
* Supports or not ?
*
* @param registryURL the {@link URL url} of registry
* @return if supported, return <code>true</code>, or <code>false</code>
*/
public static boolean supports(URL registryURL) {
return SERVICE_REGISTRY_TYPE.equalsIgnoreCase(registryURL.getParameter(REGISTRY_TYPE_KEY));
}
public Map<String, ServiceInstancesChangedListener> getServiceListeners() {
return serviceListeners;
}
private class DefaultMappingListener implements MappingListener {
private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DefaultMappingListener.class);
private final URL url;
private Set<String> oldApps;
private NotifyListener listener;
private volatile boolean stopped;
public DefaultMappingListener(URL subscribedURL, Set<String> serviceNames, NotifyListener listener) {
this.url = subscribedURL;
this.oldApps = serviceNames;
this.listener = listener;
}
@Override
public synchronized void onEvent(MappingChangedEvent event) {
logger.info("Received mapping notification from meta server, " + event);
if (stopped) {
logger.warn(
INTERNAL_ERROR,
"",
"",
"Listener has been stopped, ignore mapping notification, check why listener is not removed.");
return;
}
Set<String> newApps = event.getApps();
Set<String> tempOldApps = oldApps;
if (CollectionUtils.isEmpty(newApps) || CollectionUtils.equals(newApps, tempOldApps)) {
return;
}
logger.info(
"Mapping of service " + event.getServiceKey() + "changed from " + tempOldApps + " to " + newApps);
Lock mappingLock = serviceNameMapping.getMappingLock(event.getServiceKey());
try {
mappingLock.lock();
if (CollectionUtils.isEmpty(tempOldApps) && !newApps.isEmpty()) {
serviceNameMapping.putCachedMapping(ServiceNameMapping.buildMappingKey(url), newApps);
subscribeURLs(url, listener, newApps);
oldApps = newApps;
return;
}
for (String newAppName : newApps) {
if (!tempOldApps.contains(newAppName)) {
serviceNameMapping.removeCachedMapping(ServiceNameMapping.buildMappingKey(url));
serviceNameMapping.putCachedMapping(ServiceNameMapping.buildMappingKey(url), newApps);
// old instance listener related to old app list that needs to be destroyed after subscribe
// refresh.
ServiceInstancesChangedListener oldListener = listener.getServiceListener();
if (oldListener != null) {
String appKey = toStringKeys(toTreeSet(tempOldApps));
Lock appSubscriptionLock = getAppSubscription(appKey);
try {
appSubscriptionLock.lock();
oldListener.removeListener(url.getServiceKey(), listener);
if (!oldListener.hasListeners()) {
oldListener.destroy();
removeAppSubscriptionLock(appKey);
}
} finally {
appSubscriptionLock.unlock();
}
}
subscribeURLs(url, listener, newApps);
oldApps = newApps;
return;
}
}
} finally {
mappingLock.unlock();
}
}
protected NotifyListener getListener() {
return listener;
}
@Override
public void stop() {
stopped = true;
}
}
public Lock getAppSubscription(String key) {
return ConcurrentHashMapUtils.computeIfAbsent(appSubscriptionLocks, key, _k -> new ReentrantLock());
}
public void removeAppSubscriptionLock(String key) {
Lock lock = appSubscriptionLocks.get(key);
if (lock != null) {
try {
lock.lock();
appSubscriptionLocks.remove(key);
} finally {
lock.unlock();
}
}
}
}
| 5,496 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/DefaultRegistryClusterIdentifier.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.registry.client;
import org.apache.dubbo.common.URL;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_CLUSTER_KEY;
public class DefaultRegistryClusterIdentifier implements RegistryClusterIdentifier {
@Override
public String providerKey(URL url) {
return url.getParameter(REGISTRY_CLUSTER_KEY);
}
@Override
public String consumerKey(URL url) {
return url.getParameter(REGISTRY_CLUSTER_KEY);
}
}
| 5,497 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/DefaultServiceInstance.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.registry.client;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.beans.Transient;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.ENDPOINTS;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.EXPORTED_SERVICES_REVISION_PROPERTY_NAME;
/**
* The default implementation of {@link ServiceInstance}.
*
* @since 2.7.5
*/
public class DefaultServiceInstance implements ServiceInstance {
private static final long serialVersionUID = 1149677083747278100L;
private String rawAddress;
private String serviceName;
private String host;
private int port;
private boolean enabled = true;
private boolean healthy = true;
private Map<String, String> metadata = new HashMap<>();
private transient String address;
private transient MetadataInfo serviceMetadata;
/**
* used at runtime
*/
private transient String registryCluster;
/**
* extendParams can be more flexible, but one single property uses less space
*/
private transient Map<String, String> extendParams;
private transient List<Endpoint> endpoints;
private transient ApplicationModel applicationModel;
private transient Map<String, InstanceAddressURL> instanceAddressURL = new ConcurrentHashMap<>();
public DefaultServiceInstance() {}
public DefaultServiceInstance(DefaultServiceInstance other) {
this.serviceName = other.serviceName;
this.host = other.host;
this.port = other.port;
this.enabled = other.enabled;
this.healthy = other.healthy;
this.serviceMetadata = other.serviceMetadata;
this.registryCluster = other.registryCluster;
this.address = null;
this.metadata = new HashMap<>(other.metadata);
this.applicationModel = other.applicationModel;
this.extendParams = other.extendParams != null ? new HashMap<>(other.extendParams) : other.extendParams;
this.endpoints = other.endpoints != null ? new ArrayList<>(other.endpoints) : other.endpoints;
}
public DefaultServiceInstance(String serviceName, String host, Integer port, ApplicationModel applicationModel) {
if (port == null || port < 1) {
throw new IllegalArgumentException("The port value is illegal, the value is " + port);
}
this.serviceName = serviceName;
this.host = host;
this.port = port;
setApplicationModel(applicationModel);
}
public DefaultServiceInstance(String serviceName, ApplicationModel applicationModel) {
this.serviceName = serviceName;
setApplicationModel(applicationModel);
}
public void setRawAddress(String rawAddress) {
this.rawAddress = rawAddress;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
public void setHost(String host) {
this.host = host;
}
@Override
public String getServiceName() {
return serviceName;
}
@Override
public String getHost() {
return host;
}
public void setPort(int port) {
this.port = port;
}
@Override
public int getPort() {
return port;
}
@Override
public String getAddress() {
if (address == null) {
address = getAddress(host, port);
}
return address;
}
private static String getAddress(String host, Integer port) {
return port != null && port <= 0 ? host : host + ':' + port;
}
@Override
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
@Override
public boolean isHealthy() {
return healthy;
}
public void setHealthy(boolean healthy) {
this.healthy = healthy;
}
@Override
public Map<String, String> getMetadata() {
return metadata;
}
@Override
public SortedMap<String, String> getSortedMetadata() {
return new TreeMap<>(getMetadata());
}
@Override
public String getRegistryCluster() {
return registryCluster;
}
@Override
public void setRegistryCluster(String registryCluster) {
this.registryCluster = registryCluster;
}
@Override
public Map<String, String> getExtendParams() {
if (extendParams == null) {
return Collections.emptyMap();
}
return extendParams;
}
@Override
public String getExtendParam(String key) {
if (extendParams == null) {
return null;
}
return extendParams.get(key);
}
@Override
public String putExtendParam(String key, String value) {
if (extendParams == null) {
extendParams = new HashMap<>();
}
return extendParams.put(key, value);
}
@Override
public String putExtendParamIfAbsent(String key, String value) {
if (extendParams == null) {
extendParams = new HashMap<>();
}
return extendParams.putIfAbsent(key, value);
}
@Override
public String removeExtendParam(String key) {
if (extendParams == null) {
return null;
}
return extendParams.remove(key);
}
public void setEndpoints(List<Endpoint> endpoints) {
this.endpoints = endpoints;
}
public List<Endpoint> getEndpoints() {
if (endpoints == null) {
endpoints = new LinkedList<>(JsonUtils.toJavaList(metadata.get(ENDPOINTS), Endpoint.class));
}
return endpoints;
}
public DefaultServiceInstance copyFrom(Endpoint endpoint) {
DefaultServiceInstance copyOfInstance = new DefaultServiceInstance(this);
copyOfInstance.setPort(endpoint.getPort());
return copyOfInstance;
}
public DefaultServiceInstance copyFrom(int port) {
DefaultServiceInstance copyOfInstance = new DefaultServiceInstance(this);
copyOfInstance.setPort(port);
return copyOfInstance;
}
@Override
public Map<String, String> getAllParams() {
if (extendParams == null) {
return metadata;
} else {
Map<String, String> allParams = new HashMap<>((int) ((metadata.size() + extendParams.size()) / 0.75f + 1));
allParams.putAll(metadata);
allParams.putAll(extendParams);
return allParams;
}
}
@Override
public void setApplicationModel(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
}
@Override
@Transient
public ApplicationModel getApplicationModel() {
return applicationModel;
}
public void setMetadata(Map<String, String> metadata) {
this.metadata = metadata;
}
@Override
public MetadataInfo getServiceMetadata() {
return serviceMetadata;
}
@Override
public void setServiceMetadata(MetadataInfo serviceMetadata) {
this.serviceMetadata = serviceMetadata;
this.instanceAddressURL.clear();
}
@Override
public InstanceAddressURL toURL(String protocol) {
return instanceAddressURL.computeIfAbsent(
protocol, key -> new InstanceAddressURL(this, serviceMetadata, protocol));
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof DefaultServiceInstance)) {
return false;
}
DefaultServiceInstance that = (DefaultServiceInstance) o;
boolean equals = Objects.equals(getServiceName(), that.getServiceName())
&& Objects.equals(getHost(), that.getHost())
&& Objects.equals(getPort(), that.getPort());
for (Map.Entry<String, String> entry : this.getMetadata().entrySet()) {
if (entry.getKey().equals(EXPORTED_SERVICES_REVISION_PROPERTY_NAME)) {
continue;
}
if (entry.getValue() == null) {
equals = equals && (entry.getValue() == that.getMetadata().get(entry.getKey()));
} else {
equals = equals && entry.getValue().equals(that.getMetadata().get(entry.getKey()));
}
}
return equals;
}
@Override
public int hashCode() {
int result = Objects.hash(getServiceName(), getHost(), getPort());
for (Map.Entry<String, String> entry : this.getMetadata().entrySet()) {
if (entry.getKey().equals(EXPORTED_SERVICES_REVISION_PROPERTY_NAME)) {
continue;
}
result = 31 * result
+ (entry.getValue() == null ? 0 : entry.getValue().hashCode());
}
return result;
}
@Override
public String toString() {
return rawAddress == null ? toFullString() : rawAddress;
}
public String toFullString() {
return "DefaultServiceInstance{" + "serviceName='"
+ serviceName + '\'' + ", host='"
+ host + '\'' + ", port="
+ port + ", enabled="
+ enabled + ", healthy="
+ healthy + ", metadata="
+ metadata + '}';
}
public static class Endpoint {
int port;
String protocol;
public Endpoint() {}
public Endpoint(int port, String protocol) {
this.port = port;
this.protocol = protocol;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
}
}
| 5,498 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ReflectionBasedServiceDiscovery.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.registry.client;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.common.utils.NamedThreadFactory;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.metadata.InstanceMetadataChangedListener;
import org.apache.dubbo.metadata.MetadataService;
import org.apache.dubbo.metadata.RevisionResolver;
import org.apache.dubbo.registry.Constants;
import org.apache.dubbo.registry.client.event.ServiceInstancesChangedEvent;
import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener;
import org.apache.dubbo.registry.client.metadata.MetadataServiceDelegation;
import org.apache.dubbo.registry.client.metadata.MetadataUtils;
import org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ScopeModelUtil;
import org.apache.dubbo.rpc.service.Destroyable;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_NOTIFY_EVENT;
public class ReflectionBasedServiceDiscovery extends AbstractServiceDiscovery {
private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
/**
* Echo check if consumer is still work
* echo task may take a lot of time when consumer offline, create a new ScheduledThreadPool
*/
private final ScheduledExecutorService echoCheckExecutor =
Executors.newScheduledThreadPool(1, new NamedThreadFactory("Dubbo-Registry-EchoCheck-Consumer"));
// =================================== Provider side =================================== //
/**
* Local {@link ServiceInstance} Metadata's revision
*/
private String lastMetadataRevision;
// =================================== Consumer side =================================== //
/**
* Local Cache of {@link ServiceInstance} Metadata
* <p>
* Key - {@link ServiceInstance} ID ( usually ip + port )
* Value - Json processed metadata string
*/
private final ConcurrentHashMap<String, String> metadataMap = new ConcurrentHashMap<>();
/**
* Local Cache of {@link ServiceInstance}
* <p>
* Key - Service Name
* Value - List {@link ServiceInstance}
*/
private final ConcurrentHashMap<String, List<ServiceInstance>> cachedServiceInstances = new ConcurrentHashMap<>();
private final MetadataServiceDelegation metadataService;
public ConcurrentMap<String, MetadataService> metadataServiceProxies = new ConcurrentHashMap<>();
/**
* Local Cache of Service's {@link ServiceInstance} list revision,
* used to check if {@link ServiceInstance} list has been updated
* <p>
* Key - ServiceName
* Value - a revision calculate from {@link List} of {@link ServiceInstance}
*/
private final ConcurrentHashMap<String, String> serviceInstanceRevisionMap = new ConcurrentHashMap<>();
public ReflectionBasedServiceDiscovery(ApplicationModel applicationModel, URL registryURL) {
super(applicationModel, registryURL);
long echoPollingCycle =
registryURL.getParameter(Constants.ECHO_POLLING_CYCLE_KEY, Constants.DEFAULT_ECHO_POLLING_CYCLE);
this.metadataService = applicationModel.getBeanFactory().getOrRegisterBean(MetadataServiceDelegation.class);
// Echo check: test if consumer is offline, remove MetadataChangeListener,
// reduce the probability of failure when metadata update
echoCheckExecutor.scheduleAtFixedRate(
() -> {
Map<String, InstanceMetadataChangedListener> listenerMap =
metadataService.getInstanceMetadataChangedListenerMap();
Iterator<Map.Entry<String, InstanceMetadataChangedListener>> iterator =
listenerMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, InstanceMetadataChangedListener> entry = iterator.next();
try {
entry.getValue().echo(CommonConstants.DUBBO);
} catch (RpcException e) {
if (logger.isInfoEnabled()) {
logger.info(
"Send echo message to consumer error. Possible cause: consumer is offline.");
}
iterator.remove();
}
}
},
echoPollingCycle,
echoPollingCycle,
TimeUnit.MILLISECONDS);
}
public void doInitialize(URL registryURL) {}
@Override
public void doDestroy() throws Exception {
metadataMap.clear();
serviceInstanceRevisionMap.clear();
echoCheckExecutor.shutdown();
}
private void updateInstanceMetadata(ServiceInstance serviceInstance) {
String metadataString = JsonUtils.toJson(serviceInstance.getMetadata());
String metadataRevision = RevisionResolver.calRevision(metadataString);
// check if metadata updated
if (!metadataRevision.equalsIgnoreCase(lastMetadataRevision)) {
if (logger.isDebugEnabled()) {
logger.debug("Update Service Instance Metadata of DNS registry. Newer metadata: " + metadataString);
}
lastMetadataRevision = metadataRevision;
// save the newest metadata to local
metadataService.exportInstanceMetadata(metadataString);
// notify to consumer
Map<String, InstanceMetadataChangedListener> listenerMap =
metadataService.getInstanceMetadataChangedListenerMap();
Iterator<Map.Entry<String, InstanceMetadataChangedListener>> iterator =
listenerMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, InstanceMetadataChangedListener> entry = iterator.next();
try {
entry.getValue().onEvent(metadataString);
} catch (RpcException e) {
// 1-7 - Failed to notify registry event.
// The updating of metadata to consumer is a type of registry event.
logger.warn(
REGISTRY_FAILED_NOTIFY_EVENT,
"consumer is offline",
"",
"Notify to consumer error, removing listener.");
// remove listener if consumer is offline
iterator.remove();
}
}
}
}
@Override
public void doRegister(ServiceInstance serviceInstance) throws RuntimeException {
updateInstanceMetadata(serviceInstance);
}
@Override
public void doUnregister(ServiceInstance serviceInstance) throws RuntimeException {
// notify empty message to consumer
metadataService.exportInstanceMetadata("");
metadataService.getInstanceMetadataChangedListenerMap().forEach((consumerId, listener) -> listener.onEvent(""));
metadataService.getInstanceMetadataChangedListenerMap().clear();
}
@SuppressWarnings("unchecked")
public final void fillServiceInstance(DefaultServiceInstance serviceInstance) {
String hostId = serviceInstance.getAddress();
if (metadataMap.containsKey(hostId)) {
// Use cached metadata.
// Metadata will be updated by provider callback
String metadataString = metadataMap.get(hostId);
serviceInstance.setMetadata(JsonUtils.toJavaObject(metadataString, Map.class));
} else {
// refer from MetadataUtils, this proxy is different from the one used to refer exportedURL
MetadataService metadataService = getMetadataServiceProxy(serviceInstance);
String consumerId = ScopeModelUtil.getApplicationModel(registryURL.getScopeModel())
.getApplicationName()
+ NetUtils.getLocalHost();
String metadata = metadataService.getAndListenInstanceMetadata(consumerId, metadataString -> {
if (logger.isDebugEnabled()) {
logger.debug("Receive callback: " + metadataString + serviceInstance);
}
if (StringUtils.isEmpty(metadataString)) {
// provider is shutdown
metadataMap.remove(hostId);
} else {
metadataMap.put(hostId, metadataString);
}
});
metadataMap.put(hostId, metadata);
serviceInstance.setMetadata(JsonUtils.toJavaObject(metadata, Map.class));
}
}
public final void notifyListener(
String serviceName, ServiceInstancesChangedListener listener, List<ServiceInstance> instances) {
String serviceInstanceRevision = RevisionResolver.calRevision(JsonUtils.toJson(instances));
boolean changed = !serviceInstanceRevision.equalsIgnoreCase(
serviceInstanceRevisionMap.put(serviceName, serviceInstanceRevision));
if (logger.isDebugEnabled()) {
logger.debug("Service changed event received (possibly because of DNS polling). "
+ "Service Instance changed: " + changed + " Service Name: " + serviceName);
}
if (changed) {
List<ServiceInstance> oldServiceInstances =
cachedServiceInstances.getOrDefault(serviceName, new LinkedList<>());
// remove expired invoker
Set<ServiceInstance> allServiceInstances = new HashSet<>(oldServiceInstances.size() + instances.size());
allServiceInstances.addAll(oldServiceInstances);
allServiceInstances.addAll(instances);
oldServiceInstances.forEach(allServiceInstances::remove);
allServiceInstances.forEach(this::destroyMetadataServiceProxy);
cachedServiceInstances.put(serviceName, instances);
listener.onEvent(new ServiceInstancesChangedEvent(serviceName, instances));
}
}
@Override
public Set<String> getServices() {
return Collections.emptySet();
}
@Override
public List<ServiceInstance> getInstances(String serviceName) throws NullPointerException {
return Collections.emptyList();
}
private String computeKey(ServiceInstance serviceInstance) {
return serviceInstance.getServiceName() + "##" + serviceInstance.getAddress() + "##"
+ ServiceInstanceMetadataUtils.getExportedServicesRevision(serviceInstance);
}
private synchronized MetadataService getMetadataServiceProxy(ServiceInstance instance) {
return ConcurrentHashMapUtils.computeIfAbsent(
metadataServiceProxies, computeKey(instance), k -> MetadataUtils.referProxy(instance)
.getProxy());
}
private synchronized void destroyMetadataServiceProxy(ServiceInstance instance) {
String key = computeKey(instance);
if (metadataServiceProxies.containsKey(key)) {
Object metadataServiceProxy = metadataServiceProxies.remove(key);
if (metadataServiceProxy instanceof Destroyable) {
((Destroyable) metadataServiceProxy).$destroy();
}
}
}
/**
* UT used only
*/
@Deprecated
public final ConcurrentHashMap<String, List<ServiceInstance>> getCachedServiceInstances() {
return cachedServiceInstances;
}
}
| 5,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.