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-xds/src/test/java/org/apache/dubbo/registry/xds/util/protocol
Create_ds/dubbo/dubbo-xds/src/test/java/org/apache/dubbo/registry/xds/util/protocol/impl/RdsProtocolMock.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.xds.util.protocol.impl; import org.apache.dubbo.registry.xds.util.AdsObserver; import org.apache.dubbo.registry.xds.util.protocol.message.RouteResult; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Consumer; import io.envoyproxy.envoy.config.core.v3.Node; public class RdsProtocolMock extends RdsProtocol { public RdsProtocolMock(AdsObserver adsObserver, Node node, int checkInterval) { super(adsObserver, node, checkInterval); } public Map<String, RouteResult> getResourcesMap() { return resourcesMap; } public void setResourcesMap(Map<String, RouteResult> resourcesMap) { this.resourcesMap = resourcesMap; } public Set<String> getObserveResourcesName() { return observeResourcesName; } public void setConsumerObserveMap(Map<Set<String>, List<Consumer<Map<String, RouteResult>>>> consumerObserveMap) { this.consumerObserveMap = consumerObserveMap; } public void setObserveResourcesName(Set<String> observeResourcesName) { this.observeResourcesName = observeResourcesName; } }
6,200
0
Create_ds/dubbo/dubbo-xds/src/test/java/org/apache/dubbo/registry/xds/util/protocol
Create_ds/dubbo/dubbo-xds/src/test/java/org/apache/dubbo/registry/xds/util/protocol/impl/EdsProtocolMock.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.xds.util.protocol.impl; import org.apache.dubbo.registry.xds.util.AdsObserver; import org.apache.dubbo.registry.xds.util.protocol.message.EndpointResult; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Consumer; import io.envoyproxy.envoy.config.core.v3.Node; public class EdsProtocolMock extends EdsProtocol { public EdsProtocolMock(AdsObserver adsObserver, Node node, int checkInterval) { super(adsObserver, node, checkInterval); } public Map<String, EndpointResult> getResourcesMap() { return resourcesMap; } public void setResourcesMap(Map<String, EndpointResult> resourcesMap) { this.resourcesMap = resourcesMap; } public void setConsumerObserveMap( Map<Set<String>, List<Consumer<Map<String, EndpointResult>>>> consumerObserveMap) { this.consumerObserveMap = consumerObserveMap; } public void setObserveResourcesName(Set<String> observeResourcesName) { this.observeResourcesName = observeResourcesName; } }
6,201
0
Create_ds/dubbo/dubbo-xds/src/test/java/org/apache/dubbo/registry/xds/util/protocol
Create_ds/dubbo/dubbo-xds/src/test/java/org/apache/dubbo/registry/xds/util/protocol/impl/LdsProtocolMock.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.xds.util.protocol.impl; import org.apache.dubbo.registry.xds.util.AdsObserver; import org.apache.dubbo.registry.xds.util.protocol.message.ListenerResult; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Consumer; import io.envoyproxy.envoy.config.core.v3.Node; import io.envoyproxy.envoy.service.discovery.v3.DiscoveryRequest; public class LdsProtocolMock extends LdsProtocol { public LdsProtocolMock(AdsObserver adsObserver, Node node, int checkInterval) { super(adsObserver, node, checkInterval); } public Map<String, ListenerResult> getResourcesMap() { return resourcesMap; } public void setResourcesMap(Map<String, ListenerResult> resourcesMap) { this.resourcesMap = resourcesMap; } protected DiscoveryRequest buildDiscoveryRequest(Set<String> resourceNames) { return DiscoveryRequest.newBuilder() .setNode(node) .setTypeUrl(getTypeUrl()) .addAllResourceNames(resourceNames) .build(); } public Set<String> getObserveResourcesName() { return observeResourcesName; } public void setObserveResourcesName(Set<String> observeResourcesName) { this.observeResourcesName = observeResourcesName; } public Map<Set<String>, List<Consumer<Map<String, ListenerResult>>>> getConsumerObserveMap() { return consumerObserveMap; } public void setConsumerObserveMap( Map<Set<String>, List<Consumer<Map<String, ListenerResult>>>> consumerObserveMap) { this.consumerObserveMap = consumerObserveMap; } }
6,202
0
Create_ds/dubbo/dubbo-xds/src/test/java/org/apache/dubbo/rpc/cluster/router
Create_ds/dubbo/dubbo-xds/src/test/java/org/apache/dubbo/rpc/cluster/router/xds/RdsRouteRuleManagerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.router.xds; import org.apache.dubbo.rpc.cluster.router.xds.rule.HTTPRouteDestination; import org.apache.dubbo.rpc.cluster.router.xds.rule.HttpRequestMatch; import org.apache.dubbo.rpc.cluster.router.xds.rule.XdsRouteRule; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; 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; public class RdsRouteRuleManagerTest { @BeforeEach public void before() { RdsRouteRuleManager.getRuleListeners().clear(); RdsRouteRuleManager.getRouteDataCache().clear(); RdsRouteRuleManager.getRdsListeners().clear(); } @Test public void subscribeRdsTest() { RdsRouteRuleManager manager = new RdsRouteRuleManager(); String domain = "testApp"; int subscribeNum = 3; for (int i = 0; i < subscribeNum; i++) { manager.subscribeRds(domain, new XdsRouteRuleListener() { @Override public void onRuleChange(String appName, List<XdsRouteRule> xdsRouteRules) {} @Override public void clearRule(String appName) {} }); } assertNotNull(RdsRouteRuleManager.getRdsListeners().get(domain)); assertEquals(RdsRouteRuleManager.getRuleListeners().get(domain).size(), subscribeNum); } @Test public void unsubscribeRdsTest() { RdsRouteRuleManager manager = new RdsRouteRuleManager(); String domain = "testApp"; XdsRouteRuleListener listener = new XdsRouteRuleListener() { @Override public void onRuleChange(String appName, List<XdsRouteRule> xdsRouteRules) {} @Override public void clearRule(String appName) {} }; manager.subscribeRds(domain, listener); assertNotNull(RdsRouteRuleManager.getRdsListeners().get(domain)); assertEquals(RdsRouteRuleManager.getRuleListeners().get(domain).size(), 1); manager.unSubscribeRds(domain, listener); assertNull(RdsRouteRuleManager.getRdsListeners().get(domain)); assertNull(RdsRouteRuleManager.getRuleListeners().get(domain)); } @Test public void notifyRuleChangeTest() { Map<String, List<XdsRouteRule>> cacheData = new HashMap<>(); String domain = "testApp"; List<XdsRouteRule> xdsRouteRules = new ArrayList<>(); XdsRouteRule rule = new XdsRouteRule(new HttpRequestMatch(null, null), new HTTPRouteDestination()); xdsRouteRules.add(rule); XdsRouteRuleListener listener = new XdsRouteRuleListener() { @Override public void onRuleChange(String appName, List<XdsRouteRule> xdsRouteRules) { cacheData.put(appName, xdsRouteRules); } @Override public void clearRule(String appName) { cacheData.remove(appName); } }; RdsRouteRuleManager manager = new RdsRouteRuleManager(); manager.subscribeRds(domain, listener); manager.notifyRuleChange(domain, xdsRouteRules); assertEquals(cacheData.get(domain), xdsRouteRules); Map<String, List<XdsRouteRule>> cacheData2 = new HashMap<>(); XdsRouteRuleListener listener2 = new XdsRouteRuleListener() { @Override public void onRuleChange(String appName, List<XdsRouteRule> xdsRouteRules) { cacheData2.put(appName, xdsRouteRules); } @Override public void clearRule(String appName) { cacheData2.remove(appName); } }; manager.subscribeRds(domain, listener2); assertEquals(cacheData2.get(domain), xdsRouteRules); // clear manager.notifyRuleChange(domain, new ArrayList<>()); assertNull(cacheData.get(domain)); } }
6,203
0
Create_ds/dubbo/dubbo-xds/src/test/java/org/apache/dubbo/rpc/cluster/router
Create_ds/dubbo/dubbo-xds/src/test/java/org/apache/dubbo/rpc/cluster/router/xds/EdsEndpointManagerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.router.xds; import org.apache.dubbo.registry.xds.util.protocol.message.Endpoint; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; 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; public class EdsEndpointManagerTest { @BeforeEach public void before() { EdsEndpointManager.getEdsListeners().clear(); EdsEndpointManager.getEndpointListeners().clear(); EdsEndpointManager.getEndpointDataCache().clear(); } @Test public void subscribeEdsTest() { EdsEndpointManager manager = new EdsEndpointManager(); String cluster = "testApp"; int subscribeNum = 3; for (int i = 0; i < subscribeNum; i++) { manager.subscribeEds(cluster, new EdsEndpointListener() { @Override public void onEndPointChange(String cluster, Set<Endpoint> endpoints) {} }); } assertNotNull(EdsEndpointManager.getEdsListeners().get(cluster)); assertEquals(EdsEndpointManager.getEndpointListeners().get(cluster).size(), subscribeNum); } @Test public void unsubscribeRdsTest() { EdsEndpointManager manager = new EdsEndpointManager(); String domain = "testApp"; EdsEndpointListener listener = new EdsEndpointListener() { @Override public void onEndPointChange(String cluster, Set<Endpoint> endpoints) {} }; manager.subscribeEds(domain, listener); assertNotNull(EdsEndpointManager.getEdsListeners().get(domain)); assertEquals(EdsEndpointManager.getEndpointListeners().get(domain).size(), 1); manager.unSubscribeEds(domain, listener); assertNull(EdsEndpointManager.getEdsListeners().get(domain)); assertNull(EdsEndpointManager.getEndpointListeners().get(domain)); } @Test public void notifyRuleChangeTest() { Map<String, Set<Endpoint>> cacheData = new HashMap<>(); String domain = "testApp"; Set<Endpoint> endpoints = new HashSet<>(); Endpoint endpoint = new Endpoint(); endpoints.add(endpoint); EdsEndpointListener listener = new EdsEndpointListener() { @Override public void onEndPointChange(String cluster, Set<Endpoint> endpoints) { cacheData.put(cluster, endpoints); } }; EdsEndpointManager manager = new EdsEndpointManager(); manager.subscribeEds(domain, listener); manager.notifyEndpointChange(domain, endpoints); assertEquals(cacheData.get(domain), endpoints); Map<String, Set<Endpoint>> cacheData2 = new HashMap<>(); EdsEndpointListener listener2 = new EdsEndpointListener() { @Override public void onEndPointChange(String cluster, Set<Endpoint> endpoints) { cacheData2.put(cluster, endpoints); } }; manager.subscribeEds(domain, listener2); assertEquals(cacheData2.get(domain), endpoints); // clear manager.notifyEndpointChange(domain, new HashSet<>()); assertEquals(cacheData.get(domain).size(), 0); } }
6,204
0
Create_ds/dubbo/dubbo-xds/src/test/java/org/apache/dubbo/rpc/cluster/router
Create_ds/dubbo/dubbo-xds/src/test/java/org/apache/dubbo/rpc/cluster/router/xds/RdsVirtualHostListenerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.router.xds; import org.apache.dubbo.rpc.cluster.router.xds.rule.ClusterWeight; import org.apache.dubbo.rpc.cluster.router.xds.rule.XdsRouteRule; import java.util.HashMap; import java.util.List; import java.util.Map; import com.google.protobuf.BoolValue; import com.google.protobuf.UInt32Value; import io.envoyproxy.envoy.config.route.v3.HeaderMatcher; import io.envoyproxy.envoy.config.route.v3.Route; import io.envoyproxy.envoy.config.route.v3.RouteAction; import io.envoyproxy.envoy.config.route.v3.RouteMatch; import io.envoyproxy.envoy.config.route.v3.VirtualHost; import io.envoyproxy.envoy.config.route.v3.WeightedCluster; import io.envoyproxy.envoy.type.matcher.v3.RegexMatcher; import io.envoyproxy.envoy.type.v3.Int64Range; 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.assertTrue; public class RdsVirtualHostListenerTest { private final String domain = "testApp"; private final Map<String, List<XdsRouteRule>> dataCache = new HashMap<>(); private final XdsRouteRuleListener listener = new XdsRouteRuleListener() { @Override public void onRuleChange(String appName, List<XdsRouteRule> xdsRouteRules) { dataCache.put(appName, xdsRouteRules); } @Override public void clearRule(String appName) { dataCache.remove(appName); } }; private final RdsRouteRuleManager manager = new RdsRouteRuleManager(); private final RdsVirtualHostListener rdsVirtualHostListener = new RdsVirtualHostListener("testApp", manager); @BeforeEach public void init() { dataCache.clear(); manager.subscribeRds(domain, listener); } @Test public void parsePathPathMatcherTest() { String path = "/test/name"; VirtualHost virtualHost = VirtualHost.newBuilder() .addDomains(domain) .addRoutes(Route.newBuilder() .setName("route-test") .setMatch(RouteMatch.newBuilder() .setPath(path) .setCaseSensitive( BoolValue.newBuilder().setValue(true).build()) .build()) .setRoute(RouteAction.newBuilder() .setCluster("cluster-test") .build()) .build()) .build(); rdsVirtualHostListener.parseVirtualHost(virtualHost); List<XdsRouteRule> rules = dataCache.get(domain); assertNotNull(rules); assertEquals(rules.get(0).getMatch().getPathMatcher().getPath(), path); assertTrue(rules.get(0).getMatch().getPathMatcher().isCaseSensitive()); } @Test public void parsePrefixPathMatcherTest() { String prefix = "/test"; VirtualHost virtualHost = VirtualHost.newBuilder() .addDomains(domain) .addRoutes(Route.newBuilder() .setName("route-test") .setMatch(RouteMatch.newBuilder().setPrefix(prefix).build()) .setRoute(RouteAction.newBuilder() .setCluster("cluster-test") .build()) .build()) .build(); rdsVirtualHostListener.parseVirtualHost(virtualHost); List<XdsRouteRule> rules = dataCache.get(domain); assertNotNull(rules); assertEquals(rules.get(0).getMatch().getPathMatcher().getPrefix(), prefix); } @Test public void parseRegexPathMatcherTest() { String regex = "/test/.*"; VirtualHost virtualHost = VirtualHost.newBuilder() .addDomains(domain) .addRoutes(Route.newBuilder() .setName("route-test") .setMatch(RouteMatch.newBuilder() .setSafeRegex(RegexMatcher.newBuilder() .setRegex(regex) .build()) .build()) .setRoute(RouteAction.newBuilder() .setCluster("cluster-test") .build()) .build()) .build(); rdsVirtualHostListener.parseVirtualHost(virtualHost); List<XdsRouteRule> rules = dataCache.get(domain); assertNotNull(rules); assertEquals(rules.get(0).getMatch().getPathMatcher().getRegex(), regex); } @Test public void parseHeadMatcherTest() { VirtualHost virtualHost = VirtualHost.newBuilder() .addDomains(domain) .addRoutes(Route.newBuilder() .setName("route-test") .setMatch(RouteMatch.newBuilder() .addHeaders(HeaderMatcher.newBuilder() .setName("head-exactValue") .setExactMatch("exactValue") .setInvertMatch(true) .build()) .addHeaders(HeaderMatcher.newBuilder() .setName("head-regex") .setSafeRegexMatch(RegexMatcher.newBuilder() .setRegex("regex") .build()) .build()) .addHeaders(HeaderMatcher.newBuilder() .setName("head-range") .setRangeMatch(Int64Range.newBuilder() .setStart(1) .setEnd(100) .build()) .build()) .addHeaders(HeaderMatcher.newBuilder() .setName("head-present") .setPresentMatch(true) .build()) .addHeaders(HeaderMatcher.newBuilder() .setName("head-prefix") .setPrefixMatch("prefix") .build()) .addHeaders(HeaderMatcher.newBuilder() .setName("head-suffix") .setSuffixMatch("suffix") .build()) .build()) .setRoute(RouteAction.newBuilder() .setCluster("cluster-test") .build()) .build()) .build(); rdsVirtualHostListener.parseVirtualHost(virtualHost); List<XdsRouteRule> rules = dataCache.get(domain); assertNotNull(rules); List<org.apache.dubbo.rpc.cluster.router.xds.rule.HeaderMatcher> headerMatcherList = rules.get(0).getMatch().getHeaderMatcherList(); for (org.apache.dubbo.rpc.cluster.router.xds.rule.HeaderMatcher matcher : headerMatcherList) { if (matcher.getName().equals("head-exactValue")) { assertEquals(matcher.getExactValue(), "exactValue"); } else if (matcher.getName().equals("head-regex")) { assertEquals(matcher.getRegex(), "regex"); } else if (matcher.getName().equals("head-range")) { assertEquals(matcher.getRange().getStart(), 1); assertEquals(matcher.getRange().getEnd(), 100); } else if (matcher.getName().equals("head-present")) { assertTrue(matcher.getPresent()); } else if (matcher.getName().equals("head-prefix")) { assertEquals(matcher.getPrefix(), "prefix"); } else if (matcher.getName().equals("head-suffix")) { assertEquals(matcher.getSuffix(), "suffix"); } } } @Test public void parseRouteClusterTest() { String cluster = "cluster-test"; VirtualHost virtualHost = VirtualHost.newBuilder() .addDomains(domain) .addRoutes(Route.newBuilder() .setName("route-test") .setMatch(RouteMatch.newBuilder().setPrefix("/test").build()) .setRoute(RouteAction.newBuilder().setCluster(cluster).build()) .build()) .build(); rdsVirtualHostListener.parseVirtualHost(virtualHost); List<XdsRouteRule> rules = dataCache.get(domain); assertNotNull(rules); assertEquals(rules.get(0).getRoute().getCluster(), cluster); } @Test public void parseRouteWeightClusterTest() { VirtualHost virtualHost = VirtualHost.newBuilder() .addDomains(domain) .addRoutes(Route.newBuilder() .setName("route-test") .setMatch(RouteMatch.newBuilder().setPrefix("/test").build()) .setRoute(RouteAction.newBuilder() .setWeightedClusters(WeightedCluster.newBuilder() .addClusters(WeightedCluster.ClusterWeight.newBuilder() .setName("cluster-test1") .setWeight(UInt32Value.newBuilder() .setValue(40) .build()) .build()) .addClusters(WeightedCluster.ClusterWeight.newBuilder() .setName("cluster-test2") .setWeight(UInt32Value.newBuilder() .setValue(60) .build()) .build()) .build()) .build()) .build()) .build(); rdsVirtualHostListener.parseVirtualHost(virtualHost); List<XdsRouteRule> rules = dataCache.get(domain); assertNotNull(rules); List<ClusterWeight> weightedClusters = rules.get(0).getRoute().getWeightedClusters(); assertEquals(weightedClusters.size(), 2); for (ClusterWeight weightedCluster : weightedClusters) { if (weightedCluster.getName().equals("cluster-test1")) { assertEquals(weightedCluster.getWeight(), 40); } else if (weightedCluster.getName().equals("cluster-test2")) { assertEquals(weightedCluster.getWeight(), 60); } } } }
6,205
0
Create_ds/dubbo/dubbo-xds/src/test/java/org/apache/dubbo/rpc/cluster/router
Create_ds/dubbo/dubbo-xds/src/test/java/org/apache/dubbo/rpc/cluster/router/xds/XdsRouteTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.router.xds; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.Holder; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.registry.xds.util.protocol.message.Endpoint; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.cluster.router.mesh.util.TracingContextProvider; import org.apache.dubbo.rpc.cluster.router.state.BitList; import org.apache.dubbo.rpc.cluster.router.xds.rule.DestinationSubset; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import com.google.protobuf.UInt32Value; import io.envoyproxy.envoy.config.route.v3.HeaderMatcher; import io.envoyproxy.envoy.config.route.v3.Route; import io.envoyproxy.envoy.config.route.v3.RouteAction; import io.envoyproxy.envoy.config.route.v3.RouteMatch; import io.envoyproxy.envoy.config.route.v3.VirtualHost; import io.envoyproxy.envoy.config.route.v3.WeightedCluster; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class XdsRouteTest { private EdsEndpointManager edsEndpointManager; private RdsRouteRuleManager rdsRouteRuleManager; private Set<TracingContextProvider> tracingContextProviders; private URL url; @BeforeEach public void setup() { edsEndpointManager = Mockito.spy(EdsEndpointManager.class); rdsRouteRuleManager = Mockito.spy(RdsRouteRuleManager.class); tracingContextProviders = new HashSet<>(); url = URL.valueOf("test://localhost/DemoInterface"); } private Invoker<Object> createInvoker(String app) { URL url = URL.valueOf( "dubbo://localhost/DemoInterface?" + (StringUtils.isEmpty(app) ? "" : "remote.application=" + app)); Invoker invoker = Mockito.mock(Invoker.class); when(invoker.getUrl()).thenReturn(url); return invoker; } private Invoker<Object> createInvoker(String app, String address) { URL url = URL.valueOf("dubbo://" + address + "/DemoInterface?" + (StringUtils.isEmpty(app) ? "" : "remote.application=" + app)); Invoker invoker = Mockito.mock(Invoker.class); when(invoker.getUrl()).thenReturn(url); return invoker; } @Test public void testNotifyInvoker() { XdsRouter<Object> xdsRouter = new XdsRouter<>(url, rdsRouteRuleManager, edsEndpointManager, true); xdsRouter.notify(null); assertEquals(0, xdsRouter.getSubscribeApplications().size()); BitList<Invoker<Object>> invokers = new BitList<>(Arrays.asList(createInvoker(""), createInvoker("app1"))); xdsRouter.notify(invokers); assertEquals(1, xdsRouter.getSubscribeApplications().size()); assertTrue(xdsRouter.getSubscribeApplications().contains("app1")); assertEquals(invokers, xdsRouter.getInvokerList()); verify(rdsRouteRuleManager, times(1)).subscribeRds("app1", xdsRouter); invokers = new BitList<>(Arrays.asList(createInvoker("app2"))); xdsRouter.notify(invokers); verify(rdsRouteRuleManager, times(1)).subscribeRds("app2", xdsRouter); verify(rdsRouteRuleManager, times(1)).unSubscribeRds("app1", xdsRouter); assertEquals(invokers, xdsRouter.getInvokerList()); xdsRouter.stop(); verify(rdsRouteRuleManager, times(1)).unSubscribeRds("app2", xdsRouter); } @Test public void testRuleChange() { XdsRouter<Object> xdsRouter = new XdsRouter<>(url, rdsRouteRuleManager, edsEndpointManager, true); String appName = "app1"; String cluster1 = "cluster-test1"; String cluster2 = "cluster-test2"; BitList<Invoker<Object>> invokers = new BitList<>(Arrays.asList(createInvoker(appName))); xdsRouter.notify(invokers); String path = "/DemoInterface/call"; VirtualHost virtualHost = VirtualHost.newBuilder() .addDomains(appName) .addRoutes(Route.newBuilder() .setName("route-test") .setMatch(RouteMatch.newBuilder().setPath(path).build()) .setRoute(RouteAction.newBuilder().setCluster(cluster1).build()) .build()) .build(); RdsVirtualHostListener hostListener = new RdsVirtualHostListener(appName, rdsRouteRuleManager); hostListener.parseVirtualHost(virtualHost); assertEquals(xdsRouter.getXdsRouteRuleMap().get(appName).size(), 1); verify(edsEndpointManager, times(1)).subscribeEds(cluster1, xdsRouter); VirtualHost virtualHost2 = VirtualHost.newBuilder() .addDomains(appName) .addRoutes(Route.newBuilder() .setName("route-test") .setMatch(RouteMatch.newBuilder().setPath(path).build()) .setRoute(RouteAction.newBuilder() .setCluster("cluster-test2") .build()) .build()) .build(); hostListener.parseVirtualHost(virtualHost2); assertEquals(xdsRouter.getXdsRouteRuleMap().get(appName).size(), 1); verify(edsEndpointManager, times(1)).subscribeEds(cluster2, xdsRouter); verify(edsEndpointManager, times(1)).unSubscribeEds(cluster1, xdsRouter); } @Test public void testEndpointChange() { XdsRouter<Object> xdsRouter = new XdsRouter<>(url, rdsRouteRuleManager, edsEndpointManager, true); String appName = "app1"; String cluster1 = "cluster-test1"; BitList<Invoker<Object>> invokers = new BitList<>( Arrays.asList(createInvoker(appName, "1.1.1.1:20880"), createInvoker(appName, "2.2.2.2:20880"))); xdsRouter.notify(invokers); String path = "/DemoInterface/call"; VirtualHost virtualHost = VirtualHost.newBuilder() .addDomains(appName) .addRoutes(Route.newBuilder() .setName("route-test") .setMatch(RouteMatch.newBuilder().setPath(path).build()) .setRoute(RouteAction.newBuilder().setCluster(cluster1).build()) .build()) .build(); RdsVirtualHostListener hostListener = new RdsVirtualHostListener(appName, rdsRouteRuleManager); hostListener.parseVirtualHost(virtualHost); assertEquals(xdsRouter.getXdsRouteRuleMap().get(appName).size(), 1); verify(edsEndpointManager, times(1)).subscribeEds(cluster1, xdsRouter); Set<Endpoint> endpoints = new HashSet<>(); Endpoint endpoint1 = new Endpoint(); endpoint1.setAddress("1.1.1.1"); endpoint1.setPortValue(20880); Endpoint endpoint2 = new Endpoint(); endpoint2.setAddress("2.2.2.2"); endpoint2.setPortValue(20880); endpoints.add(endpoint1); endpoints.add(endpoint2); edsEndpointManager.notifyEndpointChange(cluster1, endpoints); DestinationSubset<Object> objectDestinationSubset = xdsRouter.getDestinationSubsetMap().get(cluster1); assertEquals(invokers, objectDestinationSubset.getInvokers()); } @Test public void testRouteNotMatch() { XdsRouter<Object> xdsRouter = new XdsRouter<>(url, rdsRouteRuleManager, edsEndpointManager, true); String appName = "app1"; BitList<Invoker<Object>> invokers = new BitList<>( Arrays.asList(createInvoker(appName, "1.1.1.1:20880"), createInvoker(appName, "2.2.2.2:20880"))); assertEquals(invokers, xdsRouter.route(invokers.clone(), null, null, false, null)); Holder<String> message = new Holder<>(); xdsRouter.doRoute(invokers.clone(), null, null, true, null, message); assertEquals("Directly Return. Reason: xds route rule is empty.", message.get()); } @Test public void testRoutePathMatch() { XdsRouter<Object> xdsRouter = new XdsRouter<>(url, rdsRouteRuleManager, edsEndpointManager, true); String appName = "app1"; String cluster1 = "cluster-test1"; Invoker<Object> invoker1 = createInvoker(appName, "1.1.1.1:20880"); BitList<Invoker<Object>> invokers = new BitList<>(Arrays.asList(invoker1, createInvoker(appName, "2.2.2.2:20880"))); xdsRouter.notify(invokers); String path = "/DemoInterface/call"; VirtualHost virtualHost = VirtualHost.newBuilder() .addDomains(appName) .addRoutes(Route.newBuilder() .setName("route-test") .setMatch(RouteMatch.newBuilder().setPath(path).build()) .setRoute(RouteAction.newBuilder().setCluster(cluster1).build()) .build()) .build(); RdsVirtualHostListener hostListener = new RdsVirtualHostListener(appName, rdsRouteRuleManager); hostListener.parseVirtualHost(virtualHost); Invocation invocation = Mockito.mock(Invocation.class); Invoker invoker = Mockito.mock(Invoker.class); URL url1 = Mockito.mock(URL.class); when(invoker.getUrl()).thenReturn(url1); when(url1.getPath()).thenReturn("DemoInterface"); when(invocation.getInvoker()).thenReturn(invoker); when(invocation.getMethodName()).thenReturn("call"); Set<Endpoint> endpoints = new HashSet<>(); Endpoint endpoint1 = new Endpoint(); endpoint1.setAddress("1.1.1.1"); endpoint1.setPortValue(20880); endpoints.add(endpoint1); edsEndpointManager.notifyEndpointChange(cluster1, endpoints); BitList<Invoker<Object>> routes = xdsRouter.route(invokers.clone(), null, invocation, false, null); assertEquals(1, routes.size()); assertEquals(invoker1, routes.get(0)); } @Test public void testRouteHeadMatch() { XdsRouter<Object> xdsRouter = new XdsRouter<>(url, rdsRouteRuleManager, edsEndpointManager, true); String appName = "app1"; String cluster1 = "cluster-test1"; Invoker<Object> invoker1 = createInvoker(appName, "1.1.1.1:20880"); BitList<Invoker<Object>> invokers = new BitList<>(Arrays.asList(invoker1, createInvoker(appName, "2.2.2.2:20880"))); xdsRouter.notify(invokers); VirtualHost virtualHost = VirtualHost.newBuilder() .addDomains(appName) .addRoutes(Route.newBuilder() .setName("route-test") .setMatch(RouteMatch.newBuilder() .addHeaders(HeaderMatcher.newBuilder() .setName("userId") .setExactMatch("123") .build()) .build()) .setRoute(RouteAction.newBuilder().setCluster(cluster1).build()) .build()) .build(); RdsVirtualHostListener hostListener = new RdsVirtualHostListener(appName, rdsRouteRuleManager); hostListener.parseVirtualHost(virtualHost); Invocation invocation = Mockito.mock(Invocation.class); when(invocation.getAttachment("userId")).thenReturn("123"); Set<Endpoint> endpoints = new HashSet<>(); Endpoint endpoint1 = new Endpoint(); endpoint1.setAddress("1.1.1.1"); endpoint1.setPortValue(20880); endpoints.add(endpoint1); edsEndpointManager.notifyEndpointChange(cluster1, endpoints); BitList<Invoker<Object>> routes = xdsRouter.route(invokers.clone(), null, invocation, false, null); assertEquals(1, routes.size()); assertEquals(invoker1, routes.get(0)); } @Test public void testRouteWeightCluster() { XdsRouter<Object> xdsRouter = new XdsRouter<>(url, rdsRouteRuleManager, edsEndpointManager, true); String appName = "app1"; String cluster1 = "cluster-test1"; String cluster2 = "cluster-test2"; Invoker<Object> invoker1 = createInvoker(appName, "1.1.1.1:20880"); BitList<Invoker<Object>> invokers = new BitList<>(Arrays.asList(invoker1, createInvoker(appName, "2.2.2.2:20880"))); xdsRouter.notify(invokers); VirtualHost virtualHost = VirtualHost.newBuilder() .addDomains(appName) .addRoutes(Route.newBuilder() .setName("route-test") .setMatch(RouteMatch.newBuilder() .addHeaders(HeaderMatcher.newBuilder() .setName("userId") .setExactMatch("123") .build()) .build()) .setRoute(RouteAction.newBuilder() .setWeightedClusters(WeightedCluster.newBuilder() .addClusters(WeightedCluster.ClusterWeight.newBuilder() .setName(cluster1) .setWeight(UInt32Value.newBuilder() .setValue(100) .build()) .build()) .addClusters(WeightedCluster.ClusterWeight.newBuilder() .setName(cluster2) .setWeight(UInt32Value.newBuilder() .setValue(0) .build()) .build()) .build()) .build()) .build()) .build(); RdsVirtualHostListener hostListener = new RdsVirtualHostListener(appName, rdsRouteRuleManager); hostListener.parseVirtualHost(virtualHost); Invocation invocation = Mockito.mock(Invocation.class); when(invocation.getAttachment("userId")).thenReturn("123"); Set<Endpoint> endpoints = new HashSet<>(); Endpoint endpoint1 = new Endpoint(); endpoint1.setAddress("1.1.1.1"); endpoint1.setPortValue(20880); endpoints.add(endpoint1); edsEndpointManager.notifyEndpointChange(cluster1, endpoints); endpoints = new HashSet<>(); Endpoint endpoint2 = new Endpoint(); endpoint2.setAddress("2.2.2.2"); endpoint2.setPortValue(20880); endpoints.add(endpoint2); edsEndpointManager.notifyEndpointChange(cluster2, endpoints); for (int i = 0; i < 10; i++) { BitList<Invoker<Object>> routes = xdsRouter.route(invokers.clone(), null, invocation, false, null); assertEquals(1, routes.size()); assertEquals(invoker1, routes.get(0)); } } @Test public void testRouteMultiApp() { XdsRouter<Object> xdsRouter = new XdsRouter<>(url, rdsRouteRuleManager, edsEndpointManager, true); String appName1 = "app1"; String appName2 = "app2"; String cluster1 = "cluster-test1"; Invoker<Object> invoker1 = createInvoker(appName2, "1.1.1.1:20880"); Invoker<Object> invoker2 = createInvoker(appName1, "2.2.2.2:20880"); BitList<Invoker<Object>> invokers = new BitList<>(Arrays.asList(invoker1, invoker2)); xdsRouter.notify(invokers); assertEquals(xdsRouter.getSubscribeApplications().size(), 2); String path = "/DemoInterface/call"; VirtualHost virtualHost = VirtualHost.newBuilder() .addDomains(appName2) .addRoutes(Route.newBuilder() .setName("route-test") .setMatch(RouteMatch.newBuilder().setPath(path).build()) .setRoute(RouteAction.newBuilder().setCluster(cluster1).build()) .build()) .build(); RdsVirtualHostListener hostListener = new RdsVirtualHostListener(appName2, rdsRouteRuleManager); hostListener.parseVirtualHost(virtualHost); Invocation invocation = Mockito.mock(Invocation.class); Invoker invoker = Mockito.mock(Invoker.class); URL url1 = Mockito.mock(URL.class); when(invoker.getUrl()).thenReturn(url1); when(url1.getPath()).thenReturn("DemoInterface"); when(invocation.getInvoker()).thenReturn(invoker); when(invocation.getMethodName()).thenReturn("call"); Set<Endpoint> endpoints = new HashSet<>(); Endpoint endpoint1 = new Endpoint(); endpoint1.setAddress("1.1.1.1"); endpoint1.setPortValue(20880); endpoints.add(endpoint1); edsEndpointManager.notifyEndpointChange(cluster1, endpoints); BitList<Invoker<Object>> routes = xdsRouter.route(invokers.clone(), null, invocation, false, null); assertEquals(1, routes.size()); assertEquals(invoker1, routes.get(0)); } }
6,206
0
Create_ds/dubbo/dubbo-xds/src/test/java/org/apache/dubbo/rpc/cluster/router/xds
Create_ds/dubbo/dubbo-xds/src/test/java/org/apache/dubbo/rpc/cluster/router/xds/rule/HeaderMatcherTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.router.xds.rule; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; public class HeaderMatcherTest { @Test public void exactValueMatcherTest() { HeaderMatcher headMatcher = new HeaderMatcher(); headMatcher.setName("testHead"); String value = "testValue"; headMatcher.setExactValue(value); assertTrue(headMatcher.match(value)); } @Test public void regexMatcherTest() { HeaderMatcher headMatcher = new HeaderMatcher(); headMatcher.setRegex("test.*"); String value = "testValue"; headMatcher.setExactValue(value); assertTrue(headMatcher.match(value)); } @Test public void rangMatcherTest() { HeaderMatcher headMatcher = new HeaderMatcher(); LongRangeMatch range = new LongRangeMatch(); range.setStart(100); range.setEnd(500); headMatcher.setRange(range); assertTrue(headMatcher.match("300")); } @Test public void presentMatcherTest() { HeaderMatcher headMatcher = new HeaderMatcher(); headMatcher.setName("testHead"); headMatcher.setPresent(true); assertTrue(headMatcher.match("value")); headMatcher.setPresent(false); assertTrue(headMatcher.match(null)); } @Test public void prefixMatcherTest() { HeaderMatcher headMatcher = new HeaderMatcher(); headMatcher.setName("testHead"); headMatcher.setPrefix("test"); assertTrue(headMatcher.match("testValue")); } @Test public void suffixMatcherTest() { HeaderMatcher headMatcher = new HeaderMatcher(); headMatcher.setName("testHead"); headMatcher.setSuffix("Value"); assertTrue(headMatcher.match("testValue")); } @Test public void invertedMatcherTest() { HeaderMatcher headMatcher = new HeaderMatcher(); headMatcher.setName("testHead"); String value = "testValue"; headMatcher.setExactValue(value); headMatcher.setInverted(true); assertFalse(headMatcher.match("testValue")); } }
6,207
0
Create_ds/dubbo/dubbo-xds/src/test/java/org/apache/dubbo/rpc/cluster/router/xds
Create_ds/dubbo/dubbo-xds/src/test/java/org/apache/dubbo/rpc/cluster/router/xds/rule/PathMatcherTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.router.xds.rule; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; public class PathMatcherTest { @Test public void pathMatcherTest() { PathMatcher pathMatcher = new PathMatcher(); String path = "/testService/test"; pathMatcher.setPath(path); assertTrue(pathMatcher.isMatch(path)); assertTrue(pathMatcher.isMatch(path.toUpperCase())); pathMatcher.setCaseSensitive(true); assertFalse(pathMatcher.isMatch(path.toUpperCase())); } @Test public void prefixMatcherTest() { PathMatcher pathMatcher = new PathMatcher(); String prefix = "/test"; String path = "/testService/test"; pathMatcher.setPrefix(prefix); assertTrue(pathMatcher.isMatch(path)); assertTrue(pathMatcher.isMatch(path.toUpperCase())); pathMatcher.setCaseSensitive(true); assertFalse(pathMatcher.isMatch(path.toUpperCase())); } @Test public void regexMatcherTest() { PathMatcher pathMatcher = new PathMatcher(); String regex = "/testService/.*"; String path = "/testService/test"; pathMatcher.setRegex(regex); assertTrue(pathMatcher.isMatch(path)); } }
6,208
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/XdsRegistry.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.xds; import org.apache.dubbo.common.URL; import org.apache.dubbo.registry.NotifyListener; import org.apache.dubbo.registry.support.FailbackRegistry; /** * Empty implements for xDS <br/> * xDS only support `Service Discovery` mode register <br/> * Used to compat past version like 2.6.x, 2.7.x with interface level register <br/> * {@link XdsServiceDiscovery} is the real implementation of xDS */ public class XdsRegistry extends FailbackRegistry { public XdsRegistry(URL url) { super(url); } @Override public boolean isAvailable() { return true; } @Override public void doRegister(URL url) {} @Override public void doUnregister(URL url) {} @Override public void doSubscribe(URL url, NotifyListener listener) {} @Override public void doUnsubscribe(URL url, NotifyListener listener) {} }
6,209
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/XdsEnv.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.xds; public interface XdsEnv { String getCluster(); }
6,210
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/XdsServiceDiscovery.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.xds; 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.ReflectionBasedServiceDiscovery; import org.apache.dubbo.registry.client.ServiceInstance; import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener; import org.apache.dubbo.registry.xds.util.PilotExchanger; import org.apache.dubbo.registry.xds.util.protocol.message.Endpoint; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ScopeModelUtil; import java.util.Collection; import java.util.Comparator; import java.util.LinkedList; import java.util.List; import java.util.Set; import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ERROR_INITIALIZE_XDS; import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ERROR_PARSING_XDS; public class XdsServiceDiscovery extends ReflectionBasedServiceDiscovery { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(XdsServiceDiscovery.class); private PilotExchanger exchanger; public XdsServiceDiscovery(ApplicationModel applicationModel, URL registryURL) { super(applicationModel, registryURL); } @Override public void doInitialize(URL registryURL) { try { exchanger = PilotExchanger.initialize(registryURL); } catch (Throwable t) { logger.error(REGISTRY_ERROR_INITIALIZE_XDS, "", "", t.getMessage(), t); } } @Override public void doDestroy() { try { if (exchanger == null) { return; } exchanger.destroy(); } catch (Throwable t) { logger.error(REGISTRY_ERROR_INITIALIZE_XDS, "", "", t.getMessage(), t); } } @Override public Set<String> getServices() { return exchanger.getServices(); } @Override public List<ServiceInstance> getInstances(String serviceName) throws NullPointerException { Set<Endpoint> endpoints = exchanger.getEndpoints(serviceName); return changedToInstances(serviceName, endpoints); } @Override public void addServiceInstancesChangedListener(ServiceInstancesChangedListener listener) throws NullPointerException, IllegalArgumentException { listener.getServiceNames() .forEach(serviceName -> exchanger.observeEndpoints( serviceName, (endpoints -> notifyListener(serviceName, listener, changedToInstances(serviceName, endpoints))))); } private List<ServiceInstance> changedToInstances(String serviceName, Collection<Endpoint> endpoints) { List<ServiceInstance> instances = new LinkedList<>(); endpoints.forEach(endpoint -> { try { DefaultServiceInstance serviceInstance = new DefaultServiceInstance( serviceName, endpoint.getAddress(), endpoint.getPortValue(), ScopeModelUtil.getApplicationModel(getUrl().getScopeModel())); // fill metadata by SelfHostMetaServiceDiscovery, will be fetched by RPC request serviceInstance.putExtendParam("clusterName", endpoint.getClusterName()); fillServiceInstance(serviceInstance); instances.add(serviceInstance); } catch (Throwable t) { logger.error( REGISTRY_ERROR_PARSING_XDS, "", "", "Error occurred when parsing endpoints. Endpoints List:" + endpoints, t); } }); instances.sort(Comparator.comparingInt(ServiceInstance::hashCode)); return instances; } }
6,211
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/XdsCertificateSigner.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.xds; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Adaptive; import org.apache.dubbo.common.extension.SPI; @SPI public interface XdsCertificateSigner { @Adaptive(value = "signer") CertPair GenerateCert(URL url); class CertPair { private final String privateKey; private final String publicKey; private final long createTime; private final long expireTime; public CertPair(String privateKey, String publicKey, long createTime, long expireTime) { this.privateKey = privateKey; this.publicKey = publicKey; this.createTime = createTime; this.expireTime = expireTime; } public String getPrivateKey() { return privateKey; } public String getPublicKey() { return publicKey; } public long getCreateTime() { return createTime; } public boolean isExpire() { return System.currentTimeMillis() < expireTime; } } }
6,212
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/XdsServiceDiscoveryFactory.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.xds; 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.AbstractServiceDiscoveryFactory; import org.apache.dubbo.registry.client.ServiceDiscovery; import org.apache.dubbo.rpc.model.ApplicationModel; import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ERROR_INITIALIZE_XDS; public class XdsServiceDiscoveryFactory extends AbstractServiceDiscoveryFactory { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(XdsServiceDiscoveryFactory.class); @Override protected ServiceDiscovery createDiscovery(URL registryURL) { XdsServiceDiscovery xdsServiceDiscovery = new XdsServiceDiscovery(ApplicationModel.defaultModel(), registryURL); try { xdsServiceDiscovery.doInitialize(registryURL); } catch (Exception e) { logger.error( REGISTRY_ERROR_INITIALIZE_XDS, "", "", "Error occurred when initialize xDS service discovery impl.", e); } return xdsServiceDiscovery; } }
6,213
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/XdsInitializationException.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.xds; public final class XdsInitializationException extends Exception { public XdsInitializationException(String message) { super(message); } public XdsInitializationException(String message, Throwable cause) { super(message, cause); } }
6,214
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/XdsRegistryFactory.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.xds; import org.apache.dubbo.common.URL; import org.apache.dubbo.registry.Registry; import org.apache.dubbo.registry.support.AbstractRegistryFactory; public class XdsRegistryFactory extends AbstractRegistryFactory { @Override protected String createRegistryCacheKey(URL url) { return url.toFullString(); } @Override protected Registry createRegistry(URL url) { return new XdsRegistry(url); } }
6,215
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/XdsListener.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.xds.util; import io.envoyproxy.envoy.service.discovery.v3.DiscoveryResponse; public interface XdsListener { void process(DiscoveryResponse discoveryResponse); }
6,216
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/NodeBuilder.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.xds.util; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.registry.xds.istio.IstioEnv; import io.envoyproxy.envoy.config.core.v3.Node; public class NodeBuilder { private static final String SVC_CLUSTER_LOCAL = ".svc.cluster.local"; public static Node build() { // String podName = System.getenv("metadata.name"); // String podNamespace = System.getenv("metadata.namespace"); String podName = IstioEnv.getInstance().getPodName(); String podNamespace = IstioEnv.getInstance().getWorkloadNameSpace(); String svcName = IstioEnv.getInstance().getIstioMetaClusterId(); // id -> sidecar~ip~{POD_NAME}~{NAMESPACE_NAME}.svc.cluster.local // cluster -> {SVC_NAME} return Node.newBuilder() .setId("sidecar~" + NetUtils.getLocalHost() + "~" + podName + "~" + podNamespace + SVC_CLUSTER_LOCAL) .setCluster(svcName) .build(); } }
6,217
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/AdsObserver.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.xds.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.common.threadpool.manager.FrameworkExecutorRepository; import org.apache.dubbo.registry.xds.util.protocol.AbstractProtocol; import org.apache.dubbo.registry.xds.util.protocol.DeltaResource; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import io.envoyproxy.envoy.config.core.v3.Node; import io.envoyproxy.envoy.service.discovery.v3.DiscoveryRequest; import io.envoyproxy.envoy.service.discovery.v3.DiscoveryResponse; import io.grpc.stub.StreamObserver; import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ERROR_REQUEST_XDS; public class AdsObserver { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AdsObserver.class); private final ApplicationModel applicationModel; private final URL url; private final Node node; private volatile XdsChannel xdsChannel; private final Map<String, XdsListener> listeners = new ConcurrentHashMap<>(); protected StreamObserver<DiscoveryRequest> requestObserver; private final Map<String, DiscoveryRequest> observedResources = new ConcurrentHashMap<>(); public AdsObserver(URL url, Node node) { this.url = url; this.node = node; this.xdsChannel = new XdsChannel(url); this.applicationModel = url.getOrDefaultApplicationModel(); } public <T, S extends DeltaResource<T>> void addListener(AbstractProtocol<T, S> protocol) { listeners.put(protocol.getTypeUrl(), protocol); } public void request(DiscoveryRequest discoveryRequest) { if (requestObserver == null) { requestObserver = xdsChannel.createDeltaDiscoveryRequest(new ResponseObserver(this)); } requestObserver.onNext(discoveryRequest); observedResources.put(discoveryRequest.getTypeUrl(), discoveryRequest); } private static class ResponseObserver implements StreamObserver<DiscoveryResponse> { private AdsObserver adsObserver; public ResponseObserver(AdsObserver adsObserver) { this.adsObserver = adsObserver; } @Override public void onNext(DiscoveryResponse discoveryResponse) { XdsListener xdsListener = adsObserver.listeners.get(discoveryResponse.getTypeUrl()); xdsListener.process(discoveryResponse); adsObserver.requestObserver.onNext(buildAck(discoveryResponse)); } protected DiscoveryRequest buildAck(DiscoveryResponse response) { // for ACK return DiscoveryRequest.newBuilder() .setNode(adsObserver.node) .setTypeUrl(response.getTypeUrl()) .setVersionInfo(response.getVersionInfo()) .setResponseNonce(response.getNonce()) .addAllResourceNames(adsObserver .observedResources .get(response.getTypeUrl()) .getResourceNamesList()) .build(); } @Override public void onError(Throwable throwable) { logger.error(REGISTRY_ERROR_REQUEST_XDS, "", "", "xDS Client received error message! detail:", throwable); adsObserver.triggerReConnectTask(); } @Override public void onCompleted() { logger.info("xDS Client completed"); adsObserver.triggerReConnectTask(); } } private void triggerReConnectTask() { ScheduledExecutorService scheduledFuture = applicationModel .getFrameworkModel() .getBeanFactory() .getBean(FrameworkExecutorRepository.class) .getSharedScheduledExecutor(); scheduledFuture.schedule(this::recover, 3, TimeUnit.SECONDS); } private void recover() { try { xdsChannel = new XdsChannel(url); if (xdsChannel.getChannel() != null) { requestObserver = xdsChannel.createDeltaDiscoveryRequest(new ResponseObserver(this)); observedResources.values().forEach(requestObserver::onNext); return; } else { logger.error( REGISTRY_ERROR_REQUEST_XDS, "", "", "Recover failed for xDS connection. Will retry. Create channel failed."); } } catch (Exception e) { logger.error(REGISTRY_ERROR_REQUEST_XDS, "", "", "Recover failed for xDS connection. Will retry.", e); } triggerReConnectTask(); } }
6,218
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/XdsChannel.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.xds.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.common.url.component.URLAddress; import org.apache.dubbo.registry.xds.XdsCertificateSigner; import org.apache.dubbo.registry.xds.util.bootstrap.Bootstrapper; import org.apache.dubbo.registry.xds.util.bootstrap.BootstrapperImpl; import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; import io.envoyproxy.envoy.service.discovery.v3.AggregatedDiscoveryServiceGrpc; import io.envoyproxy.envoy.service.discovery.v3.DeltaDiscoveryRequest; import io.envoyproxy.envoy.service.discovery.v3.DeltaDiscoveryResponse; import io.envoyproxy.envoy.service.discovery.v3.DiscoveryRequest; import io.envoyproxy.envoy.service.discovery.v3.DiscoveryResponse; import io.grpc.ManagedChannel; import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; import io.grpc.netty.shaded.io.netty.channel.epoll.EpollDomainSocketChannel; import io.grpc.netty.shaded.io.netty.channel.epoll.EpollEventLoopGroup; import io.grpc.netty.shaded.io.netty.channel.unix.DomainSocketAddress; import io.grpc.netty.shaded.io.netty.handler.ssl.SslContext; import io.grpc.netty.shaded.io.netty.handler.ssl.util.InsecureTrustManagerFactory; import io.grpc.stub.StreamObserver; import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ERROR_CREATE_CHANNEL_XDS; public class XdsChannel { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(XdsChannel.class); private static final String USE_AGENT = "use-agent"; private URL url; private static final String SECURE = "secure"; private static final String PLAINTEXT = "plaintext"; private final ManagedChannel channel; public URL getUrl() { return url; } public ManagedChannel getChannel() { return channel; } public XdsChannel(URL url) { ManagedChannel managedChannel = null; this.url = url; try { if (!url.getParameter(USE_AGENT, false)) { if (PLAINTEXT.equals(url.getParameter(SECURE))) { managedChannel = NettyChannelBuilder.forAddress(url.getHost(), url.getPort()) .usePlaintext() .build(); } else { XdsCertificateSigner signer = url.getOrDefaultApplicationModel() .getExtensionLoader(XdsCertificateSigner.class) .getExtension(url.getParameter("signer", "istio")); XdsCertificateSigner.CertPair certPair = signer.GenerateCert(url); SslContext context = GrpcSslContexts.forClient() .trustManager(InsecureTrustManagerFactory.INSTANCE) .keyManager( new ByteArrayInputStream( certPair.getPublicKey().getBytes(StandardCharsets.UTF_8)), new ByteArrayInputStream( certPair.getPrivateKey().getBytes(StandardCharsets.UTF_8))) .build(); managedChannel = NettyChannelBuilder.forAddress(url.getHost(), url.getPort()) .sslContext(context) .build(); } } else { BootstrapperImpl bootstrapper = new BootstrapperImpl(); Bootstrapper.BootstrapInfo bootstrapInfo = bootstrapper.bootstrap(); URLAddress address = URLAddress.parse(bootstrapInfo.servers().get(0).target(), null, false); EpollEventLoopGroup elg = new EpollEventLoopGroup(); managedChannel = NettyChannelBuilder.forAddress(new DomainSocketAddress("/" + address.getPath())) .eventLoopGroup(elg) .channelType(EpollDomainSocketChannel.class) .usePlaintext() .build(); } } catch (Exception e) { logger.error( REGISTRY_ERROR_CREATE_CHANNEL_XDS, "", "", "Error occurred when creating gRPC channel to control panel.", e); } channel = managedChannel; } public StreamObserver<DeltaDiscoveryRequest> observeDeltaDiscoveryRequest( StreamObserver<DeltaDiscoveryResponse> observer) { return AggregatedDiscoveryServiceGrpc.newStub(channel).deltaAggregatedResources(observer); } public StreamObserver<DiscoveryRequest> createDeltaDiscoveryRequest(StreamObserver<DiscoveryResponse> observer) { return AggregatedDiscoveryServiceGrpc.newStub(channel).streamAggregatedResources(observer); } public StreamObserver<io.envoyproxy.envoy.api.v2.DeltaDiscoveryRequest> observeDeltaDiscoveryRequestV2( StreamObserver<io.envoyproxy.envoy.api.v2.DeltaDiscoveryResponse> observer) { return io.envoyproxy.envoy.service.discovery.v2.AggregatedDiscoveryServiceGrpc.newStub(channel) .deltaAggregatedResources(observer); } public StreamObserver<io.envoyproxy.envoy.api.v2.DiscoveryRequest> createDeltaDiscoveryRequestV2( StreamObserver<io.envoyproxy.envoy.api.v2.DiscoveryResponse> observer) { return io.envoyproxy.envoy.service.discovery.v2.AggregatedDiscoveryServiceGrpc.newStub(channel) .streamAggregatedResources(observer); } public void destroy() { channel.shutdown(); } }
6,219
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/PilotExchanger.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.xds.util; import org.apache.dubbo.common.URL; 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.registry.xds.util.protocol.AbstractProtocol; import org.apache.dubbo.registry.xds.util.protocol.impl.EdsProtocol; import org.apache.dubbo.registry.xds.util.protocol.impl.LdsProtocol; import org.apache.dubbo.registry.xds.util.protocol.impl.RdsProtocol; import org.apache.dubbo.registry.xds.util.protocol.message.Endpoint; import org.apache.dubbo.registry.xds.util.protocol.message.EndpointResult; import org.apache.dubbo.registry.xds.util.protocol.message.ListenerResult; import org.apache.dubbo.registry.xds.util.protocol.message.RouteResult; import org.apache.dubbo.rpc.cluster.router.xds.RdsVirtualHostListener; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; import java.util.stream.Collectors; public class PilotExchanger { protected final XdsChannel xdsChannel; protected final LdsProtocol ldsProtocol; protected final RdsProtocol rdsProtocol; protected final EdsProtocol edsProtocol; protected Map<String, ListenerResult> listenerResult; protected Map<String, RouteResult> routeResult; private final AtomicBoolean isRdsObserve = new AtomicBoolean(false); private final Set<String> domainObserveRequest = new ConcurrentHashSet<String>(); private final Map<String, Set<Consumer<Set<Endpoint>>>> domainObserveConsumer = new ConcurrentHashMap<>(); private final Map<String, Consumer<RdsVirtualHostListener>> rdsObserveConsumer = new ConcurrentHashMap<>(); private static PilotExchanger GLOBAL_PILOT_EXCHANGER = null; private final ApplicationModel applicationModel; protected PilotExchanger(URL url) { xdsChannel = new XdsChannel(url); int pollingTimeout = url.getParameter("pollingTimeout", 10); this.applicationModel = url.getOrDefaultApplicationModel(); AdsObserver adsObserver = new AdsObserver(url, NodeBuilder.build()); this.ldsProtocol = new LdsProtocol(adsObserver, NodeBuilder.build(), pollingTimeout); this.rdsProtocol = new RdsProtocol(adsObserver, NodeBuilder.build(), pollingTimeout); this.edsProtocol = new EdsProtocol(adsObserver, NodeBuilder.build(), pollingTimeout); this.listenerResult = ldsProtocol.getListeners(); this.routeResult = rdsProtocol.getResource( listenerResult.values().iterator().next().getRouteConfigNames()); Set<String> ldsResourcesName = new HashSet<>(); ldsResourcesName.add(AbstractProtocol.emptyResourceName); // Observer RDS update if (CollectionUtils.isNotEmpty(listenerResult.values().iterator().next().getRouteConfigNames())) { createRouteObserve(); isRdsObserve.set(true); } // Observe LDS updated ldsProtocol.observeResource( ldsResourcesName, (newListener) -> { // update local cache if (!newListener.equals(listenerResult)) { this.listenerResult = newListener; // update RDS observation if (isRdsObserve.get()) { createRouteObserve(); } } }, false); } private void createRouteObserve() { rdsProtocol.observeResource( listenerResult.values().iterator().next().getRouteConfigNames(), (newResult) -> { // check if observed domain update ( will update endpoint observation ) List<String> domainsToUpdate = new LinkedList<>(); domainObserveConsumer.forEach((domain, consumer) -> { newResult.values().forEach(o -> { Set<String> newRoute = o.searchDomain(domain); for (Map.Entry<String, RouteResult> entry : routeResult.entrySet()) { if (!entry.getValue().searchDomain(domain).equals(newRoute)) { // routers in observed domain has been updated // Long domainRequest = domainObserveRequest.get(domain); // router list is empty when observeEndpoints() called and domainRequest has not // been created yet // create new observation domainsToUpdate.add(domain); // doObserveEndpoints(domain); } } }); }); routeResult = newResult; ExecutorService executorService = applicationModel .getFrameworkModel() .getBeanFactory() .getBean(FrameworkExecutorRepository.class) .getSharedExecutor(); executorService.submit(() -> domainsToUpdate.forEach(this::doObserveEndpoints)); }, false); } public static PilotExchanger initialize(URL url) { synchronized (PilotExchanger.class) { if (GLOBAL_PILOT_EXCHANGER != null) { return GLOBAL_PILOT_EXCHANGER; } return (GLOBAL_PILOT_EXCHANGER = new PilotExchanger(url)); } } public static PilotExchanger getInstance() { synchronized (PilotExchanger.class) { return GLOBAL_PILOT_EXCHANGER; } } public static boolean isEnabled() { return GLOBAL_PILOT_EXCHANGER != null; } public void destroy() { xdsChannel.destroy(); } public Set<String> getServices() { Set<String> domains = new HashSet<>(); for (Map.Entry<String, RouteResult> entry : routeResult.entrySet()) { domains.addAll(entry.getValue().getDomains()); } return domains; } public Set<Endpoint> getEndpoints(String domain) { Set<Endpoint> endpoints = new HashSet<>(); for (Map.Entry<String, RouteResult> entry : routeResult.entrySet()) { Set<String> cluster = entry.getValue().searchDomain(domain); if (CollectionUtils.isNotEmpty(cluster)) { Map<String, EndpointResult> endpointResultList = edsProtocol.getResource(cluster); endpointResultList.forEach((k, v) -> endpoints.addAll(v.getEndpoints())); } else { return Collections.emptySet(); } } return endpoints; } public void observeEndpoints(String domain, Consumer<Set<Endpoint>> consumer) { // store Consumer domainObserveConsumer.compute(domain, (k, v) -> { if (v == null) { v = new ConcurrentHashSet<>(); } // support multi-consumer v.add(consumer); return v; }); if (!domainObserveRequest.contains(domain)) { doObserveEndpoints(domain); } } private void doObserveEndpoints(String domain) { for (Map.Entry<String, RouteResult> entry : routeResult.entrySet()) { Set<String> router = entry.getValue().searchDomain(domain); // if router is empty, do nothing // observation will be created when RDS updates if (CollectionUtils.isNotEmpty(router)) { edsProtocol.observeResource( router, (endpointResultMap) -> { Set<Endpoint> endpoints = endpointResultMap.values().stream() .map(EndpointResult::getEndpoints) .flatMap(Set::stream) .collect(Collectors.toSet()); for (Consumer<Set<Endpoint>> consumer : domainObserveConsumer.get(domain)) { consumer.accept(endpoints); } }, false); domainObserveRequest.add(domain); } } } public void unObserveEndpoints(String domain, Consumer<Set<Endpoint>> consumer) { domainObserveConsumer.get(domain).remove(consumer); domainObserveRequest.remove(domain); } public void observeEds(Set<String> clusterNames, Consumer<Map<String, EndpointResult>> consumer) { edsProtocol.observeResource(clusterNames, consumer, false); } public void unObserveEds(Set<String> clusterNames, Consumer<Map<String, EndpointResult>> consumer) { edsProtocol.unobserveResource(clusterNames, consumer); } public void observeRds(Set<String> clusterNames, Consumer<Map<String, RouteResult>> consumer) { rdsProtocol.observeResource(clusterNames, consumer, false); } public void unObserveRds(Set<String> clusterNames, Consumer<Map<String, RouteResult>> consumer) { rdsProtocol.unobserveResource(clusterNames, consumer); } public void observeLds(Consumer<Map<String, ListenerResult>> consumer) { ldsProtocol.observeResource(Collections.singleton(AbstractProtocol.emptyResourceName), consumer, false); } public void unObserveLds(Consumer<Map<String, ListenerResult>> consumer) { ldsProtocol.unobserveResource(Collections.singleton(AbstractProtocol.emptyResourceName), consumer); } }
6,220
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/bootstrap/BootstrapInfoImpl.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.xds.util.bootstrap; import javax.annotation.Nullable; import java.util.LinkedList; import java.util.List; import java.util.Map; import io.envoyproxy.envoy.config.core.v3.Node; public final class BootstrapInfoImpl extends Bootstrapper.BootstrapInfo { private final List<Bootstrapper.ServerInfo> servers; private final String serverListenerResourceNameTemplate; private final Map<String, Bootstrapper.CertificateProviderInfo> certProviders; private final Node node; BootstrapInfoImpl( List<Bootstrapper.ServerInfo> servers, String serverListenerResourceNameTemplate, Map<String, Bootstrapper.CertificateProviderInfo> certProviders, Node node) { this.servers = servers; this.serverListenerResourceNameTemplate = serverListenerResourceNameTemplate; this.certProviders = certProviders; this.node = node; } @Override public List<Bootstrapper.ServerInfo> servers() { return servers; } public Map<String, Bootstrapper.CertificateProviderInfo> certProviders() { return certProviders; } @Override public Node node() { return node; } @Override public String serverListenerResourceNameTemplate() { return serverListenerResourceNameTemplate; } @Override public String toString() { return "BootstrapInfo{" + "servers=" + servers + ", " + "serverListenerResourceNameTemplate=" + serverListenerResourceNameTemplate + ", " + "node=" + node + ", " + "}"; } public static final class Builder extends Bootstrapper.BootstrapInfo.Builder { private List<Bootstrapper.ServerInfo> servers; private Node node; private Map<String, Bootstrapper.CertificateProviderInfo> certProviders; private String serverListenerResourceNameTemplate; Builder() {} @Override Bootstrapper.BootstrapInfo.Builder servers(List<Bootstrapper.ServerInfo> servers) { this.servers = new LinkedList<>(servers); return this; } @Override Bootstrapper.BootstrapInfo.Builder node(Node node) { if (node == null) { throw new NullPointerException("Null node"); } this.node = node; return this; } @Override Bootstrapper.BootstrapInfo.Builder certProviders( @Nullable Map<String, Bootstrapper.CertificateProviderInfo> certProviders) { this.certProviders = certProviders; return this; } @Override Bootstrapper.BootstrapInfo.Builder serverListenerResourceNameTemplate( @Nullable String serverListenerResourceNameTemplate) { this.serverListenerResourceNameTemplate = serverListenerResourceNameTemplate; return this; } @Override Bootstrapper.BootstrapInfo build() { if (this.servers == null || this.node == null) { StringBuilder missing = new StringBuilder(); if (this.servers == null) { missing.append(" servers"); } if (this.node == null) { missing.append(" node"); } throw new IllegalStateException("Missing required properties:" + missing); } return new BootstrapInfoImpl( this.servers, this.serverListenerResourceNameTemplate, this.certProviders, this.node); } } }
6,221
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/bootstrap/BootstrapperImpl.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.xds.util.bootstrap; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.registry.xds.XdsInitializationException; import javax.annotation.Nullable; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import io.envoyproxy.envoy.config.core.v3.Node; import io.grpc.ChannelCredentials; import io.grpc.internal.JsonParser; import io.grpc.internal.JsonUtil; public class BootstrapperImpl extends Bootstrapper { static final String BOOTSTRAP_PATH_SYS_ENV_VAR = "GRPC_XDS_BOOTSTRAP"; static String bootstrapPathFromEnvVar = System.getenv(BOOTSTRAP_PATH_SYS_ENV_VAR); private static final Logger logger = LoggerFactory.getLogger(BootstrapperImpl.class); private FileReader reader = LocalFileReader.INSTANCE; private static final String SERVER_FEATURE_XDS_V3 = "xds_v3"; private static final String SERVER_FEATURE_IGNORE_RESOURCE_DELETION = "ignore_resource_deletion"; public BootstrapInfo bootstrap() throws XdsInitializationException { String filePath = bootstrapPathFromEnvVar; String fileContent = null; if (filePath != null) { try { fileContent = reader.readFile(filePath); } catch (IOException e) { throw new XdsInitializationException("Fail to read bootstrap file", e); } } if (fileContent == null) throw new XdsInitializationException("Cannot find bootstrap configuration"); Map<String, ?> rawBootstrap; try { rawBootstrap = (Map<String, ?>) JsonParser.parse(fileContent); } catch (IOException e) { throw new XdsInitializationException("Failed to parse JSON", e); } return bootstrap(rawBootstrap); } @Override BootstrapInfo bootstrap(Map<String, ?> rawData) throws XdsInitializationException { BootstrapInfo.Builder builder = new BootstrapInfoImpl.Builder(); List<?> rawServerConfigs = JsonUtil.getList(rawData, "xds_servers"); if (rawServerConfigs == null) { throw new XdsInitializationException("Invalid bootstrap: 'xds_servers' does not exist."); } List<ServerInfo> servers = parseServerInfos(rawServerConfigs); builder.servers(servers); Node.Builder nodeBuilder = Node.newBuilder(); Map<String, ?> rawNode = JsonUtil.getObject(rawData, "node"); if (rawNode != null) { String id = JsonUtil.getString(rawNode, "id"); if (id != null) { nodeBuilder.setId(id); } String cluster = JsonUtil.getString(rawNode, "cluster"); if (cluster != null) { nodeBuilder.setCluster(cluster); } Map<String, ?> metadata = JsonUtil.getObject(rawNode, "metadata"); Map<String, ?> rawLocality = JsonUtil.getObject(rawNode, "locality"); } builder.node(nodeBuilder.build()); Map<String, ?> certProvidersBlob = JsonUtil.getObject(rawData, "certificate_providers"); if (certProvidersBlob != null) { Map<String, CertificateProviderInfo> certProviders = new HashMap<>(certProvidersBlob.size()); for (String name : certProvidersBlob.keySet()) { Map<String, ?> valueMap = JsonUtil.getObject(certProvidersBlob, name); String pluginName = checkForNull(JsonUtil.getString(valueMap, "plugin_name"), "plugin_name"); Map<String, ?> config = checkForNull(JsonUtil.getObject(valueMap, "config"), "config"); CertificateProviderInfoImpl certificateProviderInfo = new CertificateProviderInfoImpl(pluginName, config); certProviders.put(name, certificateProviderInfo); } builder.certProviders(certProviders); } return builder.build(); } private static List<ServerInfo> parseServerInfos(List<?> rawServerConfigs) throws XdsInitializationException { List<ServerInfo> servers = new LinkedList<>(); List<Map<String, ?>> serverConfigList = JsonUtil.checkObjectList(rawServerConfigs); for (Map<String, ?> serverConfig : serverConfigList) { String serverUri = JsonUtil.getString(serverConfig, "server_uri"); if (serverUri == null) { throw new XdsInitializationException("Invalid bootstrap: missing 'server_uri'"); } List<?> rawChannelCredsList = JsonUtil.getList(serverConfig, "channel_creds"); if (rawChannelCredsList == null || rawChannelCredsList.isEmpty()) { throw new XdsInitializationException( "Invalid bootstrap: server " + serverUri + " 'channel_creds' required"); } ChannelCredentials channelCredentials = parseChannelCredentials(JsonUtil.checkObjectList(rawChannelCredsList), serverUri); // if (channelCredentials == null) { // throw new XdsInitializationException( // "Server " + serverUri + ": no supported channel credentials found"); // } boolean useProtocolV3 = false; boolean ignoreResourceDeletion = false; List<String> serverFeatures = JsonUtil.getListOfStrings(serverConfig, "server_features"); if (serverFeatures != null) { useProtocolV3 = serverFeatures.contains(SERVER_FEATURE_XDS_V3); ignoreResourceDeletion = serverFeatures.contains(SERVER_FEATURE_IGNORE_RESOURCE_DELETION); } servers.add(new ServerInfoImpl(serverUri, channelCredentials, useProtocolV3, ignoreResourceDeletion)); } return servers; } void setFileReader(FileReader reader) { this.reader = reader; } /** * Reads the content of the file with the given path in the file system. */ interface FileReader { String readFile(String path) throws IOException; } private enum LocalFileReader implements FileReader { INSTANCE; @Override public String readFile(String path) throws IOException { return new String(Files.readAllBytes(Paths.get(path)), StandardCharsets.UTF_8); } } private static <T> T checkForNull(T value, String fieldName) throws XdsInitializationException { if (value == null) { throw new XdsInitializationException("Invalid bootstrap: '" + fieldName + "' does not exist."); } return value; } @Nullable private static ChannelCredentials parseChannelCredentials(List<Map<String, ?>> jsonList, String serverUri) throws XdsInitializationException { return null; } }
6,222
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/bootstrap/ServerInfoImpl.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.xds.util.bootstrap; import io.grpc.ChannelCredentials; final class ServerInfoImpl extends Bootstrapper.ServerInfo { private final String target; private final ChannelCredentials channelCredentials; private final boolean useProtocolV3; private final boolean ignoreResourceDeletion; ServerInfoImpl( String target, ChannelCredentials channelCredentials, boolean useProtocolV3, boolean ignoreResourceDeletion) { this.target = target; this.channelCredentials = channelCredentials; this.useProtocolV3 = useProtocolV3; this.ignoreResourceDeletion = ignoreResourceDeletion; } @Override public String target() { return target; } @Override ChannelCredentials channelCredentials() { return channelCredentials; } @Override boolean useProtocolV3() { return useProtocolV3; } @Override boolean ignoreResourceDeletion() { return ignoreResourceDeletion; } @Override public String toString() { return "ServerInfo{" + "target=" + target + ", " + "channelCredentials=" + channelCredentials + ", " + "useProtocolV3=" + useProtocolV3 + ", " + "ignoreResourceDeletion=" + ignoreResourceDeletion + "}"; } }
6,223
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/bootstrap/Bootstrapper.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.xds.util.bootstrap; import org.apache.dubbo.registry.xds.XdsInitializationException; import javax.annotation.Nullable; import java.util.List; import java.util.Map; import io.envoyproxy.envoy.config.core.v3.Node; import io.grpc.ChannelCredentials; public abstract class Bootstrapper { public abstract BootstrapInfo bootstrap() throws XdsInitializationException; BootstrapInfo bootstrap(Map<String, ?> rawData) throws XdsInitializationException { throw new UnsupportedOperationException(); } public abstract static class ServerInfo { public abstract String target(); abstract ChannelCredentials channelCredentials(); abstract boolean useProtocolV3(); abstract boolean ignoreResourceDeletion(); } public abstract static class CertificateProviderInfo { public abstract String pluginName(); public abstract Map<String, ?> config(); } public abstract static class BootstrapInfo { public abstract List<ServerInfo> servers(); public abstract Map<String, CertificateProviderInfo> certProviders(); public abstract Node node(); public abstract String serverListenerResourceNameTemplate(); abstract static class Builder { abstract Builder servers(List<ServerInfo> servers); abstract Builder node(Node node); abstract Builder certProviders(@Nullable Map<String, CertificateProviderInfo> certProviders); abstract Builder serverListenerResourceNameTemplate(@Nullable String serverListenerResourceNameTemplate); abstract BootstrapInfo build(); } } }
6,224
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/bootstrap/CertificateProviderInfoImpl.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.xds.util.bootstrap; import java.util.Map; final class CertificateProviderInfoImpl extends Bootstrapper.CertificateProviderInfo { private final String pluginName; private final Map<String, ?> config; CertificateProviderInfoImpl(String pluginName, Map<String, ?> config) { this.pluginName = pluginName; this.config = config; } @Override public String pluginName() { return pluginName; } @Override public Map<String, ?> config() { return config; } @Override public String toString() { return "CertificateProviderInfo{" + "pluginName=" + pluginName + ", " + "config=" + config + "}"; } }
6,225
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/AbstractProtocol.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.xds.util.protocol; 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.StringUtils; import org.apache.dubbo.registry.xds.util.AdsObserver; import org.apache.dubbo.registry.xds.util.XdsListener; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.function.Consumer; import java.util.stream.Collectors; import io.envoyproxy.envoy.config.core.v3.Node; import io.envoyproxy.envoy.service.discovery.v3.DiscoveryRequest; import io.envoyproxy.envoy.service.discovery.v3.DiscoveryResponse; import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_INTERRUPTED; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_REQUEST; public abstract class AbstractProtocol<T, S extends DeltaResource<T>> implements XdsProtocol<T>, XdsListener { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbstractProtocol.class); protected AdsObserver adsObserver; protected final Node node; private final int checkInterval; protected final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); protected final ReentrantReadWriteLock.ReadLock readLock = lock.readLock(); protected final ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock(); protected Set<String> observeResourcesName; public static final String emptyResourceName = "emptyResourcesName"; private final ReentrantLock resourceLock = new ReentrantLock(); protected Map<Set<String>, List<Consumer<Map<String, T>>>> consumerObserveMap = new ConcurrentHashMap<>(); public Map<Set<String>, List<Consumer<Map<String, T>>>> getConsumerObserveMap() { return consumerObserveMap; } protected Map<String, T> resourcesMap = new ConcurrentHashMap<>(); public AbstractProtocol(AdsObserver adsObserver, Node node, int checkInterval) { this.adsObserver = adsObserver; this.node = node; this.checkInterval = checkInterval; adsObserver.addListener(this); } /** * Abstract method to obtain Type-URL from sub-class * * @return Type-URL of xDS */ public abstract String getTypeUrl(); public boolean isCacheExistResource(Set<String> resourceNames) { for (String resourceName : resourceNames) { if ("".equals(resourceName)) { continue; } if (!resourcesMap.containsKey(resourceName)) { return false; } } return true; } public T getCacheResource(String resourceName) { if (resourceName == null || resourceName.length() == 0) { return null; } return resourcesMap.get(resourceName); } @Override public Map<String, T> getResource(Set<String> resourceNames) { resourceNames = resourceNames == null ? Collections.emptySet() : resourceNames; if (!resourceNames.isEmpty() && isCacheExistResource(resourceNames)) { return getResourceFromCache(resourceNames); } else { return getResourceFromRemote(resourceNames); } } private Map<String, T> getResourceFromCache(Set<String> resourceNames) { return resourceNames.stream() .filter(o -> !StringUtils.isEmpty(o)) .collect(Collectors.toMap(k -> k, this::getCacheResource)); } public Map<String, T> getResourceFromRemote(Set<String> resourceNames) { try { resourceLock.lock(); CompletableFuture<Map<String, T>> future = new CompletableFuture<>(); observeResourcesName = resourceNames; Set<String> consumerObserveResourceNames = new HashSet<>(); if (resourceNames.isEmpty()) { consumerObserveResourceNames.add(emptyResourceName); } else { consumerObserveResourceNames = resourceNames; } Consumer<Map<String, T>> futureConsumer = future::complete; try { writeLock.lock(); ConcurrentHashMapUtils.computeIfAbsent( (ConcurrentHashMap<Set<String>, List<Consumer<Map<String, T>>>>) consumerObserveMap, consumerObserveResourceNames, key -> new ArrayList<>()) .add(futureConsumer); } finally { writeLock.unlock(); } Set<String> resourceNamesToObserve = new HashSet<>(resourceNames); resourceNamesToObserve.addAll(resourcesMap.keySet()); adsObserver.request(buildDiscoveryRequest(resourceNamesToObserve)); logger.info("Send xDS Observe request to remote. Resource count: " + resourceNamesToObserve.size() + ". Resource Type: " + getTypeUrl()); try { Map<String, T> result = future.get(); try { writeLock.lock(); consumerObserveMap.get(consumerObserveResourceNames).removeIf(o -> o.equals(futureConsumer)); } finally { writeLock.unlock(); } return result; } catch (InterruptedException e) { logger.error( INTERNAL_INTERRUPTED, "", "", "InterruptedException occur when request control panel. error=", e); Thread.currentThread().interrupt(); } catch (Exception e) { logger.error(PROTOCOL_FAILED_REQUEST, "", "", "Error occur when request control panel. error=", e); } } finally { resourceLock.unlock(); } return Collections.emptyMap(); } public void observeResource(Set<String> resourceNames, Consumer<Map<String, T>> consumer, boolean isReConnect) { // call once for full data if (!isReConnect) { consumer.accept(getResource(resourceNames)); try { writeLock.lock(); consumerObserveMap.compute(resourceNames, (k, v) -> { if (v == null) { v = new ArrayList<>(); } // support multi-consumer v.add(consumer); return v; }); } finally { writeLock.unlock(); } } try { writeLock.lock(); this.observeResourcesName = consumerObserveMap.keySet().stream().flatMap(Set::stream).collect(Collectors.toSet()); } finally { writeLock.unlock(); } } public void unobserveResource(Set<String> resourceNames, Consumer<Map<String, T>> consumer) { // TODO } protected DiscoveryRequest buildDiscoveryRequest(Set<String> resourceNames) { return DiscoveryRequest.newBuilder() .setNode(node) .setTypeUrl(getTypeUrl()) .addAllResourceNames(resourceNames) .build(); } protected abstract Map<String, T> decodeDiscoveryResponse(DiscoveryResponse response); @Override public final void process(DiscoveryResponse discoveryResponse) { Map<String, T> newResult = decodeDiscoveryResponse(discoveryResponse); Map<String, T> oldResource = resourcesMap; discoveryResponseListener(oldResource, newResult); resourcesMap = newResult; } private void discoveryResponseListener(Map<String, T> oldResult, Map<String, T> newResult) { Set<String> changedResourceNames = new HashSet<>(); oldResult.forEach((key, origin) -> { if (!Objects.equals(origin, newResult.get(key))) { changedResourceNames.add(key); } }); newResult.forEach((key, origin) -> { if (!Objects.equals(origin, oldResult.get(key))) { changedResourceNames.add(key); } }); if (changedResourceNames.isEmpty()) { return; } logger.info("Receive resource update notification from xds server. Change resource count: " + changedResourceNames.stream() + ". Type: " + getTypeUrl()); // call once for full data try { readLock.lock(); for (Map.Entry<Set<String>, List<Consumer<Map<String, T>>>> entry : consumerObserveMap.entrySet()) { if (entry.getKey().stream().noneMatch(changedResourceNames::contains)) { // none update continue; } Map<String, T> dsResultMap = entry.getKey().stream().collect(Collectors.toMap(k -> k, v -> newResult.get(v))); entry.getValue().forEach(o -> o.accept(dsResultMap)); } } finally { readLock.unlock(); } } }
6,226
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/DeltaResource.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.xds.util.protocol; /** * A interface for resources in xDS, which can be updated by ADS delta stream * <br/> * This interface is design to unify the way of fetching data in delta stream * in {@link org.apache.dubbo.registry.xds.util.PilotExchanger} */ public interface DeltaResource<T> { /** * Get resource from delta stream * * @return the newest resource from stream */ T getResource(); }
6,227
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/XdsProtocol.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.xds.util.protocol; import java.util.Map; import java.util.Set; import java.util.function.Consumer; public interface XdsProtocol<T> { /** * Gets all {@link T resource} by the specified resource name. * For LDS, the {@param resourceNames} is ignored * * @param resourceNames specified resource name * @return resources, null if request failed */ Map<String, T> getResource(Set<String> resourceNames); /** * Add a observer resource with {@link Consumer} * * @param resourceNames specified resource name * @param consumer resource notifier, will be called when resource updated * @return requestId, used when resourceNames update with {@link XdsProtocol#updateObserve(long, Set)} */ void observeResource(Set<String> resourceNames, Consumer<Map<String, T>> consumer, boolean isReConnect); }
6,228
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/delta/DeltaListener.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.xds.util.protocol.delta; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.registry.xds.util.protocol.DeltaResource; import org.apache.dubbo.registry.xds.util.protocol.message.ListenerResult; import java.util.Collection; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; public class DeltaListener implements DeltaResource<ListenerResult> { private final Map<String, Set<String>> data = new ConcurrentHashMap<>(); public void addResource(String resourceName, Set<String> listeners) { data.put(resourceName, listeners); } public void removeResource(Collection<String> resourceName) { if (CollectionUtils.isNotEmpty(resourceName)) { resourceName.forEach(data::remove); } } @Override public ListenerResult getResource() { Set<String> set = data.values().stream().flatMap(Set::stream).collect(Collectors.toSet()); return new ListenerResult(set); } }
6,229
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/delta/DeltaEndpoint.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.xds.util.protocol.delta; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.registry.xds.util.protocol.DeltaResource; import org.apache.dubbo.registry.xds.util.protocol.message.Endpoint; import org.apache.dubbo.registry.xds.util.protocol.message.EndpointResult; import java.util.Collection; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; public class DeltaEndpoint implements DeltaResource<EndpointResult> { private final Map<String, Set<Endpoint>> data = new ConcurrentHashMap<>(); public void addResource(String resourceName, Set<Endpoint> endpoints) { data.put(resourceName, endpoints); } public void removeResource(Collection<String> resourceName) { if (CollectionUtils.isNotEmpty(resourceName)) { resourceName.forEach(data::remove); } } @Override public EndpointResult getResource() { Set<Endpoint> set = data.values().stream().flatMap(Set::stream).collect(Collectors.toSet()); return new EndpointResult(set); } }
6,230
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/delta/DeltaRoute.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.xds.util.protocol.delta; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.registry.xds.util.protocol.DeltaResource; import org.apache.dubbo.registry.xds.util.protocol.message.RouteResult; import java.util.Collection; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; public class DeltaRoute implements DeltaResource<RouteResult> { private final Map<String, Map<String, Set<String>>> data = new ConcurrentHashMap<>(); public void addResource(String resourceName, Map<String, Set<String>> route) { data.put(resourceName, route); } public void removeResource(Collection<String> resourceName) { if (CollectionUtils.isNotEmpty(resourceName)) { resourceName.forEach(data::remove); } } @Override public RouteResult getResource() { Map<String, Set<String>> result = new ConcurrentHashMap<>(); data.values().forEach(result::putAll); return new RouteResult(result); } }
6,231
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/impl/LdsProtocol.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.xds.util.protocol.impl; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.registry.xds.util.AdsObserver; import org.apache.dubbo.registry.xds.util.protocol.AbstractProtocol; import org.apache.dubbo.registry.xds.util.protocol.delta.DeltaListener; import org.apache.dubbo.registry.xds.util.protocol.message.ListenerResult; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; import com.google.protobuf.Any; import com.google.protobuf.InvalidProtocolBufferException; import io.envoyproxy.envoy.config.core.v3.Node; import io.envoyproxy.envoy.config.listener.v3.Filter; import io.envoyproxy.envoy.config.listener.v3.Listener; import io.envoyproxy.envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager; import io.envoyproxy.envoy.extensions.filters.network.http_connection_manager.v3.Rds; import io.envoyproxy.envoy.service.discovery.v3.DiscoveryResponse; import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ERROR_RESPONSE_XDS; public class LdsProtocol extends AbstractProtocol<ListenerResult, DeltaListener> { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(LdsProtocol.class); public LdsProtocol(AdsObserver adsObserver, Node node, int checkInterval) { super(adsObserver, node, checkInterval); } @Override public String getTypeUrl() { return "type.googleapis.com/envoy.config.listener.v3.Listener"; } public Map<String, ListenerResult> getListeners() { return getResource(null); } @Override protected Map<String, ListenerResult> decodeDiscoveryResponse(DiscoveryResponse response) { if (getTypeUrl().equals(response.getTypeUrl())) { Set<String> set = response.getResourcesList().stream() .map(LdsProtocol::unpackListener) .filter(Objects::nonNull) .flatMap(e -> decodeResourceToListener(e).stream()) .collect(Collectors.toSet()); Map<String, ListenerResult> listenerDecodeResult = new ConcurrentHashMap<>(); listenerDecodeResult.put(emptyResourceName, new ListenerResult(set)); return listenerDecodeResult; } return new HashMap<>(); } private Set<String> decodeResourceToListener(Listener resource) { return resource.getFilterChainsList().stream() .flatMap(e -> e.getFiltersList().stream()) .map(Filter::getTypedConfig) .map(LdsProtocol::unpackHttpConnectionManager) .filter(Objects::nonNull) .map(HttpConnectionManager::getRds) .map(Rds::getRouteConfigName) .collect(Collectors.toSet()); } private static Listener unpackListener(Any any) { try { return any.unpack(Listener.class); } catch (InvalidProtocolBufferException e) { logger.error(REGISTRY_ERROR_RESPONSE_XDS, "", "", "Error occur when decode xDS response.", e); return null; } } private static HttpConnectionManager unpackHttpConnectionManager(Any any) { try { if (!any.is(HttpConnectionManager.class)) { return null; } return any.unpack(HttpConnectionManager.class); } catch (InvalidProtocolBufferException e) { logger.error(REGISTRY_ERROR_RESPONSE_XDS, "", "", "Error occur when decode xDS response.", e); return null; } } }
6,232
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/impl/EdsProtocol.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.xds.util.protocol.impl; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.registry.xds.util.AdsObserver; import org.apache.dubbo.registry.xds.util.protocol.AbstractProtocol; import org.apache.dubbo.registry.xds.util.protocol.delta.DeltaEndpoint; import org.apache.dubbo.registry.xds.util.protocol.message.Endpoint; import org.apache.dubbo.registry.xds.util.protocol.message.EndpointResult; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import com.google.protobuf.Any; import com.google.protobuf.InvalidProtocolBufferException; import io.envoyproxy.envoy.config.core.v3.HealthStatus; import io.envoyproxy.envoy.config.core.v3.Node; import io.envoyproxy.envoy.config.core.v3.SocketAddress; import io.envoyproxy.envoy.config.endpoint.v3.ClusterLoadAssignment; import io.envoyproxy.envoy.config.endpoint.v3.LbEndpoint; import io.envoyproxy.envoy.service.discovery.v3.DiscoveryResponse; import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ERROR_RESPONSE_XDS; public class EdsProtocol extends AbstractProtocol<EndpointResult, DeltaEndpoint> { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(EdsProtocol.class); public EdsProtocol(AdsObserver adsObserver, Node node, int checkInterval) { super(adsObserver, node, checkInterval); } @Override public String getTypeUrl() { return "type.googleapis.com/envoy.config.endpoint.v3.ClusterLoadAssignment"; } @Override protected Map<String, EndpointResult> decodeDiscoveryResponse(DiscoveryResponse response) { if (getTypeUrl().equals(response.getTypeUrl())) { return response.getResourcesList().stream() .map(EdsProtocol::unpackClusterLoadAssignment) .filter(Objects::nonNull) .collect(Collectors.toConcurrentMap( ClusterLoadAssignment::getClusterName, this::decodeResourceToEndpoint)); } return new HashMap<>(); } private EndpointResult decodeResourceToEndpoint(ClusterLoadAssignment resource) { Set<Endpoint> endpoints = resource.getEndpointsList().stream() .flatMap(e -> e.getLbEndpointsList().stream()) .map(e -> decodeLbEndpointToEndpoint(resource.getClusterName(), e)) .collect(Collectors.toSet()); return new EndpointResult(endpoints); } private static Endpoint decodeLbEndpointToEndpoint(String clusterName, LbEndpoint lbEndpoint) { Endpoint endpoint = new Endpoint(); SocketAddress address = lbEndpoint.getEndpoint().getAddress().getSocketAddress(); endpoint.setAddress(address.getAddress()); endpoint.setPortValue(address.getPortValue()); boolean healthy = HealthStatus.HEALTHY.equals(lbEndpoint.getHealthStatus()) || HealthStatus.UNKNOWN.equals(lbEndpoint.getHealthStatus()); endpoint.setHealthy(healthy); endpoint.setWeight(lbEndpoint.getLoadBalancingWeight().getValue()); return endpoint; } private static ClusterLoadAssignment unpackClusterLoadAssignment(Any any) { try { return any.unpack(ClusterLoadAssignment.class); } catch (InvalidProtocolBufferException e) { logger.error(REGISTRY_ERROR_RESPONSE_XDS, "", "", "Error occur when decode xDS response.", e); return null; } } }
6,233
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/impl/RdsProtocol.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.xds.util.protocol.impl; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.registry.xds.util.AdsObserver; import org.apache.dubbo.registry.xds.util.protocol.AbstractProtocol; import org.apache.dubbo.registry.xds.util.protocol.delta.DeltaRoute; import org.apache.dubbo.registry.xds.util.protocol.message.RouteResult; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; import com.google.protobuf.Any; import com.google.protobuf.InvalidProtocolBufferException; import io.envoyproxy.envoy.config.core.v3.Node; import io.envoyproxy.envoy.config.route.v3.Route; import io.envoyproxy.envoy.config.route.v3.RouteAction; import io.envoyproxy.envoy.config.route.v3.RouteConfiguration; import io.envoyproxy.envoy.config.route.v3.VirtualHost; import io.envoyproxy.envoy.service.discovery.v3.DiscoveryResponse; import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ERROR_RESPONSE_XDS; public class RdsProtocol extends AbstractProtocol<RouteResult, DeltaRoute> { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(RdsProtocol.class); public RdsProtocol(AdsObserver adsObserver, Node node, int checkInterval) { super(adsObserver, node, checkInterval); } @Override public String getTypeUrl() { return "type.googleapis.com/envoy.config.route.v3.RouteConfiguration"; } @Override protected Map<String, RouteResult> decodeDiscoveryResponse(DiscoveryResponse response) { if (getTypeUrl().equals(response.getTypeUrl())) { return response.getResourcesList().stream() .map(RdsProtocol::unpackRouteConfiguration) .filter(Objects::nonNull) .collect(Collectors.toConcurrentMap(RouteConfiguration::getName, this::decodeResourceToListener)); } return new HashMap<>(); } private RouteResult decodeResourceToListener(RouteConfiguration resource) { Map<String, Set<String>> map = new HashMap<>(); Map<String, VirtualHost> rdsVirtualhostMap = new ConcurrentHashMap<>(); resource.getVirtualHostsList().forEach(virtualHost -> { Set<String> cluster = virtualHost.getRoutesList().stream() .map(Route::getRoute) .map(RouteAction::getCluster) .collect(Collectors.toSet()); for (String domain : virtualHost.getDomainsList()) { map.put(domain, cluster); rdsVirtualhostMap.put(domain, virtualHost); } }); return new RouteResult(map, rdsVirtualhostMap); } private static RouteConfiguration unpackRouteConfiguration(Any any) { try { return any.unpack(RouteConfiguration.class); } catch (InvalidProtocolBufferException e) { logger.error(REGISTRY_ERROR_RESPONSE_XDS, "", "", "Error occur when decode xDS response.", e); return null; } } }
6,234
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/message/RouteResult.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.xds.util.protocol.message; import org.apache.dubbo.common.utils.ConcurrentHashSet; import java.util.Collections; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import io.envoyproxy.envoy.config.route.v3.VirtualHost; public class RouteResult { private final Map<String, Set<String>> domainMap; private Map<String, VirtualHost> virtualHostMap; public RouteResult() { this.domainMap = new ConcurrentHashMap<>(); this.virtualHostMap = new ConcurrentHashMap<>(); } public RouteResult(Map<String, Set<String>> domainMap) { this.domainMap = domainMap; this.virtualHostMap = new ConcurrentHashMap<>(); } public RouteResult(Map<String, Set<String>> domainMap, Map<String, VirtualHost> virtualHostMap) { this.domainMap = domainMap; this.virtualHostMap = virtualHostMap; } public Map<String, Set<String>> getDomainMap() { return domainMap; } public boolean isNotEmpty() { return !domainMap.isEmpty(); } public Set<String> searchDomain(String domain) { return domainMap.getOrDefault(domain, new ConcurrentHashSet<>()); } public Set<String> getDomains() { return Collections.unmodifiableSet(domainMap.keySet()); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RouteResult that = (RouteResult) o; return Objects.equals(domainMap, that.domainMap) && Objects.equals(virtualHostMap, that.virtualHostMap); } @Override public int hashCode() { return Objects.hash(domainMap, virtualHostMap); } public VirtualHost searchVirtualHost(String domain) { return virtualHostMap.get(domain); } public void removeVirtualHost(String domain) { virtualHostMap.remove(domain); } @Override public String toString() { return "RouteResult{" + "domainMap=" + domainMap + ", virtualHostMap=" + virtualHostMap + '}'; } }
6,235
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/message/EndpointResult.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.xds.util.protocol.message; import org.apache.dubbo.common.utils.ConcurrentHashSet; import java.util.Objects; import java.util.Set; public class EndpointResult { private Set<Endpoint> endpoints; public EndpointResult() { this.endpoints = new ConcurrentHashSet<>(); } public EndpointResult(Set<Endpoint> endpoints) { this.endpoints = endpoints; } public Set<Endpoint> getEndpoints() { return endpoints; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } EndpointResult that = (EndpointResult) o; return Objects.equals(endpoints, that.endpoints); } @Override public int hashCode() { return Objects.hash(endpoints); } @Override public String toString() { return "EndpointResult{" + "endpoints=" + endpoints + '}'; } }
6,236
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/message/Endpoint.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.xds.util.protocol.message; import java.util.Objects; public class Endpoint { private String clusterName; private String address; private int portValue; private boolean healthy; private int weight; public String getClusterName() { return clusterName; } public void setClusterName(String clusterName) { this.clusterName = clusterName; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getPortValue() { return portValue; } public void setPortValue(int portValue) { this.portValue = portValue; } public boolean isHealthy() { return healthy; } public void setHealthy(boolean healthy) { this.healthy = healthy; } public int getWeight() { return weight; } public void setWeight(int weight) { this.weight = weight; } @Override public String toString() { return "Endpoint{" + "address='" + address + '\'' + ", portValue='" + portValue + '\'' + ", healthy=" + healthy + ", weight=" + weight + '}'; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Endpoint endpoint = (Endpoint) o; return healthy == endpoint.healthy && weight == endpoint.weight && Objects.equals(address, endpoint.address) && Objects.equals(portValue, endpoint.portValue); } @Override public int hashCode() { return Objects.hash(address, portValue, healthy, weight); } }
6,237
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/message/ListenerResult.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.xds.util.protocol.message; import org.apache.dubbo.common.utils.ConcurrentHashSet; import java.util.Objects; import java.util.Set; public class ListenerResult { private Set<String> routeConfigNames; public ListenerResult() { this.routeConfigNames = new ConcurrentHashSet<>(); } public ListenerResult(Set<String> routeConfigNames) { this.routeConfigNames = routeConfigNames; } public Set<String> getRouteConfigNames() { return routeConfigNames; } public void setRouteConfigNames(Set<String> routeConfigNames) { this.routeConfigNames = routeConfigNames; } public void mergeRouteConfigNames(Set<String> names) { this.routeConfigNames.addAll(names); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ListenerResult listenerResult = (ListenerResult) o; return Objects.equals(routeConfigNames, listenerResult.routeConfigNames); } @Override public int hashCode() { return Objects.hash(routeConfigNames); } @Override public String toString() { return "ListenerResult{" + "routeConfigNames=" + routeConfigNames + '}'; } }
6,238
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/istio/IstioCitadelCertificateSigner.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.xds.istio; 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.StringUtils; import org.apache.dubbo.registry.xds.XdsCertificateSigner; import org.apache.dubbo.rpc.RpcException; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.StringWriter; import java.nio.charset.StandardCharsets; import java.security.InvalidAlgorithmParameterException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.spec.ECGenParameterSpec; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import io.grpc.ManagedChannel; import io.grpc.Metadata; import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; import io.grpc.netty.shaded.io.netty.handler.ssl.util.InsecureTrustManagerFactory; import io.grpc.stub.MetadataUtils; import io.grpc.stub.StreamObserver; import istio.v1.auth.IstioCertificateRequest; import istio.v1.auth.IstioCertificateResponse; import istio.v1.auth.IstioCertificateServiceGrpc; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x509.Extension; import org.bouncycastle.asn1.x509.ExtensionsGenerator; import org.bouncycastle.asn1.x509.GeneralName; import org.bouncycastle.asn1.x509.GeneralNames; import org.bouncycastle.openssl.jcajce.JcaPEMWriter; import org.bouncycastle.operator.ContentSigner; import org.bouncycastle.operator.OperatorCreationException; import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; import org.bouncycastle.pkcs.PKCS10CertificationRequest; import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder; import org.bouncycastle.util.io.pem.PemObject; import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_GENERATE_CERT_ISTIO; import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_GENERATE_KEY_ISTIO; import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_RECEIVE_ERROR_MSG_ISTIO; public class IstioCitadelCertificateSigner implements XdsCertificateSigner { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(IstioCitadelCertificateSigner.class); private final org.apache.dubbo.registry.xds.istio.IstioEnv istioEnv; private CertPair certPair; public IstioCitadelCertificateSigner() { // watch cert, Refresh every 30s ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(1); scheduledThreadPool.scheduleAtFixedRate(new GenerateCertTask(), 0, 30, TimeUnit.SECONDS); istioEnv = IstioEnv.getInstance(); } @Override public CertPair GenerateCert(URL url) { if (certPair != null && !certPair.isExpire()) { return certPair; } return doGenerateCert(); } private class GenerateCertTask implements Runnable { @Override public void run() { doGenerateCert(); } } private CertPair doGenerateCert() { synchronized (this) { if (certPair == null || certPair.isExpire()) { try { certPair = createCert(); } catch (IOException e) { logger.error(REGISTRY_FAILED_GENERATE_CERT_ISTIO, "", "", "Generate Cert from Istio failed.", e); throw new RpcException("Generate Cert from Istio failed.", e); } } } return certPair; } public CertPair createCert() throws IOException { PublicKey publicKey = null; PrivateKey privateKey = null; ContentSigner signer = null; if (istioEnv.isECCFirst()) { try { ECGenParameterSpec ecSpec = new ECGenParameterSpec("secp256r1"); KeyPairGenerator g = KeyPairGenerator.getInstance("EC"); g.initialize(ecSpec, new SecureRandom()); KeyPair keypair = g.generateKeyPair(); publicKey = keypair.getPublic(); privateKey = keypair.getPrivate(); signer = new JcaContentSignerBuilder("SHA256withECDSA").build(keypair.getPrivate()); } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException | OperatorCreationException e) { logger.error( REGISTRY_FAILED_GENERATE_KEY_ISTIO, "", "", "Generate Key with secp256r1 algorithm failed. Please check if your system support. " + "Will attempt to generate with RSA2048.", e); } } if (publicKey == null) { try { KeyPairGenerator kpGenerator = KeyPairGenerator.getInstance("RSA"); kpGenerator.initialize(istioEnv.getRasKeySize()); KeyPair keypair = kpGenerator.generateKeyPair(); publicKey = keypair.getPublic(); privateKey = keypair.getPrivate(); signer = new JcaContentSignerBuilder("SHA256WithRSA").build(keypair.getPrivate()); } catch (NoSuchAlgorithmException | OperatorCreationException e) { logger.error( REGISTRY_FAILED_GENERATE_KEY_ISTIO, "", "", "Generate Key with SHA256WithRSA algorithm failed. Please check if your system support.", e); throw new RpcException(e); } } String csr = generateCsr(publicKey, signer); String caCert = istioEnv.getCaCert(); ManagedChannel channel; if (StringUtils.isNotEmpty(caCert)) { channel = NettyChannelBuilder.forTarget(istioEnv.getCaAddr()) .sslContext(GrpcSslContexts.forClient() .trustManager(new ByteArrayInputStream(caCert.getBytes(StandardCharsets.UTF_8))) .build()) .build(); } else { channel = NettyChannelBuilder.forTarget(istioEnv.getCaAddr()) .sslContext(GrpcSslContexts.forClient() .trustManager(InsecureTrustManagerFactory.INSTANCE) .build()) .build(); } Metadata header = new Metadata(); Metadata.Key<String> key = Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER); header.put(key, "Bearer " + istioEnv.getServiceAccount()); key = Metadata.Key.of("ClusterID", Metadata.ASCII_STRING_MARSHALLER); header.put(key, istioEnv.getIstioMetaClusterId()); IstioCertificateServiceGrpc.IstioCertificateServiceStub stub = IstioCertificateServiceGrpc.newStub(channel); stub = stub.withInterceptors(MetadataUtils.newAttachHeadersInterceptor(header)); CountDownLatch countDownLatch = new CountDownLatch(1); StringBuffer publicKeyBuilder = new StringBuffer(); AtomicBoolean failed = new AtomicBoolean(false); stub.createCertificate( generateRequest(csr), generateResponseObserver(countDownLatch, publicKeyBuilder, failed)); long expireTime = System.currentTimeMillis() + (long) (istioEnv.getSecretTTL() * istioEnv.getSecretGracePeriodRatio()); try { countDownLatch.await(); } catch (InterruptedException e) { throw new RpcException("Generate Cert Failed. Wait for cert failed.", e); } if (failed.get()) { throw new RpcException("Generate Cert Failed. Send csr request failed. Please check log above."); } String privateKeyPem = generatePrivatePemKey(privateKey); CertPair certPair = new CertPair(privateKeyPem, publicKeyBuilder.toString(), System.currentTimeMillis(), expireTime); channel.shutdown(); return certPair; } private IstioCertificateRequest generateRequest(String csr) { return IstioCertificateRequest.newBuilder() .setCsr(csr) .setValidityDuration(istioEnv.getSecretTTL()) .build(); } private StreamObserver<IstioCertificateResponse> generateResponseObserver( CountDownLatch countDownLatch, StringBuffer publicKeyBuilder, AtomicBoolean failed) { return new StreamObserver<IstioCertificateResponse>() { @Override public void onNext(IstioCertificateResponse istioCertificateResponse) { for (int i = 0; i < istioCertificateResponse.getCertChainCount(); i++) { publicKeyBuilder.append( istioCertificateResponse.getCertChainBytes(i).toStringUtf8()); } if (logger.isDebugEnabled()) { logger.debug("Receive Cert chain from Istio Citadel. \n" + publicKeyBuilder); } countDownLatch.countDown(); } @Override public void onError(Throwable throwable) { failed.set(true); logger.error( REGISTRY_RECEIVE_ERROR_MSG_ISTIO, "", "", "Receive error message from Istio Citadel grpc stub.", throwable); countDownLatch.countDown(); } @Override public void onCompleted() { countDownLatch.countDown(); } }; } private String generatePrivatePemKey(PrivateKey privateKey) throws IOException { String key = generatePemKey("RSA PRIVATE KEY", privateKey.getEncoded()); if (logger.isDebugEnabled()) { logger.debug("Generated Private Key. \n" + key); } return key; } private String generatePemKey(String type, byte[] content) throws IOException { PemObject pemObject = new PemObject(type, content); StringWriter str = new StringWriter(); JcaPEMWriter jcaPEMWriter = new JcaPEMWriter(str); jcaPEMWriter.writeObject(pemObject); jcaPEMWriter.close(); str.close(); return str.toString(); } private String generateCsr(PublicKey publicKey, ContentSigner signer) throws IOException { GeneralNames subjectAltNames = new GeneralNames(new GeneralName[] {new GeneralName(6, istioEnv.getCsrHost())}); ExtensionsGenerator extGen = new ExtensionsGenerator(); extGen.addExtension(Extension.subjectAlternativeName, true, subjectAltNames); PKCS10CertificationRequest request = new JcaPKCS10CertificationRequestBuilder( new X500Name("O=" + istioEnv.getTrustDomain()), publicKey) .addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extGen.generate()) .build(signer); String csr = generatePemKey("CERTIFICATE REQUEST", request.getEncoded()); if (logger.isDebugEnabled()) { logger.debug("CSR Request to Istio Citadel. \n" + csr); } return csr; } }
6,239
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/istio/IstioEnv.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.xds.istio; import org.apache.dubbo.common.constants.LoggerCodeConstants; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.registry.xds.XdsEnv; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Optional; import org.apache.commons.io.FileUtils; import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ERROR_READ_FILE_ISTIO; import static org.apache.dubbo.registry.xds.istio.IstioConstant.NS; import static org.apache.dubbo.registry.xds.istio.IstioConstant.SA; import static org.apache.dubbo.registry.xds.istio.IstioConstant.SPIFFE; public class IstioEnv implements XdsEnv { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(IstioEnv.class); private static final IstioEnv INSTANCE = new IstioEnv(); private String podName; private String caAddr; private String jwtPolicy; private String trustDomain; private String workloadNameSpace; private int rasKeySize; private String eccSigAlg; private int secretTTL; private float secretGracePeriodRatio; private String istioMetaClusterId; private String pilotCertProvider; private IstioEnv() { jwtPolicy = Optional.ofNullable(System.getenv(IstioConstant.JWT_POLICY)).orElse(IstioConstant.DEFAULT_JWT_POLICY); podName = Optional.ofNullable(System.getenv("POD_NAME")).orElse(System.getenv("HOSTNAME")); trustDomain = Optional.ofNullable(System.getenv(IstioConstant.TRUST_DOMAIN_KEY)) .orElse(IstioConstant.DEFAULT_TRUST_DOMAIN); workloadNameSpace = Optional.ofNullable(System.getenv(IstioConstant.WORKLOAD_NAMESPACE_KEY)) .orElseGet(() -> { File namespaceFile = new File(IstioConstant.KUBERNETES_NAMESPACE_PATH); if (namespaceFile.canRead()) { try { return FileUtils.readFileToString(namespaceFile, StandardCharsets.UTF_8); } catch (IOException e) { logger.error(REGISTRY_ERROR_READ_FILE_ISTIO, "", "", "read namespace file error", e); } } return IstioConstant.DEFAULT_WORKLOAD_NAMESPACE; }); caAddr = Optional.ofNullable(System.getenv(IstioConstant.CA_ADDR_KEY)).orElse(IstioConstant.DEFAULT_CA_ADDR); rasKeySize = Integer.parseInt(Optional.ofNullable(System.getenv(IstioConstant.RSA_KEY_SIZE_KEY)) .orElse(IstioConstant.DEFAULT_RSA_KEY_SIZE)); eccSigAlg = Optional.ofNullable(System.getenv(IstioConstant.ECC_SIG_ALG_KEY)) .orElse(IstioConstant.DEFAULT_ECC_SIG_ALG); secretTTL = Integer.parseInt(Optional.ofNullable(System.getenv(IstioConstant.SECRET_TTL_KEY)) .orElse(IstioConstant.DEFAULT_SECRET_TTL)); secretGracePeriodRatio = Float.parseFloat(Optional.ofNullable(System.getenv(IstioConstant.SECRET_GRACE_PERIOD_RATIO_KEY)) .orElse(IstioConstant.DEFAULT_SECRET_GRACE_PERIOD_RATIO)); istioMetaClusterId = Optional.ofNullable(System.getenv(IstioConstant.ISTIO_META_CLUSTER_ID_KEY)) .orElse(IstioConstant.DEFAULT_ISTIO_META_CLUSTER_ID); pilotCertProvider = Optional.ofNullable(System.getenv(IstioConstant.PILOT_CERT_PROVIDER_KEY)) .orElse(""); if (getServiceAccount() == null) { throw new UnsupportedOperationException("Unable to found kubernetes service account token file. " + "Please check if work in Kubernetes and mount service account token file correctly."); } } public static IstioEnv getInstance() { return INSTANCE; } public String getPodName() { return podName; } public String getCaAddr() { return caAddr; } public String getServiceAccount() { File saFile; switch (jwtPolicy) { case IstioConstant.FIRST_PARTY_JWT: saFile = new File(IstioConstant.KUBERNETES_SA_PATH); break; case IstioConstant.THIRD_PARTY_JWT: default: saFile = new File(IstioConstant.ISTIO_SA_PATH); } if (saFile.canRead()) { try { return FileUtils.readFileToString(saFile, StandardCharsets.UTF_8); } catch (IOException e) { logger.error( LoggerCodeConstants.REGISTRY_ISTIO_EXCEPTION, "File Read Failed", "", "Unable to read token file.", e); } } return null; } public String getCsrHost() { // spiffe://<trust_domain>/ns/<namespace>/sa/<service_account> return SPIFFE + trustDomain + NS + workloadNameSpace + SA + getServiceAccount(); } public String getTrustDomain() { return trustDomain; } public String getWorkloadNameSpace() { return workloadNameSpace; } @Override public String getCluster() { return null; } public int getRasKeySize() { return rasKeySize; } public boolean isECCFirst() { return IstioConstant.DEFAULT_ECC_SIG_ALG.equals(eccSigAlg); } public int getSecretTTL() { return secretTTL; } public float getSecretGracePeriodRatio() { return secretGracePeriodRatio; } public String getIstioMetaClusterId() { return istioMetaClusterId; } public String getCaCert() { File caFile; if (IstioConstant.ISTIO_PILOT_CERT_PROVIDER.equals(pilotCertProvider)) { caFile = new File(IstioConstant.ISTIO_CA_PATH); } else { return null; } if (caFile.canRead()) { try { return FileUtils.readFileToString(caFile, StandardCharsets.UTF_8); } catch (IOException e) { logger.error( LoggerCodeConstants.REGISTRY_ISTIO_EXCEPTION, "File Read Failed", "", "read ca file error", e); } } return null; } }
6,240
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/istio/IstioConstant.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.xds.istio; public class IstioConstant { /** * Address of the spiffe certificate provider. Defaults to discoveryAddress */ public static final String CA_ADDR_KEY = "CA_ADDR"; /** * CA and xDS services */ public static final String DEFAULT_CA_ADDR = "istiod.istio-system.svc:15012"; /** * The trust domain for spiffe certificates */ public static final String TRUST_DOMAIN_KEY = "TRUST_DOMAIN"; /** * The trust domain for spiffe certificates default value */ public static final String DEFAULT_TRUST_DOMAIN = "cluster.local"; public static final String WORKLOAD_NAMESPACE_KEY = "WORKLOAD_NAMESPACE"; public static final String DEFAULT_WORKLOAD_NAMESPACE = "default"; /** * k8s jwt token */ public static final String KUBERNETES_SA_PATH = "/var/run/secrets/kubernetes.io/serviceaccount/token"; public static final String KUBERNETES_CA_PATH = "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt"; public static final String ISTIO_SA_PATH = "/var/run/secrets/tokens/istio-token"; public static final String ISTIO_CA_PATH = "/var/run/secrets/istio/root-cert.pem"; public static final String KUBERNETES_NAMESPACE_PATH = "/var/run/secrets/kubernetes.io/serviceaccount/namespace"; public static final String RSA_KEY_SIZE_KEY = "RSA_KEY_SIZE"; public static final String DEFAULT_RSA_KEY_SIZE = "2048"; /** * The type of ECC signature algorithm to use when generating private keys */ public static final String ECC_SIG_ALG_KEY = "ECC_SIGNATURE_ALGORITHM"; public static final String DEFAULT_ECC_SIG_ALG = "ECDSA"; /** * The cert lifetime requested by istio agent */ public static final String SECRET_TTL_KEY = "SECRET_TTL"; /** * The cert lifetime default value 24h0m0s */ public static final String DEFAULT_SECRET_TTL = "86400"; // 24 * 60 * 60 /** * The grace period ratio for the cert rotation */ public static final String SECRET_GRACE_PERIOD_RATIO_KEY = "SECRET_GRACE_PERIOD_RATIO"; /** * The grace period ratio for the cert rotation, by default 0.5 */ public static final String DEFAULT_SECRET_GRACE_PERIOD_RATIO = "0.5"; public static final String ISTIO_META_CLUSTER_ID_KEY = "ISTIO_META_CLUSTER_ID"; public static final String PILOT_CERT_PROVIDER_KEY = "PILOT_CERT_PROVIDER"; public static final String ISTIO_PILOT_CERT_PROVIDER = "istiod"; public static final String DEFAULT_ISTIO_META_CLUSTER_ID = "Kubernetes"; public static final String SPIFFE = "spiffe://"; public static final String NS = "/ns/"; public static final String SA = "/sa/"; public static final String JWT_POLICY = "JWT_POLICY"; public static final String DEFAULT_JWT_POLICY = "first-party-jwt"; public static final String FIRST_PARTY_JWT = "first-party-jwt"; public static final String THIRD_PARTY_JWT = "third-party-jwt"; }
6,241
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/XdsRouteRuleListener.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.router.xds; import org.apache.dubbo.rpc.cluster.router.xds.rule.XdsRouteRule; import java.util.List; public interface XdsRouteRuleListener { void onRuleChange(String appName, List<XdsRouteRule> xdsRouteRules); void clearRule(String appName); }
6,242
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/XdsRouter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.router.xds; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.ConcurrentHashSet; import org.apache.dubbo.common.utils.Holder; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.registry.xds.util.PilotExchanger; import org.apache.dubbo.registry.xds.util.protocol.message.Endpoint; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.cluster.router.RouterSnapshotNode; import org.apache.dubbo.rpc.cluster.router.state.AbstractStateRouter; import org.apache.dubbo.rpc.cluster.router.state.BitList; import org.apache.dubbo.rpc.cluster.router.xds.rule.ClusterWeight; import org.apache.dubbo.rpc.cluster.router.xds.rule.DestinationSubset; import org.apache.dubbo.rpc.cluster.router.xds.rule.HTTPRouteDestination; import org.apache.dubbo.rpc.cluster.router.xds.rule.HeaderMatcher; import org.apache.dubbo.rpc.cluster.router.xds.rule.HttpRequestMatch; import org.apache.dubbo.rpc.cluster.router.xds.rule.PathMatcher; import org.apache.dubbo.rpc.cluster.router.xds.rule.XdsRouteRule; import org.apache.dubbo.rpc.support.RpcUtils; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.Collectors; public class XdsRouter<T> extends AbstractStateRouter<T> implements XdsRouteRuleListener, EdsEndpointListener { private Set<String> subscribeApplications; private final ConcurrentHashMap<String, List<XdsRouteRule>> xdsRouteRuleMap; private final ConcurrentHashMap<String, DestinationSubset<T>> destinationSubsetMap; private final RdsRouteRuleManager rdsRouteRuleManager; private final EdsEndpointManager edsEndpointManager; private volatile BitList<Invoker<T>> currentInvokeList; private static final String BINARY_HEADER_SUFFIX = "-bin"; private final boolean isEnable; public XdsRouter(URL url) { super(url); isEnable = PilotExchanger.isEnabled(); rdsRouteRuleManager = url.getOrDefaultApplicationModel().getBeanFactory().getBean(RdsRouteRuleManager.class); edsEndpointManager = url.getOrDefaultApplicationModel().getBeanFactory().getBean(EdsEndpointManager.class); subscribeApplications = new ConcurrentHashSet<>(); destinationSubsetMap = new ConcurrentHashMap<>(); xdsRouteRuleMap = new ConcurrentHashMap<>(); currentInvokeList = new BitList<>(new ArrayList<>()); } /** * @deprecated only for uts */ protected XdsRouter( URL url, RdsRouteRuleManager rdsRouteRuleManager, EdsEndpointManager edsEndpointManager, boolean isEnable) { super(url); this.isEnable = isEnable; this.rdsRouteRuleManager = rdsRouteRuleManager; this.edsEndpointManager = edsEndpointManager; subscribeApplications = new ConcurrentHashSet<>(); destinationSubsetMap = new ConcurrentHashMap<>(); xdsRouteRuleMap = new ConcurrentHashMap<>(); currentInvokeList = new BitList<>(new ArrayList<>()); } @Override protected BitList<Invoker<T>> doRoute( BitList<Invoker<T>> invokers, URL url, Invocation invocation, boolean needToPrintMessage, Holder<RouterSnapshotNode<T>> nodeHolder, Holder<String> messageHolder) throws RpcException { if (!isEnable) { if (needToPrintMessage) { messageHolder.set( "Directly Return. Reason: Pilot exchanger has not been initialized, may not in mesh mode."); } return invokers; } if (CollectionUtils.isEmpty(invokers)) { if (needToPrintMessage) { messageHolder.set("Directly Return. Reason: Invokers from previous router is empty."); } return invokers; } if (CollectionUtils.isEmptyMap(xdsRouteRuleMap)) { if (needToPrintMessage) { messageHolder.set("Directly Return. Reason: xds route rule is empty."); } return invokers; } StringBuilder stringBuilder = needToPrintMessage ? new StringBuilder() : null; // find match cluster String matchCluster = null; Set<String> appNames = subscribeApplications; for (String subscribeApplication : appNames) { List<XdsRouteRule> rules = xdsRouteRuleMap.get(subscribeApplication); if (CollectionUtils.isEmpty(rules)) { continue; } for (XdsRouteRule rule : rules) { String cluster = computeMatchCluster(invocation, rule); if (cluster != null) { matchCluster = cluster; break; } } if (matchCluster != null) { if (stringBuilder != null) { stringBuilder .append("Match App: ") .append(subscribeApplication) .append(" Cluster: ") .append(matchCluster) .append(' '); } break; } } // not match request just return if (matchCluster == null) { if (needToPrintMessage) { messageHolder.set("Directly Return. Reason: xds rule not match."); } return invokers; } DestinationSubset<T> destinationSubset = destinationSubsetMap.get(matchCluster); // cluster no target provider if (destinationSubset == null) { if (needToPrintMessage) { messageHolder.set(stringBuilder.append("no target subset").toString()); } return BitList.emptyList(); } if (needToPrintMessage) { messageHolder.set(stringBuilder.toString()); } if (destinationSubset.getInvokers() == null) { return BitList.emptyList(); } return destinationSubset.getInvokers().and(invokers); } private String computeMatchCluster(Invocation invocation, XdsRouteRule rule) { // compute request match cluster HttpRequestMatch requestMatch = rule.getMatch(); if (requestMatch.getPathMatcher() == null && CollectionUtils.isEmpty(requestMatch.getHeaderMatcherList())) { return null; } PathMatcher pathMatcher = requestMatch.getPathMatcher(); if (pathMatcher != null) { String path = "/" + invocation.getInvoker().getUrl().getPath() + "/" + RpcUtils.getMethodName(invocation); if (!pathMatcher.isMatch(path)) { return null; } } List<HeaderMatcher> headerMatchers = requestMatch.getHeaderMatcherList(); for (HeaderMatcher headerMatcher : headerMatchers) { String headerName = headerMatcher.getName(); // not support byte if (headerName.endsWith(BINARY_HEADER_SUFFIX)) { return null; } String headValue = invocation.getAttachment(headerName); if (!headerMatcher.match(headValue)) { return null; } } HTTPRouteDestination route = rule.getRoute(); if (route.getCluster() != null) { return route.getCluster(); } return computeWeightCluster(route.getWeightedClusters()); } private String computeWeightCluster(List<ClusterWeight> weightedClusters) { int totalWeight = Math.max( weightedClusters.stream().mapToInt(ClusterWeight::getWeight).sum(), 1); // target must greater than 0 // if weight is 0, the destination will not receive any traffic. int target = ThreadLocalRandom.current().nextInt(1, totalWeight + 1); for (ClusterWeight weightedCluster : weightedClusters) { int weight = weightedCluster.getWeight(); target -= weight; if (target <= 0) { return weightedCluster.getName(); } } return null; } public void notify(BitList<Invoker<T>> invokers) { BitList<Invoker<T>> invokerList = invokers == null ? BitList.emptyList() : invokers; currentInvokeList = invokerList.clone(); // compute need subscribe/unsubscribe rds application Set<String> currentApplications = new HashSet<>(); for (Invoker<T> invoker : invokerList) { String applicationName = invoker.getUrl().getRemoteApplication(); if (StringUtils.isNotEmpty(applicationName)) { currentApplications.add(applicationName); } } if (!subscribeApplications.equals(currentApplications)) { synchronized (this) { for (String currentApplication : currentApplications) { if (!subscribeApplications.contains(currentApplication)) { rdsRouteRuleManager.subscribeRds(currentApplication, this); } } for (String preApplication : subscribeApplications) { if (!currentApplications.contains(preApplication)) { rdsRouteRuleManager.unSubscribeRds(preApplication, this); } } subscribeApplications = currentApplications; } } // update subset synchronized (this) { BitList<Invoker<T>> allInvokers = currentInvokeList.clone(); for (DestinationSubset<T> subset : destinationSubsetMap.values()) { computeSubset(subset, allInvokers); } } } private void computeSubset(DestinationSubset<T> subset, BitList<Invoker<T>> invokers) { Set<Endpoint> endpoints = subset.getEndpoints(); List<Invoker<T>> filterInvokers = invokers.stream() .filter(inv -> { String host = inv.getUrl().getHost(); int port = inv.getUrl().getPort(); Optional<Endpoint> any = endpoints.stream() .filter(end -> host.equals(end.getAddress()) && port == end.getPortValue()) .findAny(); return any.isPresent(); }) .collect(Collectors.toList()); subset.setInvokers(new BitList<>(filterInvokers)); } @Override public synchronized void onRuleChange(String appName, List<XdsRouteRule> xdsRouteRules) { if (CollectionUtils.isEmpty(xdsRouteRules)) { clearRule(appName); return; } Set<String> oldCluster = getAllCluster(); xdsRouteRuleMap.put(appName, xdsRouteRules); Set<String> newCluster = getAllCluster(); changeClusterSubscribe(oldCluster, newCluster); } private Set<String> getAllCluster() { if (CollectionUtils.isEmptyMap(xdsRouteRuleMap)) { return new HashSet<>(); } Set<String> clusters = new HashSet<>(); xdsRouteRuleMap.forEach((appName, rules) -> { for (XdsRouteRule rule : rules) { HTTPRouteDestination action = rule.getRoute(); if (action.getCluster() != null) { clusters.add(action.getCluster()); } else if (CollectionUtils.isNotEmpty(action.getWeightedClusters())) { for (ClusterWeight weightedCluster : action.getWeightedClusters()) { clusters.add(weightedCluster.getName()); } } } }); return clusters; } private void changeClusterSubscribe(Set<String> oldCluster, Set<String> newCluster) { Set<String> removeSubscribe = new HashSet<>(oldCluster); Set<String> addSubscribe = new HashSet<>(newCluster); removeSubscribe.removeAll(newCluster); addSubscribe.removeAll(oldCluster); // remove subscribe cluster for (String cluster : removeSubscribe) { edsEndpointManager.unSubscribeEds(cluster, this); destinationSubsetMap.remove(cluster); } // add subscribe cluster for (String cluster : addSubscribe) { destinationSubsetMap.put(cluster, new DestinationSubset<>(cluster)); edsEndpointManager.subscribeEds(cluster, this); } } @Override public synchronized void clearRule(String appName) { Set<String> oldCluster = getAllCluster(); List<XdsRouteRule> oldRules = xdsRouteRuleMap.remove(appName); if (CollectionUtils.isEmpty(oldRules)) { return; } Set<String> newCluster = getAllCluster(); changeClusterSubscribe(oldCluster, newCluster); } @Override public synchronized void onEndPointChange(String cluster, Set<Endpoint> endpoints) { // find and update subset DestinationSubset<T> subset = destinationSubsetMap.get(cluster); if (subset == null) { return; } subset.setEndpoints(endpoints); computeSubset(subset, currentInvokeList.clone()); } @Override public void stop() { for (String app : subscribeApplications) { rdsRouteRuleManager.unSubscribeRds(app, this); } for (String cluster : getAllCluster()) { edsEndpointManager.unSubscribeEds(cluster, this); } } @Deprecated Set<String> getSubscribeApplications() { return subscribeApplications; } /** * for ut only */ @Deprecated BitList<Invoker<T>> getInvokerList() { return currentInvokeList; } /** * for ut only */ @Deprecated ConcurrentHashMap<String, List<XdsRouteRule>> getXdsRouteRuleMap() { return xdsRouteRuleMap; } /** * for ut only */ @Deprecated ConcurrentHashMap<String, DestinationSubset<T>> getDestinationSubsetMap() { return destinationSubsetMap; } }
6,243
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/EdsEndpointManager.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.router.xds; import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository; 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.registry.xds.util.PilotExchanger; import org.apache.dubbo.registry.xds.util.protocol.message.Endpoint; import org.apache.dubbo.registry.xds.util.protocol.message.EndpointResult; import org.apache.dubbo.rpc.model.FrameworkModel; import java.util.Collections; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Consumer; import java.util.stream.Collectors; public class EdsEndpointManager { private static final ConcurrentHashMap<String, Set<EdsEndpointListener>> ENDPOINT_LISTENERS = new ConcurrentHashMap<>(); private static final ConcurrentHashMap<String, Set<Endpoint>> ENDPOINT_DATA_CACHE = new ConcurrentHashMap<>(); private static final ConcurrentHashMap<String, Consumer<Map<String, EndpointResult>>> EDS_LISTENERS = new ConcurrentHashMap<>(); public EdsEndpointManager() {} public synchronized void subscribeEds(String cluster, EdsEndpointListener listener) { Set<EdsEndpointListener> listeners = ConcurrentHashMapUtils.computeIfAbsent(ENDPOINT_LISTENERS, cluster, key -> new ConcurrentHashSet<>()); if (CollectionUtils.isEmpty(listeners)) { doSubscribeEds(cluster); } listeners.add(listener); if (ENDPOINT_DATA_CACHE.containsKey(cluster)) { listener.onEndPointChange(cluster, ENDPOINT_DATA_CACHE.get(cluster)); } } private void doSubscribeEds(String cluster) { ConcurrentHashMapUtils.computeIfAbsent(EDS_LISTENERS, cluster, key -> endpoints -> { Set<Endpoint> result = endpoints.values().stream() .map(EndpointResult::getEndpoints) .flatMap(Set::stream) .collect(Collectors.toSet()); notifyEndpointChange(cluster, result); }); Consumer<Map<String, EndpointResult>> consumer = EDS_LISTENERS.get(cluster); if (PilotExchanger.isEnabled()) { FrameworkModel.defaultModel() .getBeanFactory() .getBean(FrameworkExecutorRepository.class) .getSharedExecutor() .submit(() -> PilotExchanger.getInstance().observeEds(Collections.singleton(cluster), consumer)); } } public synchronized void unSubscribeEds(String cluster, EdsEndpointListener listener) { Set<EdsEndpointListener> listeners = ENDPOINT_LISTENERS.get(cluster); if (CollectionUtils.isEmpty(listeners)) { return; } listeners.remove(listener); if (listeners.isEmpty()) { ENDPOINT_LISTENERS.remove(cluster); doUnsubscribeEds(cluster); } } private void doUnsubscribeEds(String cluster) { Consumer<Map<String, EndpointResult>> consumer = EDS_LISTENERS.remove(cluster); if (consumer != null && PilotExchanger.isEnabled()) { PilotExchanger.getInstance().unObserveEds(Collections.singleton(cluster), consumer); } ENDPOINT_DATA_CACHE.remove(cluster); } public void notifyEndpointChange(String cluster, Set<Endpoint> endpoints) { ENDPOINT_DATA_CACHE.put(cluster, endpoints); Set<EdsEndpointListener> listeners = ENDPOINT_LISTENERS.get(cluster); if (CollectionUtils.isEmpty(listeners)) { return; } for (EdsEndpointListener listener : listeners) { listener.onEndPointChange(cluster, endpoints); } } // for test static ConcurrentHashMap<String, Set<EdsEndpointListener>> getEndpointListeners() { return ENDPOINT_LISTENERS; } // for test static ConcurrentHashMap<String, Set<Endpoint>> getEndpointDataCache() { return ENDPOINT_DATA_CACHE; } // for test static ConcurrentHashMap<String, Consumer<Map<String, EndpointResult>>> getEdsListeners() { return EDS_LISTENERS; } }
6,244
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/XdsRouterFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.router.xds; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.rpc.cluster.router.state.StateRouter; import org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory; @Activate(order = 100) public class XdsRouterFactory implements StateRouterFactory { @Override public <T> StateRouter<T> getRouter(Class<T> interfaceClass, URL url) { return new XdsRouter<>(url); } }
6,245
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/RdsRouteRuleManager.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.router.xds; 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.registry.xds.util.PilotExchanger; import org.apache.dubbo.registry.xds.util.protocol.message.ListenerResult; import org.apache.dubbo.registry.xds.util.protocol.message.RouteResult; import org.apache.dubbo.rpc.cluster.router.xds.rule.XdsRouteRule; 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.function.Consumer; import io.envoyproxy.envoy.config.route.v3.VirtualHost; public class RdsRouteRuleManager { private static final ConcurrentHashMap<String, Set<XdsRouteRuleListener>> RULE_LISTENERS = new ConcurrentHashMap<>(); private static final ConcurrentHashMap<String, List<XdsRouteRule>> ROUTE_DATA_CACHE = new ConcurrentHashMap<>(); private static final ConcurrentMap<String, RdsVirtualHostListener> RDS_LISTENERS = new ConcurrentHashMap<>(); private static volatile Consumer<Map<String, ListenerResult>> LDS_LISTENER; private static volatile Consumer<Map<String, RouteResult>> RDS_LISTENER; private static Map<String, RouteResult> RDS_RESULT; public RdsRouteRuleManager() {} public synchronized void subscribeRds(String domain, XdsRouteRuleListener listener) { Set<XdsRouteRuleListener> listeners = ConcurrentHashMapUtils.computeIfAbsent(RULE_LISTENERS, domain, key -> new ConcurrentHashSet<>()); if (CollectionUtils.isEmpty(listeners)) { doSubscribeRds(domain); } listeners.add(listener); if (ROUTE_DATA_CACHE.containsKey(domain)) { listener.onRuleChange(domain, ROUTE_DATA_CACHE.get(domain)); } } private void doSubscribeRds(String domain) { synchronized (RdsRouteRuleManager.class) { if (RDS_LISTENER == null) { RDS_LISTENER = rds -> { if (rds == null) { return; } for (RouteResult routeResult : rds.values()) { for (String domainToNotify : RDS_LISTENERS.keySet()) { VirtualHost virtualHost = routeResult.searchVirtualHost(domainToNotify); if (virtualHost != null) { RDS_LISTENERS.get(domainToNotify).parseVirtualHost(virtualHost); } } } RDS_RESULT = rds; }; } if (LDS_LISTENER == null) { LDS_LISTENER = new Consumer<Map<String, ListenerResult>>() { private volatile Set<String> configNames = null; @Override public void accept(Map<String, ListenerResult> listenerResults) { if (listenerResults.size() == 1) { for (ListenerResult listenerResult : listenerResults.values()) { Set<String> newConfigNames = listenerResult.getRouteConfigNames(); if (configNames == null) { PilotExchanger.getInstance().observeRds(newConfigNames, RDS_LISTENER); } else if (!configNames.equals(newConfigNames)) { PilotExchanger.getInstance().unObserveRds(configNames, RDS_LISTENER); PilotExchanger.getInstance().observeRds(newConfigNames, RDS_LISTENER); } configNames = newConfigNames; } } } }; if (PilotExchanger.isEnabled()) { PilotExchanger.getInstance().observeLds(LDS_LISTENER); } } } ConcurrentHashMapUtils.computeIfAbsent(RDS_LISTENERS, domain, key -> new RdsVirtualHostListener(domain, this)); RDS_LISTENER.accept(RDS_RESULT); } public synchronized void unSubscribeRds(String domain, XdsRouteRuleListener listener) { Set<XdsRouteRuleListener> listeners = RULE_LISTENERS.get(domain); if (CollectionUtils.isEmpty(listeners)) { return; } listeners.remove(listener); if (listeners.isEmpty()) { RULE_LISTENERS.remove(domain); doUnsubscribeRds(domain); } } private void doUnsubscribeRds(String domain) { RDS_LISTENERS.remove(domain); } public void notifyRuleChange(String domain, List<XdsRouteRule> xdsRouteRules) { ROUTE_DATA_CACHE.put(domain, xdsRouteRules); Set<XdsRouteRuleListener> listeners = RULE_LISTENERS.get(domain); if (CollectionUtils.isEmpty(listeners)) { return; } boolean empty = CollectionUtils.isEmpty(xdsRouteRules); for (XdsRouteRuleListener listener : listeners) { if (empty) { listener.clearRule(domain); } else { listener.onRuleChange(domain, xdsRouteRules); } } } // for test static ConcurrentHashMap<String, Set<XdsRouteRuleListener>> getRuleListeners() { return RULE_LISTENERS; } // for test static ConcurrentHashMap<String, List<XdsRouteRule>> getRouteDataCache() { return ROUTE_DATA_CACHE; } // for test static Map<String, RdsVirtualHostListener> getRdsListeners() { return RDS_LISTENERS; } }
6,246
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/RdsVirtualHostListener.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.router.xds; import org.apache.dubbo.common.constants.LoggerCodeConstants; 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.rpc.cluster.router.xds.rule.ClusterWeight; import org.apache.dubbo.rpc.cluster.router.xds.rule.HTTPRouteDestination; import org.apache.dubbo.rpc.cluster.router.xds.rule.HeaderMatcher; import org.apache.dubbo.rpc.cluster.router.xds.rule.HttpRequestMatch; import org.apache.dubbo.rpc.cluster.router.xds.rule.LongRangeMatch; import org.apache.dubbo.rpc.cluster.router.xds.rule.PathMatcher; import org.apache.dubbo.rpc.cluster.router.xds.rule.XdsRouteRule; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import io.envoyproxy.envoy.config.route.v3.Route; import io.envoyproxy.envoy.config.route.v3.RouteAction; import io.envoyproxy.envoy.config.route.v3.RouteMatch; import io.envoyproxy.envoy.config.route.v3.VirtualHost; public class RdsVirtualHostListener { private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(RdsVirtualHostListener.class); private final String domain; private final RdsRouteRuleManager routeRuleManager; public RdsVirtualHostListener(String domain, RdsRouteRuleManager routeRuleManager) { this.domain = domain; this.routeRuleManager = routeRuleManager; } public void parseVirtualHost(VirtualHost virtualHost) { if (virtualHost == null || CollectionUtils.isEmpty(virtualHost.getRoutesList())) { // post empty routeRuleManager.notifyRuleChange(domain, new ArrayList<>()); return; } try { List<XdsRouteRule> xdsRouteRules = virtualHost.getRoutesList().stream() .map(route -> { if (route.getMatch().getQueryParametersCount() != 0) { return null; } HttpRequestMatch match = parseMatch(route.getMatch()); HTTPRouteDestination action = parseAction(route); return new XdsRouteRule(match, action); }) .filter(Objects::nonNull) .collect(Collectors.toList()); // post rules routeRuleManager.notifyRuleChange(domain, xdsRouteRules); } catch (Exception e) { LOGGER.error( LoggerCodeConstants.INTERNAL_ERROR, "", "", "parse domain: " + domain + " xds VirtualHost error", e); } } private HttpRequestMatch parseMatch(RouteMatch match) { PathMatcher pathMatcher = parsePathMatch(match); List<HeaderMatcher> headerMatchers = parseHeadMatch(match); return new HttpRequestMatch(pathMatcher, headerMatchers); } private PathMatcher parsePathMatch(RouteMatch match) { boolean caseSensitive = match.getCaseSensitive().getValue(); PathMatcher pathMatcher = new PathMatcher(); pathMatcher.setCaseSensitive(caseSensitive); switch (match.getPathSpecifierCase()) { case PREFIX: pathMatcher.setPrefix(match.getPrefix()); return pathMatcher; case PATH: pathMatcher.setPath(match.getPath()); return pathMatcher; case SAFE_REGEX: String regex = match.getSafeRegex().getRegex(); pathMatcher.setRegex(regex); return pathMatcher; case PATHSPECIFIER_NOT_SET: return null; default: throw new IllegalArgumentException("Path specifier is not expect"); } } private List<HeaderMatcher> parseHeadMatch(RouteMatch routeMatch) { List<HeaderMatcher> headerMatchers = new ArrayList<>(); List<io.envoyproxy.envoy.config.route.v3.HeaderMatcher> headersList = routeMatch.getHeadersList(); for (io.envoyproxy.envoy.config.route.v3.HeaderMatcher headerMatcher : headersList) { HeaderMatcher matcher = new HeaderMatcher(); matcher.setName(headerMatcher.getName()); matcher.setInverted(headerMatcher.getInvertMatch()); switch (headerMatcher.getHeaderMatchSpecifierCase()) { case EXACT_MATCH: matcher.setExactValue(headerMatcher.getExactMatch()); headerMatchers.add(matcher); break; case SAFE_REGEX_MATCH: matcher.setRegex(headerMatcher.getSafeRegexMatch().getRegex()); headerMatchers.add(matcher); break; case RANGE_MATCH: LongRangeMatch rang = new LongRangeMatch(); rang.setStart(headerMatcher.getRangeMatch().getStart()); rang.setEnd(headerMatcher.getRangeMatch().getEnd()); matcher.setRange(rang); headerMatchers.add(matcher); break; case PRESENT_MATCH: matcher.setPresent(headerMatcher.getPresentMatch()); headerMatchers.add(matcher); break; case PREFIX_MATCH: matcher.setPrefix(headerMatcher.getPrefixMatch()); headerMatchers.add(matcher); break; case SUFFIX_MATCH: matcher.setSuffix(headerMatcher.getSuffixMatch()); headerMatchers.add(matcher); break; case HEADERMATCHSPECIFIER_NOT_SET: default: throw new IllegalArgumentException("Header specifier is not expect"); } } return headerMatchers; } private HTTPRouteDestination parseAction(Route route) { switch (route.getActionCase()) { case ROUTE: HTTPRouteDestination httpRouteDestination = new HTTPRouteDestination(); // only support cluster and weight cluster RouteAction routeAction = route.getRoute(); RouteAction.ClusterSpecifierCase clusterSpecifierCase = routeAction.getClusterSpecifierCase(); if (clusterSpecifierCase == RouteAction.ClusterSpecifierCase.CLUSTER) { httpRouteDestination.setCluster(routeAction.getCluster()); return httpRouteDestination; } else if (clusterSpecifierCase == RouteAction.ClusterSpecifierCase.WEIGHTED_CLUSTERS) { List<ClusterWeight> clusterWeights = routeAction.getWeightedClusters().getClustersList().stream() .map(c -> new ClusterWeight(c.getName(), c.getWeight().getValue())) .sorted(Comparator.comparing(ClusterWeight::getWeight)) .collect(Collectors.toList()); httpRouteDestination.setWeightedClusters(clusterWeights); return httpRouteDestination; } case REDIRECT: case DIRECT_RESPONSE: case FILTER_ACTION: case ACTION_NOT_SET: default: throw new IllegalArgumentException("Cluster specifier is not expect"); } } }
6,247
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/EdsEndpointListener.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.router.xds; import org.apache.dubbo.registry.xds.util.protocol.message.Endpoint; import java.util.Set; public interface EdsEndpointListener { void onEndPointChange(String cluster, Set<Endpoint> endpoints); }
6,248
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/XdsScopeModelInitializer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.router.xds; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; 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 XdsScopeModelInitializer implements ScopeModelInitializer { @Override public void initializeFrameworkModel(FrameworkModel frameworkModel) {} @Override public void initializeApplicationModel(ApplicationModel applicationModel) { ScopeBeanFactory beanFactory = applicationModel.getBeanFactory(); beanFactory.registerBean(RdsRouteRuleManager.class); beanFactory.registerBean(EdsEndpointManager.class); } @Override public void initializeModuleModel(ModuleModel moduleModel) {} }
6,249
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/rule/HeaderMatcher.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.router.xds.rule; public class HeaderMatcher { public String name; public String exactValue; private String regex; public LongRangeMatch range; public Boolean present; public String prefix; public String suffix; public boolean inverted; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getExactValue() { return exactValue; } public void setExactValue(String exactValue) { this.exactValue = exactValue; } public String getRegex() { return regex; } public void setRegex(String regex) { this.regex = regex; } public LongRangeMatch getRange() { return range; } public void setRange(LongRangeMatch range) { this.range = range; } public Boolean getPresent() { return present; } public void setPresent(Boolean present) { this.present = present; } public String getPrefix() { return prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getSuffix() { return suffix; } public void setSuffix(String suffix) { this.suffix = suffix; } public boolean isInverted() { return inverted; } public void setInverted(boolean inverted) { this.inverted = inverted; } public boolean match(String input) { if (getPresent() != null) { return (input == null) == getPresent().equals(isInverted()); } if (input == null) { return false; } if (getExactValue() != null) { return getExactValue().equals(input) != isInverted(); } else if (getRegex() != null) { return input.matches(getRegex()) != isInverted(); } else if (getRange() != null) { return getRange().isMatch(input) != isInverted(); } else if (getPrefix() != null) { return input.startsWith(getPrefix()) != isInverted(); } else if (getSuffix() != null) { return input.endsWith(getSuffix()) != isInverted(); } return false; } }
6,250
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/rule/PathMatcher.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.router.xds.rule; public class PathMatcher { private String path; private String prefix; private String regex; private boolean caseSensitive; public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getPrefix() { return prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getRegex() { return regex; } public void setRegex(String regex) { this.regex = regex; } public boolean isCaseSensitive() { return caseSensitive; } public void setCaseSensitive(boolean caseSensitive) { this.caseSensitive = caseSensitive; } public boolean isMatch(String input) { if (getPath() != null) { return isCaseSensitive() ? getPath().equals(input) : getPath().equalsIgnoreCase(input); } else if (getPrefix() != null) { return isCaseSensitive() ? input.startsWith(getPrefix()) : input.toLowerCase().startsWith(getPrefix()); } return input.matches(getRegex()); } }
6,251
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/rule/DestinationSubset.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.router.xds.rule; import org.apache.dubbo.registry.xds.util.protocol.message.Endpoint; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.cluster.router.state.BitList; import java.util.HashSet; import java.util.Set; public class DestinationSubset<T> { public DestinationSubset(String clusterName) { this.clusterName = clusterName; } private final String clusterName; private Set<Endpoint> endpoints = new HashSet<>(); private BitList<Invoker<T>> invokers; public String getClusterName() { return clusterName; } public Set<Endpoint> getEndpoints() { return endpoints; } public void setEndpoints(Set<Endpoint> endpoints) { this.endpoints = endpoints; } public BitList<Invoker<T>> getInvokers() { return invokers; } public void setInvokers(BitList<Invoker<T>> invokers) { this.invokers = invokers; } }
6,252
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/rule/HttpRequestMatch.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.router.xds.rule; import java.util.List; public class HttpRequestMatch { private final PathMatcher pathMatcher; private final List<HeaderMatcher> headerMatcherList; public HttpRequestMatch(PathMatcher pathMatcher, List<HeaderMatcher> headerMatcherList) { this.pathMatcher = pathMatcher; this.headerMatcherList = headerMatcherList; } public PathMatcher getPathMatcher() { return pathMatcher; } public List<HeaderMatcher> getHeaderMatcherList() { return headerMatcherList; } }
6,253
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/rule/XdsRouteRule.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.router.xds.rule; public class XdsRouteRule { private final HttpRequestMatch match; private final HTTPRouteDestination route; public XdsRouteRule(HttpRequestMatch match, HTTPRouteDestination route) { this.match = match; this.route = route; } public HttpRequestMatch getMatch() { return match; } public HTTPRouteDestination getRoute() { return route; } }
6,254
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/rule/LongRangeMatch.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.router.xds.rule; public class LongRangeMatch { private long start; private long end; public long getStart() { return start; } public void setStart(long start) { this.start = start; } public long getEnd() { return end; } public void setEnd(long end) { this.end = end; } public boolean isMatch(String input) { try { long num = Long.parseLong(input); return num >= getStart() && num <= getEnd(); } catch (NumberFormatException ignore) { return false; } } }
6,255
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/rule/HTTPRouteDestination.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.router.xds.rule; import java.util.List; public class HTTPRouteDestination { private String cluster; private List<ClusterWeight> weightedClusters; public String getCluster() { return cluster; } public void setCluster(String cluster) { this.cluster = cluster; } public List<ClusterWeight> getWeightedClusters() { return weightedClusters; } public void setWeightedClusters(List<ClusterWeight> weightedClusters) { this.weightedClusters = weightedClusters; } }
6,256
0
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds
Create_ds/dubbo/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/rule/ClusterWeight.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.cluster.router.xds.rule; public class ClusterWeight { private final String name; private final int weight; public ClusterWeight(String name, int weight) { this.name = name; this.weight = weight; } public String getName() { return name; } public int getWeight() { return weight; } }
6,257
0
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/config/AbstractInterfaceConfigTest.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.config; import org.apache.dubbo.common.constants.CommonConstants; import java.io.File; import java.nio.file.Path; import java.util.Collections; 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 org.junit.jupiter.api.io.TempDir; class AbstractInterfaceConfigTest { @BeforeAll public static void setUp(@TempDir Path folder) { File dubboProperties = folder.resolve(CommonConstants.DUBBO_PROPERTIES_KEY).toFile(); System.setProperty(CommonConstants.DUBBO_PROPERTIES_KEY, dubboProperties.getAbsolutePath()); } @AfterAll public static void tearDown() { System.clearProperty(CommonConstants.DUBBO_PROPERTIES_KEY); } @Test void checkStub1() { Assertions.assertThrows(IllegalStateException.class, () -> { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setLocal(GreetingLocal1.class.getName()); interfaceConfig.checkStubAndLocal(Greeting.class); }); } @Test void checkStub2() { Assertions.assertThrows(IllegalStateException.class, () -> { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setLocal(GreetingLocal2.class.getName()); interfaceConfig.checkStubAndLocal(Greeting.class); }); } @Test void checkStub3() { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setLocal(GreetingLocal3.class.getName()); interfaceConfig.checkStubAndLocal(Greeting.class); } @Test void checkStub4() { Assertions.assertThrows(IllegalStateException.class, () -> { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setStub(GreetingLocal1.class.getName()); interfaceConfig.checkStubAndLocal(Greeting.class); }); } @Test void checkStub5() { Assertions.assertThrows(IllegalStateException.class, () -> { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setStub(GreetingLocal2.class.getName()); interfaceConfig.checkStubAndLocal(Greeting.class); }); } @Test void checkStub6() { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setStub(GreetingLocal3.class.getName()); interfaceConfig.checkStubAndLocal(Greeting.class); } @Test void testLocal() { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setLocal((Boolean) null); Assertions.assertNull(interfaceConfig.getLocal()); interfaceConfig.setLocal(true); Assertions.assertEquals("true", interfaceConfig.getLocal()); interfaceConfig.setLocal("GreetingMock"); Assertions.assertEquals("GreetingMock", interfaceConfig.getLocal()); } @Test void testStub() { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setStub((Boolean) null); Assertions.assertNull(interfaceConfig.getStub()); interfaceConfig.setStub(true); Assertions.assertEquals("true", interfaceConfig.getStub()); interfaceConfig.setStub("GreetingMock"); Assertions.assertEquals("GreetingMock", interfaceConfig.getStub()); } @Test void testCluster() { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setCluster("mockcluster"); Assertions.assertEquals("mockcluster", interfaceConfig.getCluster()); } @Test void testProxy() { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setProxy("mockproxyfactory"); Assertions.assertEquals("mockproxyfactory", interfaceConfig.getProxy()); } @Test void testConnections() { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setConnections(1); Assertions.assertEquals(1, interfaceConfig.getConnections().intValue()); } @Test void testFilter() { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setFilter("mockfilter"); Assertions.assertEquals("mockfilter", interfaceConfig.getFilter()); } @Test void testListener() { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setListener("mockinvokerlistener"); Assertions.assertEquals("mockinvokerlistener", interfaceConfig.getListener()); } @Test void testLayer() { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setLayer("layer"); Assertions.assertEquals("layer", interfaceConfig.getLayer()); } @Test void testApplication() { InterfaceConfig interfaceConfig = new InterfaceConfig(); ApplicationConfig applicationConfig = new ApplicationConfig("AbstractInterfaceConfigTest"); interfaceConfig.setApplication(applicationConfig); Assertions.assertSame(applicationConfig, interfaceConfig.getApplication()); } @Test void testModule() { InterfaceConfig interfaceConfig = new InterfaceConfig(); ModuleConfig moduleConfig = new ModuleConfig(); interfaceConfig.setModule(moduleConfig); Assertions.assertSame(moduleConfig, interfaceConfig.getModule()); } @Test void testRegistry() { InterfaceConfig interfaceConfig = new InterfaceConfig(); RegistryConfig registryConfig = new RegistryConfig(); interfaceConfig.setRegistry(registryConfig); Assertions.assertSame(registryConfig, interfaceConfig.getRegistry()); } @Test void testRegistries() { InterfaceConfig interfaceConfig = new InterfaceConfig(); RegistryConfig registryConfig = new RegistryConfig(); interfaceConfig.setRegistries(Collections.singletonList(registryConfig)); Assertions.assertEquals(1, interfaceConfig.getRegistries().size()); Assertions.assertSame(registryConfig, interfaceConfig.getRegistries().get(0)); } @Test void testMonitor() { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setMonitor("monitor-addr"); Assertions.assertEquals("monitor-addr", interfaceConfig.getMonitor().getAddress()); MonitorConfig monitorConfig = new MonitorConfig(); monitorConfig.setAddress("monitor-addr"); interfaceConfig.setMonitor(monitorConfig); Assertions.assertSame(monitorConfig, interfaceConfig.getMonitor()); } @Test void testOwner() { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setOwner("owner"); Assertions.assertEquals("owner", interfaceConfig.getOwner()); } @Test void testCallbacks() { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setCallbacks(2); Assertions.assertEquals(2, interfaceConfig.getCallbacks().intValue()); } @Test void testOnconnect() { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setOnconnect("onConnect"); Assertions.assertEquals("onConnect", interfaceConfig.getOnconnect()); } @Test void testOndisconnect() { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setOndisconnect("onDisconnect"); Assertions.assertEquals("onDisconnect", interfaceConfig.getOndisconnect()); } @Test void testScope() { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setScope("scope"); Assertions.assertEquals("scope", interfaceConfig.getScope()); } @Test void testVerifyMethod() { InterfaceConfig2 interfaceConfig2 = new InterfaceConfig2(); MethodConfig methodConfig = new MethodConfig(); methodConfig.setTimeout(5000); methodConfig.setName("sayHello"); Class<?> clazz = Greeting.class; boolean verifyResult = interfaceConfig2.verifyMethodConfig(methodConfig, clazz, false); Assertions.assertTrue(verifyResult); boolean verifyResult2 = interfaceConfig2.verifyMethodConfig(methodConfig, clazz, true); Assertions.assertFalse(verifyResult2); } public static class InterfaceConfig2 extends AbstractInterfaceConfig { @Override protected boolean isNeedCheckMethod() { return false; } } public static class InterfaceConfig extends AbstractInterfaceConfig {} }
6,258
0
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/config/GreetingLocal2.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.config; public class GreetingLocal2 implements Greeting { @Override public String hello() { return "local"; } }
6,259
0
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/config/GreetingLocal3.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.config; public class GreetingLocal3 implements Greeting { private Greeting greeting; public GreetingLocal3(Greeting greeting) { this.greeting = greeting; } @Override public String hello() { return null; } }
6,260
0
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/config/Greeting.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.config; import org.apache.dubbo.common.extension.SPI; @SPI public interface Greeting { String hello(); }
6,261
0
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/config/GreetingLocal1.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.config; public class GreetingLocal1 {}
6,262
0
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/config
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/config/context/ConfigConfigurationAdapterTest.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.config.context; import org.apache.dubbo.config.RegistryConfig; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * {@link ConfigConfigurationAdapter} */ class ConfigConfigurationAdapterTest { @Test void test() { RegistryConfig registryConfig = new RegistryConfig(); registryConfig.setAddress("127.0.0.1"); registryConfig.setPort(2181); String prefix = "dubbo.registry"; ConfigConfigurationAdapter configConfigurationAdapter = new ConfigConfigurationAdapter(registryConfig, prefix); Assertions.assertEquals(configConfigurationAdapter.getInternalProperty(prefix + "." + "address"), "127.0.0.1"); Assertions.assertEquals(configConfigurationAdapter.getInternalProperty(prefix + "." + "port"), "2181"); } }
6,263
0
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/config
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/config/context/ConfigManagerTest.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.config.context; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ConfigCenterConfig; import org.apache.dubbo.config.ConsumerConfig; import org.apache.dubbo.config.MetricsConfig; import org.apache.dubbo.config.ModuleConfig; import org.apache.dubbo.config.MonitorConfig; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.ProviderConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Collection; import java.util.Optional; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static java.util.Arrays.asList; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY; import static org.apache.dubbo.common.constants.MetricsConstants.PROTOCOL_PROMETHEUS; import static org.apache.dubbo.config.context.ConfigManager.DUBBO_CONFIG_MODE; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; /** * {@link AbstractConfigManager} Test * {@link ConfigManager} Test * {@link ModuleConfigManager} Test * * @since 2.7.5 */ class ConfigManagerTest { private ConfigManager configManager; private ModuleConfigManager moduleConfigManager; @BeforeEach public void init() { ApplicationModel.defaultModel().destroy(); ApplicationModel applicationModel = ApplicationModel.defaultModel(); configManager = applicationModel.getApplicationConfigManager(); moduleConfigManager = applicationModel.getDefaultModule().getConfigManager(); } @Test void testDestroy() { assertTrue(configManager.configsCache.isEmpty()); } @Test void testDefaultValues() { // assert single assertFalse(configManager.getApplication().isPresent()); assertFalse(configManager.getMonitor().isPresent()); assertFalse(configManager.getMetrics().isPresent()); // protocols assertTrue(configManager.getProtocols().isEmpty()); assertTrue(configManager.getDefaultProtocols().isEmpty()); // registries assertTrue(configManager.getRegistries().isEmpty()); assertTrue(configManager.getDefaultRegistries().isEmpty()); // config centers assertTrue(configManager.getConfigCenters().isEmpty()); // metadata assertTrue(configManager.getMetadataConfigs().isEmpty()); // services and references assertTrue(moduleConfigManager.getServices().isEmpty()); assertTrue(moduleConfigManager.getReferences().isEmpty()); // providers and consumers assertFalse(moduleConfigManager.getModule().isPresent()); assertFalse(moduleConfigManager.getDefaultProvider().isPresent()); assertFalse(moduleConfigManager.getDefaultConsumer().isPresent()); assertTrue(moduleConfigManager.getProviders().isEmpty()); assertTrue(moduleConfigManager.getConsumers().isEmpty()); } // Test ApplicationConfig correlative methods @Test void testApplicationConfig() { ApplicationConfig config = new ApplicationConfig("ConfigManagerTest"); configManager.setApplication(config); assertTrue(configManager.getApplication().isPresent()); assertEquals(config, configManager.getApplication().get()); assertEquals(config, moduleConfigManager.getApplication().get()); } // Test MonitorConfig correlative methods @Test void testMonitorConfig() { MonitorConfig monitorConfig = new MonitorConfig(); monitorConfig.setGroup("test"); configManager.setMonitor(monitorConfig); assertTrue(configManager.getMonitor().isPresent()); assertEquals(monitorConfig, configManager.getMonitor().get()); assertEquals(monitorConfig, moduleConfigManager.getMonitor().get()); } // Test ModuleConfig correlative methods @Test void testModuleConfig() { ModuleConfig config = new ModuleConfig(); moduleConfigManager.setModule(config); assertTrue(moduleConfigManager.getModule().isPresent()); assertEquals(config, moduleConfigManager.getModule().get()); } // Test MetricsConfig correlative methods @Test void testMetricsConfig() { MetricsConfig config = new MetricsConfig(); config.setProtocol(PROTOCOL_PROMETHEUS); configManager.setMetrics(config); assertTrue(configManager.getMetrics().isPresent()); assertEquals(config, configManager.getMetrics().get()); assertEquals(config, moduleConfigManager.getMetrics().get()); } // Test ProviderConfig correlative methods @Test void testProviderConfig() { ProviderConfig config = new ProviderConfig(); moduleConfigManager.addProviders(asList(config, null)); Collection<ProviderConfig> configs = moduleConfigManager.getProviders(); assertEquals(1, configs.size()); assertEquals(config, configs.iterator().next()); assertTrue(moduleConfigManager.getDefaultProvider().isPresent()); config = new ProviderConfig(); config.setId(DEFAULT_KEY); config.setQueues(10); moduleConfigManager.addProvider(config); assertTrue(moduleConfigManager.getDefaultProvider().isPresent()); configs = moduleConfigManager.getProviders(); assertEquals(2, configs.size()); } // Test ConsumerConfig correlative methods @Test void testConsumerConfig() { ConsumerConfig config = new ConsumerConfig(); moduleConfigManager.addConsumers(asList(config, null)); Collection<ConsumerConfig> configs = moduleConfigManager.getConsumers(); assertEquals(1, configs.size()); assertEquals(config, configs.iterator().next()); assertTrue(moduleConfigManager.getDefaultConsumer().isPresent()); config = new ConsumerConfig(); config.setId(DEFAULT_KEY); config.setThreads(10); moduleConfigManager.addConsumer(config); assertTrue(moduleConfigManager.getDefaultConsumer().isPresent()); configs = moduleConfigManager.getConsumers(); assertEquals(2, configs.size()); } // Test ProtocolConfig correlative methods @Test void testProtocolConfig() { ProtocolConfig config = new ProtocolConfig(); configManager.addProtocols(asList(config, null)); Collection<ProtocolConfig> configs = configManager.getProtocols(); assertEquals(1, configs.size()); assertEquals(config, configs.iterator().next()); assertFalse(configManager.getDefaultProtocols().isEmpty()); assertEquals(configs, moduleConfigManager.getProtocols()); assertNotEquals(20881, config.getPort()); assertNotEquals(config.getSerialization(), "fastjson2"); ProtocolConfig defaultConfig = new ProtocolConfig(); defaultConfig.setPort(20881); defaultConfig.setSerialization("fastjson2"); config.mergeProtocol(defaultConfig); assertEquals(config.getPort(), 20881); assertEquals(config.getSerialization(), "fastjson2"); } // Test RegistryConfig correlative methods @Test void testRegistryConfig() { RegistryConfig config = new RegistryConfig(); configManager.addRegistries(asList(config, null)); Collection<RegistryConfig> configs = configManager.getRegistries(); assertEquals(1, configs.size()); assertEquals(config, configs.iterator().next()); assertFalse(configManager.getDefaultRegistries().isEmpty()); assertEquals(configs, moduleConfigManager.getRegistries()); } // Test ConfigCenterConfig correlative methods @Test void testConfigCenterConfig() { String address = "zookeeper://127.0.0.1:2181"; ConfigCenterConfig config = new ConfigCenterConfig(); config.setAddress(address); configManager.addConfigCenters(asList(config, null)); Collection<ConfigCenterConfig> configs = configManager.getConfigCenters(); assertEquals(1, configs.size()); assertEquals(config, configs.iterator().next()); // add duplicated config, expecting ignore equivalent configs ConfigCenterConfig config2 = new ConfigCenterConfig(); config2.setAddress(address); configManager.addConfigCenter(config2); configs = configManager.getConfigCenters(); assertEquals(1, configs.size()); assertEquals(config, configs.iterator().next()); assertEquals(configs, moduleConfigManager.getConfigCenters()); } @Test void testAddConfig() { configManager.addConfig(new ApplicationConfig("ConfigManagerTest")); configManager.addConfig(new ProtocolConfig()); moduleConfigManager.addConfig(new ProviderConfig()); assertTrue(configManager.getApplication().isPresent()); assertFalse(configManager.getProtocols().isEmpty()); assertFalse(moduleConfigManager.getProviders().isEmpty()); } @Test void testRefreshAll() { configManager.refreshAll(); moduleConfigManager.refreshAll(); } @Test void testDefaultConfig() { ProviderConfig providerConfig = new ProviderConfig(); providerConfig.setDefault(false); assertFalse(ConfigManager.isDefaultConfig(providerConfig)); ProviderConfig providerConfig1 = new ProviderConfig(); assertNull(ConfigManager.isDefaultConfig(providerConfig1)); ProviderConfig providerConfig3 = new ProviderConfig(); providerConfig3.setDefault(true); assertTrue(ConfigManager.isDefaultConfig(providerConfig3)); ProtocolConfig protocolConfig = new ProtocolConfig(); protocolConfig.setDefault(false); assertFalse(ConfigManager.isDefaultConfig(protocolConfig)); } @Test void testConfigMode() { ApplicationConfig applicationConfig1 = new ApplicationConfig("app1"); ApplicationConfig applicationConfig2 = new ApplicationConfig("app2"); try { // test strict mode ApplicationModel.reset(); ConfigManager configManager = ApplicationModel.defaultModel().getApplicationConfigManager(); Assertions.assertEquals(ConfigMode.STRICT, configManager.getConfigMode()); System.setProperty(DUBBO_CONFIG_MODE, ConfigMode.STRICT.name()); ApplicationModel.reset(); Assertions.assertEquals(ConfigMode.STRICT, configManager.getConfigMode()); configManager.addConfig(applicationConfig1); try { configManager.addConfig(applicationConfig2); fail("strict mode cannot add two application configs"); } catch (Exception e) { assertEquals(IllegalStateException.class, e.getClass()); assertTrue(e.getMessage().contains("please remove redundant configs and keep only one")); } // test override mode System.setProperty(DUBBO_CONFIG_MODE, ConfigMode.OVERRIDE.name()); ApplicationModel.reset(); configManager = ApplicationModel.defaultModel().getApplicationConfigManager(); Assertions.assertEquals(ConfigMode.OVERRIDE, configManager.getConfigMode()); configManager.addConfig(applicationConfig1); configManager.addConfig(applicationConfig2); assertEquals(applicationConfig2, configManager.getApplicationOrElseThrow()); // test ignore mode System.setProperty(DUBBO_CONFIG_MODE, ConfigMode.IGNORE.name()); ApplicationModel.reset(); configManager = ApplicationModel.defaultModel().getApplicationConfigManager(); Assertions.assertEquals(ConfigMode.IGNORE, configManager.getConfigMode()); configManager.addConfig(applicationConfig1); configManager.addConfig(applicationConfig2); assertEquals(applicationConfig1, configManager.getApplicationOrElseThrow()); // test OVERRIDE_ALL mode System.setProperty(DUBBO_CONFIG_MODE, ConfigMode.OVERRIDE_ALL.name()); ApplicationModel.reset(); configManager = ApplicationModel.defaultModel().getApplicationConfigManager(); Assertions.assertEquals(ConfigMode.OVERRIDE_ALL, configManager.getConfigMode()); ApplicationConfig applicationConfig11 = new ApplicationConfig("app11"); ApplicationConfig applicationConfig22 = new ApplicationConfig("app22"); applicationConfig11.setParameters(CollectionUtils.toStringMap("k1", "v1", "k2", "v2")); applicationConfig22.setParameters(CollectionUtils.toStringMap("k1", "v11", "k2", "v22", "k3", "v3")); configManager.addConfig(applicationConfig11); configManager.addConfig(applicationConfig22); assertEquals(applicationConfig11, configManager.getApplicationOrElseThrow()); assertEquals(applicationConfig11.getName(), "app22"); assertEquals( applicationConfig11.getParameters(), CollectionUtils.toStringMap("k1", "v11", "k2", "v22", "k3", "v3")); // test OVERRIDE_IF_ABSENT mode System.setProperty(DUBBO_CONFIG_MODE, ConfigMode.OVERRIDE_IF_ABSENT.name()); ApplicationModel.reset(); configManager = ApplicationModel.defaultModel().getApplicationConfigManager(); Assertions.assertEquals(ConfigMode.OVERRIDE_IF_ABSENT, configManager.getConfigMode()); ApplicationConfig applicationConfig33 = new ApplicationConfig("app33"); ApplicationConfig applicationConfig44 = new ApplicationConfig("app44"); applicationConfig33.setParameters(CollectionUtils.toStringMap("k1", "v1", "k2", "v2")); applicationConfig44.setParameters(CollectionUtils.toStringMap("k1", "v11", "k2", "v22", "k3", "v3")); configManager.addConfig(applicationConfig33); configManager.addConfig(applicationConfig44); assertEquals(applicationConfig33, configManager.getApplicationOrElseThrow()); assertEquals("app33", applicationConfig33.getName()); assertEquals( CollectionUtils.toStringMap("k1", "v1", "k2", "v2", "k3", "v3"), applicationConfig33.getParameters()); } finally { System.clearProperty(DUBBO_CONFIG_MODE); } } @Test void testGetConfigByIdOrName() { RegistryConfig registryConfig = new RegistryConfig(); registryConfig.setId("registryID_1"); configManager.addRegistry(registryConfig); Optional<RegistryConfig> registryConfigOptional = configManager.getConfig(RegistryConfig.class, registryConfig.getId()); if (registryConfigOptional.isPresent()) { Assertions.assertEquals(registryConfigOptional.get(), registryConfig); } else { fail("registryConfigOptional is empty! "); } ProtocolConfig protocolConfig = new ProtocolConfig("dubbo"); configManager.addProtocol(protocolConfig); Optional<ProtocolConfig> protocolConfigOptional = configManager.getConfig(ProtocolConfig.class, protocolConfig.getName()); if (protocolConfigOptional.isPresent()) { Assertions.assertEquals(protocolConfigOptional.get(), protocolConfig); } else { fail("protocolConfigOptional is empty! "); } // test multi config has same name(dubbo) ProtocolConfig protocolConfig2 = new ProtocolConfig("dubbo"); protocolConfig2.setPort(9103); configManager.addProtocol(protocolConfig2); try { configManager.getConfig(ProtocolConfig.class, protocolConfig.getName()); Assertions.fail(); } catch (Exception e) { Assertions.assertTrue(e instanceof IllegalStateException); Assertions.assertEquals( e.getMessage(), "Found more than one config by name: dubbo, instances: " + "[<dubbo:protocol port=\"9103\" name=\"dubbo\" />, <dubbo:protocol name=\"dubbo\" />]. " + "Please remove redundant configs or get config by id."); } ModuleConfig moduleConfig = new ModuleConfig(); moduleConfig.setId("moduleID_1"); moduleConfigManager.setModule(moduleConfig); Optional<ModuleConfig> moduleConfigOptional = moduleConfigManager.getConfig(ModuleConfig.class, moduleConfig.getId()); Assertions.assertEquals(moduleConfig, moduleConfigOptional.get()); Optional<RegistryConfig> config = moduleConfigManager.getConfig(RegistryConfig.class, registryConfig.getId()); Assertions.assertEquals(config.get(), registryConfig); } @Test void testLoadConfigsOfTypeFromProps() { try { // dubbo.application.enable-file-cache = false configManager.loadConfigsOfTypeFromProps(ApplicationConfig.class); Optional<ApplicationConfig> application = configManager.getApplication(); Assertions.assertTrue(application.isPresent()); configManager.removeConfig(application.get()); System.setProperty("dubbo.protocols.dubbo1.port", "20880"); System.setProperty("dubbo.protocols.dubbo2.port", "20881"); System.setProperty("dubbo.protocols.rest1.port", "8080"); System.setProperty("dubbo.protocols.rest2.port", "8081"); configManager.loadConfigsOfTypeFromProps(ProtocolConfig.class); Collection<ProtocolConfig> protocols = configManager.getProtocols(); Assertions.assertEquals(4, protocols.size()); System.setProperty("dubbo.applications.app1.name", "app-demo1"); System.setProperty("dubbo.applications.app2.name", "app-demo2"); try { configManager.loadConfigsOfTypeFromProps(ApplicationConfig.class); Assertions.fail(); } catch (Exception e) { Assertions.assertTrue(e.getMessage().contains("load config failed")); } } finally { System.clearProperty("dubbo.protocols.dubbo1.port"); System.clearProperty("dubbo.protocols.dubbo2.port"); System.clearProperty("dubbo.protocols.rest1.port"); System.clearProperty("dubbo.protocols.rest2.port"); System.clearProperty("dubbo.applications.app1.name"); System.clearProperty("dubbo.applications.app2.name"); } } @Test void testLoadConfig() { configManager.loadConfigs(); Assertions.assertTrue(configManager.getApplication().isPresent()); Assertions.assertTrue(configManager.getSsl().isPresent()); Assertions.assertFalse(configManager.getProtocols().isEmpty()); int port = 20880; ProtocolConfig config1 = new ProtocolConfig(); config1.setName("dubbo"); config1.setPort(port); ProtocolConfig config2 = new ProtocolConfig(); config2.setName("rest"); config2.setPort(port); configManager.addProtocols(asList(config1, config2)); try { configManager.loadConfigs(); Assertions.fail(); } catch (Exception e) { Assertions.assertTrue(e instanceof IllegalStateException); Assertions.assertTrue(e.getMessage().contains("Duplicated port used by protocol configs, port: " + port)); } moduleConfigManager.loadConfigs(); Assertions.assertTrue(moduleConfigManager.getModule().isPresent()); Assertions.assertFalse(moduleConfigManager.getProviders().isEmpty()); Assertions.assertFalse(moduleConfigManager.getConsumers().isEmpty()); } }
6,264
0
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/BaseServiceMetadataTest.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.common; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_VERSION; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; class BaseServiceMetadataTest { @Test void test() { BaseServiceMetadata baseServiceMetadata = new BaseServiceMetadata(); baseServiceMetadata.setGroup("group1"); baseServiceMetadata.setServiceInterfaceName("org.apache.dubbo.common.TestInterface"); baseServiceMetadata.setVersion("1.0.0"); baseServiceMetadata.setServiceKey( BaseServiceMetadata.buildServiceKey("org.apache.dubbo.common.TestInterface", "group1", "1.0.0")); assertEquals(baseServiceMetadata.getGroup(), "group1"); assertEquals(baseServiceMetadata.getServiceInterfaceName(), "org.apache.dubbo.common.TestInterface"); assertEquals(baseServiceMetadata.getVersion(), "1.0.0"); assertEquals(baseServiceMetadata.getServiceKey(), "group1/org.apache.dubbo.common.TestInterface:1.0.0"); assertEquals(baseServiceMetadata.getDisplayServiceKey(), "org.apache.dubbo.common.TestInterface:1.0.0"); baseServiceMetadata.setServiceKey( BaseServiceMetadata.buildServiceKey("org.apache.dubbo.common.TestInterface", null, null)); assertEquals(baseServiceMetadata.getServiceKey(), "org.apache.dubbo.common.TestInterface"); baseServiceMetadata.setServiceKey( BaseServiceMetadata.buildServiceKey("org.apache.dubbo.common.TestInterface", "", "")); assertEquals(baseServiceMetadata.getServiceKey(), "org.apache.dubbo.common.TestInterface"); baseServiceMetadata.setVersion("2.0.0"); baseServiceMetadata.generateServiceKey(); assertEquals(baseServiceMetadata.getServiceKey(), "group1/org.apache.dubbo.common.TestInterface:2.0.0"); assertEquals( BaseServiceMetadata.versionFromServiceKey("group1/org.apache.dubbo.common.TestInterface:1.0.0"), "1.0.0"); assertEquals( BaseServiceMetadata.groupFromServiceKey("group1/org.apache.dubbo.common.TestInterface:1.0.0"), "group1"); assertEquals( BaseServiceMetadata.interfaceFromServiceKey("group1/org.apache.dubbo.common.TestInterface:1.0.0"), "org.apache.dubbo.common.TestInterface"); assertEquals(DEFAULT_VERSION, BaseServiceMetadata.versionFromServiceKey("")); assertNull(BaseServiceMetadata.groupFromServiceKey("")); assertEquals(BaseServiceMetadata.interfaceFromServiceKey(""), ""); assertEquals( BaseServiceMetadata.revertDisplayServiceKey("org.apache.dubbo.common.TestInterface:1.0.0") .getDisplayServiceKey(), "org.apache.dubbo.common.TestInterface:1.0.0"); assertEquals( BaseServiceMetadata.revertDisplayServiceKey("org.apache.dubbo.common.TestInterface") .getDisplayServiceKey(), "org.apache.dubbo.common.TestInterface:null"); assertEquals(BaseServiceMetadata.revertDisplayServiceKey(null).getDisplayServiceKey(), "null:null"); assertEquals( BaseServiceMetadata.revertDisplayServiceKey("org.apache.dubbo.common.TestInterface:1.0.0:1") .getDisplayServiceKey(), "null:null"); } }
6,265
0
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/ServiceKeyTest.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.common; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class ServiceKeyTest { @Test void test() { ServiceKey serviceKey = new ServiceKey("DemoService", "1.0.0", "group1"); Assertions.assertEquals("DemoService", serviceKey.getInterfaceName()); Assertions.assertEquals("1.0.0", serviceKey.getVersion()); Assertions.assertEquals("group1", serviceKey.getGroup()); Assertions.assertEquals("group1/DemoService:1.0.0", serviceKey.toString()); Assertions.assertEquals("DemoService", new ServiceKey("DemoService", null, null).toString()); Assertions.assertEquals("DemoService:1.0.0", new ServiceKey("DemoService", "1.0.0", null).toString()); Assertions.assertEquals("group1/DemoService", new ServiceKey("DemoService", null, "group1").toString()); Assertions.assertEquals(serviceKey, serviceKey); ServiceKey serviceKey1 = new ServiceKey("DemoService", "1.0.0", "group1"); Assertions.assertEquals(serviceKey, serviceKey1); Assertions.assertEquals(serviceKey.hashCode(), serviceKey1.hashCode()); ServiceKey serviceKey2 = new ServiceKey("DemoService", "1.0.0", "group2"); Assertions.assertNotEquals(serviceKey, serviceKey2); ServiceKey serviceKey3 = new ServiceKey("DemoService", "1.0.1", "group1"); Assertions.assertNotEquals(serviceKey, serviceKey3); ServiceKey serviceKey4 = new ServiceKey("DemoInterface", "1.0.0", "group1"); Assertions.assertNotEquals(serviceKey, serviceKey4); ProtocolServiceKey protocolServiceKey = new ProtocolServiceKey("DemoService", "1.0.0", "group1", "protocol1"); Assertions.assertNotEquals(serviceKey, protocolServiceKey); } }
6,266
0
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/InterfaceAddressURLTest.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.common; 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.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotSame; class InterfaceAddressURLTest { private static final String rawURL = "dubbo://10.20.130.230:20880/context/path?version=1.0.0&group=g1&application=provider&timeout=1000&category=provider&side=provider&sayHello.weight=222"; private static final URL overrideURL = URL.valueOf( "override://10.20.130.230:20880/context/path?version=1.0.0&application=morgan&timeout=2000&category=configurators&sayHello.overrideKey=override"); private static final URL consumerURL = URL.valueOf( "consumer://10.20.130.230/context/path?version=2.0.0,1.0.0&group=g2&application=morgan&timeout=3000&side=consumer&sayHello.timeout=5000"); @Test void testMergeOverriden() { URL url = URL.valueOf(rawURL); ServiceAddressURL interfaceAddressURL = new DubboServiceAddressURL(url.getUrlAddress(), url.getUrlParam(), null, null); assertEquals("1000", interfaceAddressURL.getParameter(TIMEOUT_KEY)); ServiceAddressURL withConsumer = DubboServiceAddressURL.valueOf(rawURL, consumerURL); assertEquals("3000", withConsumer.getParameter(TIMEOUT_KEY)); ServiceAddressURL withOverriden = DubboServiceAddressURL.valueOf(rawURL, consumerURL, (ServiceConfigURL) overrideURL); assertEquals("2000", withOverriden.getParameter(TIMEOUT_KEY)); } @Test void testGetParameter() { URL url = URL.valueOf(rawURL); ServiceAddressURL interfaceAddressURL = new DubboServiceAddressURL(url.getUrlAddress(), url.getUrlParam(), consumerURL, null); assertEquals("3000", interfaceAddressURL.getParameter(TIMEOUT_KEY)); assertEquals("morgan", interfaceAddressURL.getApplication()); assertEquals("provider", interfaceAddressURL.getRemoteApplication()); assertEquals("dubbo", interfaceAddressURL.getProtocol()); assertEquals("context/path", interfaceAddressURL.getPath()); assertEquals("consumer", interfaceAddressURL.getSide()); assertEquals("1.0.0", interfaceAddressURL.getVersion()); assertEquals("g1", interfaceAddressURL.getGroup()); } @Test void testGetMethodParameter() { URL url = URL.valueOf(rawURL); ServiceAddressURL interfaceAddressURL = new DubboServiceAddressURL( url.getUrlAddress(), url.getUrlParam(), consumerURL, (ServiceConfigURL) overrideURL); assertEquals("5000", interfaceAddressURL.getMethodParameter("sayHello", TIMEOUT_KEY)); assertEquals("2000", interfaceAddressURL.getMethodParameter("non-exist-methods", TIMEOUT_KEY)); assertEquals("222", interfaceAddressURL.getMethodParameter("sayHello", "weight")); assertEquals("222", interfaceAddressURL.getMethodParameter("sayHello", "weight")); assertEquals("override", interfaceAddressURL.getMethodParameter("sayHello", "overrideKey")); } @Test void testURLEquals() { URL url1 = URL.valueOf(rawURL); URL url2 = URL.valueOf(rawURL); assertNotSame(url1, url2); assertEquals(url1, url2); // with consumer ServiceAddressURL withConsumer = new DubboServiceAddressURL(url1.getUrlAddress(), url1.getUrlParam(), consumerURL, null); ServiceAddressURL withConsumer2 = new DubboServiceAddressURL(url1.getUrlAddress(), url1.getUrlParam(), consumerURL, null); assertEquals(withConsumer, withConsumer2); ServiceAddressURL withOverride = new DubboServiceAddressURL( url1.getUrlAddress(), url1.getUrlParam(), consumerURL, (ServiceConfigURL) overrideURL); url2 = url2.addParameter("timeout", "4444"); ServiceAddressURL withOverride2 = new DubboServiceAddressURL( url2.getUrlAddress(), url2.getUrlParam(), consumerURL, (ServiceConfigURL) overrideURL); assertNotEquals(url1, url2); assertEquals(withOverride, withOverride2); } @Test void testToString() { URL url1 = URL.valueOf(rawURL); System.out.println(url1.toString()); ServiceAddressURL withConsumer = new DubboServiceAddressURL(url1.getUrlAddress(), url1.getUrlParam(), consumerURL, null); System.out.println(withConsumer.toString()); ServiceAddressURL withOverride2 = new DubboServiceAddressURL( url1.getUrlAddress(), url1.getUrlParam(), consumerURL, (ServiceConfigURL) overrideURL); System.out.println(withOverride2.toString()); } }
6,267
0
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/ProtocolServiceKeyTest.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.common; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class ProtocolServiceKeyTest { @Test void test() { ProtocolServiceKey protocolServiceKey = new ProtocolServiceKey("DemoService", "1.0.0", "group1", "protocol1"); Assertions.assertEquals("DemoService", protocolServiceKey.getInterfaceName()); Assertions.assertEquals("1.0.0", protocolServiceKey.getVersion()); Assertions.assertEquals("group1", protocolServiceKey.getGroup()); Assertions.assertEquals("protocol1", protocolServiceKey.getProtocol()); Assertions.assertEquals("group1/DemoService:1.0.0:protocol1", protocolServiceKey.toString()); Assertions.assertEquals("group1/DemoService:1.0.0", protocolServiceKey.getServiceKeyString()); Assertions.assertEquals(protocolServiceKey, protocolServiceKey); ProtocolServiceKey protocolServiceKey1 = new ProtocolServiceKey("DemoService", "1.0.0", "group1", "protocol1"); Assertions.assertEquals(protocolServiceKey, protocolServiceKey1); Assertions.assertEquals(protocolServiceKey.hashCode(), protocolServiceKey1.hashCode()); ProtocolServiceKey protocolServiceKey2 = new ProtocolServiceKey("DemoService", "1.0.0", "group1", "protocol2"); Assertions.assertNotEquals(protocolServiceKey, protocolServiceKey2); ProtocolServiceKey protocolServiceKey3 = new ProtocolServiceKey("DemoService", "1.0.0", "group2", "protocol1"); Assertions.assertNotEquals(protocolServiceKey, protocolServiceKey3); ProtocolServiceKey protocolServiceKey4 = new ProtocolServiceKey("DemoService", "1.0.1", "group1", "protocol1"); Assertions.assertNotEquals(protocolServiceKey, protocolServiceKey4); ProtocolServiceKey protocolServiceKey5 = new ProtocolServiceKey("DemoInterface", "1.0.0", "group1", "protocol1"); Assertions.assertNotEquals(protocolServiceKey, protocolServiceKey5); ServiceKey serviceKey = new ServiceKey("DemoService", "1.0.0", "group1"); Assertions.assertNotEquals(protocolServiceKey, serviceKey); Assertions.assertTrue(protocolServiceKey.isSameWith(protocolServiceKey)); Assertions.assertTrue( protocolServiceKey.isSameWith(new ProtocolServiceKey("DemoService", "1.0.0", "group1", ""))); Assertions.assertTrue( protocolServiceKey.isSameWith(new ProtocolServiceKey("DemoService", "1.0.0", "group1", null))); Assertions.assertFalse( protocolServiceKey.isSameWith(new ProtocolServiceKey("DemoService", "1.0.0", "group2", "protocol1"))); Assertions.assertFalse( protocolServiceKey.isSameWith(new ProtocolServiceKey("DemoService", "1.0.0", "group2", ""))); Assertions.assertFalse( protocolServiceKey.isSameWith(new ProtocolServiceKey("DemoService", "1.0.0", "group2", null))); ProtocolServiceKey protocolServiceKey6 = new ProtocolServiceKey("DemoService", "1.0.0", "group1", null); Assertions.assertTrue(protocolServiceKey6.isSameWith(protocolServiceKey6)); Assertions.assertTrue( protocolServiceKey6.isSameWith(new ProtocolServiceKey("DemoService", "1.0.0", "group1", ""))); Assertions.assertTrue( protocolServiceKey6.isSameWith(new ProtocolServiceKey("DemoService", "1.0.0", "group1", "protocol1"))); Assertions.assertTrue( protocolServiceKey6.isSameWith(new ProtocolServiceKey("DemoService", "1.0.0", "group1", "protocol2"))); ProtocolServiceKey protocolServiceKey7 = new ProtocolServiceKey("DemoService", "1.0.0", "group1", "*"); Assertions.assertFalse( protocolServiceKey7.isSameWith(new ProtocolServiceKey("DemoService", "1.0.0", "group1", null))); Assertions.assertFalse( protocolServiceKey7.isSameWith(new ProtocolServiceKey("DemoService", "1.0.0", "group1", ""))); Assertions.assertFalse( protocolServiceKey7.isSameWith(new ProtocolServiceKey("DemoService", "1.0.0", "group1", "protocol1"))); Assertions.assertFalse( protocolServiceKey7.isSameWith(new ProtocolServiceKey("DemoService", "1.0.0", "group1", "protocol2"))); } }
6,268
0
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/CommonScopeModelInitializerTest.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.common; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; import org.apache.dubbo.common.config.ConfigurationCache; import org.apache.dubbo.common.lang.ShutdownHookCallbacks; import org.apache.dubbo.common.status.reporter.FrameworkStatusReportService; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleModel; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** * {@link CommonScopeModelInitializer} */ class CommonScopeModelInitializerTest { private FrameworkModel frameworkModel; private ApplicationModel applicationModel; private ModuleModel moduleModel; @BeforeEach public void setUp() { frameworkModel = new FrameworkModel(); applicationModel = frameworkModel.newApplication(); moduleModel = applicationModel.newModule(); } @AfterEach public void reset() { frameworkModel.destroy(); } @Test void test() { ScopeBeanFactory applicationModelBeanFactory = applicationModel.getBeanFactory(); Assertions.assertNotNull(applicationModelBeanFactory.getBean(ShutdownHookCallbacks.class)); Assertions.assertNotNull(applicationModelBeanFactory.getBean(FrameworkStatusReportService.class)); Assertions.assertNotNull(applicationModelBeanFactory.getBean(ConfigurationCache.class)); ScopeBeanFactory moduleModelBeanFactory = moduleModel.getBeanFactory(); Assertions.assertNotNull(moduleModelBeanFactory.getBean(ConfigurationCache.class)); } }
6,269
0
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/ProtocolServiceKeyMatcherTest.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.common; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class ProtocolServiceKeyMatcherTest { @Test void testProtocol() { Assertions.assertTrue(ProtocolServiceKey.Matcher.isMatch( new ProtocolServiceKey(null, null, null, "dubbo"), new ProtocolServiceKey(null, null, null, "dubbo"))); Assertions.assertFalse(ProtocolServiceKey.Matcher.isMatch( new ProtocolServiceKey(null, null, null, "dubbo"), new ProtocolServiceKey(null, null, null, null))); Assertions.assertFalse(ProtocolServiceKey.Matcher.isMatch( new ProtocolServiceKey(null, null, null, "dubbo"), new ProtocolServiceKey("DemoService", null, null, "dubbo"))); Assertions.assertTrue(ProtocolServiceKey.Matcher.isMatch( new ProtocolServiceKey(null, null, null, null), new ProtocolServiceKey(null, null, null, "dubbo"))); Assertions.assertTrue(ProtocolServiceKey.Matcher.isMatch( new ProtocolServiceKey(null, null, null, ""), new ProtocolServiceKey(null, null, null, "dubbo"))); Assertions.assertTrue(ProtocolServiceKey.Matcher.isMatch( new ProtocolServiceKey(null, null, null, "*"), new ProtocolServiceKey(null, null, null, "dubbo"))); Assertions.assertFalse(ProtocolServiceKey.Matcher.isMatch( new ProtocolServiceKey(null, null, null, "dubbo1,dubbo2"), new ProtocolServiceKey(null, null, null, "dubbo"))); Assertions.assertTrue(ProtocolServiceKey.Matcher.isMatch( new ProtocolServiceKey(null, null, null, "dubbo1,dubbo2"), new ProtocolServiceKey(null, null, null, "dubbo1"))); Assertions.assertTrue(ProtocolServiceKey.Matcher.isMatch( new ProtocolServiceKey(null, null, null, "dubbo1,dubbo2"), new ProtocolServiceKey(null, null, null, "dubbo2"))); Assertions.assertTrue(ProtocolServiceKey.Matcher.isMatch( new ProtocolServiceKey(null, null, null, "dubbo1,,dubbo2"), new ProtocolServiceKey(null, null, null, null))); Assertions.assertTrue(ProtocolServiceKey.Matcher.isMatch( new ProtocolServiceKey(null, null, null, "dubbo1,,dubbo2"), new ProtocolServiceKey(null, null, null, ""))); Assertions.assertTrue(ProtocolServiceKey.Matcher.isMatch( new ProtocolServiceKey(null, null, null, ",dubbo1,dubbo2"), new ProtocolServiceKey(null, null, null, null))); Assertions.assertTrue(ProtocolServiceKey.Matcher.isMatch( new ProtocolServiceKey(null, null, null, ",dubbo1,dubbo2"), new ProtocolServiceKey(null, null, null, ""))); Assertions.assertTrue(ProtocolServiceKey.Matcher.isMatch( new ProtocolServiceKey(null, null, null, "dubbo1,dubbo2,"), new ProtocolServiceKey(null, null, null, null))); Assertions.assertTrue(ProtocolServiceKey.Matcher.isMatch( new ProtocolServiceKey(null, null, null, "dubbo1,dubbo2,"), new ProtocolServiceKey(null, null, null, ""))); Assertions.assertFalse(ProtocolServiceKey.Matcher.isMatch( new ProtocolServiceKey(null, null, null, "dubbo1,,dubbo2"), new ProtocolServiceKey(null, null, null, "dubbo"))); Assertions.assertFalse(ProtocolServiceKey.Matcher.isMatch( new ProtocolServiceKey(null, null, null, ",dubbo1,dubbo2"), new ProtocolServiceKey(null, null, null, "dubbo"))); Assertions.assertFalse(ProtocolServiceKey.Matcher.isMatch( new ProtocolServiceKey(null, null, null, "dubbo1,dubbo2,"), new ProtocolServiceKey(null, null, null, "dubbo"))); } }
6,270
0
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/URLStrParserTest.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.common; import java.util.HashSet; import java.util.Set; import net.bytebuddy.utility.RandomString; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; /** * Created by LinShunkang on 2020/03/12 */ class URLStrParserTest { private static Set<String> testCases = new HashSet<>(16); private static Set<String> errorDecodedCases = new HashSet<>(8); private static Set<String> errorEncodedCases = new HashSet<>(8); static { testCases.add("dubbo://192.168.1.1"); testCases.add("dubbo://192.168.1.1?"); testCases.add("dubbo://127.0.0.1?test=中文测试"); testCases.add( "dubbo://admin:admin123@192.168.1.41:28113/org.test.api.DemoService$Iface?anyhost=true&application=demo-service&dubbo=2.6.1&generic=false&interface=org.test.api.DemoService$Iface&methods=orbCompare,checkText,checkPicture&pid=65557&revision=1.4.17&service.filter=bootMetrics&side=provider&status=server&threads=200&timestamp=1583136298859&version=1.0.0"); // super long text test testCases.add("dubbo://192.168.1.1/" + RandomString.make(10240)); testCases.add("file:/path/to/file.txt"); testCases.add("dubbo://fe80:0:0:0:894:aeec:f37d:23e1%en0/path?abc=abc"); testCases.add("dubbo://[fe80:0:0:0:894:aeec:f37d:23e1]:20880/path?abc=abc"); testCases.add("nacos://192.168.1.1:8848?username=&password="); testCases.add("dubbo://127.0.0.1?timeout=1234&default.timeout=5678"); testCases.add("dubbo://127.0.0.1?default.timeout=5678"); errorDecodedCases.add("dubbo:192.168.1.1"); errorDecodedCases.add("://192.168.1.1"); errorDecodedCases.add(":/192.168.1.1"); errorEncodedCases.add("dubbo%3a%2f%2f192.168.1.41%3fabc%3"); errorEncodedCases.add("dubbo%3a192.168.1.1%3fabc%3dabc"); errorEncodedCases.add("%3a%2f%2f192.168.1.1%3fabc%3dabc"); errorEncodedCases.add("%3a%2f192.168.1.1%3fabc%3dabc"); errorEncodedCases.add( "dubbo%3a%2f%2f127.0.0.1%3ftest%3d%e2%96%b2%e2%96%bc%e2%97%80%e2%96%b6%e2%86%90%e2%86%91%e2%86%92%e2%86%93%e2%86%94%e2%86%95%e2%88%9e%c2%b1%e9%be%98%e9%9d%90%e9%bd%89%9%d%b"); } @Test void testEncoded() { testCases.forEach(testCase -> { assertThat(URLStrParser.parseEncodedStr(URL.encode(testCase)), equalTo(URL.valueOf(testCase))); }); errorEncodedCases.forEach(errorCase -> { Assertions.assertThrows(RuntimeException.class, () -> URLStrParser.parseEncodedStr(errorCase)); }); } @Test void testDecoded() { testCases.forEach(testCase -> { assertThat(URLStrParser.parseDecodedStr(testCase), equalTo(URL.valueOf(testCase))); }); errorDecodedCases.forEach(errorCase -> { Assertions.assertThrows(RuntimeException.class, () -> URLStrParser.parseDecodedStr(errorCase)); }); } @Test void testDefault() { URL url1 = URLStrParser.parseEncodedStr(URL.encode("dubbo://127.0.0.1?timeout=1234&default.timeout=5678")); assertThat(url1.getParameter("timeout"), equalTo("1234")); assertThat(url1.getParameter("default.timeout"), equalTo("5678")); URL url2 = URLStrParser.parseEncodedStr(URL.encode("dubbo://127.0.0.1?default.timeout=5678")); assertThat(url2.getParameter("timeout"), equalTo("5678")); assertThat(url2.getParameter("default.timeout"), equalTo("5678")); } }
6,271
0
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/URLBuilderTest.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.common; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.common.utils.NetUtils; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Test; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; class URLBuilderTest { @Test void testNoArgConstructor() { URL url = new URLBuilder().build(); assertThat(url.toString(), equalTo("")); } @Test void shouldAddParameter() { URL url1 = URL.valueOf( "dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"); URL url2 = URLBuilder.from(url1) .addParameter("newKey1", "newValue1") // string .addParameter("newKey2", 2) // int .addParameter("version", 1) // override .build(); assertThat(url2.getParameter("newKey1"), equalTo("newValue1")); assertThat(url2.getParameter("newKey2"), equalTo("2")); assertThat(url2.getVersion(), equalTo("1")); } @Test void testDefault() { ServiceConfigURL url1 = URLBuilder.from(URL.valueOf("")) .addParameter("timeout", "1234") .addParameter("default.timeout", "5678") .build(); assertThat(url1.getParameter("timeout"), equalTo("1234")); assertThat(url1.getParameter("default.timeout"), equalTo("5678")); ServiceConfigURL url2 = URLBuilder.from(URL.valueOf("")) .addParameter("default.timeout", "5678") .build(); assertThat(url2.getParameter("timeout"), equalTo("5678")); assertThat(url2.getParameter("default.timeout"), equalTo("5678")); } @Test void shouldSet() { URL url1 = URL.valueOf( "dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"); int port = NetUtils.getAvailablePort(); URL url2 = URLBuilder.from(url1) .setProtocol("rest") .setUsername("newUsername") .setPassword("newPassword") .setHost("newHost") .setPath("newContext") .setPort(port) .build(); assertThat(url2.getProtocol(), equalTo("rest")); assertThat(url2.getUsername(), equalTo("newUsername")); assertThat(url2.getPassword(), equalTo("newPassword")); assertThat(url2.getHost(), equalTo("newHost")); assertThat(url2.getPort(), equalTo(port)); assertThat(url2.getPath(), equalTo("newContext")); int port2 = NetUtils.getAvailablePort(); url2 = URLBuilder.from(url1).setAddress("newHost2:" + port2).build(); assertThat(url2.getHost(), equalTo("newHost2")); assertThat(url2.getPort(), equalTo(port2)); } @Test void shouldClearParameters() { URL url1 = URL.valueOf( "dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"); URL url2 = URLBuilder.from(url1).clearParameters().build(); assertThat(url2.getParameters().size(), equalTo(0)); } @Test void shouldRemoveParameters() { URL url1 = URL.valueOf( "dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan&key2=v2"); URL url2 = URLBuilder.from(url1) .removeParameters(Arrays.asList("key2", "application")) .build(); assertThat(url2.getParameters().size(), equalTo(1)); assertThat(url2.getVersion(), equalTo("1.0.0")); } @Test void shouldAddIfAbsent() { URL url1 = URL.valueOf( "dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan&key2=v2"); URL url2 = URLBuilder.from(url1) .addParameterIfAbsent("absentKey", "absentValue") .addParameterIfAbsent("version", "2.0.0") // should not override .build(); assertThat(url2.getVersion(), equalTo("1.0.0")); assertThat(url2.getParameter("absentKey"), equalTo("absentValue")); } @Test void shouldAddParameters() { URL url1 = URL.valueOf( "dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan&key2=v2"); // string pairs test URL url2 = URLBuilder.from(url1) .addParameters("version", "1.0.0", "absentKey1", "absentValue1") .build(); assertThat(url2.getParameter("version"), equalTo("1.0.0")); assertThat(url2.getParameter("absentKey1"), equalTo("absentValue1")); // map test Map<String, String> parameters = new HashMap<String, String>() { { this.put("version", "2.0.0"); this.put("absentKey2", "absentValue2"); } }; url2 = URLBuilder.from(url1).addParameters(parameters).build(); assertThat(url2.getParameter("version"), equalTo("2.0.0")); assertThat(url2.getParameter("absentKey2"), equalTo("absentValue2")); } @Test void shouldAddParametersIfAbsent() { URL url1 = URL.valueOf( "dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan&key2=v2"); Map<String, String> parameters = new HashMap<String, String>() { { this.put("version", "2.0.0"); this.put("absentKey", "absentValue"); } }; URL url2 = URLBuilder.from(url1).addParametersIfAbsent(parameters).build(); assertThat(url2.getParameter("version"), equalTo("1.0.0")); assertThat(url2.getParameter("absentKey"), equalTo("absentValue")); } }
6,272
0
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/URLTest.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.common; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.common.utils.CollectionUtils; import java.io.File; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.function.Predicate; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.OS_NAME_KEY; import static org.apache.dubbo.common.constants.CommonConstants.OS_WIN_PREFIX; import static org.hamcrest.CoreMatchers.anyOf; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; class URLTest { @Test void test_ignore_pond() { URL url = URL.valueOf( "dubbo://admin:hello1234@10.20.130.230:20880/context/path#index?version=1.0.0&id=org.apache.dubbo.config.RegistryConfig#0"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("1.0.0", url.getVersion()); assertEquals("org.apache.dubbo.config.RegistryConfig#0", url.getParameter("id")); } @Test void testDefault() { URL url1 = URL.valueOf("dubbo://127.0.0.1:12345?timeout=1234&default.timeout=5678"); assertEquals(1234, url1.getParameter("timeout", 0)); assertEquals(5678, url1.getParameter("default.timeout", 0)); URL url2 = URL.valueOf("dubbo://127.0.0.1:12345?default.timeout=5678"); assertEquals(5678, url2.getParameter("timeout", 0)); assertEquals(5678, url2.getParameter("default.timeout", 0)); } @Test void test_valueOf_noProtocolAndHost() throws Exception { URL url = URL.valueOf("/context/path?version=1.0.0&application=morgan"); assertURLStrDecoder(url); assertNull(url.getProtocol()); assertNull(url.getUsername()); assertNull(url.getPassword()); assertNull(url.getHost()); assertNull(url.getAddress()); assertEquals(0, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("1.0.0", url.getVersion()); assertEquals("morgan", url.getParameter("application")); url = URL.valueOf("context/path?version=1.0.0&application=morgan"); // ^^^^^^^ Caution , parse as host assertURLStrDecoder(url); assertNull(url.getProtocol()); assertNull(url.getUsername()); assertNull(url.getPassword()); assertEquals("context", url.getHost()); assertEquals(0, url.getPort()); assertEquals("path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("1.0.0", url.getVersion()); assertEquals("morgan", url.getParameter("application")); } private void assertURLStrDecoder(URL url) { String fullURLStr = url.toFullString(); URL newUrl = URLStrParser.parseEncodedStr(URL.encode(fullURLStr)); assertEquals(URL.valueOf(fullURLStr), newUrl); URL newUrl2 = URLStrParser.parseDecodedStr(fullURLStr); assertEquals(URL.valueOf(fullURLStr), newUrl2); } @Test void test_valueOf_noProtocol() throws Exception { URL url = URL.valueOf("10.20.130.230"); assertURLStrDecoder(url); assertNull(url.getProtocol()); assertNull(url.getUsername()); assertNull(url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230", url.getAddress()); assertEquals(0, url.getPort()); assertNull(url.getPath()); assertEquals(0, url.getParameters().size()); url = URL.valueOf("10.20.130.230:20880"); assertURLStrDecoder(url); assertNull(url.getProtocol()); assertNull(url.getUsername()); assertNull(url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertNull(url.getPath()); assertEquals(0, url.getParameters().size()); url = URL.valueOf("10.20.130.230/context/path"); assertURLStrDecoder(url); assertNull(url.getProtocol()); assertNull(url.getUsername()); assertNull(url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230", url.getAddress()); assertEquals(0, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(0, url.getParameters().size()); url = URL.valueOf("10.20.130.230:20880/context/path"); assertURLStrDecoder(url); assertNull(url.getProtocol()); assertNull(url.getUsername()); assertNull(url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(0, url.getParameters().size()); url = URL.valueOf("admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"); assertURLStrDecoder(url); assertNull(url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("1.0.0", url.getVersion()); assertEquals("morgan", url.getParameter("application")); } @Test void test_valueOf_noHost() throws Exception { URL url = URL.valueOf("file:///home/user1/router.js"); assertURLStrDecoder(url); assertEquals("file", url.getProtocol()); assertNull(url.getUsername()); assertNull(url.getPassword()); assertNull(url.getHost()); assertNull(url.getAddress()); assertEquals(0, url.getPort()); assertEquals("home/user1/router.js", url.getPath()); assertEquals(0, url.getParameters().size()); // Caution!! url = URL.valueOf("file://home/user1/router.js"); // ^^ only tow slash! assertURLStrDecoder(url); assertEquals("file", url.getProtocol()); assertNull(url.getUsername()); assertNull(url.getPassword()); assertEquals("home", url.getHost()); assertEquals(0, url.getPort()); assertEquals("user1/router.js", url.getPath()); assertEquals(0, url.getParameters().size()); url = URL.valueOf("file:/home/user1/router.js"); assertURLStrDecoder(url); assertEquals("file", url.getProtocol()); assertNull(url.getUsername()); assertNull(url.getPassword()); assertNull(url.getHost()); assertNull(url.getAddress()); assertEquals(0, url.getPort()); assertEquals("home/user1/router.js", url.getPath()); assertEquals(0, url.getParameters().size()); url = URL.valueOf("file:///d:/home/user1/router.js"); assertURLStrDecoder(url); assertEquals("file", url.getProtocol()); assertNull(url.getUsername()); assertNull(url.getPassword()); assertNull(url.getHost()); assertNull(url.getAddress()); assertEquals(0, url.getPort()); assertEquals("d:/home/user1/router.js", url.getPath()); assertEquals(0, url.getParameters().size()); url = URL.valueOf("file:///home/user1/router.js?p1=v1&p2=v2"); assertURLStrDecoder(url); assertEquals("file", url.getProtocol()); assertNull(url.getUsername()); assertNull(url.getPassword()); assertNull(url.getHost()); assertNull(url.getAddress()); assertEquals(0, url.getPort()); assertEquals("home/user1/router.js", url.getPath()); assertEquals(2, url.getParameters().size()); Map<String, String> params = new HashMap<String, String>(); params.put("p1", "v1"); params.put("p2", "v2"); assertEquals(params, url.getParameters()); url = URL.valueOf("file:/home/user1/router.js?p1=v1&p2=v2"); assertURLStrDecoder(url); assertEquals("file", url.getProtocol()); assertNull(url.getUsername()); assertNull(url.getPassword()); assertNull(url.getHost()); assertNull(url.getAddress()); assertEquals(0, url.getPort()); assertEquals("home/user1/router.js", url.getPath()); assertEquals(2, url.getParameters().size()); params = new HashMap<String, String>(); params.put("p1", "v1"); params.put("p2", "v2"); assertEquals(params, url.getParameters()); } @Test void test_valueOf_WithProtocolHost() throws Exception { URL url = URL.valueOf("dubbo://10.20.130.230"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertNull(url.getUsername()); assertNull(url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230", url.getAddress()); assertEquals(0, url.getPort()); assertNull(url.getPath()); assertEquals(0, url.getParameters().size()); url = URL.valueOf("dubbo://10.20.130.230:20880/context/path"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertNull(url.getUsername()); assertNull(url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(0, url.getParameters().size()); url = URL.valueOf("dubbo://admin:hello1234@10.20.130.230:20880"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertNull(url.getPath()); assertEquals(0, url.getParameters().size()); url = URL.valueOf("dubbo://admin:hello1234@10.20.130.230:20880?version=1.0.0"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertNull(url.getPath()); assertEquals(1, url.getParameters().size()); assertEquals("1.0.0", url.getVersion()); url = URL.valueOf("dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("1.0.0", url.getVersion()); assertEquals("morgan", url.getParameter("application")); url = URL.valueOf( "dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan&noValue="); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(3, url.getParameters().size()); assertEquals("1.0.0", url.getVersion()); assertEquals("morgan", url.getParameter("application")); assertEquals("", url.getParameter("noValue")); } // TODO Do not want to use spaces? See: DUBBO-502, URL class handles special conventions for special characters. @Test void test_valueOf_spaceSafe() throws Exception { URL url = URL.valueOf("http://1.2.3.4:8080/path?key=value1 value2"); assertURLStrDecoder(url); assertEquals("http://1.2.3.4:8080/path?key=value1 value2", url.toString()); assertEquals("value1 value2", url.getParameter("key")); } @Test void test_noValueKey() throws Exception { URL url = URL.valueOf("http://1.2.3.4:8080/path?k0=&k1=v1"); assertURLStrDecoder(url); assertFalse(url.hasParameter("k0")); // If a Key has no corresponding Value, then empty string used as the Value. assertEquals("", url.getParameter("k0")); } @Test void test_valueOf_Exception_noProtocol() throws Exception { try { URL.valueOf("://1.2.3.4:8080/path"); fail(); } catch (IllegalStateException expected) { assertEquals("url missing protocol: \"://1.2.3.4:8080/path\"", expected.getMessage()); } try { String encodedURLStr = URL.encode("://1.2.3.4:8080/path"); URLStrParser.parseEncodedStr(encodedURLStr); fail(); } catch (IllegalStateException expected) { assertEquals("url missing protocol: \"://1.2.3.4:8080/path\"", URL.decode(expected.getMessage())); } try { URLStrParser.parseDecodedStr("://1.2.3.4:8080/path"); fail(); } catch (IllegalStateException expected) { assertEquals("url missing protocol: \"://1.2.3.4:8080/path\"", expected.getMessage()); } } @Test void test_getAddress() throws Exception { URL url1 = URL.valueOf( "dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"); assertURLStrDecoder(url1); assertEquals("10.20.130.230:20880", url1.getAddress()); } @Test void test_getAbsolutePath() throws Exception { URL url = new ServiceConfigURL("p1", "1.2.2.2", 33); assertURLStrDecoder(url); assertNull(url.getAbsolutePath()); url = new ServiceConfigURL("file", null, 90, "/home/user1/route.js"); assertURLStrDecoder(url); assertEquals("/home/user1/route.js", url.getAbsolutePath()); } @Test void test_equals() throws Exception { URL url1 = URL.valueOf( "dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"); assertURLStrDecoder(url1); Map<String, String> params = new HashMap<String, String>(); params.put("version", "1.0.0"); params.put("application", "morgan"); URL url2 = new ServiceConfigURL("dubbo", "admin", "hello1234", "10.20.130.230", 20880, "context/path", params); assertURLStrDecoder(url2); assertEquals(url1, url2); } @Test void test_toString() throws Exception { URL url1 = URL.valueOf( "dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"); assertURLStrDecoder(url1); assertThat( url1.toString(), anyOf( equalTo("dubbo://10.20.130.230:20880/context/path?version=1.0.0&application=morgan"), equalTo("dubbo://10.20.130.230:20880/context/path?application=morgan&version=1.0.0"))); } @Test void test_toFullString() throws Exception { URL url1 = URL.valueOf( "dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"); assertURLStrDecoder(url1); assertThat( url1.toFullString(), anyOf( equalTo( "dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"), equalTo( "dubbo://admin:hello1234@10.20.130.230:20880/context/path?application=morgan&version=1.0.0"))); } @Test void test_set_methods() throws Exception { URL url = URL.valueOf( "dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"); assertURLStrDecoder(url); url = url.setHost("host"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("host", url.getHost()); assertEquals("host:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("1.0.0", url.getVersion()); assertEquals("morgan", url.getParameter("application")); url = url.setPort(1); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("host", url.getHost()); assertEquals("host:1", url.getAddress()); assertEquals(1, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("1.0.0", url.getVersion()); assertEquals("morgan", url.getParameter("application")); url = url.setPath("path"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("host", url.getHost()); assertEquals("host:1", url.getAddress()); assertEquals(1, url.getPort()); assertEquals("path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("1.0.0", url.getVersion()); assertEquals("morgan", url.getParameter("application")); url = url.setProtocol("protocol"); assertURLStrDecoder(url); assertEquals("protocol", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("host", url.getHost()); assertEquals("host:1", url.getAddress()); assertEquals(1, url.getPort()); assertEquals("path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("1.0.0", url.getVersion()); assertEquals("morgan", url.getParameter("application")); url = url.setUsername("username"); assertURLStrDecoder(url); assertEquals("protocol", url.getProtocol()); assertEquals("username", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("host", url.getHost()); assertEquals("host:1", url.getAddress()); assertEquals(1, url.getPort()); assertEquals("path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("1.0.0", url.getVersion()); assertEquals("morgan", url.getParameter("application")); url = url.setPassword("password"); assertURLStrDecoder(url); assertEquals("protocol", url.getProtocol()); assertEquals("username", url.getUsername()); assertEquals("password", url.getPassword()); assertEquals("host", url.getHost()); assertEquals("host:1", url.getAddress()); assertEquals(1, url.getPort()); assertEquals("path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("1.0.0", url.getVersion()); assertEquals("morgan", url.getParameter("application")); } @Test void test_removeParameters() throws Exception { URL url = URL.valueOf( "dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan&k1=v1&k2=v2"); assertURLStrDecoder(url); url = url.removeParameter("version"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(3, url.getParameters().size()); assertEquals("morgan", url.getParameter("application")); assertEquals("v1", url.getParameter("k1")); assertEquals("v2", url.getParameter("k2")); assertNull(url.getVersion()); url = URL.valueOf( "dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan&k1=v1&k2=v2"); url = url.removeParameters("version", "application", "NotExistedKey"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("v1", url.getParameter("k1")); assertEquals("v2", url.getParameter("k2")); assertNull(url.getVersion()); assertNull(url.getParameter("application")); url = URL.valueOf( "dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan&k1=v1&k2=v2"); url = url.removeParameters(Arrays.asList("version", "application")); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("v1", url.getParameter("k1")); assertEquals("v2", url.getParameter("k2")); assertNull(url.getVersion()); assertNull(url.getParameter("application")); } @Test void test_addParameter() throws Exception { URL url = URL.valueOf("dubbo://admin:hello1234@10.20.130.230:20880/context/path?application=morgan"); url = url.addParameter("k1", "v1"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("morgan", url.getParameter("application")); assertEquals("v1", url.getParameter("k1")); } @Test void test_addParameter_sameKv() throws Exception { URL url = URL.valueOf("dubbo://admin:hello1234@10.20.130.230:20880/context/path?application=morgan&k1=v1"); URL newUrl = url.addParameter("k1", "v1"); assertURLStrDecoder(url); assertSame(newUrl, url); } @Test void test_addParameters() throws Exception { URL url = URL.valueOf("dubbo://admin:hello1234@10.20.130.230:20880/context/path?application=morgan"); url = url.addParameters(CollectionUtils.toStringMap("k1", "v1", "k2", "v2")); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(3, url.getParameters().size()); assertEquals("morgan", url.getParameter("application")); assertEquals("v1", url.getParameter("k1")); assertEquals("v2", url.getParameter("k2")); url = URL.valueOf("dubbo://admin:hello1234@10.20.130.230:20880/context/path?application=morgan"); url = url.addParameters("k1", "v1", "k2", "v2", "application", "xxx"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(3, url.getParameters().size()); assertEquals("xxx", url.getParameter("application")); assertEquals("v1", url.getParameter("k1")); assertEquals("v2", url.getParameter("k2")); url = URL.valueOf("dubbo://admin:hello1234@10.20.130.230:20880/context/path?application=morgan"); url = url.addParametersIfAbsent(CollectionUtils.toStringMap("k1", "v1", "k2", "v2", "application", "xxx")); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(3, url.getParameters().size()); assertEquals("morgan", url.getParameter("application")); assertEquals("v1", url.getParameter("k1")); assertEquals("v2", url.getParameter("k2")); url = URL.valueOf("dubbo://admin:hello1234@10.20.130.230:20880/context/path?application=morgan"); url = url.addParameter("k1", "v1"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("morgan", url.getParameter("application")); assertEquals("v1", url.getParameter("k1")); url = URL.valueOf("dubbo://admin:hello1234@10.20.130.230:20880/context/path?application=morgan"); url = url.addParameter("application", "xxx"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(1, url.getParameters().size()); assertEquals("xxx", url.getParameter("application")); } @Test void test_addParameters_SameKv() throws Exception { { URL url = URL.valueOf("dubbo://admin:hello1234@10.20.130.230:20880/context/path?application=morgan&k1=v1"); URL newUrl = url.addParameters(CollectionUtils.toStringMap("k1", "v1")); assertURLStrDecoder(url); assertSame(url, newUrl); } { URL url = URL.valueOf( "dubbo://admin:hello1234@10.20.130.230:20880/context/path?application=morgan&k1=v1&k2=v2"); URL newUrl = url.addParameters(CollectionUtils.toStringMap("k1", "v1", "k2", "v2")); assertURLStrDecoder(url); assertSame(newUrl, url); } } @Test void test_addParameterIfAbsent() throws Exception { URL url = URL.valueOf("dubbo://admin:hello1234@10.20.130.230:20880/context/path?application=morgan"); url = url.addParameterIfAbsent("application", "xxx"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(1, url.getParameters().size()); assertEquals("morgan", url.getParameter("application")); } @Test void test_windowAbsolutePathBeginWithSlashIsValid() throws Exception { final String osProperty = System.getProperties().getProperty(OS_NAME_KEY); if (!osProperty.toLowerCase().contains(OS_WIN_PREFIX)) return; System.out.println("Test Windows valid path string."); File f0 = new File("C:/Windows"); File f1 = new File("/C:/Windows"); File f2 = new File("C:\\Windows"); File f3 = new File("/C:\\Windows"); File f4 = new File("\\C:\\Windows"); assertEquals(f0, f1); assertEquals(f0, f2); assertEquals(f0, f3); assertEquals(f0, f4); } @Test void test_javaNetUrl() throws Exception { java.net.URL url = new java.net.URL( "http://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan#anchor1"); assertEquals("http", url.getProtocol()); assertEquals("admin:hello1234", url.getUserInfo()); assertEquals("10.20.130.230", url.getHost()); assertEquals(20880, url.getPort()); assertEquals("/context/path", url.getPath()); assertEquals("version=1.0.0&application=morgan", url.getQuery()); assertEquals("anchor1", url.getRef()); assertEquals("admin:hello1234@10.20.130.230:20880", url.getAuthority()); assertEquals("/context/path?version=1.0.0&application=morgan", url.getFile()); } @Test void test_Anyhost() throws Exception { URL url = URL.valueOf("dubbo://0.0.0.0:20880"); assertURLStrDecoder(url); assertEquals("0.0.0.0", url.getHost()); assertTrue(url.isAnyHost()); } @Test void test_Localhost() throws Exception { URL url = URL.valueOf("dubbo://127.0.0.1:20880"); assertURLStrDecoder(url); assertEquals("127.0.0.1", url.getHost()); assertEquals("127.0.0.1:20880", url.getAddress()); assertTrue(url.isLocalHost()); url = URL.valueOf("dubbo://127.0.1.1:20880"); assertURLStrDecoder(url); assertEquals("127.0.1.1", url.getHost()); assertEquals("127.0.1.1:20880", url.getAddress()); assertTrue(url.isLocalHost()); url = URL.valueOf("dubbo://localhost:20880"); assertURLStrDecoder(url); assertEquals("localhost", url.getHost()); assertEquals("localhost:20880", url.getAddress()); assertTrue(url.isLocalHost()); } @Test void test_Path() throws Exception { URL url = new ServiceConfigURL("dubbo", "localhost", 20880, "////path"); assertURLStrDecoder(url); assertEquals("path", url.getPath()); } @Test void testAddParameters() throws Exception { URL url = URL.valueOf("dubbo://127.0.0.1:20880"); assertURLStrDecoder(url); Map<String, String> parameters = new HashMap<String, String>(); parameters.put("version", null); url.addParameters(parameters); assertURLStrDecoder(url); } @Test void testUserNamePasswordContainsAt() { // Test username or password contains "@" URL url = URL.valueOf("ad@min:hello@1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"); assertURLStrDecoder(url); assertNull(url.getProtocol()); assertEquals("ad@min", url.getUsername()); assertEquals("hello@1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("1.0.0", url.getVersion()); assertEquals("morgan", url.getParameter("application")); } @Test void testIpV6Address() { // Test username or password contains "@" URL url = URL.valueOf( "ad@min111:haha@1234@2001:0db8:85a3:08d3:1319:8a2e:0370:7344:20880/context/path?version=1.0.0&application=morgan"); assertURLStrDecoder(url); assertNull(url.getProtocol()); assertEquals("ad@min111", url.getUsername()); assertEquals("haha@1234", url.getPassword()); assertEquals("2001:0db8:85a3:08d3:1319:8a2e:0370:7344", url.getHost()); assertEquals("2001:0db8:85a3:08d3:1319:8a2e:0370:7344:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("1.0.0", url.getVersion()); assertEquals("morgan", url.getParameter("application")); } @Test void testIpV6AddressWithScopeId() { URL url = URL.valueOf("2001:0db8:85a3:08d3:1319:8a2e:0370:7344%5/context/path?version=1.0.0&application=morgan"); assertURLStrDecoder(url); assertNull(url.getProtocol()); assertEquals("2001:0db8:85a3:08d3:1319:8a2e:0370:7344%5", url.getHost()); assertEquals("2001:0db8:85a3:08d3:1319:8a2e:0370:7344%5", url.getAddress()); assertEquals(0, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("1.0.0", url.getVersion()); assertEquals("morgan", url.getParameter("application")); } @Test void testDefaultPort() { Assertions.assertEquals("10.20.153.10:2181", URL.appendDefaultPort("10.20.153.10:0", 2181)); Assertions.assertEquals("10.20.153.10:2181", URL.appendDefaultPort("10.20.153.10", 2181)); } @Test void testGetServiceKey() { URL url1 = URL.valueOf("10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName"); assertURLStrDecoder(url1); Assertions.assertEquals("org.apache.dubbo.test.interfaceName", url1.getServiceKey()); URL url2 = URL.valueOf( "10.20.130.230:20880/org.apache.dubbo.test.interfaceName?interface=org.apache.dubbo.test.interfaceName"); assertURLStrDecoder(url2); Assertions.assertEquals("org.apache.dubbo.test.interfaceName", url2.getServiceKey()); URL url3 = URL.valueOf( "10.20.130.230:20880/org.apache.dubbo.test.interfaceName?interface=org.apache.dubbo.test.interfaceName&group=group1&version=1.0.0"); assertURLStrDecoder(url3); Assertions.assertEquals("group1/org.apache.dubbo.test.interfaceName:1.0.0", url3.getServiceKey()); URL url4 = URL.valueOf("10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName"); assertURLStrDecoder(url4); Assertions.assertEquals("context/path", url4.getPathKey()); URL url5 = URL.valueOf( "10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName&group=group1&version=1.0.0"); assertURLStrDecoder(url5); Assertions.assertEquals("group1/context/path:1.0.0", url5.getPathKey()); } @Test void testGetColonSeparatedKey() { URL url1 = URL.valueOf( "10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName&group=group&version=1.0.0"); assertURLStrDecoder(url1); Assertions.assertEquals("org.apache.dubbo.test.interfaceName:1.0.0:group", url1.getColonSeparatedKey()); URL url2 = URL.valueOf( "10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName&version=1.0.0"); assertURLStrDecoder(url2); Assertions.assertEquals("org.apache.dubbo.test.interfaceName:1.0.0:", url2.getColonSeparatedKey()); URL url3 = URL.valueOf( "10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName&group=group"); assertURLStrDecoder(url3); Assertions.assertEquals("org.apache.dubbo.test.interfaceName::group", url3.getColonSeparatedKey()); URL url4 = URL.valueOf("10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName"); assertURLStrDecoder(url4); Assertions.assertEquals("org.apache.dubbo.test.interfaceName::", url4.getColonSeparatedKey()); URL url5 = URL.valueOf("10.20.130.230:20880/org.apache.dubbo.test.interfaceName"); assertURLStrDecoder(url5); Assertions.assertEquals("org.apache.dubbo.test.interfaceName::", url5.getColonSeparatedKey()); URL url6 = URL.valueOf( "10.20.130.230:20880/org.apache.dubbo.test.interfaceName?interface=org.apache.dubbo.test.interfaceName1"); assertURLStrDecoder(url6); Assertions.assertEquals("org.apache.dubbo.test.interfaceName1::", url6.getColonSeparatedKey()); } @Test void testValueOf() { URL url = URL.valueOf("10.20.130.230"); assertURLStrDecoder(url); url = URL.valueOf("10.20.130.230:20880"); assertURLStrDecoder(url); url = URL.valueOf("dubbo://10.20.130.230:20880"); assertURLStrDecoder(url); url = URL.valueOf("dubbo://10.20.130.230:20880/path"); assertURLStrDecoder(url); } /** * Test {@link URL#getParameters(Predicate)} method * * @since 2.7.8 */ @Test void testGetParameters() { URL url = URL.valueOf( "10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName&group=group&version=1.0.0"); Map<String, String> parameters = url.getParameters(i -> "version".equals(i)); String version = parameters.get("version"); assertEquals(1, parameters.size()); assertEquals("1.0.0", version); } @Test void testGetParameter() { URL url = URL.valueOf("http://127.0.0.1:8080/path?i=1&b=false"); assertEquals(Integer.valueOf(1), url.getParameter("i", Integer.class)); assertEquals(Boolean.FALSE, url.getParameter("b", Boolean.class)); } @Test void testEquals() { URL url1 = URL.valueOf( "10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName&group=group&version=1.0.0"); URL url2 = URL.valueOf( "10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName&group=group&version=1.0.0"); Assertions.assertEquals(url1, url2); URL url3 = URL.valueOf( "10.20.130.230:20881/context/path?interface=org.apache.dubbo.test.interfaceName&group=group&version=1.0.0"); Assertions.assertNotEquals(url1, url3); URL url4 = URL.valueOf( "10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName&weight=10&group=group&version=1.0.0"); Assertions.assertNotEquals(url1, url4); URL url5 = URL.valueOf( "10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName&weight=10&group=group&version=1.0.0"); Assertions.assertEquals(url4, url5); URL url6 = URL.valueOf("consumer://30.225.20.150/org.apache.dubbo.rpc.service.GenericService?application=" + "dubbo-demo-api-consumer&category=consumers&check=false&dubbo=2.0.2&generic=true&interface=" + "org.apache.dubbo.demo.DemoService&pid=7375&side=consumer&sticky=false&timestamp=1599556506417"); URL url7 = URL.valueOf("consumer://30.225.20.150/org.apache.dubbo.rpc.service.GenericService?application=" + "dubbo-demo-api-consumer&category=consumers&check=false&dubbo=2.0.2&generic=true&interface=" + "org.apache.dubbo.demo.DemoService&pid=7375&side=consumer&sticky=false&timestamp=2299556506417"); assertEquals(url6, url7); URL url8 = URL.valueOf("consumer://30.225.20.150/org.apache.dubbo.rpc.service.GenericService?application=" + "dubbo-demo-api-consumer&category=consumers&check=false&dubbo=2.0.2&interface=" + "org.apache.dubbo.demo.DemoService&pid=7375&side=consumer&sticky=false&timestamp=2299556506417"); assertNotEquals(url7, url8); URL url9 = URL.valueOf("consumer://30.225.20.150/org.apache.dubbo.rpc.service.GenericService?application=" + "dubbo-demo-api-consumer&category=consumers&check=true&dubbo=2.0.2&interface=" + "org.apache.dubbo.demo.DemoService&pid=7375&side=consumer&sticky=false&timestamp=2299556506417"); assertNotEquals(url8, url9); } @Test void testEqualsWithPassword() { URL url1 = URL.valueOf("ad@min:hello@1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"); URL url2 = URL.valueOf("ad@min:hello@4321@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"); URL url3 = URL.valueOf("ad@min:hello@1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"); boolean actual1 = url1.equals(url2); boolean actual2 = url1.equals(url3); assertFalse(actual1); assertTrue(actual2); } @Test void testEqualsWithPath() { URL url1 = URL.valueOf("ad@min:hello@1234@10.20.130.230:20880/context/path1?version=1.0.0&application=morgan"); URL url2 = URL.valueOf("ad@min:hello@1234@10.20.130.230:20880/context/path2?version=1.0.0&application=morgan"); URL url3 = URL.valueOf("ad@min:hello@1234@10.20.130.230:20880/context/path1?version=1.0.0&application=morgan"); boolean actual1 = url1.equals(url2); boolean actual2 = url1.equals(url3); assertFalse(actual1); assertTrue(actual2); } @Test void testEqualsWithPort() { URL url1 = URL.valueOf("ad@min:hello@1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"); URL url2 = URL.valueOf("ad@min:hello@1234@10.20.130.230:20881/context/path?version=1.0.0&application=morgan"); URL url3 = URL.valueOf("ad@min:hello@1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"); boolean actual1 = url1.equals(url2); boolean actual2 = url1.equals(url3); assertFalse(actual1); assertTrue(actual2); } @Test void testEqualsWithProtocol() { URL url1 = URL.valueOf( "dubbo://ad@min:hello@1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"); URL url2 = URL.valueOf( "file://ad@min:hello@1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"); URL url3 = URL.valueOf( "dubbo://ad@min:hello@1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"); boolean actual1 = url1.equals(url2); boolean actual2 = url1.equals(url3); assertFalse(actual1); assertTrue(actual2); } @Test void testEqualsWithUser() { URL url1 = URL.valueOf("ad@min1:hello@1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"); URL url2 = URL.valueOf("ad@min2:hello@1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"); URL url3 = URL.valueOf("ad@min1:hello@1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"); boolean actual1 = url1.equals(url2); boolean actual2 = url1.equals(url3); assertFalse(actual1); assertTrue(actual2); } @Test void testHashcode() { URL url1 = URL.valueOf("consumer://30.225.20.150/org.apache.dubbo.rpc.service.GenericService?application=" + "dubbo-demo-api-consumer&category=consumers&check=false&dubbo=2.0.2&generic=true&interface=" + "org.apache.dubbo.demo.DemoService&pid=7375&side=consumer&sticky=false&timestamp=1599556506417"); URL url2 = URL.valueOf("consumer://30.225.20.150/org.apache.dubbo.rpc.service.GenericService?application=" + "dubbo-demo-api-consumer&category=consumers&check=false&dubbo=2.0.2&generic=true&interface=" + "org.apache.dubbo.demo.DemoService&pid=7375&side=consumer&sticky=false&timestamp=2299556506417"); assertEquals(url1.hashCode(), url2.hashCode()); URL url3 = URL.valueOf("consumer://30.225.20.150/org.apache.dubbo.rpc.service.GenericService?application=" + "dubbo-demo-api-consumer&category=consumers&check=false&dubbo=2.0.2&interface=" + "org.apache.dubbo.demo.DemoService&pid=7375&side=consumer&sticky=false&timestamp=2299556506417"); assertNotEquals(url2.hashCode(), url3.hashCode()); URL url4 = URL.valueOf("consumer://30.225.20.150/org.apache.dubbo.rpc.service.GenericService?application=" + "dubbo-demo-api-consumer&category=consumers&check=true&dubbo=2.0.2&interface=" + "org.apache.dubbo.demo.DemoService&pid=7375&side=consumer&sticky=false&timestamp=2299556506417"); assertNotEquals(url3.hashCode(), url4.hashCode()); } @Test void testParameterContainPound() { URL url = URL.valueOf( "dubbo://ad@min:hello@1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan&pound=abcd#efg&protocol=registry"); Assertions.assertEquals("abcd#efg", url.getParameter("pound")); Assertions.assertEquals("registry", url.getParameter("protocol")); } @Test void test_valueOfHasNameWithoutValue() throws Exception { URL url = URL.valueOf( "dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan&noValue"); Assertions.assertEquals("", url.getParameter("noValue")); } @Test void testGetAuthority() { URL url = URL.valueOf("admin1:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=app1"); assertEquals("admin1:hello1234@10.20.130.230:20880", url.getAuthority()); URL urlWithoutUsername = URL.valueOf(":hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=app1"); assertEquals(":hello1234@10.20.130.230:20880", urlWithoutUsername.getAuthority()); URL urlWithoutPassword = URL.valueOf("admin1:@10.20.130.230:20880/context/path?version=1.0.0&application=app1"); assertEquals("admin1:@10.20.130.230:20880", urlWithoutPassword.getAuthority()); URL urlWithoutUserInformation = URL.valueOf("10.20.130.230:20880/context/path?version=1.0.0&application=app1"); assertEquals("10.20.130.230:20880", urlWithoutUserInformation.getAuthority()); URL urlWithoutPort = URL.valueOf("admin1:hello1234@10.20.130.230/context/path?version=1.0.0&application=app1"); assertEquals("admin1:hello1234@10.20.130.230", urlWithoutPort.getAuthority()); } @Test void testGetUserInformation() { URL url = URL.valueOf("admin1:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=app1"); assertEquals("admin1:hello1234", url.getUserInformation()); URL urlWithoutUsername = URL.valueOf(":hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=app1"); assertEquals(":hello1234@10.20.130.230:20880", urlWithoutUsername.getAuthority()); URL urlWithoutPassword = URL.valueOf("admin1:@10.20.130.230:20880/context/path?version=1.0.0&application=app1"); assertEquals("admin1:@10.20.130.230:20880", urlWithoutPassword.getAuthority()); URL urlWithoutUserInformation = URL.valueOf("10.20.130.230:20880/context/path?version=1.0.0&application=app1"); assertEquals("10.20.130.230:20880", urlWithoutUserInformation.getAuthority()); } @Test void testIPV6() { URL url = URL.valueOf("dubbo://[2408:4004:194:8896:3e8a:82ae:814a:398]:20881?name=apache"); assertEquals("[2408:4004:194:8896:3e8a:82ae:814a:398]", url.getHost()); assertEquals(20881, url.getPort()); assertEquals("apache", url.getParameter("name")); } }
6,273
0
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/ServiceKeyMatcherTest.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.common; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class ServiceKeyMatcherTest { @Test void testInterface() { Assertions.assertTrue( ServiceKey.Matcher.isMatch(new ServiceKey(null, null, null), new ServiceKey(null, null, null))); Assertions.assertFalse(ServiceKey.Matcher.isMatch( new ServiceKey("DemoService", null, null), new ServiceKey(null, null, null))); Assertions.assertFalse(ServiceKey.Matcher.isMatch( new ServiceKey(null, null, null), new ServiceKey("DemoService", null, null))); Assertions.assertFalse( ServiceKey.Matcher.isMatch(new ServiceKey("*", null, null), new ServiceKey("DemoService", null, null))); Assertions.assertFalse( ServiceKey.Matcher.isMatch(new ServiceKey("*", null, null), new ServiceKey(null, null, null))); } @Test void testVersion() { Assertions.assertTrue( ServiceKey.Matcher.isMatch(new ServiceKey(null, "1.0.0", null), new ServiceKey(null, "1.0.0", null))); Assertions.assertTrue( ServiceKey.Matcher.isMatch(new ServiceKey(null, null, null), new ServiceKey(null, null, null))); Assertions.assertFalse( ServiceKey.Matcher.isMatch(new ServiceKey(null, "1.0.0", null), new ServiceKey(null, null, null))); Assertions.assertFalse( ServiceKey.Matcher.isMatch(new ServiceKey(null, null, null), new ServiceKey(null, "1.0.0", null))); Assertions.assertTrue(ServiceKey.Matcher.isMatch( new ServiceKey(null, "1.0.0,1.0.1", null), new ServiceKey(null, "1.0.0", null))); Assertions.assertFalse(ServiceKey.Matcher.isMatch( new ServiceKey(null, "1.0.0,1.0.1", null), new ServiceKey(null, "1.0.2", null))); Assertions.assertFalse(ServiceKey.Matcher.isMatch( new ServiceKey(null, "1.0.0,1.0.1", null), new ServiceKey(null, null, null))); Assertions.assertTrue(ServiceKey.Matcher.isMatch( new ServiceKey(null, ",1.0.0,1.0.1", null), new ServiceKey(null, null, null))); Assertions.assertTrue( ServiceKey.Matcher.isMatch(new ServiceKey(null, ",1.0.0,1.0.1", null), new ServiceKey(null, "", null))); Assertions.assertTrue(ServiceKey.Matcher.isMatch( new ServiceKey(null, "1.0.0,,1.0.1", null), new ServiceKey(null, null, null))); Assertions.assertTrue( ServiceKey.Matcher.isMatch(new ServiceKey(null, "1.0.0,,1.0.1", null), new ServiceKey(null, "", null))); Assertions.assertTrue(ServiceKey.Matcher.isMatch( new ServiceKey(null, "1.0.0,1.0.1,", null), new ServiceKey(null, null, null))); Assertions.assertTrue( ServiceKey.Matcher.isMatch(new ServiceKey(null, "1.0.0,1.0.1,", null), new ServiceKey(null, "", null))); Assertions.assertFalse(ServiceKey.Matcher.isMatch( new ServiceKey(null, "1.0.0,1.0.1", null), new ServiceKey(null, null, null))); Assertions.assertFalse( ServiceKey.Matcher.isMatch(new ServiceKey(null, "1.0.0,1.0.1", null), new ServiceKey(null, "", null))); Assertions.assertFalse(ServiceKey.Matcher.isMatch( new ServiceKey(null, ",1.0.0,1.0.1", null), new ServiceKey(null, "1.0.2", null))); Assertions.assertFalse(ServiceKey.Matcher.isMatch( new ServiceKey(null, ",1.0.0,1.0.1", null), new ServiceKey(null, "1.0.2", null))); Assertions.assertTrue( ServiceKey.Matcher.isMatch(new ServiceKey(null, "*", null), new ServiceKey(null, null, null))); Assertions.assertTrue( ServiceKey.Matcher.isMatch(new ServiceKey(null, "*", null), new ServiceKey(null, "", null))); Assertions.assertTrue( ServiceKey.Matcher.isMatch(new ServiceKey(null, "*", null), new ServiceKey(null, "1.0.0", null))); } @Test void testGroup() { Assertions.assertTrue( ServiceKey.Matcher.isMatch(new ServiceKey(null, null, "group1"), new ServiceKey(null, null, "group1"))); Assertions.assertFalse( ServiceKey.Matcher.isMatch(new ServiceKey(null, null, "group1"), new ServiceKey(null, null, null))); Assertions.assertFalse( ServiceKey.Matcher.isMatch(new ServiceKey(null, null, null), new ServiceKey(null, null, "group1"))); Assertions.assertTrue(ServiceKey.Matcher.isMatch( new ServiceKey(null, null, "group1, group2"), new ServiceKey(null, null, "group1"))); Assertions.assertFalse(ServiceKey.Matcher.isMatch( new ServiceKey(null, null, "group2, group3"), new ServiceKey(null, null, "group1"))); Assertions.assertFalse(ServiceKey.Matcher.isMatch( new ServiceKey(null, null, "group2, group3"), new ServiceKey(null, null, null))); Assertions.assertFalse(ServiceKey.Matcher.isMatch( new ServiceKey(null, null, "group2, group3"), new ServiceKey(null, null, ""))); Assertions.assertTrue( ServiceKey.Matcher.isMatch(new ServiceKey(null, null, ",group2"), new ServiceKey(null, null, ""))); Assertions.assertTrue( ServiceKey.Matcher.isMatch(new ServiceKey(null, null, "group2,"), new ServiceKey(null, null, ""))); Assertions.assertTrue(ServiceKey.Matcher.isMatch( new ServiceKey(null, null, "group2, ,group3"), new ServiceKey(null, null, ""))); Assertions.assertFalse(ServiceKey.Matcher.isMatch( new ServiceKey(null, null, ",group2"), new ServiceKey(null, null, "group1"))); Assertions.assertFalse(ServiceKey.Matcher.isMatch( new ServiceKey(null, null, "group2,"), new ServiceKey(null, null, "group1"))); Assertions.assertFalse(ServiceKey.Matcher.isMatch( new ServiceKey(null, null, "group2, ,group3"), new ServiceKey(null, null, "group1"))); Assertions.assertTrue( ServiceKey.Matcher.isMatch(new ServiceKey(null, null, "*"), new ServiceKey(null, null, ""))); Assertions.assertTrue( ServiceKey.Matcher.isMatch(new ServiceKey(null, null, "*"), new ServiceKey(null, null, null))); Assertions.assertTrue( ServiceKey.Matcher.isMatch(new ServiceKey(null, null, "*"), new ServiceKey(null, null, "group1"))); } }
6,274
0
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/PojoUtilsForNonPublicStaticTest.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.common; import org.apache.dubbo.common.utils.PojoUtils; import org.junit.jupiter.api.Test; class PojoUtilsForNonPublicStaticTest { @Test void testNonPublicStaticClass() { NonPublicStaticData nonPublicStaticData = new NonPublicStaticData("horizon"); PojoUtils.generalize(nonPublicStaticData); } /** * the static class need is not same package with PojoUtils, so define it here. */ static class NonPublicStaticData { private String name; public NonPublicStaticData(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } }
6,275
0
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/vo/UserVo.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.common.vo; import java.util.Objects; public class UserVo { private String name; private String addr; private int age; public UserVo(String name, String addr, int age) { this.name = name; this.addr = addr; this.age = age; } public UserVo() {} public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddr() { return addr; } public void setAddr(String addr) { this.addr = addr; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public static UserVo getInstance() { return new UserVo("dubbo", "hangzhou", 10); } @Override public String toString() { return "UserVo{" + "name='" + name + '\'' + ", addr='" + addr + '\'' + ", age=" + age + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; UserVo userVo = (UserVo) o; return age == userVo.age && Objects.equals(name, userVo.name) && Objects.equals(addr, userVo.addr); } @Override public int hashCode() { return Objects.hash(name, addr, age); } }
6,276
0
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/ssl/SSLConfigCertProviderTest.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.common.ssl; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.ssl.impl.SSLConfigCertProvider; import org.apache.dubbo.common.utils.IOUtils; import org.apache.dubbo.config.SslConfig; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import java.io.IOException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class SSLConfigCertProviderTest { @Test void testSupported() { FrameworkModel frameworkModel = new FrameworkModel(); ApplicationModel applicationModel = frameworkModel.newApplication(); SSLConfigCertProvider sslConfigCertProvider = new SSLConfigCertProvider(); URL url = URL.valueOf("").setScopeModel(applicationModel); Assertions.assertFalse(sslConfigCertProvider.isSupport(url)); SslConfig sslConfig = new SslConfig(); applicationModel.getApplicationConfigManager().setSsl(sslConfig); Assertions.assertTrue(sslConfigCertProvider.isSupport(url)); frameworkModel.destroy(); } @Test void testGetProviderConnectionConfig() throws IOException { FrameworkModel frameworkModel = new FrameworkModel(); ApplicationModel applicationModel = frameworkModel.newApplication(); SSLConfigCertProvider sslConfigCertProvider = new SSLConfigCertProvider(); URL url = URL.valueOf("").setScopeModel(applicationModel); Assertions.assertNull(sslConfigCertProvider.getProviderConnectionConfig(url)); SslConfig sslConfig = new SslConfig(); sslConfig.setServerKeyCertChainPath("keyCert"); sslConfig.setServerPrivateKeyPath("private"); applicationModel.getApplicationConfigManager().setSsl(sslConfig); ProviderCert providerCert = sslConfigCertProvider.getProviderConnectionConfig(url); Assertions.assertNull(providerCert); sslConfig.setServerKeyCertChainPath( this.getClass().getClassLoader().getResource("certs/cert.pem").getFile()); sslConfig.setServerPrivateKeyPath( this.getClass().getClassLoader().getResource("certs/key.pem").getFile()); providerCert = sslConfigCertProvider.getProviderConnectionConfig(url); Assertions.assertNotNull(providerCert); Assertions.assertArrayEquals( IOUtils.toByteArray(this.getClass().getClassLoader().getResourceAsStream("certs/cert.pem")), providerCert.getKeyCertChain()); Assertions.assertArrayEquals( IOUtils.toByteArray(this.getClass().getClassLoader().getResourceAsStream("certs/key.pem")), providerCert.getPrivateKey()); Assertions.assertNull(providerCert.getTrustCert()); sslConfig.setServerTrustCertCollectionPath( this.getClass().getClassLoader().getResource("certs/ca.pem").getFile()); providerCert = sslConfigCertProvider.getProviderConnectionConfig(url); Assertions.assertNotNull(providerCert); Assertions.assertArrayEquals( IOUtils.toByteArray(this.getClass().getClassLoader().getResourceAsStream("certs/cert.pem")), providerCert.getKeyCertChain()); Assertions.assertArrayEquals( IOUtils.toByteArray(this.getClass().getClassLoader().getResourceAsStream("certs/key.pem")), providerCert.getPrivateKey()); Assertions.assertArrayEquals( IOUtils.toByteArray(this.getClass().getClassLoader().getResourceAsStream("certs/ca.pem")), providerCert.getTrustCert()); frameworkModel.destroy(); } @Test void testGetConsumerConnectionConfig() throws IOException { FrameworkModel frameworkModel = new FrameworkModel(); ApplicationModel applicationModel = frameworkModel.newApplication(); SSLConfigCertProvider sslConfigCertProvider = new SSLConfigCertProvider(); URL url = URL.valueOf("").setScopeModel(applicationModel); Assertions.assertNull(sslConfigCertProvider.getConsumerConnectionConfig(url)); SslConfig sslConfig = new SslConfig(); sslConfig.setClientKeyCertChainPath("keyCert"); sslConfig.setClientPrivateKeyPath("private"); applicationModel.getApplicationConfigManager().setSsl(sslConfig); Cert cert = sslConfigCertProvider.getConsumerConnectionConfig(url); Assertions.assertNull(cert); sslConfig.setClientKeyCertChainPath( this.getClass().getClassLoader().getResource("certs/cert.pem").getFile()); sslConfig.setClientPrivateKeyPath( this.getClass().getClassLoader().getResource("certs/key.pem").getFile()); cert = sslConfigCertProvider.getConsumerConnectionConfig(url); Assertions.assertNotNull(cert); Assertions.assertArrayEquals( IOUtils.toByteArray(this.getClass().getClassLoader().getResourceAsStream("certs/cert.pem")), cert.getKeyCertChain()); Assertions.assertArrayEquals( IOUtils.toByteArray(this.getClass().getClassLoader().getResourceAsStream("certs/key.pem")), cert.getPrivateKey()); sslConfig.setClientTrustCertCollectionPath( this.getClass().getClassLoader().getResource("certs/ca.pem").getFile()); cert = sslConfigCertProvider.getConsumerConnectionConfig(url); Assertions.assertNotNull(cert); Assertions.assertArrayEquals( IOUtils.toByteArray(this.getClass().getClassLoader().getResourceAsStream("certs/cert.pem")), cert.getKeyCertChain()); Assertions.assertArrayEquals( IOUtils.toByteArray(this.getClass().getClassLoader().getResourceAsStream("certs/key.pem")), cert.getPrivateKey()); Assertions.assertArrayEquals( IOUtils.toByteArray(this.getClass().getClassLoader().getResourceAsStream("certs/ca.pem")), cert.getTrustCert()); frameworkModel.destroy(); } }
6,277
0
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/ssl/FirstCertProvider.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.common.ssl; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Activate; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; @Activate(order = -10000) public class FirstCertProvider implements CertProvider { private static final AtomicBoolean isSupport = new AtomicBoolean(false); private static final AtomicReference<ProviderCert> providerCert = new AtomicReference<>(); private static final AtomicReference<Cert> cert = new AtomicReference<>(); @Override public boolean isSupport(URL address) { return isSupport.get(); } @Override public ProviderCert getProviderConnectionConfig(URL localAddress) { return providerCert.get(); } @Override public Cert getConsumerConnectionConfig(URL remoteAddress) { return cert.get(); } public static void setSupport(boolean support) { isSupport.set(support); } public static void setProviderCert(ProviderCert providerCert) { FirstCertProvider.providerCert.set(providerCert); } public static void setCert(Cert cert) { FirstCertProvider.cert.set(cert); } }
6,278
0
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/ssl/SecondCertProvider.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.common.ssl; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Activate; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; @Activate(order = 10000) public class SecondCertProvider implements CertProvider { private static final AtomicBoolean isSupport = new AtomicBoolean(false); private static final AtomicReference<ProviderCert> providerCert = new AtomicReference<>(); private static final AtomicReference<Cert> cert = new AtomicReference<>(); @Override public boolean isSupport(URL address) { return isSupport.get(); } @Override public ProviderCert getProviderConnectionConfig(URL localAddress) { return providerCert.get(); } @Override public Cert getConsumerConnectionConfig(URL remoteAddress) { return cert.get(); } public static void setSupport(boolean support) { isSupport.set(support); } public static void setProviderCert(ProviderCert providerCert) { SecondCertProvider.providerCert.set(providerCert); } public static void setCert(Cert cert) { SecondCertProvider.cert.set(cert); } }
6,279
0
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/ssl/CertManagerTest.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.common.ssl; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.model.FrameworkModel; 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.Mockito; class CertManagerTest { private FrameworkModel frameworkModel; private URL url; @BeforeEach void setup() { FirstCertProvider.setProviderCert(null); FirstCertProvider.setCert(null); FirstCertProvider.setSupport(false); SecondCertProvider.setProviderCert(null); SecondCertProvider.setCert(null); SecondCertProvider.setSupport(false); frameworkModel = new FrameworkModel(); url = URL.valueOf("dubbo://").setScopeModel(frameworkModel.newApplication()); } @AfterEach void teardown() { frameworkModel.destroy(); } @Test void testGetConsumerConnectionConfig() { CertManager certManager = new CertManager(frameworkModel); Assertions.assertNull(certManager.getConsumerConnectionConfig(url)); Cert cert1 = Mockito.mock(Cert.class); FirstCertProvider.setCert(cert1); Assertions.assertNull(certManager.getConsumerConnectionConfig(url)); FirstCertProvider.setSupport(true); Assertions.assertEquals(cert1, certManager.getConsumerConnectionConfig(url)); Cert cert2 = Mockito.mock(Cert.class); SecondCertProvider.setCert(cert2); Assertions.assertEquals(cert1, certManager.getConsumerConnectionConfig(url)); SecondCertProvider.setSupport(true); Assertions.assertEquals(cert1, certManager.getConsumerConnectionConfig(url)); FirstCertProvider.setSupport(false); Assertions.assertEquals(cert2, certManager.getConsumerConnectionConfig(url)); FirstCertProvider.setSupport(true); FirstCertProvider.setCert(null); Assertions.assertEquals(cert2, certManager.getConsumerConnectionConfig(url)); } @Test void testGetProviderConnectionConfig() { CertManager certManager = new CertManager(frameworkModel); Assertions.assertNull(certManager.getProviderConnectionConfig(url, null)); ProviderCert providerCert1 = Mockito.mock(ProviderCert.class); FirstCertProvider.setProviderCert(providerCert1); Assertions.assertNull(certManager.getProviderConnectionConfig(url, null)); FirstCertProvider.setSupport(true); Assertions.assertEquals(providerCert1, certManager.getProviderConnectionConfig(url, null)); ProviderCert providerCert2 = Mockito.mock(ProviderCert.class); SecondCertProvider.setProviderCert(providerCert2); Assertions.assertEquals(providerCert1, certManager.getProviderConnectionConfig(url, null)); SecondCertProvider.setSupport(true); Assertions.assertEquals(providerCert1, certManager.getProviderConnectionConfig(url, null)); FirstCertProvider.setSupport(false); Assertions.assertEquals(providerCert2, certManager.getProviderConnectionConfig(url, null)); FirstCertProvider.setSupport(true); FirstCertProvider.setProviderCert(null); Assertions.assertEquals(providerCert2, certManager.getProviderConnectionConfig(url, null)); } }
6,280
0
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/extension/SPI1Impl.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.common.extension; @Activate public class SPI1Impl implements SPI1 { @Override public String sayHello() { return null; } }
6,281
0
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/extension/AdaptiveClassCodeGeneratorTest.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.common.extension; import org.apache.dubbo.common.extension.adaptive.HasAdaptiveExt; import org.apache.dubbo.common.utils.IOUtils; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.nio.charset.StandardCharsets; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertTrue; /** * {@link AdaptiveClassCodeGenerator} Test * * @since 2.7.5 */ class AdaptiveClassCodeGeneratorTest { @Test void testGenerate() throws IOException { AdaptiveClassCodeGenerator generator = new AdaptiveClassCodeGenerator(HasAdaptiveExt.class, "adaptive"); String value = generator.generate(); URL url = getClass().getResource("/org/apache/dubbo/common/extension/adaptive/HasAdaptiveExt$Adaptive"); try (InputStream inputStream = url.openStream()) { String content = IOUtils.read(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); // in Windows platform content get from resource contains \r delimiter content = content.replaceAll("\r", ""); assertTrue(content.contains(value)); } } }
6,282
0
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/extension/DubboExternalLoadingStrategy.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.common.extension; /** * Dubbo external {@link LoadingStrategy} for testing * * @since 2.7.7 */ public class DubboExternalLoadingStrategy implements LoadingStrategy { @Override public String directory() { return "META-INF/dubbo/external/"; } @Override public boolean overridden() { return true; } @Override public int getPriority() { return MAX_PRIORITY + 1; } }
6,283
0
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/extension/SPI4.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.common.extension; @SPI public interface SPI4 { String sayHello(); }
6,284
0
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoaderTest.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.common.extension; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.convert.Converter; import org.apache.dubbo.common.convert.StringToBooleanConverter; import org.apache.dubbo.common.convert.StringToDoubleConverter; import org.apache.dubbo.common.convert.StringToIntegerConverter; import org.apache.dubbo.common.extension.activate.ActivateExt1; import org.apache.dubbo.common.extension.activate.impl.ActivateExt1Impl1; import org.apache.dubbo.common.extension.activate.impl.GroupActivateExtImpl; import org.apache.dubbo.common.extension.activate.impl.OrderActivateExtImpl1; import org.apache.dubbo.common.extension.activate.impl.OrderActivateExtImpl2; import org.apache.dubbo.common.extension.activate.impl.ValueActivateExtImpl; import org.apache.dubbo.common.extension.convert.String2BooleanConverter; import org.apache.dubbo.common.extension.convert.String2DoubleConverter; import org.apache.dubbo.common.extension.convert.String2IntegerConverter; import org.apache.dubbo.common.extension.duplicated.DuplicatedOverriddenExt; import org.apache.dubbo.common.extension.duplicated.DuplicatedWithoutOverriddenExt; import org.apache.dubbo.common.extension.ext1.SimpleExt; import org.apache.dubbo.common.extension.ext1.impl.SimpleExtImpl1; import org.apache.dubbo.common.extension.ext1.impl.SimpleExtImpl2; import org.apache.dubbo.common.extension.ext10_multi_names.Ext10MultiNames; import org.apache.dubbo.common.extension.ext11_no_adaptive.NoAdaptiveExt; import org.apache.dubbo.common.extension.ext11_no_adaptive.NoAdaptiveExtImpl; import org.apache.dubbo.common.extension.ext2.Ext2; import org.apache.dubbo.common.extension.ext6_wrap.WrappedExt; import org.apache.dubbo.common.extension.ext6_wrap.WrappedExtWrapper; import org.apache.dubbo.common.extension.ext6_wrap.impl.Ext6Impl1; import org.apache.dubbo.common.extension.ext6_wrap.impl.Ext6Impl3; import org.apache.dubbo.common.extension.ext6_wrap.impl.Ext6Wrapper1; import org.apache.dubbo.common.extension.ext6_wrap.impl.Ext6Wrapper2; import org.apache.dubbo.common.extension.ext6_wrap.impl.Ext6Wrapper3; import org.apache.dubbo.common.extension.ext6_wrap.impl.Ext6Wrapper4; import org.apache.dubbo.common.extension.ext7.InitErrorExt; import org.apache.dubbo.common.extension.ext8_add.AddExt1; import org.apache.dubbo.common.extension.ext8_add.AddExt2; import org.apache.dubbo.common.extension.ext8_add.AddExt3; import org.apache.dubbo.common.extension.ext8_add.AddExt4; import org.apache.dubbo.common.extension.ext8_add.impl.AddExt1Impl1; import org.apache.dubbo.common.extension.ext8_add.impl.AddExt1_ManualAdaptive; import org.apache.dubbo.common.extension.ext8_add.impl.AddExt1_ManualAdd1; import org.apache.dubbo.common.extension.ext8_add.impl.AddExt1_ManualAdd2; import org.apache.dubbo.common.extension.ext8_add.impl.AddExt2_ManualAdaptive; import org.apache.dubbo.common.extension.ext8_add.impl.AddExt3_ManualAdaptive; import org.apache.dubbo.common.extension.ext8_add.impl.AddExt4_ManualAdaptive; import org.apache.dubbo.common.extension.ext9_empty.Ext9Empty; import org.apache.dubbo.common.extension.ext9_empty.impl.Ext9EmptyImpl; import org.apache.dubbo.common.extension.injection.InjectExt; import org.apache.dubbo.common.extension.injection.impl.InjectExtImpl; import org.apache.dubbo.common.extension.wrapper.Demo; import org.apache.dubbo.common.extension.wrapper.impl.DemoImpl; import org.apache.dubbo.common.extension.wrapper.impl.DemoWrapper; import org.apache.dubbo.common.extension.wrapper.impl.DemoWrapper2; import org.apache.dubbo.common.lang.Prioritized; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.extension.ExtensionLoader.getLoadingStrategies; import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.CoreMatchers.anyOf; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; class ExtensionLoaderTest { private <T> ExtensionLoader<T> getExtensionLoader(Class<T> type) { return ApplicationModel.defaultModel().getExtensionDirector().getExtensionLoader(type); } @Test void test_getExtensionLoader_Null() { try { getExtensionLoader(null); fail(); } catch (IllegalArgumentException expected) { assertThat(expected.getMessage(), containsString("Extension type == null")); } } @Test void test_getExtensionLoader_NotInterface() { try { getExtensionLoader(ExtensionLoaderTest.class); fail(); } catch (IllegalArgumentException expected) { assertThat( expected.getMessage(), containsString( "Extension type (class org.apache.dubbo.common.extension.ExtensionLoaderTest) is not an interface")); } } @Test void test_getExtensionLoader_NotSpiAnnotation() { try { getExtensionLoader(NoSpiExt.class); fail(); } catch (IllegalArgumentException expected) { assertThat( expected.getMessage(), allOf( containsString("org.apache.dubbo.common.extension.NoSpiExt"), containsString("is not an extension"), containsString("NOT annotated with @SPI"))); } } @Test void test_getDefaultExtension() { SimpleExt ext = getExtensionLoader(SimpleExt.class).getDefaultExtension(); assertThat(ext, instanceOf(SimpleExtImpl1.class)); String name = getExtensionLoader(SimpleExt.class).getDefaultExtensionName(); assertEquals("impl1", name); } @Test void test_getDefaultExtension_NULL() { Ext2 ext = getExtensionLoader(Ext2.class).getDefaultExtension(); assertNull(ext); String name = getExtensionLoader(Ext2.class).getDefaultExtensionName(); assertNull(name); } @Test void test_getExtension() { assertTrue(getExtensionLoader(SimpleExt.class).getExtension("impl1") instanceof SimpleExtImpl1); assertTrue(getExtensionLoader(SimpleExt.class).getExtension("impl2") instanceof SimpleExtImpl2); } @Test void test_getExtension_WithWrapper() { WrappedExt impl1 = getExtensionLoader(WrappedExt.class).getExtension("impl1"); assertThat(impl1, anyOf(instanceOf(Ext6Wrapper1.class), instanceOf(Ext6Wrapper2.class))); assertThat(impl1, instanceOf(WrappedExtWrapper.class)); // get origin instance from wrapper WrappedExt originImpl1 = impl1; while (originImpl1 instanceof WrappedExtWrapper) { originImpl1 = ((WrappedExtWrapper) originImpl1).getOrigin(); } // test unwrapped instance WrappedExt unwrappedImpl1 = getExtensionLoader(WrappedExt.class).getExtension("impl1", false); assertThat(unwrappedImpl1, instanceOf(Ext6Impl1.class)); assertNotSame(unwrappedImpl1, impl1); assertSame(unwrappedImpl1, originImpl1); WrappedExt impl2 = getExtensionLoader(WrappedExt.class).getExtension("impl2"); assertThat(impl2, anyOf(instanceOf(Ext6Wrapper1.class), instanceOf(Ext6Wrapper2.class))); URL url = new ServiceConfigURL("p1", "1.2.3.4", 1010, "path1"); int echoCount1 = Ext6Wrapper1.echoCount.get(); int echoCount2 = Ext6Wrapper2.echoCount.get(); assertEquals("Ext6Impl1-echo", impl1.echo(url, "ha")); assertEquals(echoCount1 + 1, Ext6Wrapper1.echoCount.get()); assertEquals(echoCount2 + 1, Ext6Wrapper2.echoCount.get()); } @Test void test_getExtension_withWrapperAnnotation() { WrappedExt impl3 = getExtensionLoader(WrappedExt.class).getExtension("impl3"); assertThat(impl3, instanceOf(Ext6Wrapper3.class)); WrappedExt originImpl3 = impl3; while (originImpl3 instanceof WrappedExtWrapper) { originImpl3 = ((WrappedExtWrapper) originImpl3).getOrigin(); } // test unwrapped instance WrappedExt unwrappedImpl3 = getExtensionLoader(WrappedExt.class).getExtension("impl3", false); assertThat(unwrappedImpl3, instanceOf(Ext6Impl3.class)); assertNotSame(unwrappedImpl3, impl3); assertSame(unwrappedImpl3, originImpl3); WrappedExt impl4 = getExtensionLoader(WrappedExt.class).getExtension("impl4"); assertThat(impl4, instanceOf(Ext6Wrapper4.class)); URL url = new ServiceConfigURL("p1", "1.2.3.4", 1010, "path1"); int echoCount3 = Ext6Wrapper3.echoCount.get(); int echoCount4 = Ext6Wrapper4.echoCount.get(); assertEquals("Ext6Impl4-echo", impl4.echo(url, "haha")); assertEquals(echoCount3, Ext6Wrapper3.echoCount.get()); assertEquals(echoCount4 + 1, Ext6Wrapper4.echoCount.get()); } @Test void test_getActivateExtension_WithWrapper1() { URL url = URL.valueOf("test://localhost/test"); List<ActivateExt1> list = getExtensionLoader(ActivateExt1.class).getActivateExtension(url, new String[] {}, "order"); assertEquals(2, list.size()); } @Test void test_getExtension_ExceptionNoExtension() { try { getExtensionLoader(SimpleExt.class).getExtension("XXX"); fail(); } catch (IllegalStateException expected) { assertThat( expected.getMessage(), containsString("No such extension org.apache.dubbo.common.extension.ext1.SimpleExt by name XXX")); } } @Test void test_getExtension_ExceptionNoExtension_WrapperNotAffactName() { try { getExtensionLoader(WrappedExt.class).getExtension("XXX"); fail(); } catch (IllegalStateException expected) { assertThat( expected.getMessage(), containsString( "No such extension org.apache.dubbo.common.extension.ext6_wrap.WrappedExt by name XXX")); } } @Test void test_getExtension_ExceptionNullArg() { try { getExtensionLoader(SimpleExt.class).getExtension(null); fail(); } catch (IllegalArgumentException expected) { assertThat(expected.getMessage(), containsString("Extension name == null")); } } @Test void test_hasExtension() { assertTrue(getExtensionLoader(SimpleExt.class).hasExtension("impl1")); assertFalse(getExtensionLoader(SimpleExt.class).hasExtension("impl1,impl2")); assertFalse(getExtensionLoader(SimpleExt.class).hasExtension("xxx")); try { getExtensionLoader(SimpleExt.class).hasExtension(null); fail(); } catch (IllegalArgumentException expected) { assertThat(expected.getMessage(), containsString("Extension name == null")); } } @Test void test_hasExtension_wrapperIsNotExt() { assertTrue(getExtensionLoader(WrappedExt.class).hasExtension("impl1")); assertFalse(getExtensionLoader(WrappedExt.class).hasExtension("impl1,impl2")); assertFalse(getExtensionLoader(WrappedExt.class).hasExtension("xxx")); assertFalse(getExtensionLoader(WrappedExt.class).hasExtension("wrapper1")); try { getExtensionLoader(WrappedExt.class).hasExtension(null); fail(); } catch (IllegalArgumentException expected) { assertThat(expected.getMessage(), containsString("Extension name == null")); } } @Test void test_getSupportedExtensions() { Set<String> exts = getExtensionLoader(SimpleExt.class).getSupportedExtensions(); Set<String> expected = new HashSet<>(); expected.add("impl1"); expected.add("impl2"); expected.add("impl3"); assertEquals(expected, exts); } @Test void test_getSupportedExtensions_wrapperIsNotExt() { Set<String> exts = getExtensionLoader(WrappedExt.class).getSupportedExtensions(); Set<String> expected = new HashSet<>(); expected.add("impl1"); expected.add("impl2"); expected.add("impl3"); expected.add("impl4"); assertEquals(expected, exts); } @Test void test_AddExtension() { try { getExtensionLoader(AddExt1.class).getExtension("Manual1"); fail(); } catch (IllegalStateException expected) { assertThat( expected.getMessage(), containsString( "No such extension org.apache.dubbo.common.extension.ext8_add.AddExt1 by name Manual")); } getExtensionLoader(AddExt1.class).addExtension("Manual1", AddExt1_ManualAdd1.class); AddExt1 ext = getExtensionLoader(AddExt1.class).getExtension("Manual1"); assertThat(ext, instanceOf(AddExt1_ManualAdd1.class)); assertEquals("Manual1", getExtensionLoader(AddExt1.class).getExtensionName(AddExt1_ManualAdd1.class)); } @Test void test_AddExtension_NoExtend() { getExtensionLoader(Ext9Empty.class).addExtension("ext9", Ext9EmptyImpl.class); Ext9Empty ext = getExtensionLoader(Ext9Empty.class).getExtension("ext9"); assertThat(ext, instanceOf(Ext9Empty.class)); assertEquals("ext9", getExtensionLoader(Ext9Empty.class).getExtensionName(Ext9EmptyImpl.class)); } @Test void test_AddExtension_ExceptionWhenExistedExtension() { SimpleExt ext = getExtensionLoader(SimpleExt.class).getExtension("impl1"); try { getExtensionLoader(AddExt1.class).addExtension("impl1", AddExt1_ManualAdd1.class); fail(); } catch (IllegalStateException expected) { assertThat( expected.getMessage(), containsString( "Extension name impl1 already exists (Extension interface org.apache.dubbo.common.extension.ext8_add.AddExt1)!")); } } @Test void test_AddExtension_Adaptive() { ExtensionLoader<AddExt2> loader = getExtensionLoader(AddExt2.class); loader.addExtension(null, AddExt2_ManualAdaptive.class); AddExt2 adaptive = loader.getAdaptiveExtension(); assertTrue(adaptive instanceof AddExt2_ManualAdaptive); } @Test void test_AddExtension_Adaptive_ExceptionWhenExistedAdaptive() { ExtensionLoader<AddExt1> loader = getExtensionLoader(AddExt1.class); loader.getAdaptiveExtension(); try { loader.addExtension(null, AddExt1_ManualAdaptive.class); fail(); } catch (IllegalStateException expected) { assertThat( expected.getMessage(), containsString( "Adaptive Extension already exists (Extension interface org.apache.dubbo.common.extension.ext8_add.AddExt1)!")); } } @Test void test_addExtension_with_error_class() { try { getExtensionLoader(SimpleExt.class).addExtension("impl1", ExtensionLoaderTest.class); } catch (IllegalStateException expected) { assertThat( expected.getMessage(), containsString( "Input type class org.apache.dubbo.common.extension.ExtensionLoaderTest " + "doesn't implement the Extension interface org.apache.dubbo.common.extension.ext1.SimpleExt")); } } @Test void test_addExtension_with_interface() { try { getExtensionLoader(SimpleExt.class).addExtension("impl1", SimpleExt.class); } catch (IllegalStateException expected) { assertThat( expected.getMessage(), containsString("Input type interface org.apache.dubbo.common.extension.ext1.SimpleExt " + "can't be interface!")); } } @Test void test_addExtension_without_adaptive_annotation() { try { getExtensionLoader(NoAdaptiveExt.class).addExtension(null, NoAdaptiveExtImpl.class); } catch (IllegalStateException expected) { assertThat( expected.getMessage(), containsString( "Extension name is blank " + "(Extension interface org.apache.dubbo.common.extension.ext11_no_adaptive.NoAdaptiveExt)!")); } } @Test void test_getLoadedExtension_name_with_null() { try { getExtensionLoader(SimpleExt.class).getLoadedExtension(null); } catch (IllegalArgumentException expected) { assertThat(expected.getMessage(), containsString("Extension name == null")); } } @Test void test_getLoadedExtension_null() { SimpleExt impl1 = getExtensionLoader(SimpleExt.class).getLoadedExtension("XXX"); assertNull(impl1); } @Test void test_getLoadedExtension() { SimpleExt simpleExt = getExtensionLoader(SimpleExt.class).getExtension("impl1"); assertThat(simpleExt, instanceOf(SimpleExtImpl1.class)); SimpleExt simpleExt1 = getExtensionLoader(SimpleExt.class).getLoadedExtension("impl1"); assertThat(simpleExt1, instanceOf(SimpleExtImpl1.class)); } @Test void test_getLoadedExtensions() { SimpleExt simpleExt1 = getExtensionLoader(SimpleExt.class).getExtension("impl1"); assertThat(simpleExt1, instanceOf(SimpleExtImpl1.class)); SimpleExt simpleExt2 = getExtensionLoader(SimpleExt.class).getExtension("impl2"); assertThat(simpleExt2, instanceOf(SimpleExtImpl2.class)); Set<String> loadedExtensions = getExtensionLoader(SimpleExt.class).getLoadedExtensions(); Assertions.assertNotNull(loadedExtensions); } @Test void test_getLoadedExtensionInstances() { SimpleExt simpleExt1 = getExtensionLoader(SimpleExt.class).getExtension("impl1"); assertThat(simpleExt1, instanceOf(SimpleExtImpl1.class)); SimpleExt simpleExt2 = getExtensionLoader(SimpleExt.class).getExtension("impl2"); assertThat(simpleExt2, instanceOf(SimpleExtImpl2.class)); List<SimpleExt> loadedExtensionInstances = getExtensionLoader(SimpleExt.class).getLoadedExtensionInstances(); Assertions.assertNotNull(loadedExtensionInstances); } @Test void test_replaceExtension_with_error_class() { try { getExtensionLoader(SimpleExt.class).replaceExtension("impl1", ExtensionLoaderTest.class); } catch (IllegalStateException expected) { assertThat( expected.getMessage(), containsString( "Input type class org.apache.dubbo.common.extension.ExtensionLoaderTest " + "doesn't implement Extension interface org.apache.dubbo.common.extension.ext1.SimpleExt")); } } @Test void test_replaceExtension_with_interface() { try { getExtensionLoader(SimpleExt.class).replaceExtension("impl1", SimpleExt.class); } catch (IllegalStateException expected) { assertThat( expected.getMessage(), containsString("Input type interface org.apache.dubbo.common.extension.ext1.SimpleExt " + "can't be interface!")); } } @Test void test_replaceExtension() { try { getExtensionLoader(AddExt1.class).getExtension("Manual2"); fail(); } catch (IllegalStateException expected) { assertThat( expected.getMessage(), containsString( "No such extension org.apache.dubbo.common.extension.ext8_add.AddExt1 by name Manual")); } { AddExt1 ext = getExtensionLoader(AddExt1.class).getExtension("impl1"); assertThat(ext, instanceOf(AddExt1Impl1.class)); assertEquals("impl1", getExtensionLoader(AddExt1.class).getExtensionName(AddExt1Impl1.class)); } { getExtensionLoader(AddExt1.class).replaceExtension("impl1", AddExt1_ManualAdd2.class); AddExt1 ext = getExtensionLoader(AddExt1.class).getExtension("impl1"); assertThat(ext, instanceOf(AddExt1_ManualAdd2.class)); assertEquals("impl1", getExtensionLoader(AddExt1.class).getExtensionName(AddExt1_ManualAdd2.class)); } } @Test void test_replaceExtension_Adaptive() { ExtensionLoader<AddExt3> loader = getExtensionLoader(AddExt3.class); AddExt3 adaptive = loader.getAdaptiveExtension(); assertFalse(adaptive instanceof AddExt3_ManualAdaptive); loader.replaceExtension(null, AddExt3_ManualAdaptive.class); adaptive = loader.getAdaptiveExtension(); assertTrue(adaptive instanceof AddExt3_ManualAdaptive); } @Test void test_replaceExtension_ExceptionWhenNotExistedExtension() { AddExt1 ext = getExtensionLoader(AddExt1.class).getExtension("impl1"); try { getExtensionLoader(AddExt1.class).replaceExtension("NotExistedExtension", AddExt1_ManualAdd1.class); fail(); } catch (IllegalStateException expected) { assertThat( expected.getMessage(), containsString( "Extension name NotExistedExtension doesn't exist (Extension interface org.apache.dubbo.common.extension.ext8_add.AddExt1)")); } } @Test void test_replaceExtension_Adaptive_ExceptionWhenNotExistedExtension() { ExtensionLoader<AddExt4> loader = getExtensionLoader(AddExt4.class); try { loader.replaceExtension(null, AddExt4_ManualAdaptive.class); fail(); } catch (IllegalStateException expected) { assertThat( expected.getMessage(), containsString( "Adaptive Extension doesn't exist (Extension interface org.apache.dubbo.common.extension.ext8_add.AddExt4)")); } } @Test void test_InitError() { ExtensionLoader<InitErrorExt> loader = getExtensionLoader(InitErrorExt.class); loader.getExtension("ok"); try { loader.getExtension("error"); fail(); } catch (IllegalStateException expected) { assertThat( expected.getMessage(), containsString( "Failed to load extension class (interface: interface org.apache.dubbo.common.extension.ext7.InitErrorExt")); assertThat(expected.getMessage(), containsString("java.lang.ExceptionInInitializerError")); } } @Test void testLoadActivateExtension() { // test default URL url = URL.valueOf("test://localhost/test"); List<ActivateExt1> list = getExtensionLoader(ActivateExt1.class).getActivateExtension(url, new String[] {}, "default_group"); Assertions.assertEquals(1, list.size()); assertSame(list.get(0).getClass(), ActivateExt1Impl1.class); // test group url = url.addParameter(GROUP_KEY, "group1"); list = getExtensionLoader(ActivateExt1.class).getActivateExtension(url, new String[] {}, "group1"); Assertions.assertEquals(1, list.size()); assertSame(list.get(0).getClass(), GroupActivateExtImpl.class); // test value url = url.removeParameter(GROUP_KEY); url = url.addParameter(GROUP_KEY, "value"); url = url.addParameter("value", "value"); list = getExtensionLoader(ActivateExt1.class).getActivateExtension(url, new String[] {}, "value"); Assertions.assertEquals(1, list.size()); assertSame(list.get(0).getClass(), ValueActivateExtImpl.class); // test order url = URL.valueOf("test://localhost/test"); url = url.addParameter(GROUP_KEY, "order"); list = getExtensionLoader(ActivateExt1.class).getActivateExtension(url, new String[] {}, "order"); Assertions.assertEquals(2, list.size()); assertSame(list.get(0).getClass(), OrderActivateExtImpl1.class); assertSame(list.get(1).getClass(), OrderActivateExtImpl2.class); } @Test void testLoadDefaultActivateExtension1() { // test default URL url = URL.valueOf("test://localhost/test?ext=order1,default"); List<ActivateExt1> list = getExtensionLoader(ActivateExt1.class).getActivateExtension(url, "ext", "default_group"); Assertions.assertEquals(2, list.size()); assertSame(list.get(0).getClass(), OrderActivateExtImpl1.class); assertSame(list.get(1).getClass(), ActivateExt1Impl1.class); url = URL.valueOf("test://localhost/test?ext=default,order1"); list = getExtensionLoader(ActivateExt1.class).getActivateExtension(url, "ext", "default_group"); Assertions.assertEquals(2, list.size()); assertSame(list.get(0).getClass(), ActivateExt1Impl1.class); assertSame(list.get(1).getClass(), OrderActivateExtImpl1.class); url = URL.valueOf("test://localhost/test?ext=order1"); list = getExtensionLoader(ActivateExt1.class).getActivateExtension(url, "ext", "default_group"); Assertions.assertEquals(2, list.size()); assertSame(list.get(0).getClass(), ActivateExt1Impl1.class); assertSame(list.get(1).getClass(), OrderActivateExtImpl1.class); } @Test void testLoadDefaultActivateExtension2() { // test default URL url = URL.valueOf("test://localhost/test?ext=order1 , default"); List<ActivateExt1> list = getExtensionLoader(ActivateExt1.class).getActivateExtension(url, "ext", "default_group"); Assertions.assertEquals(2, list.size()); assertSame(list.get(0).getClass(), OrderActivateExtImpl1.class); assertSame(list.get(1).getClass(), ActivateExt1Impl1.class); url = URL.valueOf("test://localhost/test?ext=default, order1"); list = getExtensionLoader(ActivateExt1.class).getActivateExtension(url, "ext", "default_group"); Assertions.assertEquals(2, list.size()); assertSame(list.get(0).getClass(), ActivateExt1Impl1.class); assertSame(list.get(1).getClass(), OrderActivateExtImpl1.class); url = URL.valueOf("test://localhost/test?ext=order1"); list = getExtensionLoader(ActivateExt1.class).getActivateExtension(url, "ext", "default_group"); Assertions.assertEquals(2, list.size()); assertSame(list.get(0).getClass(), ActivateExt1Impl1.class); assertSame(list.get(1).getClass(), OrderActivateExtImpl1.class); } @Test void testInjectExtension() { // register bean for test ScopeBeanExtensionInjector DemoImpl demoBean = new DemoImpl(); ApplicationModel.defaultModel().getBeanFactory().registerBean(demoBean); // test default InjectExt injectExt = getExtensionLoader(InjectExt.class).getExtension("injection"); InjectExtImpl injectExtImpl = (InjectExtImpl) injectExt; Assertions.assertNotNull(injectExtImpl.getSimpleExt()); Assertions.assertNull(injectExtImpl.getSimpleExt1()); Assertions.assertNull(injectExtImpl.getGenericType()); Assertions.assertSame(demoBean, injectExtImpl.getDemo()); } @Test void testMultiNames() { Ext10MultiNames ext10MultiNames = getExtensionLoader(Ext10MultiNames.class).getExtension("impl"); Assertions.assertNotNull(ext10MultiNames); ext10MultiNames = getExtensionLoader(Ext10MultiNames.class).getExtension("implMultiName"); Assertions.assertNotNull(ext10MultiNames); Assertions.assertThrows(IllegalStateException.class, () -> getExtensionLoader(Ext10MultiNames.class) .getExtension("impl,implMultiName")); } @Test void testGetOrDefaultExtension() { ExtensionLoader<InjectExt> loader = getExtensionLoader(InjectExt.class); InjectExt injectExt = loader.getOrDefaultExtension("non-exists"); assertEquals(InjectExtImpl.class, injectExt.getClass()); assertEquals( InjectExtImpl.class, loader.getOrDefaultExtension("injection").getClass()); } @Test void testGetSupported() { ExtensionLoader<InjectExt> loader = getExtensionLoader(InjectExt.class); assertEquals(1, loader.getSupportedExtensions().size()); assertEquals(Collections.singleton("injection"), loader.getSupportedExtensions()); } /** * @since 2.7.7 */ @Test void testOverridden() { ExtensionLoader<Converter> loader = getExtensionLoader(Converter.class); Converter converter = loader.getExtension("string-to-boolean"); assertEquals(String2BooleanConverter.class, converter.getClass()); converter = loader.getExtension("string-to-double"); assertEquals(String2DoubleConverter.class, converter.getClass()); converter = loader.getExtension("string-to-integer"); assertEquals(String2IntegerConverter.class, converter.getClass()); assertEquals("string-to-boolean", loader.getExtensionName(String2BooleanConverter.class)); assertEquals("string-to-boolean", loader.getExtensionName(StringToBooleanConverter.class)); assertEquals("string-to-double", loader.getExtensionName(String2DoubleConverter.class)); assertEquals("string-to-double", loader.getExtensionName(StringToDoubleConverter.class)); assertEquals("string-to-integer", loader.getExtensionName(String2IntegerConverter.class)); assertEquals("string-to-integer", loader.getExtensionName(StringToIntegerConverter.class)); } /** * @since 2.7.7 */ @Test void testGetLoadingStrategies() { List<LoadingStrategy> strategies = getLoadingStrategies(); assertEquals(4, strategies.size()); int i = 0; LoadingStrategy loadingStrategy = strategies.get(i++); assertEquals(DubboInternalLoadingStrategy.class, loadingStrategy.getClass()); assertEquals(Prioritized.MAX_PRIORITY, loadingStrategy.getPriority()); loadingStrategy = strategies.get(i++); assertEquals(DubboExternalLoadingStrategy.class, loadingStrategy.getClass()); assertEquals(Prioritized.MAX_PRIORITY + 1, loadingStrategy.getPriority()); loadingStrategy = strategies.get(i++); assertEquals(DubboLoadingStrategy.class, loadingStrategy.getClass()); assertEquals(Prioritized.NORMAL_PRIORITY, loadingStrategy.getPriority()); loadingStrategy = strategies.get(i++); assertEquals(ServicesLoadingStrategy.class, loadingStrategy.getClass()); assertEquals(Prioritized.MIN_PRIORITY, loadingStrategy.getPriority()); } @Test void testDuplicatedImplWithoutOverriddenStrategy() { List<LoadingStrategy> loadingStrategies = ExtensionLoader.getLoadingStrategies(); ExtensionLoader.setLoadingStrategies( new DubboExternalLoadingStrategyTest(false), new DubboInternalLoadingStrategyTest(false)); ExtensionLoader<DuplicatedWithoutOverriddenExt> extensionLoader = getExtensionLoader(DuplicatedWithoutOverriddenExt.class); try { extensionLoader.getExtension("duplicated"); fail(); } catch (IllegalStateException expected) { assertThat( expected.getMessage(), containsString( "Failed to load extension class (interface: interface org.apache.dubbo.common.extension.duplicated.DuplicatedWithoutOverriddenExt")); assertThat( expected.getMessage(), containsString( "cause: Duplicate extension org.apache.dubbo.common.extension.duplicated.DuplicatedWithoutOverriddenExt name duplicated")); } finally { // recover the loading strategies ExtensionLoader.setLoadingStrategies( loadingStrategies.toArray(new LoadingStrategy[loadingStrategies.size()])); } } @Test void testDuplicatedImplWithOverriddenStrategy() { List<LoadingStrategy> loadingStrategies = ExtensionLoader.getLoadingStrategies(); ExtensionLoader.setLoadingStrategies( new DubboExternalLoadingStrategyTest(true), new DubboInternalLoadingStrategyTest(true)); ExtensionLoader<DuplicatedOverriddenExt> extensionLoader = getExtensionLoader(DuplicatedOverriddenExt.class); DuplicatedOverriddenExt duplicatedOverriddenExt = extensionLoader.getExtension("duplicated"); assertEquals("DuplicatedOverriddenExt1", duplicatedOverriddenExt.echo()); // recover the loading strategies ExtensionLoader.setLoadingStrategies(loadingStrategies.toArray(new LoadingStrategy[loadingStrategies.size()])); } @Test void testLoadByDubboInternalSPI() { ExtensionLoader<SPI1> extensionLoader = getExtensionLoader(SPI1.class); SPI1 spi1 = extensionLoader.getExtension("1", true); assertNotNull(spi1); ExtensionLoader<SPI2> extensionLoader2 = getExtensionLoader(SPI2.class); SPI2 spi2 = extensionLoader2.getExtension("2", true); assertNotNull(spi2); try { ExtensionLoader<SPI3> extensionLoader3 = getExtensionLoader(SPI3.class); SPI3 spi3 = extensionLoader3.getExtension("3", true); assertNotNull(spi3); } catch (IllegalStateException illegalStateException) { if (!illegalStateException.getMessage().contains("No such extension")) { fail(); } } ExtensionLoader<SPI4> extensionLoader4 = getExtensionLoader(SPI4.class); SPI4 spi4 = extensionLoader4.getExtension("4", true); assertNotNull(spi4); } @Test void isWrapperClass() { assertFalse(getExtensionLoader(Demo.class).isWrapperClass(DemoImpl.class)); assertTrue(getExtensionLoader(Demo.class).isWrapperClass(DemoWrapper.class)); assertTrue(getExtensionLoader(Demo.class).isWrapperClass(DemoWrapper2.class)); } /** * The external {@link LoadingStrategy}, which can set if it supports overriding. */ private static class DubboExternalLoadingStrategyTest implements LoadingStrategy { public DubboExternalLoadingStrategyTest(boolean overridden) { this.overridden = overridden; } private boolean overridden; @Override public String directory() { return "META-INF/dubbo/external/"; } @Override public boolean overridden() { return this.overridden; } @Override public int getPriority() { return MAX_PRIORITY + 1; } } /** * The internal {@link LoadingStrategy}, which can set if it support overridden */ private static class DubboInternalLoadingStrategyTest implements LoadingStrategy { public DubboInternalLoadingStrategyTest(boolean overridden) { this.overridden = overridden; } private boolean overridden; @Override public String directory() { return "META-INF/dubbo/internal/"; } @Override public boolean overridden() { return this.overridden; } @Override public int getPriority() { return MAX_PRIORITY; } } }
6,285
0
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/extension/SPI2.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.common.extension; @SPI public interface SPI2 { String sayHello(); }
6,286
0
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/extension/NoSpiExt.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.common.extension; import org.apache.dubbo.common.URL; /** * Has no SPI annotation */ public interface NoSpiExt { @Adaptive String echo(URL url, String s); }
6,287
0
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoader_Adaptive_UseJdkCompiler_Test.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.common.extension; import org.apache.dubbo.common.compiler.support.AdaptiveCompiler; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; class ExtensionLoader_Adaptive_UseJdkCompiler_Test extends ExtensionLoader_Adaptive_Test { @BeforeAll public static void setUp() throws Exception { AdaptiveCompiler.setDefaultCompiler("jdk"); } @AfterAll public static void tearDown() throws Exception { AdaptiveCompiler.setDefaultCompiler("javassist"); } }
6,288
0
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/extension/SPI3.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.common.extension; @SPI public interface SPI3 { String sayHello(); }
6,289
0
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionDirectorTest.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.common.extension; import org.apache.dubbo.common.extension.director.FooAppService; import org.apache.dubbo.common.extension.director.FooFrameworkService; import org.apache.dubbo.common.extension.director.FooModuleService; import org.apache.dubbo.common.extension.director.impl.TestAppService; import org.apache.dubbo.common.extension.director.impl.TestFrameworkService; import org.apache.dubbo.common.extension.director.impl.TestModuleService; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleModel; import java.util.Collection; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class ExtensionDirectorTest { String testFwSrvName = "testFwSrv"; String testAppSrvName = "testAppSrv"; String testMdSrvName = "testMdSrv"; @Test void testInheritanceAndScope() { // Expecting: // 1. SPI extension only be created in ExtensionDirector which matched scope // 2. Child ExtensionDirector can get extension instance from parent // 3. Parent ExtensionDirector can't get extension instance from child ExtensionDirector fwExtensionDirector = new ExtensionDirector(null, ExtensionScope.FRAMEWORK, FrameworkModel.defaultModel()); ExtensionDirector appExtensionDirector = new ExtensionDirector(fwExtensionDirector, ExtensionScope.APPLICATION, ApplicationModel.defaultModel()); ExtensionDirector moduleExtensionDirector = new ExtensionDirector( appExtensionDirector, ExtensionScope.MODULE, ApplicationModel.defaultModel().getDefaultModule()); // test module extension loader FooFrameworkService testFwSrvFromModule = moduleExtensionDirector.getExtension(FooFrameworkService.class, testFwSrvName); FooAppService testAppSrvFromModule = moduleExtensionDirector.getExtension(FooAppService.class, testAppSrvName); FooModuleService testMdSrvFromModule = moduleExtensionDirector.getExtension(FooModuleService.class, testMdSrvName); Assertions.assertNotNull(testFwSrvFromModule); Assertions.assertNotNull(testAppSrvFromModule); Assertions.assertNotNull(testMdSrvFromModule); // test app extension loader FooFrameworkService testFwSrvFromApp = appExtensionDirector.getExtension(FooFrameworkService.class, testFwSrvName); FooAppService testAppSrvFromApp = appExtensionDirector.getExtension(FooAppService.class, testAppSrvName); FooModuleService testMdSrvFromApp = appExtensionDirector.getExtension(FooModuleService.class, testMdSrvName); Assertions.assertSame(testFwSrvFromApp, testFwSrvFromModule); Assertions.assertSame(testAppSrvFromApp, testAppSrvFromModule); Assertions.assertNull(testMdSrvFromApp); // test framework extension loader FooFrameworkService testFwSrvFromFw = fwExtensionDirector.getExtension(FooFrameworkService.class, testFwSrvName); FooAppService testAppSrvFromFw = fwExtensionDirector.getExtension(FooAppService.class, testAppSrvName); FooModuleService testMdSrvFromFw = fwExtensionDirector.getExtension(FooModuleService.class, testMdSrvName); Assertions.assertSame(testFwSrvFromFw, testFwSrvFromApp); Assertions.assertNull(testAppSrvFromFw); Assertions.assertNull(testMdSrvFromFw); } @Test void testPostProcessor() {} @Test void testModelAware() { // Expecting: // 1. Module scope SPI can be injected ModuleModel, ApplicationModel, FrameworkModel // 2. Application scope SPI can be injected ApplicationModel, FrameworkModel, but not ModuleModel // 3. Framework scope SPI can be injected FrameworkModel, but not ModuleModel, ApplicationModel FrameworkModel frameworkModel = new FrameworkModel(); ApplicationModel applicationModel = frameworkModel.newApplication(); ModuleModel moduleModel = applicationModel.newModule(); ExtensionDirector moduleExtensionDirector = moduleModel.getExtensionDirector(); ExtensionDirector appExtensionDirector = applicationModel.getExtensionDirector(); ExtensionDirector fwExtensionDirector = frameworkModel.getExtensionDirector(); // check extension director inheritance Assertions.assertSame(appExtensionDirector, moduleExtensionDirector.getParent()); Assertions.assertSame(fwExtensionDirector, appExtensionDirector.getParent()); Assertions.assertSame(null, fwExtensionDirector.getParent()); // check module extension aware TestFrameworkService testFwSrvFromModule = (TestFrameworkService) moduleExtensionDirector.getExtension(FooFrameworkService.class, testFwSrvName); TestAppService testAppSrvFromModule = (TestAppService) moduleExtensionDirector.getExtension(FooAppService.class, testAppSrvName); TestModuleService testMdSrvFromModule = (TestModuleService) moduleExtensionDirector.getExtension(FooModuleService.class, testMdSrvName); Assertions.assertSame(frameworkModel, testFwSrvFromModule.getFrameworkModel()); Assertions.assertSame(null, testFwSrvFromModule.getApplicationModel()); Assertions.assertSame(null, testFwSrvFromModule.getModuleModel()); Assertions.assertSame(frameworkModel, testAppSrvFromModule.getFrameworkModel()); Assertions.assertSame(applicationModel, testAppSrvFromModule.getApplicationModel()); Assertions.assertSame(null, testAppSrvFromModule.getModuleModel()); Assertions.assertSame(frameworkModel, testMdSrvFromModule.getFrameworkModel()); Assertions.assertSame(applicationModel, testMdSrvFromModule.getApplicationModel()); Assertions.assertSame(moduleModel, testMdSrvFromModule.getModuleModel()); // check app extension aware TestFrameworkService testFwSrvFromApp = (TestFrameworkService) appExtensionDirector.getExtension(FooFrameworkService.class, testFwSrvName); TestAppService testAppSrvFromApp = (TestAppService) appExtensionDirector.getExtension(FooAppService.class, testAppSrvName); TestModuleService testMdSrvFromApp = (TestModuleService) appExtensionDirector.getExtension(FooModuleService.class, testMdSrvName); Assertions.assertSame(testFwSrvFromApp, testFwSrvFromModule); Assertions.assertSame(testAppSrvFromApp, testAppSrvFromModule); Assertions.assertNull(testMdSrvFromApp); // check framework extension aware FooFrameworkService testFwSrvFromFw = fwExtensionDirector.getExtension(FooFrameworkService.class, testFwSrvName); FooAppService testAppSrvFromFw = fwExtensionDirector.getExtension(FooAppService.class, testAppSrvName); FooModuleService testMdSrvFromFw = fwExtensionDirector.getExtension(FooModuleService.class, testMdSrvName); Assertions.assertSame(testFwSrvFromFw, testFwSrvFromApp); Assertions.assertNull(testAppSrvFromFw); Assertions.assertNull(testMdSrvFromFw); } @Test void testModelDataIsolation() { // Model Tree // ├─frameworkModel1 // │ ├─applicationModel11 // │ │ ├─moduleModel111 // │ │ └─moduleModel112 // │ └─applicationModel12 // │ └─moduleModel121 // └─frameworkModel2 // └─applicationModel21 // └─moduleModel211 FrameworkModel frameworkModel1 = new FrameworkModel(); ApplicationModel applicationModel11 = frameworkModel1.newApplication(); ModuleModel moduleModel111 = applicationModel11.newModule(); ModuleModel moduleModel112 = applicationModel11.newModule(); ApplicationModel applicationModel12 = frameworkModel1.newApplication(); ModuleModel moduleModel121 = applicationModel12.newModule(); FrameworkModel frameworkModel2 = new FrameworkModel(); ApplicationModel applicationModel21 = frameworkModel2.newApplication(); ModuleModel moduleModel211 = applicationModel21.newModule(); // test model references Collection<ApplicationModel> applicationsOfFw1 = frameworkModel1.getApplicationModels(); Assertions.assertEquals(2, applicationsOfFw1.size()); Assertions.assertTrue(applicationsOfFw1.contains(applicationModel11)); Assertions.assertTrue(applicationsOfFw1.contains(applicationModel12)); Assertions.assertFalse(applicationsOfFw1.contains(applicationModel21)); Collection<ModuleModel> modulesOfApp11 = applicationModel11.getModuleModels(); Assertions.assertTrue(modulesOfApp11.contains(moduleModel111)); Assertions.assertTrue(modulesOfApp11.contains(moduleModel112)); // test isolation of FrameworkModel FooFrameworkService frameworkService1 = frameworkModel1.getExtensionDirector().getExtension(FooFrameworkService.class, testFwSrvName); FooFrameworkService frameworkService2 = frameworkModel2.getExtensionDirector().getExtension(FooFrameworkService.class, testFwSrvName); Assertions.assertNotSame(frameworkService1, frameworkService2); // test isolation of ApplicationModel // applicationModel11 and applicationModel12 are shared frameworkModel1 FooFrameworkService frameworkService11 = applicationModel11.getExtensionDirector().getExtension(FooFrameworkService.class, testFwSrvName); FooFrameworkService frameworkService12 = applicationModel12.getExtensionDirector().getExtension(FooFrameworkService.class, testFwSrvName); Assertions.assertSame(frameworkService1, frameworkService11); Assertions.assertSame(frameworkService1, frameworkService12); // applicationModel11 and applicationModel12 are isolated in application scope FooAppService applicationService11 = applicationModel11.getExtensionDirector().getExtension(FooAppService.class, testAppSrvName); FooAppService applicationService12 = applicationModel12.getExtensionDirector().getExtension(FooAppService.class, testAppSrvName); Assertions.assertNotSame(applicationService11, applicationService12); // applicationModel11 and applicationModel21 are isolated in both framework and application scope FooFrameworkService frameworkService21 = applicationModel21.getExtensionDirector().getExtension(FooFrameworkService.class, testFwSrvName); FooAppService applicationService21 = applicationModel21.getExtensionDirector().getExtension(FooAppService.class, testAppSrvName); Assertions.assertNotSame(frameworkService11, frameworkService21); Assertions.assertNotSame(applicationService11, applicationService21); // test isolation of ModuleModel FooModuleService moduleService111 = moduleModel111.getExtensionDirector().getExtension(FooModuleService.class, testMdSrvName); FooModuleService moduleService112 = moduleModel112.getExtensionDirector().getExtension(FooModuleService.class, testMdSrvName); // moduleModel111 and moduleModel112 are isolated in module scope Assertions.assertNotSame(moduleService111, moduleService112); // moduleModel111 and moduleModel112 are shared applicationModel11 FooAppService applicationService111 = moduleModel111.getExtensionDirector().getExtension(FooAppService.class, testAppSrvName); FooAppService applicationService112 = moduleModel112.getExtensionDirector().getExtension(FooAppService.class, testAppSrvName); Assertions.assertSame(applicationService111, applicationService112); // moduleModel111 and moduleModel121 are isolated in application scope, but shared frameworkModel1 FooAppService applicationService121 = moduleModel121.getExtensionDirector().getExtension(FooAppService.class, testAppSrvName); Assertions.assertNotSame(applicationService111, applicationService121); FooFrameworkService frameworkService111 = moduleModel111.getExtensionDirector().getExtension(FooFrameworkService.class, testFwSrvName); FooFrameworkService frameworkService121 = moduleModel121.getExtensionDirector().getExtension(FooFrameworkService.class, testFwSrvName); Assertions.assertSame(frameworkService111, frameworkService121); // moduleModel111 and moduleModel211 are isolated in both framework and application scope FooModuleService moduleService211 = moduleModel211.getExtensionDirector().getExtension(FooModuleService.class, testMdSrvName); FooAppService applicationService211 = moduleModel211.getExtensionDirector().getExtension(FooAppService.class, testAppSrvName); FooFrameworkService frameworkService211 = moduleModel211.getExtensionDirector().getExtension(FooFrameworkService.class, testFwSrvName); Assertions.assertNotSame(moduleService111, moduleService211); Assertions.assertNotSame(applicationService111, applicationService211); Assertions.assertNotSame(frameworkService111, frameworkService211); } @Test void testInjection() { // Expect: // 1. Framework scope extension can be injected to extensions of Framework/Application/Module scope // 2. Application scope extension can be injected to extensions of Application/Module scope, but not Framework // scope // 3. Module scope extension can be injected to extensions of Module scope, but not Framework/Application scope FrameworkModel frameworkModel = new FrameworkModel(); ApplicationModel applicationModel = frameworkModel.newApplication(); ModuleModel moduleModel = applicationModel.newModule(); // check module service TestModuleService moduleService = (TestModuleService) moduleModel.getExtensionDirector().getExtension(FooModuleService.class, testMdSrvName); Assertions.assertNotNull(moduleService.getFrameworkService()); Assertions.assertNotNull(moduleService.getFrameworkProvider()); Assertions.assertNotNull(moduleService.getAppService()); Assertions.assertNotNull(moduleService.getAppProvider()); Assertions.assertNotNull(moduleService.getModuleProvider()); // check app service TestAppService appService = (TestAppService) applicationModel.getExtensionDirector().getExtension(FooAppService.class, testAppSrvName); Assertions.assertNotNull(appService.getFrameworkService()); Assertions.assertNotNull(appService.getFrameworkProvider()); Assertions.assertNotNull(appService.getAppProvider()); Assertions.assertNull(appService.getModuleProvider()); // check framework service TestFrameworkService frameworkService = (TestFrameworkService) frameworkModel.getExtensionDirector().getExtension(FooFrameworkService.class, testFwSrvName); Assertions.assertNotNull(frameworkService.getFrameworkProvider()); Assertions.assertNull(frameworkService.getAppProvider()); Assertions.assertNull(frameworkService.getModuleProvider()); Assertions.assertFalse(moduleService.isDestroyed()); Assertions.assertFalse(appService.isDestroyed()); Assertions.assertFalse(frameworkService.isDestroyed()); // destroy frameworkModel.destroy(); Assertions.assertTrue(moduleService.isDestroyed()); Assertions.assertTrue(appService.isDestroyed()); Assertions.assertTrue(frameworkService.isDestroyed()); } }
6,290
0
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoader_Activate_Test.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.common.extension; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.activate.ActivateExt1; import java.util.List; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertTrue; public class ExtensionLoader_Activate_Test { @Test void test_onClass() throws Exception { URL url = URL.valueOf("test://localhost/test"); ExtensionLoader<ActivateExt1> loader = ExtensionLoader.getExtensionLoader(ActivateExt1.class); List<ActivateExt1> list = loader.getActivateExtension(url, new String[] {}, "onClass"); assertTrue(list == null || list.size() == 0); } }
6,291
0
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/extension/SPI2Impl.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.common.extension; @Activate public class SPI2Impl implements SPI2 { @Override public String sayHello() { return null; } }
6,292
0
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/extension/SPI3Impl.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.common.extension; @Activate public class SPI3Impl implements SPI3 { @Override public String sayHello() { return null; } }
6,293
0
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/extension/SPI1.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.common.extension; @SPI public interface SPI1 { String sayHello(); }
6,294
0
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/extension/SPI4Impl.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.common.extension; @Activate public class SPI4Impl implements SPI4 { @Override public String sayHello() { return null; } }
6,295
0
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoader_Compatible_Test.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.common.extension; import org.apache.dubbo.common.extension.compatible.CompatibleExt; import org.apache.dubbo.common.extension.compatible.impl.CompatibleExtImpl1; import org.apache.dubbo.common.extension.compatible.impl.CompatibleExtImpl2; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ModuleModel; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertTrue; class ExtensionLoader_Compatible_Test { @Test void test_getExtension() { ModuleModel moduleModel = ApplicationModel.defaultModel().getDefaultModule(); assertTrue( moduleModel.getExtensionLoader(CompatibleExt.class).getExtension("impl1") instanceof CompatibleExtImpl1); assertTrue( moduleModel.getExtensionLoader(CompatibleExt.class).getExtension("impl2") instanceof CompatibleExtImpl2); } }
6,296
0
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoader_Adaptive_Test.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.common.extension; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.adaptive.HasAdaptiveExt; import org.apache.dubbo.common.extension.adaptive.impl.HasAdaptiveExt_ManualAdaptive; import org.apache.dubbo.common.extension.ext1.SimpleExt; import org.apache.dubbo.common.extension.ext2.Ext2; import org.apache.dubbo.common.extension.ext2.UrlHolder; import org.apache.dubbo.common.extension.ext3.UseProtocolKeyExt; import org.apache.dubbo.common.extension.ext4.NoUrlParamExt; import org.apache.dubbo.common.extension.ext5.NoAdaptiveMethodExt; import org.apache.dubbo.common.extension.ext6_inject.Ext6; import org.apache.dubbo.common.extension.ext6_inject.impl.Ext6Impl2; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.common.utils.LogUtil; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; class ExtensionLoader_Adaptive_Test { @Test void test_useAdaptiveClass() throws Exception { ExtensionLoader<HasAdaptiveExt> loader = ExtensionLoader.getExtensionLoader(HasAdaptiveExt.class); HasAdaptiveExt ext = loader.getAdaptiveExtension(); assertTrue(ext instanceof HasAdaptiveExt_ManualAdaptive); } @Test void test_getAdaptiveExtension_defaultAdaptiveKey() throws Exception { { SimpleExt ext = ExtensionLoader.getExtensionLoader(SimpleExt.class).getAdaptiveExtension(); Map<String, String> map = new HashMap<String, String>(); URL url = new ServiceConfigURL("p1", "1.2.3.4", 1010, "path1", map); String echo = ext.echo(url, "haha"); assertEquals("Ext1Impl1-echo", echo); } { SimpleExt ext = ExtensionLoader.getExtensionLoader(SimpleExt.class).getAdaptiveExtension(); Map<String, String> map = new HashMap<String, String>(); map.put("simple.ext", "impl2"); URL url = new ServiceConfigURL("p1", "1.2.3.4", 1010, "path1", map); String echo = ext.echo(url, "haha"); assertEquals("Ext1Impl2-echo", echo); } } @Test void test_getAdaptiveExtension_customizeAdaptiveKey() throws Exception { SimpleExt ext = ExtensionLoader.getExtensionLoader(SimpleExt.class).getAdaptiveExtension(); Map<String, String> map = new HashMap<String, String>(); map.put("key2", "impl2"); URL url = new ServiceConfigURL("p1", "1.2.3.4", 1010, "path1", map); String echo = ext.yell(url, "haha"); assertEquals("Ext1Impl2-yell", echo); url = url.addParameter("key1", "impl3"); // note: URL is value's type echo = ext.yell(url, "haha"); assertEquals("Ext1Impl3-yell", echo); } @Test void test_getAdaptiveExtension_protocolKey() throws Exception { UseProtocolKeyExt ext = ExtensionLoader.getExtensionLoader(UseProtocolKeyExt.class).getAdaptiveExtension(); { String echo = ext.echo(URL.valueOf("1.2.3.4:20880"), "s"); assertEquals("Ext3Impl1-echo", echo); // default value Map<String, String> map = new HashMap<String, String>(); URL url = new ServiceConfigURL("impl3", "1.2.3.4", 1010, "path1", map); echo = ext.echo(url, "s"); assertEquals("Ext3Impl3-echo", echo); // use 2nd key, protocol url = url.addParameter("key1", "impl2"); echo = ext.echo(url, "s"); assertEquals("Ext3Impl2-echo", echo); // use 1st key, key1 } { Map<String, String> map = new HashMap<String, String>(); URL url = new ServiceConfigURL(null, "1.2.3.4", 1010, "path1", map); String yell = ext.yell(url, "s"); assertEquals("Ext3Impl1-yell", yell); // default value url = url.addParameter("key2", "impl2"); // use 2nd key, key2 yell = ext.yell(url, "s"); assertEquals("Ext3Impl2-yell", yell); url = url.setProtocol("impl3"); // use 1st key, protocol yell = ext.yell(url, "d"); assertEquals("Ext3Impl3-yell", yell); } } @Test void test_getAdaptiveExtension_UrlNpe() throws Exception { SimpleExt ext = ExtensionLoader.getExtensionLoader(SimpleExt.class).getAdaptiveExtension(); try { ext.echo(null, "haha"); fail(); } catch (IllegalArgumentException e) { assertEquals("url == null", e.getMessage()); } } @Test void test_getAdaptiveExtension_ExceptionWhenNoAdaptiveMethodOnInterface() throws Exception { try { ExtensionLoader.getExtensionLoader(NoAdaptiveMethodExt.class).getAdaptiveExtension(); fail(); } catch (IllegalStateException expected) { assertThat( expected.getMessage(), allOf( containsString( "Can't create adaptive extension interface org.apache.dubbo.common.extension.ext5.NoAdaptiveMethodExt"), containsString( "No adaptive method exist on extension org.apache.dubbo.common.extension.ext5.NoAdaptiveMethodExt, refuse to create the adaptive class"))); } // report same error when get is invoked for multiple times try { ExtensionLoader.getExtensionLoader(NoAdaptiveMethodExt.class).getAdaptiveExtension(); fail(); } catch (IllegalStateException expected) { assertThat( expected.getMessage(), allOf( containsString( "Can't create adaptive extension interface org.apache.dubbo.common.extension.ext5.NoAdaptiveMethodExt"), containsString( "No adaptive method exist on extension org.apache.dubbo.common.extension.ext5.NoAdaptiveMethodExt, refuse to create the adaptive class"))); } } @Test void test_getAdaptiveExtension_ExceptionWhenNotAdaptiveMethod() throws Exception { SimpleExt ext = ExtensionLoader.getExtensionLoader(SimpleExt.class).getAdaptiveExtension(); Map<String, String> map = new HashMap<String, String>(); URL url = new ServiceConfigURL("p1", "1.2.3.4", 1010, "path1", map); try { ext.bang(url, 33); fail(); } catch (UnsupportedOperationException expected) { assertThat(expected.getMessage(), containsString("method ")); assertThat( expected.getMessage(), containsString( "of interface org.apache.dubbo.common.extension.ext1.SimpleExt is not adaptive method!")); } } @Test void test_getAdaptiveExtension_ExceptionWhenNoUrlAttribute() throws Exception { try { ExtensionLoader.getExtensionLoader(NoUrlParamExt.class).getAdaptiveExtension(); fail(); } catch (Exception expected) { assertThat(expected.getMessage(), containsString("Failed to create adaptive class for interface ")); assertThat( expected.getMessage(), containsString(": not found url parameter or url attribute in parameters of method ")); } } @Test void test_urlHolder_getAdaptiveExtension() throws Exception { Ext2 ext = ExtensionLoader.getExtensionLoader(Ext2.class).getAdaptiveExtension(); Map<String, String> map = new HashMap<String, String>(); map.put("ext2", "impl1"); URL url = new ServiceConfigURL("p1", "1.2.3.4", 1010, "path1", map); UrlHolder holder = new UrlHolder(); holder.setUrl(url); String echo = ext.echo(holder, "haha"); assertEquals("Ext2Impl1-echo", echo); } @Test void test_urlHolder_getAdaptiveExtension_noExtension() throws Exception { Ext2 ext = ExtensionLoader.getExtensionLoader(Ext2.class).getAdaptiveExtension(); URL url = new ServiceConfigURL("p1", "1.2.3.4", 1010, "path1"); UrlHolder holder = new UrlHolder(); holder.setUrl(url); try { ext.echo(holder, "haha"); fail(); } catch (IllegalStateException expected) { assertThat(expected.getMessage(), containsString("Failed to get extension")); } url = url.addParameter("ext2", "XXX"); holder.setUrl(url); try { ext.echo(holder, "haha"); fail(); } catch (IllegalStateException expected) { assertThat(expected.getMessage(), containsString("No such extension")); } } @Test void test_urlHolder_getAdaptiveExtension_UrlNpe() throws Exception { Ext2 ext = ExtensionLoader.getExtensionLoader(Ext2.class).getAdaptiveExtension(); try { ext.echo(null, "haha"); fail(); } catch (IllegalArgumentException e) { assertEquals("org.apache.dubbo.common.extension.ext2.UrlHolder argument == null", e.getMessage()); } try { ext.echo(new UrlHolder(), "haha"); fail(); } catch (IllegalArgumentException e) { assertEquals("org.apache.dubbo.common.extension.ext2.UrlHolder argument getUrl() == null", e.getMessage()); } } @Test void test_urlHolder_getAdaptiveExtension_ExceptionWhenNotAdativeMethod() throws Exception { Ext2 ext = ExtensionLoader.getExtensionLoader(Ext2.class).getAdaptiveExtension(); Map<String, String> map = new HashMap<String, String>(); URL url = new ServiceConfigURL("p1", "1.2.3.4", 1010, "path1", map); try { ext.bang(url, 33); fail(); } catch (UnsupportedOperationException expected) { assertThat(expected.getMessage(), containsString("method ")); assertThat( expected.getMessage(), containsString("of interface org.apache.dubbo.common.extension.ext2.Ext2 is not adaptive method!")); } } @Test void test_urlHolder_getAdaptiveExtension_ExceptionWhenNameNotProvided() throws Exception { Ext2 ext = ExtensionLoader.getExtensionLoader(Ext2.class).getAdaptiveExtension(); URL url = new ServiceConfigURL("p1", "1.2.3.4", 1010, "path1"); UrlHolder holder = new UrlHolder(); holder.setUrl(url); try { ext.echo(holder, "impl1"); fail(); } catch (IllegalStateException expected) { assertThat(expected.getMessage(), containsString("Failed to get extension")); } url = url.addParameter("key1", "impl1"); holder.setUrl(url); try { ext.echo(holder, "haha"); fail(); } catch (IllegalStateException expected) { assertThat( expected.getMessage(), containsString( "Failed to get extension (org.apache.dubbo.common.extension.ext2.Ext2) name from url")); } } @Test void test_getAdaptiveExtension_inject() throws Exception { LogUtil.start(); Ext6 ext = ExtensionLoader.getExtensionLoader(Ext6.class).getAdaptiveExtension(); URL url = new ServiceConfigURL("p1", "1.2.3.4", 1010, "path1"); url = url.addParameters("ext6", "impl1"); assertEquals("Ext6Impl1-echo-Ext1Impl1-echo", ext.echo(url, "ha")); Assertions.assertTrue(LogUtil.checkNoError(), "can not find error."); LogUtil.stop(); url = url.addParameters("simple.ext", "impl2"); assertEquals("Ext6Impl1-echo-Ext1Impl2-echo", ext.echo(url, "ha")); } @Test void test_getAdaptiveExtension_InjectNotExtFail() throws Exception { Ext6 ext = ExtensionLoader.getExtensionLoader(Ext6.class).getExtension("impl2"); Ext6Impl2 impl = (Ext6Impl2) ext; assertNull(impl.getList()); } }
6,297
0
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/extension
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/extension/compatible/CompatibleExt.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.common.extension.compatible; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Adaptive; import org.apache.dubbo.common.extension.SPI; @SPI("impl1") public interface CompatibleExt { @Adaptive String echo(URL url, String s); }
6,298
0
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/extension/compatible
Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/extension/compatible/impl/CompatibleExtImpl2.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.common.extension.compatible.impl; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.compatible.CompatibleExt; public class CompatibleExtImpl2 implements CompatibleExt { public String echo(URL url, String s) { return "Ext1Impl2-echo"; } public String yell(URL url, String s) { return "Ext1Impl2-yell"; } public String bang(URL url, int i) { return "bang2"; } }
6,299