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-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule
|
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/DubboMatchRequestTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match.DubboAttachmentMatch;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match.DubboMethodMatch;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match.StringMatch;
import org.apache.dubbo.rpc.cluster.router.mesh.util.TracingContextProvider;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class DubboMatchRequestTest {
@Test
void isMatch() {
DubboMatchRequest dubboMatchRequest = new DubboMatchRequest();
// methodMatch
DubboMethodMatch dubboMethodMatch = new DubboMethodMatch();
StringMatch nameStringMatch = new StringMatch();
nameStringMatch.setExact("sayHello");
dubboMethodMatch.setName_match(nameStringMatch);
dubboMatchRequest.setMethod(dubboMethodMatch);
RpcInvocation rpcInvocation = new RpcInvocation();
rpcInvocation.setMethodName("sayHello");
assertTrue(dubboMatchRequest.isMatch(rpcInvocation, new HashMap<>(), Collections.emptySet()));
rpcInvocation.setMethodName("satHi");
assertFalse(dubboMatchRequest.isMatch(rpcInvocation, new HashMap<>(), Collections.emptySet()));
// sourceLabels
Map<String, String> sourceLabels = new HashMap<>();
sourceLabels.put("key1", "value1");
sourceLabels.put("key2", "value2");
dubboMatchRequest.setSourceLabels(sourceLabels);
Map<String, String> inputSourceLabelsMap = new HashMap<>();
inputSourceLabelsMap.put("key1", "value1");
inputSourceLabelsMap.put("key2", "value2");
inputSourceLabelsMap.put("key3", "value3");
Map<String, String> inputSourceLabelsMap2 = new HashMap<>();
inputSourceLabelsMap2.put("key1", "other");
inputSourceLabelsMap2.put("key2", "value2");
inputSourceLabelsMap2.put("key3", "value3");
rpcInvocation.setMethodName("sayHello");
assertTrue(dubboMatchRequest.isMatch(rpcInvocation, inputSourceLabelsMap, Collections.emptySet()));
assertFalse(dubboMatchRequest.isMatch(rpcInvocation, inputSourceLabelsMap2, Collections.emptySet()));
// tracingContext
DubboAttachmentMatch dubboAttachmentMatch = new DubboAttachmentMatch();
Map<String, StringMatch> tracingContextMatchMap = new HashMap<>();
StringMatch nameMatch = new StringMatch();
nameMatch.setExact("qinliujie");
tracingContextMatchMap.put("name", nameMatch);
dubboAttachmentMatch.setTracingContext(tracingContextMatchMap);
dubboMatchRequest.setAttachments(dubboAttachmentMatch);
Map<String, String> invokeTracingContextMap = new HashMap<>();
invokeTracingContextMap.put("name", "qinliujie");
invokeTracingContextMap.put("machineGroup", "test_host");
invokeTracingContextMap.put("other", "other");
TracingContextProvider tracingContextProvider = (invocation, key) -> invokeTracingContextMap.get(key);
assertTrue(dubboMatchRequest.isMatch(
rpcInvocation, inputSourceLabelsMap, Collections.singleton(tracingContextProvider)));
Map<String, String> invokeTracingContextMap2 = new HashMap<>();
invokeTracingContextMap2.put("name", "jack");
invokeTracingContextMap2.put("machineGroup", "test_host");
invokeTracingContextMap2.put("other", "other");
TracingContextProvider tracingContextProvider2 = (invocation, key) -> invokeTracingContextMap2.get(key);
assertFalse(dubboMatchRequest.isMatch(
rpcInvocation, inputSourceLabelsMap, Collections.singleton(tracingContextProvider2)));
// dubbo context
dubboAttachmentMatch = new DubboAttachmentMatch();
Map<String, StringMatch> eagleeyecontextMatchMap = new HashMap<>();
nameMatch = new StringMatch();
nameMatch.setExact("qinliujie");
eagleeyecontextMatchMap.put("name", nameMatch);
dubboAttachmentMatch.setTracingContext(eagleeyecontextMatchMap);
Map<String, StringMatch> dubboContextMatchMap = new HashMap<>();
StringMatch dpathMatch = new StringMatch();
dpathMatch.setExact("PRE");
dubboContextMatchMap.put("dpath", dpathMatch);
dubboAttachmentMatch.setDubboContext(dubboContextMatchMap);
dubboMatchRequest.setAttachments(dubboAttachmentMatch);
Map<String, String> invokeDubboContextMap = new HashMap<>();
invokeDubboContextMap.put("dpath", "PRE");
rpcInvocation.setAttachments(invokeDubboContextMap);
TracingContextProvider tracingContextProvider3 = (invocation, key) -> invokeTracingContextMap.get(key);
assertTrue(dubboMatchRequest.isMatch(
rpcInvocation, inputSourceLabelsMap, Collections.singleton(tracingContextProvider3)));
Map<String, String> invokeDubboContextMap2 = new HashMap<>();
invokeDubboContextMap.put("dpath", "other");
rpcInvocation.setAttachments(invokeDubboContextMap2);
assertFalse(dubboMatchRequest.isMatch(
rpcInvocation, inputSourceLabelsMap, Collections.singleton(tracingContextProvider3)));
}
}
| 7,800 |
0 |
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice
|
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DubboMethodMatchTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match;
import org.apache.dubbo.rpc.RpcInvocation;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class DubboMethodMatchTest {
@Test
void nameMatch() {
DubboMethodMatch dubboMethodMatch = new DubboMethodMatch();
StringMatch nameStringMatch = new StringMatch();
nameStringMatch.setExact("sayHello");
dubboMethodMatch.setName_match(nameStringMatch);
assertTrue(
dubboMethodMatch.isMatch(new RpcInvocation(null, "sayHello", "", "", new Class[] {}, new Object[] {})));
}
@Test
void argcMatch() {
DubboMethodMatch dubboMethodMatch = new DubboMethodMatch();
dubboMethodMatch.setArgc(1);
assertFalse(
dubboMethodMatch.isMatch(new RpcInvocation(null, "sayHello", "", "", new Class[] {}, new Object[] {})));
assertTrue(dubboMethodMatch.isMatch(
new RpcInvocation(null, "sayHello", "", "", new Class[] {}, new Object[] {"1"})));
}
@Test
void argpMatch() {
DubboMethodMatch dubboMethodMatch = new DubboMethodMatch();
List<StringMatch> argpMatch = new ArrayList<>();
StringMatch first = new StringMatch();
first.setExact("java.lang.Long");
StringMatch second = new StringMatch();
second.setRegex(".*");
argpMatch.add(first);
argpMatch.add(second);
dubboMethodMatch.setArgp(argpMatch);
assertTrue(dubboMethodMatch.isMatch(
new RpcInvocation(null, "sayHello", "", "", new Class[] {Long.class, String.class}, new Object[] {})));
assertFalse(dubboMethodMatch.isMatch(new RpcInvocation(
null, "sayHello", "", "", new Class[] {Long.class, String.class, String.class}, new Object[] {})));
assertFalse(
dubboMethodMatch.isMatch(new RpcInvocation(null, "sayHello", "", "", new Class[] {}, new Object[] {})));
}
@Test
void parametersMatch() {
DubboMethodMatch dubboMethodMatch = new DubboMethodMatch();
List<DubboMethodArg> parametersMatch = new ArrayList<>();
// ----- index 0
{
DubboMethodArg dubboMethodArg0 = new DubboMethodArg();
dubboMethodArg0.setIndex(0);
ListDoubleMatch listDoubleMatch = new ListDoubleMatch();
List<DoubleMatch> oneof = new ArrayList<>();
DoubleMatch doubleMatch1 = new DoubleMatch();
doubleMatch1.setExact(10.0);
oneof.add(doubleMatch1);
listDoubleMatch.setOneof(oneof);
dubboMethodArg0.setNum_value(listDoubleMatch);
parametersMatch.add(dubboMethodArg0);
}
// -----index 1
{
DubboMethodArg dubboMethodArg1 = new DubboMethodArg();
dubboMethodArg1.setIndex(1);
ListStringMatch listStringMatch = new ListStringMatch();
List<StringMatch> oneof = new ArrayList<>();
StringMatch stringMatch1 = new StringMatch();
stringMatch1.setExact("sayHello");
oneof.add(stringMatch1);
listStringMatch.setOneof(oneof);
dubboMethodArg1.setStr_value(listStringMatch);
parametersMatch.add(dubboMethodArg1);
}
dubboMethodMatch.setArgs(parametersMatch);
assertTrue(dubboMethodMatch.isMatch(new RpcInvocation(
null, "test", "", "", new Class[] {int.class, String.class}, new Object[] {10, "sayHello"})));
assertFalse(dubboMethodMatch.isMatch(new RpcInvocation(
null, "test", "", "", new Class[] {int.class, String.class}, new Object[] {10, "sayHi"})));
// -----index 2
{
DubboMethodArg dubboMethodArg2 = new DubboMethodArg();
dubboMethodArg2.setIndex(2);
BoolMatch boolMatch = new BoolMatch();
boolMatch.setExact(true);
dubboMethodArg2.setBool_value(boolMatch);
parametersMatch.add(dubboMethodArg2);
}
assertTrue(dubboMethodMatch.isMatch(new RpcInvocation(
null, "test", "", "", new Class[] {int.class, String.class, boolean.class}, new Object[] {
10, "sayHello", true
})));
assertFalse(dubboMethodMatch.isMatch(new RpcInvocation(
null, "test", "", "", new Class[] {int.class, String.class, boolean.class}, new Object[] {
10, "sayHello", false
})));
}
}
| 7,801 |
0 |
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice
|
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/ListStringMatchTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class ListStringMatchTest {
@Test
void isMatch() {
ListStringMatch listStringMatch = new ListStringMatch();
List<StringMatch> oneof = new ArrayList<>();
StringMatch stringMatch1 = new StringMatch();
stringMatch1.setExact("1");
StringMatch stringMatch2 = new StringMatch();
stringMatch2.setExact("2");
oneof.add(stringMatch1);
oneof.add(stringMatch2);
listStringMatch.setOneof(oneof);
assertTrue(listStringMatch.isMatch("1"));
assertTrue(listStringMatch.isMatch("2"));
assertFalse(listStringMatch.isMatch("3"));
}
}
| 7,802 |
0 |
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice
|
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/StringMatchTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class StringMatchTest {
@Test
void exactMatch() {
StringMatch stringMatch = new StringMatch();
stringMatch.setExact("qinliujie");
assertTrue(stringMatch.isMatch("qinliujie"));
assertFalse(stringMatch.isMatch("other"));
assertFalse(stringMatch.isMatch(null));
}
@Test
void prefixMatch() {
StringMatch stringMatch = new StringMatch();
stringMatch.setPrefix("org.apache.dubbo.rpc.cluster.router.mesh");
assertTrue(stringMatch.isMatch("org.apache.dubbo.rpc.cluster.router.mesh.test"));
assertFalse(stringMatch.isMatch("com.alibaba.hsf"));
assertFalse(stringMatch.isMatch(null));
}
@Test
void regxMatch() {
StringMatch stringMatch = new StringMatch();
stringMatch.setRegex("org.apache.dubbo.rpc.cluster.router.mesh.*");
assertTrue(stringMatch.isMatch("org.apache.dubbo.rpc.cluster.router.mesh"));
assertTrue(stringMatch.isMatch("org.apache.dubbo.rpc.cluster.router.mesh.test"));
assertFalse(stringMatch.isMatch("com.alibaba.hsf"));
assertFalse(stringMatch.isMatch("com.taobao"));
}
@Test
void emptyMatch() {
StringMatch stringMatch = new StringMatch();
stringMatch.setEmpty("empty");
assertFalse(stringMatch.isMatch("com.alibaba.hsf"));
assertTrue(stringMatch.isMatch(""));
assertTrue(stringMatch.isMatch(null));
}
@Test
void noEmptyMatch() {
StringMatch stringMatch = new StringMatch();
stringMatch.setNoempty("noempty");
assertTrue(stringMatch.isMatch("com.alibaba.hsf"));
assertFalse(stringMatch.isMatch(""));
assertFalse(stringMatch.isMatch(null));
}
}
| 7,803 |
0 |
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice
|
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DoubleMatchTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class DoubleMatchTest {
@Test
void exactMatch() {
DoubleMatch doubleMatch = new DoubleMatch();
doubleMatch.setExact(10.0);
assertTrue(doubleMatch.isMatch(10.0));
assertFalse(doubleMatch.isMatch(9.0));
}
@Test
void rangeStartMatch() {
DoubleMatch doubleMatch = new DoubleMatch();
DoubleRangeMatch doubleRangeMatch = new DoubleRangeMatch();
doubleRangeMatch.setStart(10.0);
doubleMatch.setRange(doubleRangeMatch);
assertTrue(doubleMatch.isMatch(10.0));
assertFalse(doubleMatch.isMatch(9.0));
}
@Test
void rangeEndMatch() {
DoubleMatch doubleMatch = new DoubleMatch();
DoubleRangeMatch doubleRangeMatch = new DoubleRangeMatch();
doubleRangeMatch.setEnd(10.0);
doubleMatch.setRange(doubleRangeMatch);
assertFalse(doubleMatch.isMatch(10.0));
assertTrue(doubleMatch.isMatch(9.0));
}
@Test
void rangeStartEndMatch() {
DoubleMatch doubleMatch = new DoubleMatch();
DoubleRangeMatch doubleRangeMatch = new DoubleRangeMatch();
doubleRangeMatch.setStart(5.0);
doubleRangeMatch.setEnd(10.0);
doubleMatch.setRange(doubleRangeMatch);
assertTrue(doubleMatch.isMatch(5.0));
assertFalse(doubleMatch.isMatch(10.0));
assertFalse(doubleMatch.isMatch(4.9));
assertFalse(doubleMatch.isMatch(10.1));
assertTrue(doubleMatch.isMatch(6.0));
}
@Test
void modMatch() {
DoubleMatch doubleMatch = new DoubleMatch();
doubleMatch.setMod(2.0);
doubleMatch.setExact(3.0);
assertFalse(doubleMatch.isMatch(3.0));
doubleMatch.setExact(1.0);
assertTrue(doubleMatch.isMatch(1.0));
assertFalse(doubleMatch.isMatch(2.0));
assertTrue(doubleMatch.isMatch(3.0));
}
}
| 7,804 |
0 |
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice
|
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DubboAttachmentMatchTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.router.mesh.util.TracingContextProvider;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class DubboAttachmentMatchTest {
@Test
void dubboContextMatch() {
DubboAttachmentMatch dubboAttachmentMatch = new DubboAttachmentMatch();
Map<String, StringMatch> dubbocontextMatchMap = new HashMap<>();
StringMatch nameMatch = new StringMatch();
nameMatch.setExact("qinliujie");
dubbocontextMatchMap.put("name", nameMatch);
StringMatch machineGroupMatch = new StringMatch();
machineGroupMatch.setExact("test_host");
dubbocontextMatchMap.put("machineGroup", machineGroupMatch);
dubboAttachmentMatch.setDubboContext(dubbocontextMatchMap);
Map<String, String> invokeDubboContextMap = new HashMap<>();
invokeDubboContextMap.put("name", "qinliujie");
invokeDubboContextMap.put("machineGroup", "test_host");
invokeDubboContextMap.put("other", "other");
RpcInvocation rpcInvocation = new RpcInvocation();
rpcInvocation.setAttachments(invokeDubboContextMap);
assertTrue(dubboAttachmentMatch.isMatch(rpcInvocation, Collections.emptySet()));
Map<String, String> invokeDubboContextMap2 = new HashMap<>();
invokeDubboContextMap2.put("name", "jack");
invokeDubboContextMap2.put("machineGroup", "test_host");
invokeDubboContextMap2.put("other", "other");
RpcInvocation rpcInvocation2 = new RpcInvocation();
rpcInvocation2.setAttachments(invokeDubboContextMap2);
assertFalse(dubboAttachmentMatch.isMatch(rpcInvocation2, Collections.emptySet()));
Map<String, String> invokeDubboContextMap3 = new HashMap<>();
invokeDubboContextMap3.put("name", "qinliujie");
invokeDubboContextMap3.put("machineGroup", "my_host");
invokeDubboContextMap3.put("other", "other");
RpcInvocation rpcInvocation3 = new RpcInvocation();
rpcInvocation3.setAttachments(invokeDubboContextMap3);
assertFalse(dubboAttachmentMatch.isMatch(rpcInvocation3, Collections.emptySet()));
}
@Test
void tracingContextMatch() {
DubboAttachmentMatch dubboAttachmentMatch = new DubboAttachmentMatch();
Map<String, StringMatch> tracingContextMatchMap = new HashMap<>();
StringMatch nameMatch = new StringMatch();
nameMatch.setExact("qinliujie");
tracingContextMatchMap.put("name", nameMatch);
StringMatch machineGroupMatch = new StringMatch();
machineGroupMatch.setExact("test_host");
tracingContextMatchMap.put("machineGroup", machineGroupMatch);
dubboAttachmentMatch.setTracingContext(tracingContextMatchMap);
Map<String, String> invokeEagleEyeContextMap = new HashMap<>();
invokeEagleEyeContextMap.put("name", "qinliujie");
invokeEagleEyeContextMap.put("machineGroup", "test_host");
invokeEagleEyeContextMap.put("other", "other");
TracingContextProvider tracingContextProvider = (invocation, key) -> invokeEagleEyeContextMap.get(key);
assertTrue(dubboAttachmentMatch.isMatch(
Mockito.mock(Invocation.class), Collections.singleton(tracingContextProvider)));
Map<String, String> invokeTracingContextMap2 = new HashMap<>();
invokeTracingContextMap2.put("name", "jack");
invokeTracingContextMap2.put("machineGroup", "test_host");
invokeTracingContextMap2.put("other", "other");
TracingContextProvider tracingContextProvider2 = (invocation, key) -> invokeTracingContextMap2.get(key);
assertFalse(dubboAttachmentMatch.isMatch(
Mockito.mock(Invocation.class), Collections.singleton(tracingContextProvider2)));
Map<String, String> invokeEagleEyeContextMap3 = new HashMap<>();
invokeEagleEyeContextMap3.put("name", "qinliujie");
invokeEagleEyeContextMap3.put("machineGroup", "my_host");
invokeEagleEyeContextMap3.put("other", "other");
TracingContextProvider tracingContextProvider3 = (invocation, key) -> invokeEagleEyeContextMap3.get(key);
assertFalse(dubboAttachmentMatch.isMatch(
Mockito.mock(Invocation.class), Collections.singleton(tracingContextProvider3)));
}
@Test
void contextMatch() {
DubboAttachmentMatch dubboAttachmentMatch = new DubboAttachmentMatch();
Map<String, StringMatch> tracingContextMatchMap = new HashMap<>();
StringMatch nameMatch = new StringMatch();
nameMatch.setExact("qinliujie");
tracingContextMatchMap.put("name", nameMatch);
dubboAttachmentMatch.setTracingContext(tracingContextMatchMap);
Map<String, String> invokeTracingContextMap = new HashMap<>();
invokeTracingContextMap.put("name", "qinliujie");
invokeTracingContextMap.put("machineGroup", "test_host");
invokeTracingContextMap.put("other", "other");
Map<String, StringMatch> dubboContextMatchMap = new HashMap<>();
StringMatch dpathMatch = new StringMatch();
dpathMatch.setExact("PRE");
dubboContextMatchMap.put("dpath", dpathMatch);
dubboAttachmentMatch.setDubboContext(dubboContextMatchMap);
Map<String, String> invokeDubboContextMap = new HashMap<>();
invokeDubboContextMap.put("dpath", "PRE");
TracingContextProvider tracingContextProvider = (invocation, key) -> invokeTracingContextMap.get(key);
RpcInvocation rpcInvocation = new RpcInvocation();
rpcInvocation.setAttachments(invokeDubboContextMap);
assertTrue(dubboAttachmentMatch.isMatch(rpcInvocation, Collections.singleton(tracingContextProvider)));
Map<String, String> invokeTracingContextMap1 = new HashMap<>();
invokeTracingContextMap1.put("name", "jack");
invokeTracingContextMap1.put("machineGroup", "test_host");
invokeTracingContextMap1.put("other", "other");
TracingContextProvider tracingContextProvider1 = (invocation, key) -> invokeTracingContextMap1.get(key);
RpcInvocation rpcInvocation1 = new RpcInvocation();
rpcInvocation1.setAttachments(invokeDubboContextMap);
assertFalse(dubboAttachmentMatch.isMatch(rpcInvocation1, Collections.singleton(tracingContextProvider1)));
Map<String, String> invokeDubboContextMap1 = new HashMap<>();
invokeDubboContextMap1.put("dpath", "PRE-2");
TracingContextProvider tracingContextProvider2 = (invocation, key) -> invokeTracingContextMap.get(key);
RpcInvocation rpcInvocation2 = new RpcInvocation();
rpcInvocation2.setAttachments(invokeDubboContextMap1);
assertFalse(dubboAttachmentMatch.isMatch(rpcInvocation2, Collections.singleton(tracingContextProvider2)));
TracingContextProvider tracingContextProvider3 = (invocation, key) -> invokeTracingContextMap1.get(key);
RpcInvocation rpcInvocation3 = new RpcInvocation();
rpcInvocation3.setAttachments(invokeDubboContextMap1);
assertFalse(dubboAttachmentMatch.isMatch(rpcInvocation3, Collections.singleton(tracingContextProvider3)));
Map<String, String> invokeTracingContextMap2 = new HashMap<>();
invokeTracingContextMap2.put("machineGroup", "test_host");
invokeTracingContextMap2.put("other", "other");
TracingContextProvider tracingContextProvider4 = (invocation, key) -> invokeTracingContextMap2.get(key);
RpcInvocation rpcInvocation4 = new RpcInvocation();
rpcInvocation4.setAttachments(invokeDubboContextMap);
assertFalse(dubboAttachmentMatch.isMatch(rpcInvocation4, Collections.singleton(tracingContextProvider4)));
Map<String, String> invokeDubboContextMap2 = new HashMap<>();
TracingContextProvider tracingContextProvider5 = (invocation, key) -> invokeTracingContextMap.get(key);
RpcInvocation rpcInvocation5 = new RpcInvocation();
rpcInvocation5.setAttachments(invokeDubboContextMap2);
assertFalse(dubboAttachmentMatch.isMatch(rpcInvocation5, Collections.singleton(tracingContextProvider5)));
TracingContextProvider tracingContextProvider6 = (invocation, key) -> invokeTracingContextMap2.get(key);
RpcInvocation rpcInvocation6 = new RpcInvocation();
rpcInvocation5.setAttachments(invokeDubboContextMap2);
assertFalse(dubboAttachmentMatch.isMatch(rpcInvocation6, Collections.singleton(tracingContextProvider6)));
}
}
| 7,805 |
0 |
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice
|
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/ListDoubleMatchTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class ListDoubleMatchTest {
@Test
void isMatch() {
ListDoubleMatch listDoubleMatch = new ListDoubleMatch();
List<DoubleMatch> oneof = new ArrayList<>();
DoubleMatch doubleMatch1 = new DoubleMatch();
doubleMatch1.setExact(10.0);
DoubleMatch doubleMatch2 = new DoubleMatch();
doubleMatch2.setExact(11.0);
oneof.add(doubleMatch1);
oneof.add(doubleMatch2);
listDoubleMatch.setOneof(oneof);
assertTrue(listDoubleMatch.isMatch(10.0));
assertTrue(listDoubleMatch.isMatch(11.0));
assertFalse(listDoubleMatch.isMatch(12.0));
}
}
| 7,806 |
0 |
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice
|
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/ListBoolMatchTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class ListBoolMatchTest {
@Test
void isMatch() {
ListBoolMatch listBoolMatch = new ListBoolMatch();
List<BoolMatch> oneof = new ArrayList<>();
BoolMatch boolMatch1 = new BoolMatch();
boolMatch1.setExact(true);
oneof.add(boolMatch1);
listBoolMatch.setOneof(oneof);
assertTrue(listBoolMatch.isMatch(true));
assertFalse(listBoolMatch.isMatch(false));
BoolMatch boolMatch2 = new BoolMatch();
boolMatch2.setExact(false);
oneof.add(boolMatch2);
listBoolMatch.setOneof(oneof);
assertTrue(listBoolMatch.isMatch(false));
}
}
| 7,807 |
0 |
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice
|
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/BoolMatchTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class BoolMatchTest {
@Test
void isMatch() {
BoolMatch boolMatch = new BoolMatch();
boolMatch.setExact(true);
assertTrue(boolMatch.isMatch(true));
assertFalse(boolMatch.isMatch(false));
boolMatch.setExact(false);
assertFalse(boolMatch.isMatch(true));
assertTrue(boolMatch.isMatch(false));
}
}
| 7,808 |
0 |
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router
|
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterEngineTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.file;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.metrics.event.MetricsDispatcher;
import org.apache.dubbo.rpc.AppResponse;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.cluster.LoadBalance;
import org.apache.dubbo.rpc.cluster.directory.StaticDirectory;
import org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory;
import org.apache.dubbo.rpc.cluster.support.AbstractClusterInvoker;
import org.apache.dubbo.rpc.model.ApplicationModel;
import javax.script.ScriptEngineManager;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.ENABLE_CONNECTIVITY_VALIDATION;
import static org.apache.dubbo.rpc.cluster.Constants.RUNTIME_KEY;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@SuppressWarnings("unchecked")
class FileRouterEngineTest {
private static boolean isScriptUnsupported = new ScriptEngineManager().getEngineByName("javascript") == null;
List<Invoker<FileRouterEngineTest>> invokers = new ArrayList<Invoker<FileRouterEngineTest>>();
Invoker<FileRouterEngineTest> invoker1 = mock(Invoker.class);
Invoker<FileRouterEngineTest> invoker2 = mock(Invoker.class);
Invocation invocation;
StaticDirectory<FileRouterEngineTest> dic;
Result result = new AppResponse();
private StateRouterFactory routerFactory =
ExtensionLoader.getExtensionLoader(StateRouterFactory.class).getAdaptiveExtension();
@BeforeAll
public static void setUpBeforeClass() throws Exception {
ApplicationModel.defaultModel().getBeanFactory().registerBean(MetricsDispatcher.class);
System.setProperty(ENABLE_CONNECTIVITY_VALIDATION, "false");
}
@BeforeEach
public void setUp() throws Exception {
invokers.add(invoker1);
invokers.add(invoker2);
}
@AfterEach
public void teardown() throws Exception {
System.clearProperty(ENABLE_CONNECTIVITY_VALIDATION);
RpcContext.removeContext();
}
@Test
void testRouteNotAvailable() {
if (isScriptUnsupported) return;
URL url = initUrl("notAvailablerule.javascript");
initInvocation("method1");
initInvokers(url, true, false);
initDic(url);
MockClusterInvoker<FileRouterEngineTest> sinvoker = new MockClusterInvoker<FileRouterEngineTest>(dic, url);
for (int i = 0; i < 100; i++) {
sinvoker.invoke(invocation);
Invoker<FileRouterEngineTest> invoker = sinvoker.getSelectedInvoker();
Assertions.assertEquals(invoker2, invoker);
}
}
@Test
void testRouteAvailable() {
if (isScriptUnsupported) return;
URL url = initUrl("availablerule.javascript");
initInvocation("method1");
initInvokers(url);
initDic(url);
MockClusterInvoker<FileRouterEngineTest> sinvoker = new MockClusterInvoker<FileRouterEngineTest>(dic, url);
for (int i = 0; i < 100; i++) {
sinvoker.invoke(invocation);
Invoker<FileRouterEngineTest> invoker = sinvoker.getSelectedInvoker();
Assertions.assertEquals(invoker1, invoker);
}
}
@Test
void testRouteByMethodName() {
if (isScriptUnsupported) return;
URL url = initUrl("methodrule.javascript");
{
initInvocation("method1");
initInvokers(url, true, true);
initDic(url);
MockClusterInvoker<FileRouterEngineTest> sinvoker = new MockClusterInvoker<FileRouterEngineTest>(dic, url);
for (int i = 0; i < 100; i++) {
sinvoker.invoke(invocation);
Invoker<FileRouterEngineTest> invoker = sinvoker.getSelectedInvoker();
Assertions.assertEquals(invoker1, invoker);
}
}
{
initInvocation("method2");
initInvokers(url, true, true);
initDic(url);
MockClusterInvoker<FileRouterEngineTest> sinvoker = new MockClusterInvoker<FileRouterEngineTest>(dic, url);
for (int i = 0; i < 100; i++) {
sinvoker.invoke(invocation);
Invoker<FileRouterEngineTest> invoker = sinvoker.getSelectedInvoker();
Assertions.assertEquals(invoker2, invoker);
}
}
}
private URL initUrl(String filename) {
filename = getClass()
.getClassLoader()
.getResource(getClass().getPackage().getName().replace('.', '/') + "/" + filename)
.toString();
URL url = URL.valueOf(filename);
url = url.addParameter(RUNTIME_KEY, true);
return url;
}
private void initInvocation(String methodName) {
invocation = new RpcInvocation();
((RpcInvocation) invocation).setMethodName(methodName);
}
private void initInvokers(URL url) {
initInvokers(url, true, false);
}
private void initInvokers(URL url, boolean invoker1Status, boolean invoker2Status) {
given(invoker1.invoke(invocation)).willReturn(result);
given(invoker1.isAvailable()).willReturn(invoker1Status);
given(invoker1.getUrl()).willReturn(url);
given(invoker1.getInterface()).willReturn(FileRouterEngineTest.class);
given(invoker2.invoke(invocation)).willReturn(result);
given(invoker2.isAvailable()).willReturn(invoker2Status);
given(invoker2.getUrl()).willReturn(url);
given(invoker2.getInterface()).willReturn(FileRouterEngineTest.class);
}
private void initDic(URL url) {
// FIXME: this exposes the design flaw in RouterChain
URL dicInitUrl = URL.valueOf(
"consumer://localhost:20880/org.apache.dubbo.rpc.cluster.router.file.FileRouterEngineTest?application=FileRouterEngineTest");
dic = new StaticDirectory<>(dicInitUrl, invokers);
dic.buildRouterChain();
dic.getRouterChain()
.getCurrentChain()
.setHeadStateRouter(routerFactory.getRouter(FileRouterEngineTest.class, url));
}
static class MockClusterInvoker<T> extends AbstractClusterInvoker<T> {
private Invoker<T> selectedInvoker;
public MockClusterInvoker(Directory<T> directory) {
super(directory);
}
public MockClusterInvoker(Directory<T> directory, URL url) {
super(directory, url);
}
@Override
protected Result doInvoke(Invocation invocation, List<Invoker<T>> invokers, LoadBalance loadbalance)
throws RpcException {
Invoker<T> invoker = select(loadbalance, invocation, invokers, null);
selectedInvoker = invoker;
return null;
}
public Invoker<T> getSelectedInvoker() {
return selectedInvoker;
}
}
}
| 7,809 |
0 |
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router
|
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mock/MockInvokersSelectorTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mock;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.Holder;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.apache.dubbo.rpc.cluster.Constants.INVOCATION_NEED_MOCK;
class MockInvokersSelectorTest {
@Test
void test() {
MockInvokersSelector selector = new MockInvokersSelector(URL.valueOf(""));
// Data preparation
Invoker<DemoService> invoker1 = Mockito.mock(Invoker.class);
Invoker<DemoService> invoker2 = Mockito.mock(Invoker.class);
Invoker<DemoService> invoker3 = Mockito.mock(Invoker.class);
Mockito.when(invoker1.getUrl()).thenReturn(URL.valueOf("mock://127.0.0.1/test"));
Mockito.when(invoker2.getUrl()).thenReturn(URL.valueOf("mock://127.0.0.1/test"));
Mockito.when(invoker3.getUrl()).thenReturn(URL.valueOf("dubbo://127.0.0.1/test"));
BitList<Invoker<DemoService>> providers = new BitList<>(Arrays.asList(invoker1, invoker2, invoker3));
RpcInvocation rpcInvocation = Mockito.mock(RpcInvocation.class);
URL consumerURL = URL.valueOf("test://127.0.0.1");
selector.notify(providers);
// rpcInvocation does not have an attached "invocation.need.mock" parameter, so normal invokers will be filtered
// out
List<Invoker<DemoService>> invokers =
selector.route(providers.clone(), consumerURL, rpcInvocation, false, new Holder<>());
Assertions.assertEquals(invokers.size(), 1);
Assertions.assertTrue(invokers.contains(invoker3));
// rpcInvocation have an attached "invocation.need.mock" parameter, so it will filter out the invoker whose
// protocol is mock
Mockito.when(rpcInvocation.getObjectAttachmentWithoutConvert(INVOCATION_NEED_MOCK))
.thenReturn("true");
invokers = selector.route(providers.clone(), consumerURL, rpcInvocation, false, new Holder<>());
Assertions.assertEquals(invokers.size(), 2);
Assertions.assertTrue(invokers.contains(invoker1));
Assertions.assertTrue(invokers.contains(invoker2));
}
class DemoService {}
}
| 7,810 |
0 |
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router
|
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/state/BitListTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.state;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.provider.ValueSource;
class BitListTest {
@Test
void test() {
List<String> list = Arrays.asList("A", "B", "C");
BitList<String> bitList = new BitList<>(list);
Assertions.assertEquals(bitList.getOriginList(), list);
Assertions.assertEquals(3, bitList.size());
Assertions.assertEquals("A", bitList.get(0));
Assertions.assertEquals("B", bitList.get(1));
Assertions.assertEquals("C", bitList.get(2));
Assertions.assertTrue(bitList.contains("A"));
Assertions.assertTrue(bitList.contains("B"));
Assertions.assertTrue(bitList.contains("C"));
for (String str : bitList) {
Assertions.assertTrue(list.contains(str));
}
Assertions.assertEquals(0, bitList.indexOf("A"));
Assertions.assertEquals(1, bitList.indexOf("B"));
Assertions.assertEquals(2, bitList.indexOf("C"));
Object[] objects = bitList.toArray();
for (Object obj : objects) {
Assertions.assertTrue(list.contains(obj));
}
Object[] newObjects = new Object[1];
Object[] copiedList = bitList.toArray(newObjects);
Assertions.assertEquals(3, copiedList.length);
Assertions.assertArrayEquals(copiedList, list.toArray());
newObjects = new Object[10];
copiedList = bitList.toArray(newObjects);
Assertions.assertEquals(10, copiedList.length);
Assertions.assertEquals("A", copiedList[0]);
Assertions.assertEquals("B", copiedList[1]);
Assertions.assertEquals("C", copiedList[2]);
bitList.remove(0);
Assertions.assertEquals("B", bitList.get(0));
bitList.addIndex(0);
Assertions.assertEquals("A", bitList.get(0));
bitList.removeAll(list);
Assertions.assertEquals(0, bitList.size());
bitList.clear();
}
@Test
void testIntersect() {
List<String> aList = Arrays.asList("A", "B", "C");
List<String> bList = Arrays.asList("A", "B");
List<String> totalList = Arrays.asList("A", "B", "C");
BitList<String> aBitList = new BitList<>(aList);
BitList<String> bBitList = new BitList<>(bList);
BitList<String> intersectBitList = aBitList.and(bBitList);
Assertions.assertEquals(2, intersectBitList.size());
Assertions.assertEquals(totalList.get(0), intersectBitList.get(0));
Assertions.assertEquals(totalList.get(1), intersectBitList.get(1));
aBitList.add("D");
intersectBitList = aBitList.and(bBitList);
Assertions.assertEquals(3, intersectBitList.size());
Assertions.assertEquals(totalList.get(0), intersectBitList.get(0));
Assertions.assertEquals(totalList.get(1), intersectBitList.get(1));
Assertions.assertEquals("D", intersectBitList.get(2));
}
@Test
void testIsEmpty() {
List<String> list = Arrays.asList("A", "B", "C");
BitList<String> bitList = new BitList<>(list);
bitList.add("D");
bitList.removeAll(list);
Assertions.assertEquals(1, bitList.size());
bitList.remove("D");
Assertions.assertTrue(bitList.isEmpty());
}
@Test
void testAdd() {
List<String> list = Arrays.asList("A", "B", "C");
BitList<String> bitList = new BitList<>(list);
bitList.remove("A");
Assertions.assertEquals(2, bitList.size());
bitList.addAll(Collections.singletonList("A"));
Assertions.assertEquals(3, bitList.size());
bitList.addAll(Collections.singletonList("D"));
Assertions.assertEquals(4, bitList.size());
Assertions.assertEquals("D", bitList.get(3));
Assertions.assertTrue(bitList.hasMoreElementInTailList());
Assertions.assertEquals(Collections.singletonList("D"), bitList.getTailList());
bitList.clear();
bitList.addAll(Collections.singletonList("A"));
Assertions.assertEquals(1, bitList.size());
Assertions.assertEquals("A", bitList.get(0));
}
@Test
void testAddAll() {
List<String> list = Arrays.asList("A", "B", "C");
BitList<String> bitList1 = new BitList<>(list);
BitList<String> bitList2 = new BitList<>(list);
bitList1.removeAll(list);
Assertions.assertEquals(0, bitList1.size());
bitList1.addAll(bitList2);
Assertions.assertEquals(3, bitList1.size());
Assertions.assertFalse(bitList1.hasMoreElementInTailList());
bitList1.addAll(bitList2);
Assertions.assertEquals(3, bitList1.size());
}
@Test
void testGet() {
List<String> list = Arrays.asList("A", "B", "C");
BitList<String> bitList = new BitList<>(list);
Assertions.assertEquals("A", bitList.get(0));
Assertions.assertEquals("B", bitList.get(1));
Assertions.assertEquals("C", bitList.get(2));
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> bitList.get(-1));
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> bitList.get(3));
bitList.add("D");
Assertions.assertEquals("D", bitList.get(3));
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> bitList.get(-1));
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> bitList.get(4));
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> bitList.get(5));
}
@Test
void testRemove() {
List<String> list = Arrays.asList("A", "B", "C");
BitList<String> bitList = new BitList<>(list);
Assertions.assertTrue(bitList.remove("A"));
Assertions.assertFalse(bitList.remove("A"));
Assertions.assertTrue(bitList.removeAll(Collections.singletonList("B")));
Assertions.assertFalse(bitList.removeAll(Collections.singletonList("B")));
Assertions.assertFalse(bitList.removeAll(Collections.singletonList("D")));
bitList.add("D");
Assertions.assertTrue(bitList.removeAll(Collections.singletonList("D")));
Assertions.assertFalse(bitList.hasMoreElementInTailList());
bitList.add("A");
bitList.add("E");
bitList.add("F");
Assertions.assertEquals(4, bitList.size());
Assertions.assertFalse(bitList.removeAll(Collections.singletonList("D")));
Assertions.assertTrue(bitList.removeAll(Collections.singletonList("A")));
Assertions.assertTrue(bitList.removeAll(Collections.singletonList("C")));
Assertions.assertTrue(bitList.removeAll(Collections.singletonList("E")));
Assertions.assertTrue(bitList.removeAll(Collections.singletonList("F")));
Assertions.assertTrue(bitList.isEmpty());
}
@Test
void testRemoveIndex() {
List<String> list = Arrays.asList("A", "B", "C");
BitList<String> bitList = new BitList<>(list);
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> bitList.remove(3));
Assertions.assertNotNull(bitList.remove(1));
Assertions.assertNotNull(bitList.remove(0));
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> bitList.remove(1));
bitList.add("D");
Assertions.assertNotNull(bitList.remove(1));
bitList.add("A");
bitList.add("E");
bitList.add("F");
// A C E F
Assertions.assertEquals(4, bitList.size());
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> bitList.remove(4));
Assertions.assertEquals("F", bitList.remove(3));
Assertions.assertEquals("E", bitList.remove(2));
Assertions.assertEquals("C", bitList.remove(1));
Assertions.assertEquals("A", bitList.remove(0));
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> bitList.remove(0));
Assertions.assertTrue(bitList.isEmpty());
}
@Test
void testRetain() {
List<String> list = Arrays.asList("A", "B", "C");
BitList<String> bitList = new BitList<>(list);
List<String> list1 = Arrays.asList("B", "C");
Assertions.assertTrue(bitList.retainAll(list1));
Assertions.assertTrue(bitList.containsAll(list1));
Assertions.assertFalse(bitList.containsAll(list));
Assertions.assertFalse(bitList.contains("A"));
bitList = new BitList<>(list);
bitList.add("D");
bitList.add("E");
List<String> list2 = Arrays.asList("B", "C", "D");
Assertions.assertTrue(bitList.retainAll(list2));
Assertions.assertTrue(bitList.containsAll(list2));
Assertions.assertFalse(bitList.containsAll(list));
Assertions.assertFalse(bitList.contains("A"));
Assertions.assertFalse(bitList.contains("E"));
}
@Test
void testIndex() {
List<String> list = Arrays.asList("A", "B", "A");
BitList<String> bitList = new BitList<>(list);
Assertions.assertEquals(0, bitList.indexOf("A"));
Assertions.assertEquals(2, bitList.lastIndexOf("A"));
Assertions.assertEquals(-1, bitList.indexOf("D"));
Assertions.assertEquals(-1, bitList.lastIndexOf("D"));
bitList.add("D");
bitList.add("E");
Assertions.assertEquals(0, bitList.indexOf("A"));
Assertions.assertEquals(2, bitList.lastIndexOf("A"));
Assertions.assertEquals(3, bitList.indexOf("D"));
Assertions.assertEquals(3, bitList.lastIndexOf("D"));
Assertions.assertEquals(-1, bitList.indexOf("F"));
}
@Test
void testSubList() {
List<String> list = Arrays.asList("A", "B", "C", "D", "E");
BitList<String> bitList = new BitList<>(list);
bitList.addAll(Arrays.asList("F", "G", "H", "I"));
BitList<String> subList1 = bitList.subList(0, 5);
Assertions.assertEquals(Arrays.asList("A", "B", "C", "D", "E"), subList1);
BitList<String> subList2 = bitList.subList(1, 5);
Assertions.assertEquals(Arrays.asList("B", "C", "D", "E"), subList2);
BitList<String> subList3 = bitList.subList(0, 4);
Assertions.assertEquals(Arrays.asList("A", "B", "C", "D"), subList3);
BitList<String> subList4 = bitList.subList(1, 4);
Assertions.assertEquals(Arrays.asList("B", "C", "D"), subList4);
BitList<String> subList5 = bitList.subList(2, 3);
Assertions.assertEquals(Collections.singletonList("C"), subList5);
Assertions.assertFalse(subList5.hasMoreElementInTailList());
BitList<String> subList6 = bitList.subList(0, 9);
Assertions.assertEquals(Arrays.asList("A", "B", "C", "D", "E", "F", "G", "H", "I"), subList6);
Assertions.assertEquals(Arrays.asList("F", "G", "H", "I"), subList6.getTailList());
BitList<String> subList7 = bitList.subList(1, 8);
Assertions.assertEquals(Arrays.asList("B", "C", "D", "E", "F", "G", "H"), subList7);
Assertions.assertEquals(Arrays.asList("F", "G", "H"), subList7.getTailList());
BitList<String> subList8 = bitList.subList(4, 8);
Assertions.assertEquals(Arrays.asList("E", "F", "G", "H"), subList8);
Assertions.assertEquals(Arrays.asList("F", "G", "H"), subList8.getTailList());
BitList<String> subList9 = bitList.subList(5, 8);
Assertions.assertEquals(Arrays.asList("F", "G", "H"), subList9);
Assertions.assertEquals(Arrays.asList("F", "G", "H"), subList9.getTailList());
BitList<String> subList10 = bitList.subList(6, 8);
Assertions.assertEquals(Arrays.asList("G", "H"), subList10);
Assertions.assertEquals(Arrays.asList("G", "H"), subList10.getTailList());
BitList<String> subList11 = bitList.subList(6, 7);
Assertions.assertEquals(Collections.singletonList("G"), subList11);
Assertions.assertEquals(Collections.singletonList("G"), subList11.getTailList());
}
@Test
void testListIterator1() {
List<String> list = Arrays.asList("A", "B", "C", "D", "E");
BitList<String> bitList = new BitList<>(list);
ListIterator<String> listIterator = bitList.listIterator(2);
ListIterator<String> expectedIterator = list.listIterator(2);
while (listIterator.hasNext()) {
Assertions.assertEquals(expectedIterator.nextIndex(), listIterator.nextIndex());
Assertions.assertEquals(expectedIterator.next(), listIterator.next());
}
while (listIterator.hasPrevious()) {
Assertions.assertEquals(expectedIterator.previousIndex(), listIterator.previousIndex());
Assertions.assertEquals(expectedIterator.previous(), listIterator.previous());
}
}
@Test
@ValueSource(
ints = {
2,
})
void testListIterator2() {
List<String> list = Arrays.asList("A", "B", "C", "D", "E");
BitList<String> bitList = new BitList<>(list);
bitList.addAll(Arrays.asList("F", "G", "H", "I"));
List<String> expectedResult = Arrays.asList("A", "B", "C", "D", "E", "F", "G", "H", "I");
ListIterator<String> listIterator = bitList.listIterator(2);
ListIterator<String> expectedIterator = expectedResult.listIterator(2);
while (listIterator.hasNext()) {
Assertions.assertEquals(expectedIterator.nextIndex(), listIterator.nextIndex());
Assertions.assertEquals(expectedIterator.next(), listIterator.next());
}
while (listIterator.hasPrevious()) {
Assertions.assertEquals(expectedIterator.previousIndex(), listIterator.previousIndex());
Assertions.assertEquals(expectedIterator.previous(), listIterator.previous());
}
}
@Test
void testListIterator3() {
List<String> list = Arrays.asList("A", "B", "C", "D", "E");
BitList<String> bitList = new BitList<>(list);
bitList.addAll(Arrays.asList("F", "G", "H", "I"));
List<String> expectedResult = Arrays.asList("A", "B", "C", "D", "E", "F", "G", "H", "I");
ListIterator<String> listIterator = bitList.listIterator(7);
ListIterator<String> expectedIterator = expectedResult.listIterator(7);
while (listIterator.hasNext()) {
Assertions.assertEquals(expectedIterator.nextIndex(), listIterator.nextIndex());
Assertions.assertEquals(expectedIterator.next(), listIterator.next());
}
while (listIterator.hasPrevious()) {
Assertions.assertEquals(expectedIterator.previousIndex(), listIterator.previousIndex());
Assertions.assertEquals(expectedIterator.previous(), listIterator.previous());
}
}
@Test
void testListIterator4() {
List<String> list = Arrays.asList("A", "B", "C", "D", "E");
BitList<String> bitList = new BitList<>(list);
bitList.addAll(Arrays.asList("F", "G", "H", "I"));
List<String> expectedResult = Arrays.asList("A", "B", "C", "D", "E", "F", "G", "H", "I");
ListIterator<String> listIterator = bitList.listIterator(8);
ListIterator<String> expectedIterator = expectedResult.listIterator(8);
while (listIterator.hasNext()) {
Assertions.assertEquals(expectedIterator.nextIndex(), listIterator.nextIndex());
Assertions.assertEquals(expectedIterator.next(), listIterator.next());
}
while (listIterator.hasPrevious()) {
Assertions.assertEquals(expectedIterator.previousIndex(), listIterator.previousIndex());
Assertions.assertEquals(expectedIterator.previous(), listIterator.previous());
}
}
@Test
void testListIterator5() {
List<String> list = Arrays.asList("A", "B", "C", "D", "E");
BitList<String> bitList = new BitList<>(list);
bitList.addAll(Arrays.asList("F", "G", "H", "I"));
List<String> expectedResult = new LinkedList<>(Arrays.asList("A", "B", "C", "D", "E", "F", "G", "H", "I"));
ListIterator<String> listIterator = bitList.listIterator(2);
ListIterator<String> expectedIterator = expectedResult.listIterator(2);
while (listIterator.hasNext()) {
Assertions.assertEquals(expectedIterator.nextIndex(), listIterator.nextIndex());
Assertions.assertEquals(expectedIterator.next(), listIterator.next());
listIterator.remove();
expectedIterator.remove();
}
Assertions.assertEquals(expectedResult, bitList);
while (listIterator.hasPrevious()) {
Assertions.assertEquals(expectedIterator.previousIndex(), listIterator.previousIndex());
Assertions.assertEquals(expectedIterator.previous(), listIterator.previous());
listIterator.remove();
expectedIterator.remove();
}
Assertions.assertEquals(expectedResult, bitList);
}
@Test
void testListIterator6() {
List<String> list = Arrays.asList("A", "B", "C", "D", "E");
BitList<String> bitList = new BitList<>(list);
bitList.addAll(Arrays.asList("F", "G", "H", "I"));
List<String> expectedResult = new LinkedList<>(Arrays.asList("A", "B", "C", "D", "E", "F", "G", "H", "I"));
ListIterator<String> listIterator = bitList.listIterator(2);
ListIterator<String> expectedIterator = expectedResult.listIterator(2);
while (listIterator.hasPrevious()) {
Assertions.assertEquals(expectedIterator.previousIndex(), listIterator.previousIndex());
Assertions.assertEquals(expectedIterator.previous(), listIterator.previous());
listIterator.remove();
expectedIterator.remove();
}
Assertions.assertEquals(expectedResult, bitList);
while (listIterator.hasNext()) {
Assertions.assertEquals(expectedIterator.nextIndex(), listIterator.nextIndex());
Assertions.assertEquals(expectedIterator.next(), listIterator.next());
listIterator.remove();
expectedIterator.remove();
}
Assertions.assertEquals(expectedResult, bitList);
}
@Test
void testListIterator7() {
List<String> list = Arrays.asList("A", "B", "C", "D", "E");
BitList<String> bitList = new BitList<>(list);
bitList.addAll(Arrays.asList("F", "G", "H", "I"));
List<String> expectedResult = new LinkedList<>(Arrays.asList("A", "B", "C", "D", "E", "F", "G", "H", "I"));
ListIterator<String> listIterator = bitList.listIterator(7);
ListIterator<String> expectedIterator = expectedResult.listIterator(7);
while (listIterator.hasNext()) {
Assertions.assertEquals(expectedIterator.nextIndex(), listIterator.nextIndex());
Assertions.assertEquals(expectedIterator.next(), listIterator.next());
listIterator.remove();
expectedIterator.remove();
}
Assertions.assertEquals(expectedResult, bitList);
while (listIterator.hasPrevious()) {
Assertions.assertEquals(expectedIterator.previousIndex(), listIterator.previousIndex());
Assertions.assertEquals(expectedIterator.previous(), listIterator.previous());
listIterator.remove();
expectedIterator.remove();
}
Assertions.assertEquals(expectedResult, bitList);
}
@Test
void testListIterator8() {
List<String> list = Arrays.asList("A", "B", "C", "D", "E");
BitList<String> bitList = new BitList<>(list);
bitList.addAll(Arrays.asList("F", "G", "H", "I"));
List<String> expectedResult = new LinkedList<>(Arrays.asList("A", "B", "C", "D", "E", "F", "G", "H", "I"));
ListIterator<String> listIterator = bitList.listIterator(7);
ListIterator<String> expectedIterator = expectedResult.listIterator(7);
while (listIterator.hasPrevious()) {
Assertions.assertEquals(expectedIterator.previousIndex(), listIterator.previousIndex());
Assertions.assertEquals(expectedIterator.previous(), listIterator.previous());
listIterator.remove();
expectedIterator.remove();
}
Assertions.assertEquals(expectedResult, bitList);
while (listIterator.hasNext()) {
Assertions.assertEquals(expectedIterator.nextIndex(), listIterator.nextIndex());
Assertions.assertEquals(expectedIterator.next(), listIterator.next());
listIterator.remove();
expectedIterator.remove();
}
Assertions.assertEquals(expectedResult, bitList);
}
@Test
void testClone1() {
List<String> list = Arrays.asList("A", "B", "C", "D", "E");
BitList<String> bitList = new BitList<>(list);
BitList<String> clone1 = bitList.clone();
Assertions.assertNotSame(bitList, clone1);
Assertions.assertEquals(bitList, clone1);
HashSet<Object> set = new HashSet<>();
set.add(bitList);
set.add(clone1);
Assertions.assertEquals(1, set.size());
set.add(new LinkedList<>());
Assertions.assertEquals(2, set.size());
set.add(new LinkedList<>(Arrays.asList("A", "B", "C", "D", "E")));
Assertions.assertEquals(2, set.size());
}
@Test
void testClone2() {
List<String> list = Arrays.asList("A", "B", "C", "D", "E");
BitList<String> bitList = new BitList<>(list);
bitList.addAll(Arrays.asList("F", "G"));
BitList<String> clone1 = bitList.clone();
Assertions.assertNotSame(bitList, clone1);
Assertions.assertEquals(bitList, clone1);
HashSet<Object> set = new HashSet<>();
set.add(bitList);
set.add(clone1);
Assertions.assertEquals(1, set.size());
set.add(new LinkedList<>());
Assertions.assertEquals(2, set.size());
set.add(new LinkedList<>(Arrays.asList("A", "B", "C", "D", "E", "F", "G")));
Assertions.assertEquals(2, set.size());
}
}
| 7,811 |
0 |
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router
|
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/script/ScriptStateRouterTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.script;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.Holder;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.router.MockInvoker;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import org.apache.dubbo.rpc.cluster.router.state.StateRouter;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledForJreRange;
import org.junit.jupiter.api.condition.JRE;
import static org.apache.dubbo.rpc.cluster.Constants.RULE_KEY;
@DisabledForJreRange(min = JRE.JAVA_16)
class ScriptStateRouterTest {
private URL SCRIPT_URL = URL.valueOf("script://javascript?type=javascript");
@BeforeAll
public static void setUpBeforeClass() throws Exception {}
@BeforeEach
public void setUp() throws Exception {}
private URL getRouteUrl(String rule) {
return SCRIPT_URL.addParameterAndEncoded(RULE_KEY, rule);
}
@Test
void testRouteReturnAll() {
StateRouter router = new ScriptStateRouterFactory()
.getRouter(String.class, getRouteUrl("function route(op1,op2){return op1} route(invokers)"));
List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
originInvokers.add(new MockInvoker<String>());
originInvokers.add(new MockInvoker<String>());
originInvokers.add(new MockInvoker<String>());
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
List<Invoker<String>> filteredInvokers =
router.route(invokers.clone(), invokers.get(0).getUrl(), new RpcInvocation(), false, new Holder<>());
Assertions.assertEquals(invokers, filteredInvokers);
}
@Test
void testRoutePickInvokers() {
String rule = "var result = new java.util.ArrayList(invokers.size());" + "for (i=0;i<invokers.size(); i++){ "
+ "if (invokers.get(i).isAvailable()) {"
+ "result.add(invokers.get(i)) ;"
+ "}"
+ "} ; "
+ "return result;";
String script = "function route(invokers,invocation,context){" + rule + "} route(invokers,invocation,context)";
StateRouter router = new ScriptStateRouterFactory().getRouter(String.class, getRouteUrl(script));
List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
Invoker<String> invoker1 = new MockInvoker<String>(false);
Invoker<String> invoker2 = new MockInvoker<String>(true);
Invoker<String> invoker3 = new MockInvoker<String>(true);
originInvokers.add(invoker1);
originInvokers.add(invoker2);
originInvokers.add(invoker3);
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
List<Invoker<String>> filteredInvokers =
router.route(invokers.clone(), invokers.get(0).getUrl(), new RpcInvocation(), false, new Holder<>());
Assertions.assertEquals(2, filteredInvokers.size());
Assertions.assertEquals(invoker2, filteredInvokers.get(0));
Assertions.assertEquals(invoker3, filteredInvokers.get(1));
}
@Test
void testRouteHostFilter() {
List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
MockInvoker<String> invoker1 =
new MockInvoker<String>(URL.valueOf("dubbo://10.134.108.1:20880/com.dubbo.HelloService"));
MockInvoker<String> invoker2 =
new MockInvoker<String>(URL.valueOf("dubbo://10.134.108.2:20880/com.dubbo.HelloService"));
MockInvoker<String> invoker3 =
new MockInvoker<String>(URL.valueOf("dubbo://10.134.108.3:20880/com.dubbo.HelloService"));
originInvokers.add(invoker1);
originInvokers.add(invoker2);
originInvokers.add(invoker3);
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
String script = "function route(invokers, invocation, context){ "
+ " var result = new java.util.ArrayList(invokers.size()); "
+ " var targetHost = new java.util.ArrayList(); "
+ " targetHost.add(\"10.134.108.2\"); "
+ " for (var i = 0; i < invokers.length; i++) { "
+ " if(targetHost.contains(invokers[i].getUrl().getHost())){ "
+ " result.add(invokers[i]); "
+ " } "
+ " } "
+ " return result; "
+ "} "
+ "route(invokers, invocation, context) ";
StateRouter router = new ScriptStateRouterFactory().getRouter(String.class, getRouteUrl(script));
List<Invoker<String>> routeResult =
router.route(invokers.clone(), invokers.get(0).getUrl(), new RpcInvocation(), false, new Holder<>());
Assertions.assertEquals(1, routeResult.size());
Assertions.assertEquals(invoker2, routeResult.get(0));
}
@Test
void testRoute_throwException() {
List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
MockInvoker<String> invoker1 =
new MockInvoker<String>(URL.valueOf("dubbo://10.134.108.1:20880/com.dubbo.HelloService"));
MockInvoker<String> invoker2 =
new MockInvoker<String>(URL.valueOf("dubbo://10.134.108.2:20880/com.dubbo.HelloService"));
MockInvoker<String> invoker3 =
new MockInvoker<String>(URL.valueOf("dubbo://10.134.108.3:20880/com.dubbo.HelloService"));
originInvokers.add(invoker1);
originInvokers.add(invoker2);
originInvokers.add(invoker3);
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
String script = "/";
StateRouter router = new ScriptStateRouterFactory().getRouter(String.class, getRouteUrl(script));
List<Invoker<String>> routeResult =
router.route(invokers.clone(), invokers.get(0).getUrl(), new RpcInvocation(), false, new Holder<>());
Assertions.assertEquals(3, routeResult.size());
}
}
| 7,812 |
0 |
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/script
|
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/script/config/AppScriptStateRouterTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.script.config;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.common.utils.Holder;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.governance.GovernanceRuleRepository;
import org.apache.dubbo.rpc.cluster.router.MockInvoker;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledForJreRange;
import org.junit.jupiter.api.condition.JRE;
import org.mockito.Mockito;
import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_APPLICATION_KEY;
@DisabledForJreRange(min = JRE.JAVA_16)
public class AppScriptStateRouterTest {
private static final String LOCAL_HOST = "127.0.0.1";
private static final String RULE_SUFFIX = ".script-router";
private static GovernanceRuleRepository ruleRepository;
private URL url = URL.valueOf("dubbo://1.1.1.1/com.foo.BarService");
private String rawRule = "---\n" + "configVersion: v3.0\n"
+ "key: demo-provider\n"
+ "type: javascript\n"
+ "script: |\n"
+ " (function route(invokers,invocation,context) {\n"
+ " var result = new java.util.ArrayList(invokers.size());\n"
+ " for (i = 0; i < invokers.size(); i ++) {\n"
+ " if (\"10.20.3.3\".equals(invokers.get(i).getUrl().getHost())) {\n"
+ " result.add(invokers.get(i));\n"
+ " }\n"
+ " }\n"
+ " return result;\n"
+ " } (invokers, invocation, context)); // 表示立即执行方法\n"
+ "...";
@BeforeAll
public static void setUpBeforeClass() throws Exception {
ruleRepository = Mockito.mock(GovernanceRuleRepository.class);
}
@Test
void testConfigScriptRoute() {
AppScriptStateRouter<String> router = new AppScriptStateRouter<>(url);
router = Mockito.spy(router);
Mockito.when(router.getRuleRepository()).thenReturn(ruleRepository);
Mockito.when(ruleRepository.getRule("demo-provider" + RULE_SUFFIX, DynamicConfiguration.DEFAULT_GROUP))
.thenReturn(rawRule);
// Mockito.when(ruleRepository.addListener()).thenReturn();
BitList<Invoker<String>> invokers = getInvokers();
router.notify(invokers);
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("sayHello");
List<Invoker<String>> result = router.route(invokers.clone(), url, invocation, false, new Holder<>());
Assertions.assertEquals(1, result.size());
}
private BitList<Invoker<String>> getInvokers() {
List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
Invoker<String> invoker1 = new MockInvoker<String>(
URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService?" + REMOTE_APPLICATION_KEY + "=demo-provider"));
Invoker<String> invoker2 = new MockInvoker<String>(URL.valueOf(
"dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService?" + REMOTE_APPLICATION_KEY + "=demo-provider"));
Invoker<String> invoker3 = new MockInvoker<String>(URL.valueOf(
"dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService?" + REMOTE_APPLICATION_KEY + "=demo-provider"));
originInvokers.add(invoker1);
originInvokers.add(invoker2);
originInvokers.add(invoker3);
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
return invokers;
}
}
| 7,813 |
0 |
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router
|
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionStateRouterTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.condition;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.Holder;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.router.MockInvoker;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import org.apache.dubbo.rpc.cluster.router.state.StateRouter;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.rpc.cluster.Constants.FORCE_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.RULE_KEY;
class ConditionStateRouterTest {
private static final String LOCAL_HOST = "127.0.0.1";
private URL SCRIPT_URL = URL.valueOf("condition://0.0.0.0/com.foo.BarService");
@BeforeAll
public static void setUpBeforeClass() throws Exception {}
@BeforeEach
public void setUp() throws Exception {}
private URL getRouteUrl(String rule) {
return SCRIPT_URL.addParameterAndEncoded(RULE_KEY, rule);
}
@Test
void testRoute_matchWhen() {
Invocation invocation = new RpcInvocation();
StateRouter router =
new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl(" => host = 1.2.3.4"));
boolean matchWhen = ((ConditionStateRouter) router)
.matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation);
Assertions.assertTrue(matchWhen);
router = new ConditionStateRouterFactory()
.getRouter(String.class, getRouteUrl("host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4"));
matchWhen = ((ConditionStateRouter) router)
.matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation);
Assertions.assertTrue(matchWhen);
router = new ConditionStateRouterFactory()
.getRouter(
String.class, getRouteUrl("host = 2.2.2.2,1.1.1.1,3.3.3.3 & host !=1.1.1.1 => host = 1.2.3.4"));
matchWhen = ((ConditionStateRouter) router)
.matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation);
Assertions.assertFalse(matchWhen);
router = new ConditionStateRouterFactory()
.getRouter(
String.class, getRouteUrl("host !=4.4.4.4 & host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4"));
matchWhen = ((ConditionStateRouter) router)
.matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation);
Assertions.assertTrue(matchWhen);
router = new ConditionStateRouterFactory()
.getRouter(
String.class, getRouteUrl("host !=4.4.4.* & host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4"));
matchWhen = ((ConditionStateRouter) router)
.matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation);
Assertions.assertTrue(matchWhen);
router = new ConditionStateRouterFactory()
.getRouter(
String.class,
getRouteUrl("host = 2.2.2.2,1.1.1.*,3.3.3.3 & host != 1.1.1.1 => host = 1.2.3.4"));
matchWhen = ((ConditionStateRouter) router)
.matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation);
Assertions.assertFalse(matchWhen);
router = new ConditionStateRouterFactory()
.getRouter(
String.class,
getRouteUrl("host = 2.2.2.2,1.1.1.*,3.3.3.3 & host != 1.1.1.2 => host = 1.2.3.4"));
matchWhen = ((ConditionStateRouter) router)
.matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation);
Assertions.assertTrue(matchWhen);
}
@Test
void testRoute_matchFilter() {
List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
Invoker<String> invoker1 = new MockInvoker<String>(
URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService?serialization=fastjson"));
Invoker<String> invoker2 =
new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
Invoker<String> invoker3 =
new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
originInvokers.add(invoker1);
originInvokers.add(invoker2);
originInvokers.add(invoker3);
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
System.err.println("The localhost address: " + invoker2.getUrl().getAddress());
System.err.println(invoker3.getUrl().getAddress());
StateRouter router1 = new ConditionStateRouterFactory()
.getRouter(
String.class,
getRouteUrl("host = " + LOCAL_HOST + " => " + " host = 10.20.3.3")
.addParameter(FORCE_KEY, String.valueOf(true)));
StateRouter router2 = new ConditionStateRouterFactory()
.getRouter(
String.class,
getRouteUrl("host = " + LOCAL_HOST + " => " + " host = 10.20.3.* & host != 10.20.3.3")
.addParameter(FORCE_KEY, String.valueOf(true)));
StateRouter router3 = new ConditionStateRouterFactory()
.getRouter(
String.class,
getRouteUrl("host = " + LOCAL_HOST + " => " + " host = 10.20.3.3 & host != 10.20.3.3")
.addParameter(FORCE_KEY, String.valueOf(true)));
StateRouter router4 = new ConditionStateRouterFactory()
.getRouter(
String.class,
getRouteUrl("host = " + LOCAL_HOST + " => " + " host = 10.20.3.2,10.20.3.3,10.20.3.4")
.addParameter(FORCE_KEY, String.valueOf(true)));
StateRouter router5 = new ConditionStateRouterFactory()
.getRouter(
String.class,
getRouteUrl("host = " + LOCAL_HOST + " => " + " host != 10.20.3.3")
.addParameter(FORCE_KEY, String.valueOf(true)));
StateRouter router6 = new ConditionStateRouterFactory()
.getRouter(
String.class,
getRouteUrl("host = " + LOCAL_HOST + " => " + " serialization = fastjson")
.addParameter(FORCE_KEY, String.valueOf(true)));
List<Invoker<String>> filteredInvokers1 = router1.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
new RpcInvocation(),
false,
new Holder<>());
List<Invoker<String>> filteredInvokers2 = router2.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
new RpcInvocation(),
false,
new Holder<>());
List<Invoker<String>> filteredInvokers3 = router3.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
new RpcInvocation(),
false,
new Holder<>());
List<Invoker<String>> filteredInvokers4 = router4.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
new RpcInvocation(),
false,
new Holder<>());
List<Invoker<String>> filteredInvokers5 = router5.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
new RpcInvocation(),
false,
new Holder<>());
List<Invoker<String>> filteredInvokers6 = router6.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
new RpcInvocation(),
false,
new Holder<>());
Assertions.assertEquals(1, filteredInvokers1.size());
Assertions.assertEquals(0, filteredInvokers2.size());
Assertions.assertEquals(0, filteredInvokers3.size());
Assertions.assertEquals(1, filteredInvokers4.size());
Assertions.assertEquals(2, filteredInvokers5.size());
Assertions.assertEquals(1, filteredInvokers6.size());
}
@Test
void testRoute_methodRoute() {
Invocation invocation = new RpcInvocation("getFoo", "com.foo.BarService", "", new Class<?>[0], new Object[0]);
// More than one methods, mismatch
StateRouter router = new ConditionStateRouterFactory()
.getRouter(String.class, getRouteUrl("methods=getFoo => host = 1.2.3.4"));
boolean matchWhen = ((ConditionStateRouter) router)
.matchWhen(
URL.valueOf("consumer://1.1.1.1/com.foo.BarService?methods=setFoo,getFoo,findFoo"), invocation);
Assertions.assertTrue(matchWhen);
// Exactly one method, match
matchWhen = ((ConditionStateRouter) router)
.matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService?methods=getFoo"), invocation);
Assertions.assertTrue(matchWhen);
// Method routing and Other condition routing can work together
StateRouter router2 = new ConditionStateRouterFactory()
.getRouter(String.class, getRouteUrl("methods=getFoo & host!=1.1.1.1 => host = 1.2.3.4"));
matchWhen = ((ConditionStateRouter) router2)
.matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService?methods=getFoo"), invocation);
Assertions.assertFalse(matchWhen);
StateRouter router3 = new ConditionStateRouterFactory()
.getRouter(String.class, getRouteUrl("methods=getFoo & host=1.1.1.1 => host = 1.2.3.4"));
matchWhen = ((ConditionStateRouter) router3)
.matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService?methods=getFoo"), invocation);
Assertions.assertTrue(matchWhen);
// Test filter condition
List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
Invoker<String> invoker1 = new MockInvoker<String>(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService"));
Invoker<String> invoker2 =
new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
Invoker<String> invoker3 =
new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
originInvokers.add(invoker1);
originInvokers.add(invoker2);
originInvokers.add(invoker3);
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
StateRouter router4 = new ConditionStateRouterFactory()
.getRouter(
String.class,
getRouteUrl("host = " + LOCAL_HOST + " & methods = getFoo => " + " host = 10.20.3.3")
.addParameter(FORCE_KEY, String.valueOf(true)));
List<Invoker<String>> filteredInvokers1 = router4.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
invocation,
false,
new Holder<>());
Assertions.assertEquals(1, filteredInvokers1.size());
StateRouter router5 = new ConditionStateRouterFactory()
.getRouter(
String.class,
getRouteUrl("host = " + LOCAL_HOST + " & methods = unvalidmethod => " + " host = 10.20.3.3")
.addParameter(FORCE_KEY, String.valueOf(true)));
List<Invoker<String>> filteredInvokers2 = router5.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
invocation,
false,
new Holder<>());
Assertions.assertEquals(3, filteredInvokers2.size());
// Request a non-exists method
}
@Test
void testRoute_ReturnFalse() {
StateRouter router = new ConditionStateRouterFactory()
.getRouter(String.class, getRouteUrl("host = " + LOCAL_HOST + " => false"));
List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
originInvokers.add(new MockInvoker<String>());
originInvokers.add(new MockInvoker<String>());
originInvokers.add(new MockInvoker<String>());
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
List<Invoker<String>> filteredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
new RpcInvocation(),
false,
new Holder<>());
Assertions.assertEquals(0, filteredInvokers.size());
}
@Test
void testRoute_ReturnEmpty() {
StateRouter router =
new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("host = " + LOCAL_HOST + " => "));
List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
originInvokers.add(new MockInvoker<String>());
originInvokers.add(new MockInvoker<String>());
originInvokers.add(new MockInvoker<String>());
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
List<Invoker<String>> filteredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
new RpcInvocation(),
false,
new Holder<>());
Assertions.assertEquals(0, filteredInvokers.size());
}
@Test
void testRoute_ReturnAll() {
StateRouter router = new ConditionStateRouterFactory()
.getRouter(String.class, getRouteUrl("host = " + LOCAL_HOST + " => " + " host = " + LOCAL_HOST));
List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
originInvokers.add(new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")));
originInvokers.add(new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")));
originInvokers.add(new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")));
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
List<Invoker<String>> filteredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
new RpcInvocation(),
false,
new Holder<>());
Assertions.assertEquals(invokers, filteredInvokers);
}
@Test
void testRoute_HostFilter() {
StateRouter router = new ConditionStateRouterFactory()
.getRouter(String.class, getRouteUrl("host = " + LOCAL_HOST + " => " + " host = " + LOCAL_HOST));
List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
Invoker<String> invoker1 = new MockInvoker<String>(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService"));
Invoker<String> invoker2 =
new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
Invoker<String> invoker3 =
new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
originInvokers.add(invoker1);
originInvokers.add(invoker2);
originInvokers.add(invoker3);
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
List<Invoker<String>> filteredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
new RpcInvocation(),
false,
new Holder<>());
Assertions.assertEquals(2, filteredInvokers.size());
Assertions.assertEquals(invoker2, filteredInvokers.get(0));
Assertions.assertEquals(invoker3, filteredInvokers.get(1));
}
@Test
void testRoute_Empty_HostFilter() {
StateRouter router = new ConditionStateRouterFactory()
.getRouter(String.class, getRouteUrl(" => " + " host = " + LOCAL_HOST));
List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
Invoker<String> invoker1 = new MockInvoker<String>(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService"));
Invoker<String> invoker2 =
new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
Invoker<String> invoker3 =
new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
originInvokers.add(invoker1);
originInvokers.add(invoker2);
originInvokers.add(invoker3);
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
List<Invoker<String>> filteredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
new RpcInvocation(),
false,
new Holder<>());
Assertions.assertEquals(2, filteredInvokers.size());
Assertions.assertEquals(invoker2, filteredInvokers.get(0));
Assertions.assertEquals(invoker3, filteredInvokers.get(1));
}
@Test
void testRoute_False_HostFilter() {
StateRouter router = new ConditionStateRouterFactory()
.getRouter(String.class, getRouteUrl("true => " + " host = " + LOCAL_HOST));
List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
Invoker<String> invoker1 = new MockInvoker<String>(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService"));
Invoker<String> invoker2 =
new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
Invoker<String> invoker3 =
new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
originInvokers.add(invoker1);
originInvokers.add(invoker2);
originInvokers.add(invoker3);
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
List<Invoker<String>> filteredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
new RpcInvocation(),
false,
new Holder<>());
Assertions.assertEquals(2, filteredInvokers.size());
Assertions.assertEquals(invoker2, filteredInvokers.get(0));
Assertions.assertEquals(invoker3, filteredInvokers.get(1));
}
@Test
void testRoute_Placeholder() {
StateRouter router = new ConditionStateRouterFactory()
.getRouter(String.class, getRouteUrl("host = " + LOCAL_HOST + " => " + " host = $host"));
List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
Invoker<String> invoker1 = new MockInvoker<String>(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService"));
Invoker<String> invoker2 =
new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
Invoker<String> invoker3 =
new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
originInvokers.add(invoker1);
originInvokers.add(invoker2);
originInvokers.add(invoker3);
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
List<Invoker<String>> filteredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
new RpcInvocation(),
false,
new Holder<>());
Assertions.assertEquals(2, filteredInvokers.size());
Assertions.assertEquals(invoker2, filteredInvokers.get(0));
Assertions.assertEquals(invoker3, filteredInvokers.get(1));
}
@Test
void testRoute_NoForce() {
StateRouter router = new ConditionStateRouterFactory()
.getRouter(String.class, getRouteUrl("host = " + LOCAL_HOST + " => " + " host = 1.2.3.4"));
List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
Invoker<String> invoker1 = new MockInvoker<String>(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService"));
Invoker<String> invoker2 =
new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
Invoker<String> invoker3 =
new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
originInvokers.add(invoker1);
originInvokers.add(invoker2);
originInvokers.add(invoker3);
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
List<Invoker<String>> filteredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
new RpcInvocation(),
false,
new Holder<>());
Assertions.assertEquals(invokers, filteredInvokers);
}
@Test
void testRoute_Force() {
StateRouter router = new ConditionStateRouterFactory()
.getRouter(
String.class,
getRouteUrl("host = " + LOCAL_HOST + " => " + " host = 1.2.3.4")
.addParameter(FORCE_KEY, String.valueOf(true)));
List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
Invoker<String> invoker1 = new MockInvoker<String>(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService"));
Invoker<String> invoker2 =
new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
Invoker<String> invoker3 =
new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
originInvokers.add(invoker1);
originInvokers.add(invoker2);
originInvokers.add(invoker3);
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
List<Invoker<String>> filteredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
new RpcInvocation(),
false,
new Holder<>());
Assertions.assertEquals(0, filteredInvokers.size());
}
@Test
void testRoute_Arguments() {
StateRouter router = new ConditionStateRouterFactory()
.getRouter(
String.class,
getRouteUrl("arguments[0] = a " + " => " + " host = 1.2.3.4")
.addParameter(FORCE_KEY, String.valueOf(true)));
List<Invoker<String>> originInvokers = new ArrayList<>();
Invoker<String> invoker1 = new MockInvoker<>(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService"));
Invoker<String> invoker2 =
new MockInvoker<>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
Invoker<String> invoker3 =
new MockInvoker<>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
originInvokers.add(invoker1);
originInvokers.add(invoker2);
originInvokers.add(invoker3);
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
RpcInvocation invocation = new RpcInvocation();
String p = "a";
invocation.setArguments(new Object[] {null});
List<Invoker<String>> fileredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
invocation,
false,
new Holder<>());
Assertions.assertEquals(3, fileredInvokers.size());
invocation.setArguments(new Object[] {p});
fileredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
invocation,
false,
new Holder<>());
Assertions.assertEquals(0, fileredInvokers.size());
router = new ConditionStateRouterFactory()
.getRouter(
String.class,
getRouteUrl("arguments = b " + " => " + " host = 1.2.3.4")
.addParameter(FORCE_KEY, String.valueOf(true)));
fileredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
invocation,
false,
new Holder<>());
Assertions.assertEquals(3, fileredInvokers.size());
router = new ConditionStateRouterFactory()
.getRouter(
String.class,
getRouteUrl("arguments[10].inner = a " + " => " + " host = 1.2.3.4")
.addParameter(FORCE_KEY, String.valueOf(true)));
fileredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
invocation,
false,
new Holder<>());
Assertions.assertEquals(3, fileredInvokers.size());
int integer = 1;
invocation.setArguments(new Object[] {integer});
router = new ConditionStateRouterFactory()
.getRouter(
String.class,
getRouteUrl("arguments[0].inner = 1 " + " => " + " host = 1.2.3.4")
.addParameter(FORCE_KEY, String.valueOf(true)));
fileredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
invocation,
false,
new Holder<>());
Assertions.assertEquals(0, fileredInvokers.size());
}
@Test
void testRoute_Attachments() {
StateRouter router = new ConditionStateRouterFactory()
.getRouter(
String.class,
getRouteUrl("attachments[foo] = a " + " => " + " host = 1.2.3.4")
.addParameter(FORCE_KEY, String.valueOf(true)));
List<Invoker<String>> originInvokers = new ArrayList<>();
Invoker<String> invoker1 =
new MockInvoker<>(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService?region=hangzhou"));
Invoker<String> invoker2 =
new MockInvoker<>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
Invoker<String> invoker3 =
new MockInvoker<>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
originInvokers.add(invoker1);
originInvokers.add(invoker2);
originInvokers.add(invoker3);
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
RpcInvocation invocation = new RpcInvocation();
List<Invoker<String>> fileredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
invocation,
false,
new Holder<>());
Assertions.assertEquals(3, fileredInvokers.size());
invocation.setAttachment("foo", "a");
fileredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
invocation,
false,
new Holder<>());
Assertions.assertEquals(0, fileredInvokers.size());
router = new ConditionStateRouterFactory()
.getRouter(
String.class,
getRouteUrl("attachments = a " + " => " + " host = 1.2.3.4")
.addParameter(FORCE_KEY, String.valueOf(true)));
fileredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
invocation,
false,
new Holder<>());
Assertions.assertEquals(3, fileredInvokers.size());
router = new ConditionStateRouterFactory()
.getRouter(
String.class,
getRouteUrl("attachments[foo] = a " + " => " + " region = hangzhou")
.addParameter(FORCE_KEY, String.valueOf(true)));
fileredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
invocation,
false,
new Holder<>());
Assertions.assertEquals(1, fileredInvokers.size());
}
@Test
void testRoute_Range_Pattern() {
StateRouter router = new ConditionStateRouterFactory()
.getRouter(
String.class,
getRouteUrl("attachments[user_id] = 1~100 " + " => " + " region=hangzhou")
.addParameter(FORCE_KEY, String.valueOf(true)));
List<Invoker<String>> originInvokers = new ArrayList<>();
Invoker<String> invoker1 =
new MockInvoker<>(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService?region=hangzhou"));
Invoker<String> invoker2 =
new MockInvoker<>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
Invoker<String> invoker3 =
new MockInvoker<>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
originInvokers.add(invoker1);
originInvokers.add(invoker2);
originInvokers.add(invoker3);
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
RpcInvocation invocation = new RpcInvocation();
List<Invoker<String>> fileredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
invocation,
false,
new Holder<>());
Assertions.assertEquals(3, fileredInvokers.size());
invocation.setAttachment("user_id", "80");
fileredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
invocation,
false,
new Holder<>());
Assertions.assertEquals(1, fileredInvokers.size());
invocation.setAttachment("user_id", "101");
fileredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
invocation,
false,
new Holder<>());
Assertions.assertEquals(3, fileredInvokers.size());
router = new ConditionStateRouterFactory()
.getRouter(
String.class,
getRouteUrl("attachments[user_id] = ~100 " + " => " + " region = hangzhou")
.addParameter(FORCE_KEY, String.valueOf(true)));
invocation.setAttachment("user_id", "1");
fileredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
invocation,
false,
new Holder<>());
Assertions.assertEquals(1, fileredInvokers.size());
router = new ConditionStateRouterFactory()
.getRouter(
String.class,
getRouteUrl("attachments[user_id] = ~100 " + " => " + " region = hangzhou")
.addParameter(FORCE_KEY, String.valueOf(true)));
invocation.setAttachment("user_id", "101");
fileredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
invocation,
false,
new Holder<>());
Assertions.assertEquals(3, fileredInvokers.size());
router = new ConditionStateRouterFactory()
.getRouter(
String.class,
getRouteUrl("attachments[user_id] = ~100 " + " => " + " region = hangzhou")
.addParameter(FORCE_KEY, String.valueOf(true)));
fileredInvokers = router.route(
invokers.clone(),
URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"),
invocation,
false,
new Holder<>());
Assertions.assertEquals(3, fileredInvokers.size());
}
@Test
void testRoute_Key_Not_Exist() {
StateRouter router = new ConditionStateRouterFactory()
.getRouter(
String.class,
getRouteUrl("when_key=a " + " => " + " not_exist_then_key = any_value")
.addParameter(FORCE_KEY, String.valueOf(true)));
List<Invoker<String>> originInvokers = new ArrayList<>();
Invoker<String> invoker1 =
new MockInvoker<>(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService?then_key=a"));
Invoker<String> invoker2 =
new MockInvoker<>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
Invoker<String> invoker3 =
new MockInvoker<>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
originInvokers.add(invoker1);
originInvokers.add(invoker2);
originInvokers.add(invoker3);
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
URL consumer = URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService?when_key=a");
List<Invoker<String>> fileredInvokers = router.route(invokers.clone(), consumer, null, false, new Holder<>());
Assertions.assertEquals(0, fileredInvokers.size());
router = new ConditionStateRouterFactory()
.getRouter(
String.class,
getRouteUrl("not_exist_when_key=a " + " => " + " then_key = a")
.addParameter(FORCE_KEY, String.valueOf(true)));
fileredInvokers = router.route(invokers, consumer, null, false, new Holder<>());
Assertions.assertEquals(3, fileredInvokers.size());
}
@Test
void testRoute_Multiple_Conditions() {
List<Invoker<String>> originInvokers = new ArrayList<>();
Invoker<String> invoker1 = new MockInvoker<>(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService"));
Invoker<String> invoker2 =
new MockInvoker<>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
Invoker<String> invoker3 =
new MockInvoker<>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"));
originInvokers.add(invoker1);
originInvokers.add(invoker2);
originInvokers.add(invoker3);
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
RpcInvocation invocation = new RpcInvocation();
String p = "a";
invocation.setArguments(new Object[] {p});
// all conditions match
URL consumer1 = URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService?application=consumer_app");
StateRouter router = new ConditionStateRouterFactory()
.getRouter(
String.class,
getRouteUrl("application=consumer_app&arguments[0]=a" + " => " + " host = " + LOCAL_HOST)
.addParameter(FORCE_KEY, String.valueOf(true)));
List<Invoker<String>> fileredInvokers =
router.route(invokers.clone(), consumer1, invocation, false, new Holder<>());
Assertions.assertEquals(2, fileredInvokers.size());
// one of the conditions does not match
URL consume2 = URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService?application=another_consumer_app");
StateRouter router2 = new ConditionStateRouterFactory()
.getRouter(
String.class,
getRouteUrl("application=consumer_app&arguments[0]=a" + " => " + " host = " + LOCAL_HOST)
.addParameter(FORCE_KEY, String.valueOf(true)));
fileredInvokers = router2.route(invokers.clone(), consume2, invocation, false, new Holder<>());
Assertions.assertEquals(3, fileredInvokers.size());
}
}
| 7,814 |
0 |
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition
|
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/config/ProviderAppConditionStateRouterTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.condition.config;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.common.utils.Holder;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.governance.GovernanceRuleRepository;
import org.apache.dubbo.rpc.cluster.router.MockInvoker;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_APPLICATION_KEY;
public class ProviderAppConditionStateRouterTest {
private static final String LOCAL_HOST = "127.0.0.1";
private static final String RULE_SUFFIX = ".condition-router";
private static GovernanceRuleRepository ruleRepository;
private URL url = URL.valueOf("consumer://1.1.1.1/com.foo.BarService");
private String rawRule = "---\n" + "configVersion: v3.0\n"
+ "scope: application\n"
+ "force: true\n"
+ "runtime: false\n"
+ "enabled: true\n"
+ "priority: 1\n"
+ "key: demo-provider\n"
+ "conditions:\n"
+ "- method=sayHello => region=hangzhou\n"
+ "...";
@BeforeAll
public static void setUpBeforeClass() throws Exception {
ruleRepository = Mockito.mock(GovernanceRuleRepository.class);
}
@Test
void test() {
ProviderAppStateRouter<String> router = new ProviderAppStateRouter<>(url);
router = Mockito.spy(router);
Mockito.when(router.getRuleRepository()).thenReturn(ruleRepository);
Mockito.when(ruleRepository.getRule("demo-provider" + RULE_SUFFIX, DynamicConfiguration.DEFAULT_GROUP))
.thenReturn(rawRule);
// Mockito.when(ruleRepository.addListener()).thenReturn();
BitList<Invoker<String>> invokers = getInvokers();
router.notify(invokers);
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("sayHello");
List<Invoker<String>> result = router.route(invokers.clone(), url, invocation, false, new Holder<>());
Assertions.assertEquals(1, result.size());
invocation.setMethodName("sayHi");
result = router.route(invokers.clone(), url, invocation, false, new Holder<>());
Assertions.assertEquals(3, result.size());
}
private BitList<Invoker<String>> getInvokers() {
List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
Invoker<String> invoker1 = new MockInvoker<String>(
URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService?" + REMOTE_APPLICATION_KEY + "=demo-provider"));
Invoker<String> invoker2 = new MockInvoker<String>(URL.valueOf("dubbo://" + LOCAL_HOST
+ ":20880/com.foo.BarService?" + REMOTE_APPLICATION_KEY + "=demo-provider®ion=hangzhou"));
Invoker<String> invoker3 = new MockInvoker<String>(URL.valueOf(
"dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService?" + REMOTE_APPLICATION_KEY + "=demo-provider"));
originInvokers.add(invoker1);
originInvokers.add(invoker2);
originInvokers.add(invoker3);
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
return invokers;
}
}
| 7,815 |
0 |
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router
|
Create_ds/dubbo/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/tag/TagStateRouterTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.tag;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.beans.factory.ScopeBeanFactory;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.utils.Holder;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.router.MockInvoker;
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.state.StateRouter;
import org.apache.dubbo.rpc.cluster.router.tag.model.TagRouterRule;
import org.apache.dubbo.rpc.cluster.router.tag.model.TagRuleParser;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.apache.dubbo.common.constants.CommonConstants.TAG_KEY;
import static org.mockito.Mockito.when;
class TagStateRouterTest {
private URL url;
private ModuleModel originModel;
private ModuleModel moduleModel;
private Set<TracingContextProvider> tracingContextProviders;
@BeforeEach
public void setup() {
originModel = ApplicationModel.defaultModel().getDefaultModule();
moduleModel = Mockito.spy(originModel);
ScopeBeanFactory originBeanFactory = originModel.getBeanFactory();
ScopeBeanFactory beanFactory = Mockito.spy(originBeanFactory);
when(moduleModel.getBeanFactory()).thenReturn(beanFactory);
ExtensionLoader<TracingContextProvider> extensionLoader = Mockito.mock(ExtensionLoader.class);
tracingContextProviders = new HashSet<>();
when(extensionLoader.getSupportedExtensionInstances()).thenReturn(tracingContextProviders);
when(moduleModel.getExtensionLoader(TracingContextProvider.class)).thenReturn(extensionLoader);
url = URL.valueOf("test://localhost/DemoInterface").setScopeModel(moduleModel);
}
@Test
void testTagRoutePickInvokers() {
StateRouter router = new TagStateRouterFactory().getRouter(TagRouterRule.class, url);
List<Invoker<String>> originInvokers = new ArrayList<>();
URL url1 = URL.valueOf("test://127.0.0.1:7777/DemoInterface?dubbo.tag=tag2")
.setScopeModel(moduleModel);
URL url2 = URL.valueOf("test://127.0.0.1:7778/DemoInterface").setScopeModel(moduleModel);
URL url3 = URL.valueOf("test://127.0.0.1:7779/DemoInterface").setScopeModel(moduleModel);
Invoker<String> invoker1 = new MockInvoker<>(url1, true);
Invoker<String> invoker2 = new MockInvoker<>(url2, true);
Invoker<String> invoker3 = new MockInvoker<>(url3, true);
originInvokers.add(invoker1);
originInvokers.add(invoker2);
originInvokers.add(invoker3);
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
RpcInvocation invocation = new RpcInvocation();
invocation.setAttachment(TAG_KEY, "tag2");
List<Invoker<String>> filteredInvokers =
router.route(invokers.clone(), invokers.get(0).getUrl(), invocation, false, new Holder<>());
Assertions.assertEquals(1, filteredInvokers.size());
Assertions.assertEquals(invoker1, filteredInvokers.get(0));
}
@Test
void testTagRouteWithDynamicRuleV3() {
TagStateRouter router = (TagStateRouter) new TagStateRouterFactory().getRouter(TagRouterRule.class, url);
router = Mockito.spy(router);
List<Invoker<String>> originInvokers = new ArrayList<>();
URL url1 = URL.valueOf("test://127.0.0.1:7777/DemoInterface?application=foo&dubbo.tag=tag2&match_key=value")
.setScopeModel(moduleModel);
URL url2 = URL.valueOf("test://127.0.0.1:7778/DemoInterface?application=foo&match_key=value")
.setScopeModel(moduleModel);
URL url3 = URL.valueOf("test://127.0.0.1:7779/DemoInterface?application=foo")
.setScopeModel(moduleModel);
Invoker<String> invoker1 = new MockInvoker<>(url1, true);
Invoker<String> invoker2 = new MockInvoker<>(url2, true);
Invoker<String> invoker3 = new MockInvoker<>(url3, true);
originInvokers.add(invoker1);
originInvokers.add(invoker2);
originInvokers.add(invoker3);
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
RpcInvocation invocation = new RpcInvocation();
invocation.setAttachment(TAG_KEY, "tag2");
TagRouterRule rule = getTagRule();
Mockito.when(router.getInvokers()).thenReturn(invokers);
rule.init(router);
router.setTagRouterRule(rule);
List<Invoker<String>> filteredInvokers =
router.route(invokers, invokers.get(0).getUrl(), invocation, false, new Holder<>());
Assertions.assertEquals(2, filteredInvokers.size());
// Assertions.(invoker1, filteredInvokers.get(0));
}
/**
* TagRouterRule parse test when the tags addresses is null
*
* <pre>
* ~ -> null
* null -> null
* </pre>
*/
@Test
void tagRouterRuleParseTest() {
String tagRouterRuleConfig = "---\n" + "force: false\n"
+ "runtime: true\n"
+ "enabled: false\n"
+ "priority: 1\n"
+ "key: demo-provider\n"
+ "tags:\n"
+ " - name: tag1\n"
+ " addresses: null\n"
+ " - name: tag2\n"
+ " addresses: [\"30.5.120.37:20880\"]\n"
+ " - name: tag3\n"
+ " addresses: []\n"
+ " - name: tag4\n"
+ " addresses: ~\n"
+ "...";
TagRouterRule tagRouterRule = TagRuleParser.parse(tagRouterRuleConfig);
TagStateRouter<?> router = Mockito.mock(TagStateRouter.class);
Mockito.when(router.getInvokers()).thenReturn(BitList.emptyList());
tagRouterRule.init(router);
// assert tags
assert tagRouterRule.getKey().equals("demo-provider");
assert tagRouterRule.getPriority() == 1;
assert tagRouterRule.getTagNames().contains("tag1");
assert tagRouterRule.getTagNames().contains("tag2");
assert tagRouterRule.getTagNames().contains("tag3");
assert tagRouterRule.getTagNames().contains("tag4");
// assert addresses
assert tagRouterRule.getAddresses().contains("30.5.120.37:20880");
assert tagRouterRule.getTagnameToAddresses().get("tag1") == null;
assert tagRouterRule.getTagnameToAddresses().get("tag2").size() == 1;
assert tagRouterRule.getTagnameToAddresses().get("tag3") == null;
assert tagRouterRule.getTagnameToAddresses().get("tag4") == null;
assert tagRouterRule.getAddresses().size() == 1;
}
@Test
void tagRouterRuleParseTestV3() {
String tagRouterRuleConfig = "---\n" + "configVersion: v3.0\n"
+ "force: false\n"
+ "runtime: true\n"
+ "enabled: true\n"
+ "priority: 1\n"
+ "key: demo-provider\n"
+ "tags:\n"
+ " - name: tag1\n"
+ " match:\n"
+ " - key: match_key1\n"
+ " value:\n"
+ " exact: value1\n"
+ " - name: tag2\n"
+ " addresses:\n"
+ " - \"10.20.3.3:20880\"\n"
+ " - \"10.20.3.4:20880\"\n"
+ " match:\n"
+ " - key: match_key2\n"
+ " value:\n"
+ " exact: value2\n"
+ " - name: tag3\n"
+ " match:\n"
+ " - key: match_key2\n"
+ " value:\n"
+ " exact: value2\n"
+ " - name: tag4\n"
+ " match:\n"
+ " - key: not_exist\n"
+ " value:\n"
+ " exact: not_exist\n"
+ " - name: tag5\n"
+ " match:\n"
+ " - key: match_key2\n"
+ " value:\n"
+ " wildcard: \"*\"\n"
+ "...";
TagRouterRule tagRouterRule = TagRuleParser.parse(tagRouterRuleConfig);
TagStateRouter<String> router = Mockito.mock(TagStateRouter.class);
Mockito.when(router.getInvokers()).thenReturn(getInvokers());
tagRouterRule.init(router);
// assert tags
assert tagRouterRule.getKey().equals("demo-provider");
assert tagRouterRule.getPriority() == 1;
assert tagRouterRule.getTagNames().contains("tag1");
assert tagRouterRule.getTagNames().contains("tag2");
assert tagRouterRule.getTagNames().contains("tag3");
assert tagRouterRule.getTagNames().contains("tag4");
// assert addresses
assert tagRouterRule.getAddresses().size() == 2;
assert tagRouterRule.getAddresses().contains("10.20.3.3:20880");
assert tagRouterRule.getTagnameToAddresses().get("tag1").size() == 2;
assert tagRouterRule.getTagnameToAddresses().get("tag2").size() == 2;
assert tagRouterRule.getTagnameToAddresses().get("tag3").size() == 1;
assert tagRouterRule.getTagnameToAddresses().get("tag5").size() == 1;
assert tagRouterRule.getTagnameToAddresses().get("tag4") == null;
}
public BitList<Invoker<String>> getInvokers() {
List<Invoker<String>> originInvokers = new ArrayList<Invoker<String>>();
Invoker<String> invoker1 = new MockInvoker<String>(
URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService?match_key1=value1&match_key2=value2"));
Invoker<String> invoker2 =
new MockInvoker<String>(URL.valueOf("dubbo://10.20.3.4:20880/com.foo.BarService?match_key1=value1"));
originInvokers.add(invoker1);
originInvokers.add(invoker2);
BitList<Invoker<String>> invokers = new BitList<>(originInvokers);
return invokers;
}
private TagRouterRule getTagRule() {
String tagRouterRuleConfig = "---\n" + "configVersion: v3.0\n"
+ "force: false\n"
+ "runtime: true\n"
+ "enabled: true\n"
+ "priority: 1\n"
+ "key: demo-provider\n"
+ "tags:\n"
+ " - name: tag2\n"
+ " match:\n"
+ " - key: match_key\n"
+ " value:\n"
+ " exact: value\n"
+ "...";
TagRouterRule tagRouterRule = TagRuleParser.parse(tagRouterRuleConfig);
return tagRouterRule;
}
}
| 7,816 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/registry/AddressListener.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.registry;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.rpc.cluster.Directory;
import java.util.List;
@SPI(scope = ExtensionScope.MODULE)
public interface AddressListener {
/**
* processing when receiving the address list
*
* @param addresses provider address list
* @param consumerUrl
* @param registryDirectory
*/
List<URL> notify(List<URL> addresses, URL consumerUrl, Directory registryDirectory);
default void destroy(URL consumerUrl, Directory registryDirectory) {}
}
| 7,817 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Merger.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster;
import org.apache.dubbo.common.extension.SPI;
@SPI
public interface Merger<T> {
T merge(T... items);
}
| 7,818 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Router.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.router.RouterResult;
import java.util.List;
/**
* Router. (SPI, Prototype, ThreadSafe)
* <p>
* <a href="http://en.wikipedia.org/wiki/Routing">Routing</a>
*
* @see org.apache.dubbo.rpc.cluster.Cluster#join(Directory, boolean)
* @see org.apache.dubbo.rpc.cluster.Directory#list(Invocation)
*/
public interface Router extends Comparable<Router> {
int DEFAULT_PRIORITY = Integer.MAX_VALUE;
/**
* Get the router url.
*
* @return url
*/
URL getUrl();
/**
* Filter invokers with current routing rule and only return the invokers that comply with the rule.
*
* @param invokers invoker list
* @param url refer url
* @param invocation invocation
* @return routed invokers
* @throws RpcException
*/
@Deprecated
default <T> List<Invoker<T>> route(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException {
return null;
}
/**
* ** This method can return the state of whether routerChain needed to continue route. **
* Filter invokers with current routing rule and only return the invokers that comply with the rule.
*
* @param invokers invoker list
* @param url refer url
* @param invocation invocation
* @param needToPrintMessage whether to print router state. Such as `use router branch a`.
* @return state with route result
* @throws RpcException
*/
default <T> RouterResult<Invoker<T>> route(
List<Invoker<T>> invokers, URL url, Invocation invocation, boolean needToPrintMessage) throws RpcException {
return new RouterResult<>(route(invokers, url, invocation));
}
/**
* Notify the router the invoker list. Invoker list may change from time to time. This method gives the router a
* chance to prepare before {@link Router#route(List, URL, Invocation)} gets called.
*
* @param invokers invoker list
* @param <T> invoker's type
*/
default <T> void notify(List<Invoker<T>> invokers) {}
/**
* To decide whether this router need to execute every time an RPC comes or should only execute when addresses or
* rule change.
*
* @return true if the router need to execute every time.
*/
boolean isRuntime();
/**
* To decide whether this router should take effect when none of the invoker can match the router rule, which
* means the {@link #route(List, URL, Invocation)} would be empty. Most of time, most router implementation would
* default this value to false.
*
* @return true to execute if none of invokers matches the current router
*/
boolean isForce();
/**
* Router's priority, used to sort routers.
*
* @return router's priority
*/
int getPriority();
default void stop() {
// do nothing by default
}
@Override
default int compareTo(Router o) {
if (o == null) {
throw new IllegalArgumentException();
}
return Integer.compare(this.getPriority(), o.getPriority());
}
}
| 7,819 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/RouterChain.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.ConfigurationUtils;
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.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.cluster.router.RouterSnapshotSwitcher;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import org.apache.dubbo.rpc.cluster.router.state.StateRouter;
import org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.apache.dubbo.rpc.model.ScopeModelUtil;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.stream.Collectors;
import static org.apache.dubbo.rpc.cluster.Constants.ROUTER_KEY;
/**
* Router chain
*/
public class RouterChain<T> {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(RouterChain.class);
private volatile SingleRouterChain<T> mainChain;
private volatile SingleRouterChain<T> backupChain;
private volatile SingleRouterChain<T> currentChain;
@SuppressWarnings({"rawtypes", "unchecked"})
public static <T> RouterChain<T> buildChain(Class<T> interfaceClass, URL url) {
SingleRouterChain<T> chain1 = buildSingleChain(interfaceClass, url);
SingleRouterChain<T> chain2 = buildSingleChain(interfaceClass, url);
return new RouterChain<>(new SingleRouterChain[] {chain1, chain2});
}
public static <T> SingleRouterChain<T> buildSingleChain(Class<T> interfaceClass, URL url) {
ModuleModel moduleModel = url.getOrDefaultModuleModel();
List<RouterFactory> extensionFactories =
moduleModel.getExtensionLoader(RouterFactory.class).getActivateExtension(url, ROUTER_KEY);
List<Router> routers = extensionFactories.stream()
.map(factory -> factory.getRouter(url))
.sorted(Router::compareTo)
.collect(Collectors.toList());
List<StateRouter<T>> stateRouters =
moduleModel.getExtensionLoader(StateRouterFactory.class).getActivateExtension(url, ROUTER_KEY).stream()
.map(factory -> factory.getRouter(interfaceClass, url))
.collect(Collectors.toList());
boolean shouldFailFast = Boolean.parseBoolean(
ConfigurationUtils.getProperty(moduleModel, Constants.SHOULD_FAIL_FAST_KEY, "true"));
RouterSnapshotSwitcher routerSnapshotSwitcher =
ScopeModelUtil.getFrameworkModel(moduleModel).getBeanFactory().getBean(RouterSnapshotSwitcher.class);
return new SingleRouterChain<>(routers, stateRouters, shouldFailFast, routerSnapshotSwitcher);
}
public RouterChain(SingleRouterChain<T>[] chains) {
if (chains.length != 2) {
throw new IllegalArgumentException("chains' size should be 2.");
}
this.mainChain = chains[0];
this.backupChain = chains[1];
this.currentChain = this.mainChain;
}
private final AtomicReference<BitList<Invoker<T>>> notifyingInvokers = new AtomicReference<>();
private final ReadWriteLock lock = new ReentrantReadWriteLock();
public ReadWriteLock getLock() {
return lock;
}
public SingleRouterChain<T> getSingleChain(URL url, BitList<Invoker<T>> availableInvokers, Invocation invocation) {
// If current is in:
// 1. `setInvokers` is in progress
// 2. Most of the invocation should use backup chain => currentChain == backupChain
// 3. Main chain has been update success => notifyingInvokers.get() != null
// If `availableInvokers` is created from origin invokers => use backup chain
// If `availableInvokers` is created from newly invokers => use main chain
BitList<Invoker<T>> notifying = notifyingInvokers.get();
if (notifying != null
&& currentChain == backupChain
&& availableInvokers.getOriginList() == notifying.getOriginList()) {
return mainChain;
}
return currentChain;
}
/**
* @deprecated use {@link RouterChain#getSingleChain(URL, BitList, Invocation)} and {@link SingleRouterChain#route(URL, BitList, Invocation)} instead
*/
@Deprecated
public List<Invoker<T>> route(URL url, BitList<Invoker<T>> availableInvokers, Invocation invocation) {
return getSingleChain(url, availableInvokers, invocation).route(url, availableInvokers, invocation);
}
/**
* Notify router chain of the initial addresses from registry at the first time.
* Notify whenever addresses in registry change.
*/
public synchronized void setInvokers(BitList<Invoker<T>> invokers, Runnable switchAction) {
try {
// Lock to prevent directory continue list
lock.writeLock().lock();
// Switch to back up chain. Will update main chain first.
currentChain = backupChain;
} finally {
// Release lock to minimize the impact for each newly created invocations as much as possible.
// Should not release lock until main chain update finished. Or this may cause long hang.
lock.writeLock().unlock();
}
// Refresh main chain.
// No one can request to use main chain. `currentChain` is backup chain. `route` method cannot access main
// chain.
try {
// Lock main chain to wait all invocation end
// To wait until no one is using main chain.
mainChain.getLock().writeLock().lock();
// refresh
mainChain.setInvokers(invokers);
} catch (Throwable t) {
logger.error(LoggerCodeConstants.INTERNAL_ERROR, "", "", "Error occurred when refreshing router chain.", t);
throw t;
} finally {
// Unlock main chain
mainChain.getLock().writeLock().unlock();
}
// Set the reference of newly invokers to temp variable.
// Reason: The next step will switch the invokers reference in directory, so we should check the
// `availableInvokers`
// argument when `route`. If the current invocation use newly invokers, we should use main chain to
// route, and
// this can prevent use newly invokers to route backup chain, which can only route origin invokers now.
notifyingInvokers.set(invokers);
// Switch the invokers reference in directory.
// Cannot switch before update main chain or after backup chain update success. Or that will cause state
// inconsistent.
switchAction.run();
try {
// Lock to prevent directory continue list
// The invokers reference in directory now should be the newly one and should always use the newly one once
// lock released.
lock.writeLock().lock();
// Switch to main chain. Will update backup chain later.
currentChain = mainChain;
// Clean up temp variable.
// `availableInvokers` check is useless now, because `route` method will no longer receive any
// `availableInvokers` related
// with the origin invokers. The getter of invokers reference in directory is locked now, and will return
// newly invokers
// once lock released.
notifyingInvokers.set(null);
} finally {
// Release lock to minimize the impact for each newly created invocations as much as possible.
// Will use newly invokers and main chain now.
lock.writeLock().unlock();
}
// Refresh main chain.
// No one can request to use main chain. `currentChain` is main chain. `route` method cannot access backup
// chain.
try {
// Lock main chain to wait all invocation end
backupChain.getLock().writeLock().lock();
// refresh
backupChain.setInvokers(invokers);
} catch (Throwable t) {
logger.error(LoggerCodeConstants.INTERNAL_ERROR, "", "", "Error occurred when refreshing router chain.", t);
throw t;
} finally {
// Unlock backup chain
backupChain.getLock().writeLock().unlock();
}
}
public synchronized void destroy() {
// 1. destroy another
backupChain.destroy();
// 2. switch
lock.writeLock().lock();
currentChain = backupChain;
lock.writeLock().unlock();
// 4. destroy
mainChain.destroy();
}
public void addRouters(List<Router> routers) {
mainChain.addRouters(routers);
backupChain.addRouters(routers);
}
public SingleRouterChain<T> getCurrentChain() {
return currentChain;
}
public List<Router> getRouters() {
return currentChain.getRouters();
}
public StateRouter<T> getHeadStateRouter() {
return currentChain.getHeadStateRouter();
}
@Deprecated
public List<StateRouter<T>> getStateRouters() {
return currentChain.getStateRouters();
}
}
| 7,820 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Directory.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster;
import org.apache.dubbo.common.Node;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import java.util.List;
/**
* Directory. (SPI, Prototype, ThreadSafe)
* <p>
* <a href="http://en.wikipedia.org/wiki/Directory_service">Directory Service</a>
*
* @see org.apache.dubbo.rpc.cluster.Cluster#join(Directory)
*/
public interface Directory<T> extends Node {
/**
* get service type.
*
* @return service type.
*/
Class<T> getInterface();
/**
* list invokers.
* filtered by invocation
*
* @return invokers
*/
List<Invoker<T>> list(Invocation invocation) throws RpcException;
/**
* list invokers
* include all invokers from registry
*/
List<Invoker<T>> getAllInvokers();
URL getConsumerUrl();
boolean isDestroyed();
default boolean isEmpty() {
return CollectionUtils.isEmpty(getAllInvokers());
}
default boolean isServiceDiscovery() {
return false;
}
void discordAddresses();
RouterChain<T> getRouterChain();
/**
* invalidate an invoker, add it into reconnect task, remove from list next time
* will be recovered by address refresh notification or reconnect success notification
*
* @param invoker invoker to invalidate
*/
void addInvalidateInvoker(Invoker<T> invoker);
/**
* disable an invoker, remove from list next time
* will be removed when invoker is removed by address refresh notification
* using in service offline notification
*
* @param invoker invoker to invalidate
*/
void addDisabledInvoker(Invoker<T> invoker);
/**
* recover a disabled invoker
*
* @param invoker invoker to invalidate
*/
void recoverDisabledInvoker(Invoker<T> invoker);
default boolean isNotificationReceived() {
return false;
}
}
| 7,821 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/LoadBalance.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Adaptive;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.loadbalance.RandomLoadBalance;
import java.util.List;
/**
* LoadBalance. (SPI, Singleton, ThreadSafe)
* <p>
* <a href="http://en.wikipedia.org/wiki/Load_balancing_(computing)">Load-Balancing</a>
*
* @see org.apache.dubbo.rpc.cluster.Cluster#join(Directory)
*/
@SPI(RandomLoadBalance.NAME)
public interface LoadBalance {
/**
* select one invoker in list.
*
* @param invokers invokers.
* @param url refer url
* @param invocation invocation.
* @return selected invoker.
*/
@Adaptive("loadbalance")
<T> Invoker<T> select(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException;
}
| 7,822 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Cluster.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster;
import org.apache.dubbo.common.extension.Adaptive;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.model.ScopeModel;
import org.apache.dubbo.rpc.model.ScopeModelUtil;
/**
* Cluster. (SPI, Singleton, ThreadSafe)
* <p>
* <a href="http://en.wikipedia.org/wiki/Computer_cluster">Cluster</a>
* <a href="http://en.wikipedia.org/wiki/Fault-tolerant_system">Fault-Tolerant</a>
*
*/
@SPI(Cluster.DEFAULT)
public interface Cluster {
String DEFAULT = "failover";
/**
* Merge the directory invokers to a virtual invoker.
*
* @param <T>
* @param directory
* @return cluster invoker
* @throws RpcException
*/
@Adaptive
<T> Invoker<T> join(Directory<T> directory, boolean buildFilterChain) throws RpcException;
static Cluster getCluster(ScopeModel scopeModel, String name) {
return getCluster(scopeModel, name, true);
}
static Cluster getCluster(ScopeModel scopeModel, String name, boolean wrap) {
if (StringUtils.isEmpty(name)) {
name = Cluster.DEFAULT;
}
return ScopeModelUtil.getApplicationModel(scopeModel)
.getExtensionLoader(Cluster.class)
.getExtension(name, wrap);
}
}
| 7,823 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/CacheableRouterFactory.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* If you want to provide a router implementation based on design of v2.7.0, please extend from this abstract class.
* For 2.6.x style router, please implement and use RouterFactory directly.
*/
public abstract class CacheableRouterFactory implements RouterFactory {
private ConcurrentMap<String, Router> routerMap = new ConcurrentHashMap<>();
@Override
public Router getRouter(URL url) {
return ConcurrentHashMapUtils.computeIfAbsent(routerMap, url.getServiceKey(), k -> createRouter(url));
}
protected abstract Router createRouter(URL url);
}
| 7,824 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/ClusterInvoker.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invoker;
/**
* This is the final Invoker type referenced by the RPC proxy on Consumer side.
* <p>
* A ClusterInvoker holds a group of normal invokers, stored in a Directory, mapping to one Registry.
* The ClusterInvoker implementation usually provides LB or HA policies, like FailoverClusterInvoker.
* <p>
* In multi-registry subscription scenario, the final ClusterInvoker will refer to several sub ClusterInvokers, with each
* sub ClusterInvoker representing one Registry. Take ZoneAwareClusterInvoker as an example, it is specially customized for
* multi-registry use cases: first, pick up one ClusterInvoker, then do LB inside the chose ClusterInvoker.
*
* @param <T>
*/
public interface ClusterInvoker<T> extends Invoker<T> {
URL getRegistryUrl();
Directory<T> getDirectory();
boolean isDestroyed();
default boolean isServiceDiscovery() {
Directory<T> directory = getDirectory();
if (directory == null) {
return false;
}
return directory.isServiceDiscovery();
}
default boolean hasProxyInvokers() {
Directory<T> directory = getDirectory();
if (directory == null) {
return false;
}
return !directory.isEmpty();
}
}
| 7,825 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/SingleRouterChain.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.Version;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.Holder;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.cluster.router.RouterResult;
import org.apache.dubbo.rpc.cluster.router.RouterSnapshotNode;
import org.apache.dubbo.rpc.cluster.router.RouterSnapshotSwitcher;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import org.apache.dubbo.rpc.cluster.router.state.StateRouter;
import org.apache.dubbo.rpc.cluster.router.state.TailStateRouter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_FAILED_STOP;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_NO_VALID_PROVIDER;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR;
/**
* Router chain
*/
public class SingleRouterChain<T> {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(SingleRouterChain.class);
/**
* full list of addresses from registry, classified by method name.
*/
private volatile BitList<Invoker<T>> invokers = BitList.emptyList();
/**
* containing all routers, reconstruct every time 'route://' urls change.
*/
private volatile List<Router> routers = Collections.emptyList();
/**
* Fixed router instances: ConfigConditionRouter, TagRouter, e.g.,
* the rule for each instance may change but the instance will never delete or recreate.
*/
private volatile List<Router> builtinRouters = Collections.emptyList();
private volatile StateRouter<T> headStateRouter;
private volatile List<StateRouter<T>> stateRouters;
/**
* Should continue route if current router's result is empty
*/
private final boolean shouldFailFast;
private final RouterSnapshotSwitcher routerSnapshotSwitcher;
private final ReadWriteLock lock = new ReentrantReadWriteLock();
public SingleRouterChain(
List<Router> routers,
List<StateRouter<T>> stateRouters,
boolean shouldFailFast,
RouterSnapshotSwitcher routerSnapshotSwitcher) {
initWithRouters(routers);
initWithStateRouters(stateRouters);
this.shouldFailFast = shouldFailFast;
this.routerSnapshotSwitcher = routerSnapshotSwitcher;
}
private void initWithStateRouters(List<StateRouter<T>> stateRouters) {
StateRouter<T> stateRouter = TailStateRouter.getInstance();
for (int i = stateRouters.size() - 1; i >= 0; i--) {
StateRouter<T> nextStateRouter = stateRouters.get(i);
nextStateRouter.setNextRouter(stateRouter);
stateRouter = nextStateRouter;
}
this.headStateRouter = stateRouter;
this.stateRouters = Collections.unmodifiableList(stateRouters);
}
/**
* the resident routers must being initialized before address notification.
* only for ut
*/
public void initWithRouters(List<Router> builtinRouters) {
this.builtinRouters = builtinRouters;
this.routers = new LinkedList<>(builtinRouters);
}
/**
* If we use route:// protocol in version before 2.7.0, each URL will generate a Router instance, so we should
* keep the routers up to date, that is, each time router URLs changes, we should update the routers list, only
* keep the builtinRouters which are available all the time and the latest notified routers which are generated
* from URLs.
*
* @param routers routers from 'router://' rules in 2.6.x or before.
*/
public void addRouters(List<Router> routers) {
List<Router> newRouters = new LinkedList<>();
newRouters.addAll(builtinRouters);
newRouters.addAll(routers);
CollectionUtils.sort(newRouters);
this.routers = newRouters;
}
public List<Router> getRouters() {
return routers;
}
public StateRouter<T> getHeadStateRouter() {
return headStateRouter;
}
public List<Invoker<T>> route(URL url, BitList<Invoker<T>> availableInvokers, Invocation invocation) {
if (invokers.getOriginList() != availableInvokers.getOriginList()) {
logger.error(
INTERNAL_ERROR,
"",
"Router's invoker size: " + invokers.getOriginList().size() + " Invocation's invoker size: "
+ availableInvokers.getOriginList().size(),
"Reject to route, because the invokers has changed.");
throw new IllegalStateException("reject to route, because the invokers has changed.");
}
if (RpcContext.getServiceContext().isNeedPrintRouterSnapshot()) {
return routeAndPrint(url, availableInvokers, invocation);
} else {
return simpleRoute(url, availableInvokers, invocation);
}
}
public List<Invoker<T>> routeAndPrint(URL url, BitList<Invoker<T>> availableInvokers, Invocation invocation) {
RouterSnapshotNode<T> snapshot = buildRouterSnapshot(url, availableInvokers, invocation);
logRouterSnapshot(url, invocation, snapshot);
return snapshot.getChainOutputInvokers();
}
public List<Invoker<T>> simpleRoute(URL url, BitList<Invoker<T>> availableInvokers, Invocation invocation) {
BitList<Invoker<T>> resultInvokers = availableInvokers.clone();
// 1. route state router
resultInvokers = headStateRouter.route(resultInvokers, url, invocation, false, null);
if (resultInvokers.isEmpty() && (shouldFailFast || routers.isEmpty())) {
printRouterSnapshot(url, availableInvokers, invocation);
return BitList.emptyList();
}
if (routers.isEmpty()) {
return resultInvokers;
}
List<Invoker<T>> commonRouterResult = resultInvokers.cloneToArrayList();
// 2. route common router
for (Router router : routers) {
// Copy resultInvokers to a arrayList. BitList not support
RouterResult<Invoker<T>> routeResult = router.route(commonRouterResult, url, invocation, false);
commonRouterResult = routeResult.getResult();
if (CollectionUtils.isEmpty(commonRouterResult) && shouldFailFast) {
printRouterSnapshot(url, availableInvokers, invocation);
return BitList.emptyList();
}
// stop continue routing
if (!routeResult.isNeedContinueRoute()) {
return commonRouterResult;
}
}
if (commonRouterResult.isEmpty()) {
printRouterSnapshot(url, availableInvokers, invocation);
return BitList.emptyList();
}
return commonRouterResult;
}
/**
* store each router's input and output, log out if empty
*/
private void printRouterSnapshot(URL url, BitList<Invoker<T>> availableInvokers, Invocation invocation) {
if (logger.isWarnEnabled()) {
logRouterSnapshot(url, invocation, buildRouterSnapshot(url, availableInvokers, invocation));
}
}
/**
* Build each router's result
*/
public RouterSnapshotNode<T> buildRouterSnapshot(
URL url, BitList<Invoker<T>> availableInvokers, Invocation invocation) {
BitList<Invoker<T>> resultInvokers = availableInvokers.clone();
RouterSnapshotNode<T> parentNode = new RouterSnapshotNode<T>("Parent", resultInvokers.clone());
parentNode.setNodeOutputInvokers(resultInvokers.clone());
// 1. route state router
Holder<RouterSnapshotNode<T>> nodeHolder = new Holder<>();
nodeHolder.set(parentNode);
resultInvokers = headStateRouter.route(resultInvokers, url, invocation, true, nodeHolder);
// result is empty, log out
if (routers.isEmpty() || (resultInvokers.isEmpty() && shouldFailFast)) {
parentNode.setChainOutputInvokers(resultInvokers.clone());
return parentNode;
}
RouterSnapshotNode<T> commonRouterNode = new RouterSnapshotNode<T>("CommonRouter", resultInvokers.clone());
parentNode.appendNode(commonRouterNode);
List<Invoker<T>> commonRouterResult = resultInvokers;
// 2. route common router
for (Router router : routers) {
// Copy resultInvokers to a arrayList. BitList not support
List<Invoker<T>> inputInvokers = new ArrayList<>(commonRouterResult);
RouterSnapshotNode<T> currentNode =
new RouterSnapshotNode<T>(router.getClass().getSimpleName(), inputInvokers);
// append to router node chain
commonRouterNode.appendNode(currentNode);
commonRouterNode = currentNode;
RouterResult<Invoker<T>> routeStateResult = router.route(inputInvokers, url, invocation, true);
List<Invoker<T>> routeResult = routeStateResult.getResult();
String routerMessage = routeStateResult.getMessage();
currentNode.setNodeOutputInvokers(routeResult);
currentNode.setRouterMessage(routerMessage);
commonRouterResult = routeResult;
// result is empty, log out
if (CollectionUtils.isEmpty(routeResult) && shouldFailFast) {
break;
}
if (!routeStateResult.isNeedContinueRoute()) {
break;
}
}
commonRouterNode.setChainOutputInvokers(commonRouterNode.getNodeOutputInvokers());
// 3. set router chain output reverse
RouterSnapshotNode<T> currentNode = commonRouterNode;
while (currentNode != null) {
RouterSnapshotNode<T> parent = currentNode.getParentNode();
if (parent != null) {
// common router only has one child invoke
parent.setChainOutputInvokers(currentNode.getChainOutputInvokers());
}
currentNode = parent;
}
return parentNode;
}
private void logRouterSnapshot(URL url, Invocation invocation, RouterSnapshotNode<T> snapshotNode) {
if (snapshotNode.getChainOutputInvokers() == null
|| snapshotNode.getChainOutputInvokers().isEmpty()) {
if (logger.isWarnEnabled()) {
String message = "No provider available after route for the service " + url.getServiceKey()
+ " from registry " + url.getAddress()
+ " on the consumer " + NetUtils.getLocalHost()
+ " using the dubbo version " + Version.getVersion() + ". Router snapshot is below: \n"
+ snapshotNode.toString();
if (routerSnapshotSwitcher.isEnable()) {
routerSnapshotSwitcher.setSnapshot(message);
}
logger.warn(
CLUSTER_NO_VALID_PROVIDER, "No provider available after route for the service", "", message);
}
} else {
if (logger.isInfoEnabled()) {
String message = "Router snapshot service " + url.getServiceKey()
+ " from registry " + url.getAddress()
+ " on the consumer " + NetUtils.getLocalHost()
+ " using the dubbo version " + Version.getVersion() + " is below: \n"
+ snapshotNode.toString();
if (routerSnapshotSwitcher.isEnable()) {
routerSnapshotSwitcher.setSnapshot(message);
}
logger.info(message);
}
}
}
/**
* Notify router chain of the initial addresses from registry at the first time.
* Notify whenever addresses in registry change.
*/
public void setInvokers(BitList<Invoker<T>> invokers) {
this.invokers = (invokers == null ? BitList.emptyList() : invokers);
routers.forEach(router -> router.notify(this.invokers));
stateRouters.forEach(router -> router.notify(this.invokers));
}
/**
* for uts only
*/
@Deprecated
public void setHeadStateRouter(StateRouter<T> headStateRouter) {
this.headStateRouter = headStateRouter;
}
/**
* for uts only
*/
@Deprecated
public List<StateRouter<T>> getStateRouters() {
return stateRouters;
}
public ReadWriteLock getLock() {
return lock;
}
public void destroy() {
invokers = BitList.emptyList();
for (Router router : routers) {
try {
router.stop();
} catch (Exception e) {
logger.error(
CLUSTER_FAILED_STOP,
"route stop failed",
"",
"Error trying to stop router " + router.getClass(),
e);
}
}
routers = Collections.emptyList();
builtinRouters = Collections.emptyList();
for (StateRouter<T> router : stateRouters) {
try {
router.stop();
} catch (Exception e) {
logger.error(
CLUSTER_FAILED_STOP,
"StateRouter stop failed",
"",
"Error trying to stop StateRouter " + router.getClass(),
e);
}
}
stateRouters = Collections.emptyList();
headStateRouter = TailStateRouter.getInstance();
}
}
| 7,826 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/ClusterScopeModelInitializer.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster;
import org.apache.dubbo.common.beans.factory.ScopeBeanFactory;
import org.apache.dubbo.rpc.AdaptiveMetrics;
import org.apache.dubbo.rpc.cluster.merger.MergerFactory;
import org.apache.dubbo.rpc.cluster.router.RouterSnapshotSwitcher;
import org.apache.dubbo.rpc.cluster.router.mesh.route.MeshRuleManager;
import org.apache.dubbo.rpc.cluster.support.ClusterUtils;
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 ClusterScopeModelInitializer implements ScopeModelInitializer {
@Override
public void initializeFrameworkModel(FrameworkModel frameworkModel) {
ScopeBeanFactory beanFactory = frameworkModel.getBeanFactory();
beanFactory.registerBean(RouterSnapshotSwitcher.class);
}
@Override
public void initializeApplicationModel(ApplicationModel applicationModel) {
ScopeBeanFactory beanFactory = applicationModel.getBeanFactory();
beanFactory.registerBean(MergerFactory.class);
beanFactory.registerBean(ClusterUtils.class);
beanFactory.registerBean(AdaptiveMetrics.class);
}
@Override
public void initializeModuleModel(ModuleModel moduleModel) {
ScopeBeanFactory beanFactory = moduleModel.getBeanFactory();
beanFactory.registerBean(MeshRuleManager.class);
}
}
| 7,827 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/RuleConverter.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.SPI;
import java.util.List;
@SPI
public interface RuleConverter {
List<URL> convert(URL subscribeUrl, Object source);
}
| 7,828 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/RouterFactory.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Adaptive;
import org.apache.dubbo.common.extension.SPI;
/**
* RouterFactory. (SPI, Singleton, ThreadSafe)
* <p>
* <a href="http://en.wikipedia.org/wiki/Routing">Routing</a>
*
* @see org.apache.dubbo.rpc.cluster.Cluster#join(Directory)
* @see org.apache.dubbo.rpc.cluster.Directory#list(org.apache.dubbo.rpc.Invocation)
* <p>
* Note Router has a different behaviour since 2.7.0, for each type of Router, there will only has one Router instance
* for each service. See {@link CacheableRouterFactory} and {@link RouterChain} for how to extend a new Router or how
* the Router instances are loaded.
*/
@SPI
public interface RouterFactory {
/**
* Create router.
* Since 2.7.0, most of the time, we will not use @Adaptive feature, so it's kept only for compatibility.
*
* @param url url
* @return router instance
*/
@Adaptive(CommonConstants.PROTOCOL_KEY)
Router getRouter(URL url);
}
| 7,829 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Configurator.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.CollectionUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL;
import static org.apache.dubbo.rpc.cluster.Constants.PRIORITY_KEY;
/**
* Configurator. (SPI, Prototype, ThreadSafe)
*
*/
public interface Configurator extends Comparable<Configurator> {
/**
* Get the configurator url.
*
* @return configurator url.
*/
URL getUrl();
/**
* Configure the provider url.
*
* @param url - old provider url.
* @return new provider url.
*/
URL configure(URL url);
/**
* Convert override urls to map for use when re-refer. Send all rules every time, the urls will be reassembled and
* calculated
*
* URL contract:
* <ol>
* <li>override://0.0.0.0/...( or override://ip:port...?anyhost=true)¶1=value1... means global rules
* (all of the providers take effect)</li>
* <li>override://ip:port...?anyhost=false Special rules (only for a certain provider)</li>
* <li>override:// rule is not supported... ,needs to be calculated by registry itself</li>
* <li>override://0.0.0.0/ without parameters means clearing the override</li>
* </ol>
*
* @param urls URL list to convert
* @return converted configurator list
*/
static Optional<List<Configurator>> toConfigurators(List<URL> urls) {
if (CollectionUtils.isEmpty(urls)) {
return Optional.empty();
}
ConfiguratorFactory configuratorFactory = urls.get(0)
.getOrDefaultApplicationModel()
.getExtensionLoader(ConfiguratorFactory.class)
.getAdaptiveExtension();
List<Configurator> configurators = new ArrayList<>(urls.size());
for (URL url : urls) {
if (EMPTY_PROTOCOL.equals(url.getProtocol())) {
configurators.clear();
break;
}
Map<String, String> override = new HashMap<>(url.getParameters());
// The anyhost parameter of override may be added automatically, it can't change the judgement of changing
// url
override.remove(ANYHOST_KEY);
if (CollectionUtils.isEmptyMap(override)) {
continue;
}
configurators.add(configuratorFactory.getConfigurator(url));
}
Collections.sort(configurators);
return Optional.of(configurators);
}
/**
* Sort by host, then by priority
* 1. the url with a specific host ip should have higher priority than 0.0.0.0
* 2. if two url has the same host, compare by priority value;
*/
@Override
default int compareTo(Configurator o) {
if (o == null) {
return -1;
}
int ipCompare = getUrl().getHost().compareTo(o.getUrl().getHost());
// host is the same, sort by priority
if (ipCompare == 0) {
int i = getUrl().getParameter(PRIORITY_KEY, 0);
int j = o.getUrl().getParameter(PRIORITY_KEY, 0);
return Integer.compare(i, j);
} else {
return ipCompare;
}
}
}
| 7,830 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/ConfiguratorFactory.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Adaptive;
import org.apache.dubbo.common.extension.SPI;
/**
* ConfiguratorFactory. (SPI, Singleton, ThreadSafe)
*
*/
@SPI
public interface ConfiguratorFactory {
/**
* get the configurator instance.
*
* @param url - configurator url.
* @return configurator instance.
*/
@Adaptive(CommonConstants.PROTOCOL_KEY)
Configurator getConfigurator(URL url);
}
| 7,831 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/ProviderURLMergeProcessor.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.SPI;
import java.util.Map;
@SPI("default")
public interface ProviderURLMergeProcessor {
/**
* Merging the URL parameters of provider and consumer
*
* @param remoteUrl providerUrl
* @param localParametersMap consumer url parameters
* @return
*/
URL mergeUrl(URL remoteUrl, Map<String, String> localParametersMap);
default Map<String, String> mergeLocalParams(Map<String, String> localMap) {
return localMap;
}
default boolean accept(URL providerUrl, Map<String, String> localParametersMap) {
return true;
}
}
| 7,832 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Constants.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster;
public interface Constants {
String FAIL_BACK_TASKS_KEY = "failbacktasks";
int DEFAULT_FAILBACK_TASKS = 100;
int DEFAULT_FORKS = 2;
String WEIGHT_KEY = "weight";
int DEFAULT_WEIGHT = 100;
String MOCK_PROTOCOL = "mock";
String FORCE_KEY = "force";
String RAW_RULE_KEY = "rawRule";
String VALID_KEY = "valid";
String ENABLED_KEY = "enabled";
String DYNAMIC_KEY = "dynamic";
String SCOPE_KEY = "scope";
String KEY_KEY = "key";
String CONDITIONS_KEY = "conditions";
String TAGS_KEY = "tags";
/**
* To decide whether to exclude unavailable invoker from the cluster
*/
String CLUSTER_AVAILABLE_CHECK_KEY = "cluster.availablecheck";
/**
* The default value of cluster.availablecheck
*
* @see #CLUSTER_AVAILABLE_CHECK_KEY
*/
boolean DEFAULT_CLUSTER_AVAILABLE_CHECK = true;
/**
* To decide whether to enable sticky strategy for cluster
*/
String CLUSTER_STICKY_KEY = "sticky";
/**
* The default value of sticky
*
* @see #CLUSTER_STICKY_KEY
*/
boolean DEFAULT_CLUSTER_STICKY = false;
/**
* When this attribute appears in invocation's attachment, mock invoker will be used
*/
String INVOCATION_NEED_MOCK = "invocation.need.mock";
/**
* when ROUTER_KEY's value is set to ROUTER_TYPE_CLEAR, RegistryDirectory will clean all current routers
*/
String ROUTER_TYPE_CLEAR = "clean";
String DEFAULT_SCRIPT_TYPE_KEY = "javascript";
String PRIORITY_KEY = "priority";
String RULE_KEY = "rule";
String TYPE_KEY = "type";
String RUNTIME_KEY = "runtime";
String WARMUP_KEY = "warmup";
int DEFAULT_WARMUP = 10 * 60 * 1000;
String CONFIG_VERSION_KEY = "configVersion";
String OVERRIDE_PROVIDERS_KEY = "providerAddresses";
/**
* key for router type, for e.g., "script"/"file", corresponding to ScriptRouterFactory.NAME, FileRouterFactory.NAME
*/
String ROUTER_KEY = "router";
/**
* The key name for reference URL in register center
*/
String REFER_KEY = "refer";
String ATTRIBUTE_KEY = "attribute";
/**
* The key name for export URL in register center
*/
String EXPORT_KEY = "export";
String PEER_KEY = "peer";
String CONSUMER_URL_KEY = "CONSUMER_URL";
/**
* prefix of arguments router key
*/
String ARGUMENTS = "arguments";
String NEED_REEXPORT = "need-reexport";
/**
* The key of shortestResponseSlidePeriod
*/
String SHORTEST_RESPONSE_SLIDE_PERIOD = "shortestResponseSlidePeriod";
String SHOULD_FAIL_FAST_KEY = "dubbo.router.should-fail-fast";
String RULE_VERSION_V27 = "v2.7";
String RULE_VERSION_V30 = "v3.0";
}
| 7,833 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/AdaptiveLoadBalance.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.loadbalance;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.LoadbalanceRules;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.AdaptiveMetrics;
import org.apache.dubbo.rpc.Constants;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.support.RpcUtils;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT;
import static org.apache.dubbo.common.constants.CommonConstants.LOADBALANCE_KEY;
/**
* AdaptiveLoadBalance
* </p>
*/
public class AdaptiveLoadBalance extends AbstractLoadBalance {
public static final String NAME = "adaptive";
// default key
private String attachmentKey = "mem,load";
private final AdaptiveMetrics adaptiveMetrics;
public AdaptiveLoadBalance(ApplicationModel scopeModel) {
adaptiveMetrics = scopeModel.getBeanFactory().getBean(AdaptiveMetrics.class);
}
@Override
protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
Invoker<T> invoker = selectByP2C(invokers, invocation);
invocation.setAttachment(Constants.ADAPTIVE_LOADBALANCE_ATTACHMENT_KEY, attachmentKey);
long startTime = System.currentTimeMillis();
invocation.getAttributes().put(Constants.ADAPTIVE_LOADBALANCE_START_TIME, startTime);
invocation.getAttributes().put(LOADBALANCE_KEY, LoadbalanceRules.ADAPTIVE);
adaptiveMetrics.addConsumerReq(getServiceKey(invoker, invocation));
adaptiveMetrics.setPickTime(getServiceKey(invoker, invocation), startTime);
return invoker;
}
private <T> Invoker<T> selectByP2C(List<Invoker<T>> invokers, Invocation invocation) {
int length = invokers.size();
if (length == 1) {
return invokers.get(0);
}
if (length == 2) {
return chooseLowLoadInvoker(invokers.get(0), invokers.get(1), invocation);
}
int pos1 = ThreadLocalRandom.current().nextInt(length);
int pos2 = ThreadLocalRandom.current().nextInt(length - 1);
if (pos2 >= pos1) {
pos2 = pos2 + 1;
}
return chooseLowLoadInvoker(invokers.get(pos1), invokers.get(pos2), invocation);
}
private String getServiceKey(Invoker<?> invoker, Invocation invocation) {
String key = (String) invocation.getAttributes().get(invoker);
if (StringUtils.isNotEmpty(key)) {
return key;
}
key = buildServiceKey(invoker, invocation);
invocation.getAttributes().put(invoker, key);
return key;
}
private String buildServiceKey(Invoker<?> invoker, Invocation invocation) {
URL url = invoker.getUrl();
StringBuilder sb = new StringBuilder(128);
sb.append(url.getAddress()).append(":").append(invocation.getProtocolServiceKey());
return sb.toString();
}
private int getTimeout(Invoker<?> invoker, Invocation invocation) {
URL url = invoker.getUrl();
String methodName = RpcUtils.getMethodName(invocation);
return (int)
RpcUtils.getTimeout(url, methodName, RpcContext.getClientAttachment(), invocation, DEFAULT_TIMEOUT);
}
private <T> Invoker<T> chooseLowLoadInvoker(Invoker<T> invoker1, Invoker<T> invoker2, Invocation invocation) {
int weight1 = getWeight(invoker1, invocation);
int weight2 = getWeight(invoker2, invocation);
int timeout1 = getTimeout(invoker1, invocation);
int timeout2 = getTimeout(invoker2, invocation);
long load1 = Double.doubleToLongBits(
adaptiveMetrics.getLoad(getServiceKey(invoker1, invocation), weight1, timeout1));
long load2 = Double.doubleToLongBits(
adaptiveMetrics.getLoad(getServiceKey(invoker2, invocation), weight2, timeout2));
if (load1 == load2) {
// The sum of weights
int totalWeight = weight1 + weight2;
if (totalWeight > 0) {
int offset = ThreadLocalRandom.current().nextInt(totalWeight);
if (offset < weight1) {
return invoker1;
}
return invoker2;
}
return ThreadLocalRandom.current().nextInt(2) == 0 ? invoker1 : invoker2;
}
return load1 > load2 ? invoker2 : invoker1;
}
}
| 7,834 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/RandomLoadBalance.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.loadbalance;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.cluster.ClusterInvoker;
import org.apache.dubbo.rpc.support.RpcUtils;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_SERVICE_REFERENCE_PATH;
import static org.apache.dubbo.rpc.cluster.Constants.WEIGHT_KEY;
/**
* This class select one provider from multiple providers randomly.
* You can define weights for each provider:
* If the weights are all the same then it will use random.nextInt(number of invokers).
* If the weights are different then it will use random.nextInt(w1 + w2 + ... + wn)
* Note that if the performance of the machine is better than others, you can set a larger weight.
* If the performance is not so good, you can set a smaller weight.
*/
public class RandomLoadBalance extends AbstractLoadBalance {
public static final String NAME = "random";
/**
* Select one invoker between a list using a random criteria
*
* @param invokers List of possible invokers
* @param url URL
* @param invocation Invocation
* @param <T>
* @return The selected invoker
*/
@Override
protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
// Number of invokers
int length = invokers.size();
if (!needWeightLoadBalance(invokers, invocation)) {
return invokers.get(ThreadLocalRandom.current().nextInt(length));
}
// Every invoker has the same weight?
boolean sameWeight = true;
// the maxWeight of every invoker, the minWeight = 0 or the maxWeight of the last invoker
int[] weights = new int[length];
// The sum of weights
int totalWeight = 0;
for (int i = 0; i < length; i++) {
int weight = getWeight(invokers.get(i), invocation);
// Sum
totalWeight += weight;
// save for later use
weights[i] = totalWeight;
if (sameWeight && totalWeight != weight * (i + 1)) {
sameWeight = false;
}
}
if (totalWeight > 0 && !sameWeight) {
// If (not every invoker has the same weight & at least one invoker's weight>0), select randomly based on
// totalWeight.
int offset = ThreadLocalRandom.current().nextInt(totalWeight);
// Return an invoker based on the random value.
if (length <= 4) {
for (int i = 0; i < length; i++) {
if (offset < weights[i]) {
return invokers.get(i);
}
}
} else {
int i = Arrays.binarySearch(weights, offset);
if (i < 0) {
i = -i - 1;
} else {
while (weights[i + 1] == offset) {
i++;
}
i++;
}
return invokers.get(i);
}
}
// If all invokers have the same weight value or totalWeight=0, return evenly.
return invokers.get(ThreadLocalRandom.current().nextInt(length));
}
private <T> boolean needWeightLoadBalance(List<Invoker<T>> invokers, Invocation invocation) {
Invoker<T> invoker = invokers.get(0);
URL invokerUrl = invoker.getUrl();
if (invoker instanceof ClusterInvoker) {
invokerUrl = ((ClusterInvoker<?>) invoker).getRegistryUrl();
}
// Multiple registry scenario, load balance among multiple registries.
if (REGISTRY_SERVICE_REFERENCE_PATH.equals(invokerUrl.getServiceInterface())) {
String weight = invokerUrl.getParameter(WEIGHT_KEY);
return StringUtils.isNotEmpty(weight);
} else {
String weight = invokerUrl.getMethodParameter(RpcUtils.getMethodName(invocation), WEIGHT_KEY);
if (StringUtils.isNotEmpty(weight)) {
return true;
} else {
String timeStamp = invoker.getUrl().getParameter(TIMESTAMP_KEY);
return StringUtils.isNotEmpty(timeStamp);
}
}
}
}
| 7,835 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/ConsistentHashLoadBalance.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.loadbalance;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.io.Bytes;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.support.RpcUtils;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN;
/**
* ConsistentHashLoadBalance
*/
public class ConsistentHashLoadBalance extends AbstractLoadBalance {
public static final String NAME = "consistenthash";
/**
* Hash nodes name
*/
public static final String HASH_NODES = "hash.nodes";
/**
* Hash arguments name
*/
public static final String HASH_ARGUMENTS = "hash.arguments";
private final ConcurrentMap<String, ConsistentHashSelector<?>> selectors =
new ConcurrentHashMap<String, ConsistentHashSelector<?>>();
@SuppressWarnings("unchecked")
@Override
protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
String methodName = RpcUtils.getMethodName(invocation);
String key = invokers.get(0).getUrl().getServiceKey() + "." + methodName;
// using the hashcode of list to compute the hash only pay attention to the elements in the list
int invokersHashCode = invokers.hashCode();
ConsistentHashSelector<T> selector = (ConsistentHashSelector<T>) selectors.get(key);
if (selector == null || selector.identityHashCode != invokersHashCode) {
selectors.put(key, new ConsistentHashSelector<T>(invokers, methodName, invokersHashCode));
selector = (ConsistentHashSelector<T>) selectors.get(key);
}
return selector.select(invocation);
}
private static final class ConsistentHashSelector<T> {
private final TreeMap<Long, Invoker<T>> virtualInvokers;
private final int replicaNumber;
private final int identityHashCode;
private final int[] argumentIndex;
ConsistentHashSelector(List<Invoker<T>> invokers, String methodName, int identityHashCode) {
this.virtualInvokers = new TreeMap<Long, Invoker<T>>();
this.identityHashCode = identityHashCode;
URL url = invokers.get(0).getUrl();
this.replicaNumber = url.getMethodParameter(methodName, HASH_NODES, 160);
String[] index = COMMA_SPLIT_PATTERN.split(url.getMethodParameter(methodName, HASH_ARGUMENTS, "0"));
argumentIndex = new int[index.length];
for (int i = 0; i < index.length; i++) {
argumentIndex[i] = Integer.parseInt(index[i]);
}
for (Invoker<T> invoker : invokers) {
String address = invoker.getUrl().getAddress();
for (int i = 0; i < replicaNumber / 4; i++) {
byte[] digest = Bytes.getMD5(address + i);
for (int h = 0; h < 4; h++) {
long m = hash(digest, h);
virtualInvokers.put(m, invoker);
}
}
}
}
public Invoker<T> select(Invocation invocation) {
byte[] digest = Bytes.getMD5(RpcUtils.getMethodName(invocation));
return selectForKey(hash(digest, 0));
}
private String toKey(Object[] args, boolean isGeneric) {
return isGeneric ? toKey((Object[]) args[1]) : toKey(args);
}
private String toKey(Object[] args) {
StringBuilder buf = new StringBuilder();
for (int i : argumentIndex) {
if (i >= 0 && args != null && i < args.length) {
buf.append(args[i]);
}
}
return buf.toString();
}
private Invoker<T> selectForKey(long hash) {
Map.Entry<Long, Invoker<T>> entry = virtualInvokers.ceilingEntry(hash);
if (entry == null) {
entry = virtualInvokers.firstEntry();
}
return entry.getValue();
}
private long hash(byte[] digest, int number) {
return (((long) (digest[3 + number * 4] & 0xFF) << 24)
| ((long) (digest[2 + number * 4] & 0xFF) << 16)
| ((long) (digest[1 + number * 4] & 0xFF) << 8)
| (digest[number * 4] & 0xFF))
& 0xFFFFFFFFL;
}
}
}
| 7,836 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/ShortestResponseLoadBalance.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.loadbalance;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcStatus;
import org.apache.dubbo.rpc.cluster.Constants;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ScopeModelAware;
import org.apache.dubbo.rpc.support.RpcUtils;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* ShortestResponseLoadBalance
* </p>
* Filter the number of invokers with the shortest response time of
* success calls and count the weights and quantities of these invokers in last slide window.
* If there is only one invoker, use the invoker directly;
* if there are multiple invokers and the weights are not the same, then random according to the total weight;
* if there are multiple invokers and the same weight, then randomly called.
*/
public class ShortestResponseLoadBalance extends AbstractLoadBalance implements ScopeModelAware {
public static final String NAME = "shortestresponse";
private int slidePeriod = 30_000;
private final ConcurrentMap<RpcStatus, SlideWindowData> methodMap = new ConcurrentHashMap<>();
private final AtomicBoolean onResetSlideWindow = new AtomicBoolean(false);
private volatile long lastUpdateTime = System.currentTimeMillis();
private ExecutorService executorService;
@Override
public void setApplicationModel(ApplicationModel applicationModel) {
slidePeriod = applicationModel
.modelEnvironment()
.getConfiguration()
.getInt(Constants.SHORTEST_RESPONSE_SLIDE_PERIOD, 30_000);
executorService = applicationModel
.getFrameworkModel()
.getBeanFactory()
.getBean(FrameworkExecutorRepository.class)
.getSharedExecutor();
}
protected static class SlideWindowData {
private long succeededOffset;
private long succeededElapsedOffset;
private final RpcStatus rpcStatus;
public SlideWindowData(RpcStatus rpcStatus) {
this.rpcStatus = rpcStatus;
this.succeededOffset = 0;
this.succeededElapsedOffset = 0;
}
public void reset() {
this.succeededOffset = rpcStatus.getSucceeded();
this.succeededElapsedOffset = rpcStatus.getSucceededElapsed();
}
private long getSucceededAverageElapsed() {
long succeed = this.rpcStatus.getSucceeded() - this.succeededOffset;
if (succeed == 0) {
return 0;
}
return (this.rpcStatus.getSucceededElapsed() - this.succeededElapsedOffset) / succeed;
}
public long getEstimateResponse() {
int active = this.rpcStatus.getActive() + 1;
return getSucceededAverageElapsed() * active;
}
}
@Override
protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
// Number of invokers
int length = invokers.size();
// Estimated shortest response time of all invokers
long shortestResponse = Long.MAX_VALUE;
// The number of invokers having the same estimated shortest response time
int shortestCount = 0;
// The index of invokers having the same estimated shortest response time
int[] shortestIndexes = new int[length];
// the weight of every invokers
int[] weights = new int[length];
// The sum of the warmup weights of all the shortest response invokers
int totalWeight = 0;
// The weight of the first shortest response invokers
int firstWeight = 0;
// Every shortest response invoker has the same weight value?
boolean sameWeight = true;
// Filter out all the shortest response invokers
for (int i = 0; i < length; i++) {
Invoker<T> invoker = invokers.get(i);
RpcStatus rpcStatus = RpcStatus.getStatus(invoker.getUrl(), RpcUtils.getMethodName(invocation));
SlideWindowData slideWindowData =
ConcurrentHashMapUtils.computeIfAbsent(methodMap, rpcStatus, SlideWindowData::new);
// Calculate the estimated response time from the product of active connections and succeeded average
// elapsed time.
long estimateResponse = slideWindowData.getEstimateResponse();
int afterWarmup = getWeight(invoker, invocation);
weights[i] = afterWarmup;
// Same as LeastActiveLoadBalance
if (estimateResponse < shortestResponse) {
shortestResponse = estimateResponse;
shortestCount = 1;
shortestIndexes[0] = i;
totalWeight = afterWarmup;
firstWeight = afterWarmup;
sameWeight = true;
} else if (estimateResponse == shortestResponse) {
shortestIndexes[shortestCount++] = i;
totalWeight += afterWarmup;
if (sameWeight && i > 0 && afterWarmup != firstWeight) {
sameWeight = false;
}
}
}
if (System.currentTimeMillis() - lastUpdateTime > slidePeriod
&& onResetSlideWindow.compareAndSet(false, true)) {
// reset slideWindowData in async way
executorService.execute(() -> {
methodMap.values().forEach(SlideWindowData::reset);
lastUpdateTime = System.currentTimeMillis();
onResetSlideWindow.set(false);
});
}
if (shortestCount == 1) {
return invokers.get(shortestIndexes[0]);
}
if (!sameWeight && totalWeight > 0) {
int offsetWeight = ThreadLocalRandom.current().nextInt(totalWeight);
for (int i = 0; i < shortestCount; i++) {
int shortestIndex = shortestIndexes[i];
offsetWeight -= weights[shortestIndex];
if (offsetWeight < 0) {
return invokers.get(shortestIndex);
}
}
}
return invokers.get(shortestIndexes[ThreadLocalRandom.current().nextInt(shortestCount)]);
}
}
| 7,837 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/RoundRobinLoadBalance.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.loadbalance;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.support.RpcUtils;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicLong;
/**
* Round robin load balance.
*/
public class RoundRobinLoadBalance extends AbstractLoadBalance {
public static final String NAME = "roundrobin";
private static final int RECYCLE_PERIOD = 60000;
private final ConcurrentMap<String, ConcurrentMap<String, WeightedRoundRobin>> methodWeightMap =
new ConcurrentHashMap<>();
protected static class WeightedRoundRobin {
private int weight;
private final AtomicLong current = new AtomicLong(0);
private long lastUpdate;
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
current.set(0);
}
public long increaseCurrent() {
return current.addAndGet(weight);
}
public void sel(int total) {
current.addAndGet(-1 * total);
}
public long getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(long lastUpdate) {
this.lastUpdate = lastUpdate;
}
}
/**
* get invoker addr list cached for specified invocation
* <p>
* <b>for unit test only</b>
*
* @param invokers
* @param invocation
* @return
*/
protected <T> Collection<String> getInvokerAddrList(List<Invoker<T>> invokers, Invocation invocation) {
String key = invokers.get(0).getUrl().getServiceKey() + "." + RpcUtils.getMethodName(invocation);
Map<String, WeightedRoundRobin> map = methodWeightMap.get(key);
if (map != null) {
return map.keySet();
}
return null;
}
@Override
protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
String key = invokers.get(0).getUrl().getServiceKey() + "." + RpcUtils.getMethodName(invocation);
ConcurrentMap<String, WeightedRoundRobin> map =
ConcurrentHashMapUtils.computeIfAbsent(methodWeightMap, key, k -> new ConcurrentHashMap<>());
int totalWeight = 0;
long maxCurrent = Long.MIN_VALUE;
long now = System.currentTimeMillis();
Invoker<T> selectedInvoker = null;
WeightedRoundRobin selectedWRR = null;
for (Invoker<T> invoker : invokers) {
String identifyString = invoker.getUrl().toIdentityString();
int weight = getWeight(invoker, invocation);
WeightedRoundRobin weightedRoundRobin = ConcurrentHashMapUtils.computeIfAbsent(map, identifyString, k -> {
WeightedRoundRobin wrr = new WeightedRoundRobin();
wrr.setWeight(weight);
return wrr;
});
if (weight != weightedRoundRobin.getWeight()) {
// weight changed
weightedRoundRobin.setWeight(weight);
}
long cur = weightedRoundRobin.increaseCurrent();
weightedRoundRobin.setLastUpdate(now);
if (cur > maxCurrent) {
maxCurrent = cur;
selectedInvoker = invoker;
selectedWRR = weightedRoundRobin;
}
totalWeight += weight;
}
if (invokers.size() != map.size()) {
map.entrySet().removeIf(item -> now - item.getValue().getLastUpdate() > RECYCLE_PERIOD);
}
if (selectedInvoker != null) {
selectedWRR.sel(totalWeight);
return selectedInvoker;
}
// should not happen here
return invokers.get(0);
}
}
| 7,838 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/AbstractLoadBalance.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.loadbalance;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.cluster.ClusterInvoker;
import org.apache.dubbo.rpc.cluster.LoadBalance;
import org.apache.dubbo.rpc.support.RpcUtils;
import java.util.List;
import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_SERVICE_REFERENCE_PATH;
import static org.apache.dubbo.rpc.cluster.Constants.DEFAULT_WARMUP;
import static org.apache.dubbo.rpc.cluster.Constants.DEFAULT_WEIGHT;
import static org.apache.dubbo.rpc.cluster.Constants.WARMUP_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.WEIGHT_KEY;
/**
* AbstractLoadBalance
*/
public abstract class AbstractLoadBalance implements LoadBalance {
/**
* Calculate the weight according to the uptime proportion of warmup time
* the new weight will be within 1(inclusive) to weight(inclusive)
*
* @param uptime the uptime in milliseconds
* @param warmup the warmup time in milliseconds
* @param weight the weight of an invoker
* @return weight which takes warmup into account
*/
static int calculateWarmupWeight(int uptime, int warmup, int weight) {
int ww = (int) (uptime / ((float) warmup / weight));
return ww < 1 ? 1 : (Math.min(ww, weight));
}
@Override
public <T> Invoker<T> select(List<Invoker<T>> invokers, URL url, Invocation invocation) {
if (CollectionUtils.isEmpty(invokers)) {
return null;
}
if (invokers.size() == 1) {
return invokers.get(0);
}
return doSelect(invokers, url, invocation);
}
protected abstract <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation);
/**
* Get the weight of the invoker's invocation which takes warmup time into account
* if the uptime is within the warmup time, the weight will be reduce proportionally
*
* @param invoker the invoker
* @param invocation the invocation of this invoker
* @return weight
*/
protected int getWeight(Invoker<?> invoker, Invocation invocation) {
int weight;
URL url = invoker.getUrl();
if (invoker instanceof ClusterInvoker) {
url = ((ClusterInvoker<?>) invoker).getRegistryUrl();
}
// Multiple registry scenario, load balance among multiple registries.
if (REGISTRY_SERVICE_REFERENCE_PATH.equals(url.getServiceInterface())) {
weight = url.getParameter(WEIGHT_KEY, DEFAULT_WEIGHT);
} else {
weight = url.getMethodParameter(RpcUtils.getMethodName(invocation), WEIGHT_KEY, DEFAULT_WEIGHT);
if (weight > 0) {
long timestamp = invoker.getUrl().getParameter(TIMESTAMP_KEY, 0L);
if (timestamp > 0L) {
long uptime = System.currentTimeMillis() - timestamp;
if (uptime < 0) {
return 1;
}
int warmup = invoker.getUrl().getParameter(WARMUP_KEY, DEFAULT_WARMUP);
if (uptime > 0 && uptime < warmup) {
weight = calculateWarmupWeight((int) uptime, warmup, weight);
}
}
}
}
return Math.max(weight, 0);
}
}
| 7,839 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/LeastActiveLoadBalance.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.loadbalance;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcStatus;
import org.apache.dubbo.rpc.support.RpcUtils;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
/**
* LeastActiveLoadBalance
* <p>
* Filter the number of invokers with the least number of active calls and count the weights and quantities of these invokers.
* If there is only one invoker, use the invoker directly;
* if there are multiple invokers and the weights are not the same, then random according to the total weight;
* if there are multiple invokers and the same weight, then randomly called.
*/
public class LeastActiveLoadBalance extends AbstractLoadBalance {
public static final String NAME = "leastactive";
@Override
protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
// Number of invokers
int length = invokers.size();
// The least active value of all invokers
int leastActive = -1;
// The number of invokers having the same least active value (leastActive)
int leastCount = 0;
// The index of invokers having the same least active value (leastActive)
int[] leastIndexes = new int[length];
// the weight of every invokers
int[] weights = new int[length];
// The sum of the warmup weights of all the least active invokers
int totalWeight = 0;
// The weight of the first least active invoker
int firstWeight = 0;
// Every least active invoker has the same weight value?
boolean sameWeight = true;
// Filter out all the least active invokers
for (int i = 0; i < length; i++) {
Invoker<T> invoker = invokers.get(i);
// Get the active number of the invoker
int active = RpcStatus.getStatus(invoker.getUrl(), RpcUtils.getMethodName(invocation))
.getActive();
// Get the weight of the invoker's configuration. The default value is 100.
int afterWarmup = getWeight(invoker, invocation);
// save for later use
weights[i] = afterWarmup;
// If it is the first invoker or the active number of the invoker is less than the current least active
// number
if (leastActive == -1 || active < leastActive) {
// Reset the active number of the current invoker to the least active number
leastActive = active;
// Reset the number of least active invokers
leastCount = 1;
// Put the first least active invoker first in leastIndexes
leastIndexes[0] = i;
// Reset totalWeight
totalWeight = afterWarmup;
// Record the weight the first least active invoker
firstWeight = afterWarmup;
// Each invoke has the same weight (only one invoker here)
sameWeight = true;
// If current invoker's active value equals with leaseActive, then accumulating.
} else if (active == leastActive) {
// Record the index of the least active invoker in leastIndexes order
leastIndexes[leastCount++] = i;
// Accumulate the total weight of the least active invoker
totalWeight += afterWarmup;
// If every invoker has the same weight?
if (sameWeight && afterWarmup != firstWeight) {
sameWeight = false;
}
}
}
// Choose an invoker from all the least active invokers
if (leastCount == 1) {
// If we got exactly one invoker having the least active value, return this invoker directly.
return invokers.get(leastIndexes[0]);
}
if (!sameWeight && totalWeight > 0) {
// If (not every invoker has the same weight & at least one invoker's weight>0), select randomly based on
// totalWeight.
int offsetWeight = ThreadLocalRandom.current().nextInt(totalWeight);
// Return a invoker based on the random value.
for (int i = 0; i < leastCount; i++) {
int leastIndex = leastIndexes[i];
offsetWeight -= weights[leastIndex];
if (offsetWeight < 0) {
return invokers.get(leastIndex);
}
}
}
// If all invokers have the same weight value or totalWeight=0, return evenly.
return invokers.get(leastIndexes[ThreadLocalRandom.current().nextInt(leastCount)]);
}
}
| 7,840 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/StaticDirectory.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.directory;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.RouterChain;
import org.apache.dubbo.rpc.cluster.SingleRouterChain;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_FAILED_SITE_SELECTION;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTER_MODE_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_KEY;
/**
* StaticDirectory
*/
public class StaticDirectory<T> extends AbstractDirectory<T> {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(StaticDirectory.class);
private final Class<T> interfaceClass;
public StaticDirectory(List<Invoker<T>> invokers) {
this(null, invokers, null);
}
public StaticDirectory(List<Invoker<T>> invokers, RouterChain<T> routerChain) {
this(null, invokers, routerChain);
}
public StaticDirectory(URL url, List<Invoker<T>> invokers) {
this(url, invokers, null);
}
public StaticDirectory(URL url, List<Invoker<T>> invokers, RouterChain<T> routerChain) {
super(
url == null && CollectionUtils.isNotEmpty(invokers)
? invokers.get(0).getUrl()
: url,
routerChain,
false);
if (CollectionUtils.isEmpty(invokers)) {
throw new IllegalArgumentException("invokers == null");
}
this.setInvokers(new BitList<>(invokers));
this.interfaceClass = invokers.get(0).getInterface();
}
@Override
public Class<T> getInterface() {
return interfaceClass;
}
@Override
public List<Invoker<T>> getAllInvokers() {
return getInvokers();
}
@Override
public boolean isAvailable() {
if (isDestroyed()) {
return false;
}
for (Invoker<T> invoker : getValidInvokers()) {
if (invoker.isAvailable()) {
return true;
} else {
addInvalidateInvoker(invoker);
}
}
return false;
}
@Override
public void destroy() {
if (isDestroyed()) {
return;
}
for (Invoker<T> invoker : getInvokers()) {
invoker.destroy();
}
super.destroy();
}
public void buildRouterChain() {
RouterChain<T> routerChain = RouterChain.buildChain(getInterface(), getUrl());
routerChain.setInvokers(getInvokers(), () -> {});
this.setRouterChain(routerChain);
}
public void notify(List<Invoker<T>> invokers) {
BitList<Invoker<T>> bitList = new BitList<>(invokers);
if (routerChain != null) {
refreshRouter(bitList.clone(), () -> this.setInvokers(bitList));
} else {
this.setInvokers(bitList);
}
}
@Override
protected List<Invoker<T>> doList(
SingleRouterChain<T> singleRouterChain, BitList<Invoker<T>> invokers, Invocation invocation)
throws RpcException {
if (singleRouterChain != null) {
try {
List<Invoker<T>> finalInvokers = singleRouterChain.route(getConsumerUrl(), invokers, invocation);
return finalInvokers == null ? BitList.emptyList() : finalInvokers;
} catch (Throwable t) {
logger.error(
CLUSTER_FAILED_SITE_SELECTION,
"Failed to execute router",
"",
"Failed to execute router: " + getUrl() + ", cause: " + t.getMessage(),
t);
return BitList.emptyList();
}
}
return invokers;
}
@Override
protected Map<String, String> getDirectoryMeta() {
Map<String, String> metas = new HashMap<>();
metas.put(REGISTRY_KEY, "static");
metas.put(REGISTER_MODE_KEY, "static");
return metas;
}
}
| 7,841 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/AbstractDirectory.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.directory;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.Version;
import org.apache.dubbo.common.config.Configuration;
import org.apache.dubbo.common.config.ConfigurationUtils;
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.threadpool.manager.FrameworkExecutorRepository;
import org.apache.dubbo.common.utils.ConcurrentHashSet;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.metrics.event.MetricsEventBus;
import org.apache.dubbo.metrics.model.key.MetricsKey;
import org.apache.dubbo.metrics.registry.event.RegistryEvent;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.cluster.Router;
import org.apache.dubbo.rpc.cluster.RouterChain;
import org.apache.dubbo.rpc.cluster.SingleRouterChain;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import org.apache.dubbo.rpc.cluster.support.ClusterUtils;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_RECONNECT_TASK_PERIOD;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_RECONNECT_TASK_TRY_COUNT;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.RECONNECT_TASK_PERIOD;
import static org.apache.dubbo.common.constants.CommonConstants.RECONNECT_TASK_TRY_COUNT;
import static org.apache.dubbo.common.constants.CommonConstants.REGISTER_IP_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_NO_VALID_PROVIDER;
import static org.apache.dubbo.common.utils.StringUtils.isNotEmpty;
import static org.apache.dubbo.rpc.cluster.Constants.CONSUMER_URL_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY;
/**
* Abstract implementation of Directory: Invoker list returned from this Directory's list method have been filtered by Routers
*/
public abstract class AbstractDirectory<T> implements Directory<T> {
// logger
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbstractDirectory.class);
private final URL url;
private volatile boolean destroyed = false;
protected volatile URL consumerUrl;
protected RouterChain<T> routerChain;
protected final Map<String, String> queryMap;
/**
* Invokers initialized flag.
*/
private volatile boolean invokersInitialized = false;
/**
* All invokers from registry
*/
private volatile BitList<Invoker<T>> invokers = BitList.emptyList();
/**
* Valid Invoker. All invokers from registry exclude unavailable and disabled invokers.
*/
private volatile BitList<Invoker<T>> validInvokers = BitList.emptyList();
/**
* Waiting to reconnect invokers.
*/
protected volatile List<Invoker<T>> invokersToReconnect = new CopyOnWriteArrayList<>();
/**
* Disabled Invokers. Will not be recovered in reconnect task, but be recovered if registry remove it.
*/
protected final Set<Invoker<T>> disabledInvokers = new ConcurrentHashSet<>();
private final Semaphore checkConnectivityPermit = new Semaphore(1);
private final ScheduledExecutorService connectivityExecutor;
private volatile ScheduledFuture<?> connectivityCheckFuture;
/**
* The max count of invokers for each reconnect task select to try to reconnect.
*/
private final int reconnectTaskTryCount;
/**
* The period of reconnect task if needed. (in ms)
*/
private final int reconnectTaskPeriod;
private ApplicationModel applicationModel;
public AbstractDirectory(URL url) {
this(url, null, false);
}
public AbstractDirectory(URL url, boolean isUrlFromRegistry) {
this(url, null, isUrlFromRegistry);
}
public AbstractDirectory(URL url, RouterChain<T> routerChain, boolean isUrlFromRegistry) {
if (url == null) {
throw new IllegalArgumentException("url == null");
}
this.url = url.removeAttribute(REFER_KEY).removeAttribute(MONITOR_KEY);
Map<String, String> queryMap;
Object referParams = url.getAttribute(REFER_KEY);
if (referParams instanceof Map) {
queryMap = (Map<String, String>) referParams;
this.consumerUrl = (URL) url.getAttribute(CONSUMER_URL_KEY);
} else {
queryMap = StringUtils.parseQueryString(url.getParameterAndDecoded(REFER_KEY));
}
// remove some local only parameters
applicationModel = url.getOrDefaultApplicationModel();
this.queryMap =
applicationModel.getBeanFactory().getBean(ClusterUtils.class).mergeLocalParams(queryMap);
if (consumerUrl == null) {
String host =
isNotEmpty(queryMap.get(REGISTER_IP_KEY)) ? queryMap.get(REGISTER_IP_KEY) : this.url.getHost();
String path = isNotEmpty(queryMap.get(PATH_KEY)) ? queryMap.get(PATH_KEY) : queryMap.get(INTERFACE_KEY);
String consumedProtocol = isNotEmpty(queryMap.get(PROTOCOL_KEY)) ? queryMap.get(PROTOCOL_KEY) : CONSUMER;
URL consumerUrlFrom = this.url
.setHost(host)
.setPort(0)
.setProtocol(consumedProtocol)
.setPath(path);
if (isUrlFromRegistry) {
// reserve parameters if url is already a consumer url
consumerUrlFrom = consumerUrlFrom.clearParameters();
}
this.consumerUrl = consumerUrlFrom.addParameters(queryMap);
}
this.connectivityExecutor = applicationModel
.getFrameworkModel()
.getBeanFactory()
.getBean(FrameworkExecutorRepository.class)
.getConnectivityScheduledExecutor();
Configuration configuration = ConfigurationUtils.getGlobalConfiguration(url.getOrDefaultModuleModel());
this.reconnectTaskTryCount = configuration.getInt(RECONNECT_TASK_TRY_COUNT, DEFAULT_RECONNECT_TASK_TRY_COUNT);
this.reconnectTaskPeriod = configuration.getInt(RECONNECT_TASK_PERIOD, DEFAULT_RECONNECT_TASK_PERIOD);
setRouterChain(routerChain);
}
@Override
public List<Invoker<T>> list(Invocation invocation) throws RpcException {
if (destroyed) {
throw new RpcException(
"Directory of type " + this.getClass().getSimpleName() + " already destroyed for service "
+ getConsumerUrl().getServiceKey() + " from registry " + getUrl());
}
BitList<Invoker<T>> availableInvokers;
SingleRouterChain<T> singleChain = null;
try {
try {
if (routerChain != null) {
routerChain.getLock().readLock().lock();
}
// use clone to avoid being modified at doList().
if (invokersInitialized) {
availableInvokers = validInvokers.clone();
} else {
availableInvokers = invokers.clone();
}
if (routerChain != null) {
singleChain = routerChain.getSingleChain(getConsumerUrl(), availableInvokers, invocation);
singleChain.getLock().readLock().lock();
}
} finally {
if (routerChain != null) {
routerChain.getLock().readLock().unlock();
}
}
List<Invoker<T>> routedResult = doList(singleChain, availableInvokers, invocation);
if (routedResult.isEmpty()) {
// 2-2 - No provider available.
logger.warn(
CLUSTER_NO_VALID_PROVIDER,
"provider server or registry center crashed",
"",
"No provider available after connectivity filter for the service "
+ getConsumerUrl().getServiceKey()
+ " All routed invokers' size: " + routedResult.size()
+ " from registry " + this
+ " on the consumer " + NetUtils.getLocalHost()
+ " using the dubbo version " + Version.getVersion() + ".");
}
return Collections.unmodifiableList(routedResult);
} finally {
if (singleChain != null) {
singleChain.getLock().readLock().unlock();
}
}
}
@Override
public URL getUrl() {
return url;
}
public RouterChain<T> getRouterChain() {
return routerChain;
}
public void setRouterChain(RouterChain<T> routerChain) {
this.routerChain = routerChain;
}
protected void addRouters(List<Router> routers) {
routers = routers == null ? Collections.emptyList() : routers;
routerChain.addRouters(routers);
}
public URL getConsumerUrl() {
return consumerUrl;
}
public void setConsumerUrl(URL consumerUrl) {
this.consumerUrl = consumerUrl;
}
@Override
public boolean isDestroyed() {
return destroyed;
}
@Override
public void destroy() {
destroyed = true;
destroyInvokers();
invokersToReconnect.clear();
disabledInvokers.clear();
}
@Override
public void discordAddresses() {
// do nothing by default
}
@Override
public void addInvalidateInvoker(Invoker<T> invoker) {
// 1. remove this invoker from validInvokers list, this invoker will not be listed in the next time
if (removeValidInvoker(invoker)) {
// 2. add this invoker to reconnect list
invokersToReconnect.add(invoker);
// 3. try start check connectivity task
checkConnectivity();
logger.info("The invoker " + invoker.getUrl()
+ " has been added to invalidate list due to connectivity problem. "
+ "Will trying to reconnect to it in the background.");
}
}
public void checkConnectivity() {
// try to submit task, to ensure there is only one task at most for each directory
if (checkConnectivityPermit.tryAcquire()) {
this.connectivityCheckFuture = connectivityExecutor.schedule(
() -> {
try {
if (isDestroyed()) {
return;
}
RpcContext.getServiceContext().setConsumerUrl(getConsumerUrl());
List<Invoker<T>> needDeleteList = new ArrayList<>();
List<Invoker<T>> invokersToTry = new ArrayList<>();
// 1. pick invokers from invokersToReconnect
// limit max reconnectTaskTryCount, prevent this task hang up all the connectivityExecutor
// for long time
if (invokersToReconnect.size() < reconnectTaskTryCount) {
invokersToTry.addAll(invokersToReconnect);
} else {
for (int i = 0; i < reconnectTaskTryCount; i++) {
Invoker<T> tInvoker = invokersToReconnect.get(
ThreadLocalRandom.current().nextInt(invokersToReconnect.size()));
if (!invokersToTry.contains(tInvoker)) {
// ignore if is selected, invokersToTry's size is always smaller than
// reconnectTaskTryCount + 1
invokersToTry.add(tInvoker);
}
}
}
// 2. try to check the invoker's status
for (Invoker<T> invoker : invokersToTry) {
if (invokers.contains(invoker)) {
if (invoker.isAvailable()) {
needDeleteList.add(invoker);
}
} else {
needDeleteList.add(invoker);
}
}
// 3. recover valid invoker
for (Invoker<T> tInvoker : needDeleteList) {
if (invokers.contains(tInvoker)) {
addValidInvoker(tInvoker);
logger.info(
"Recover service address: " + tInvoker.getUrl() + " from invalid list.");
}
invokersToReconnect.remove(tInvoker);
}
} finally {
checkConnectivityPermit.release();
}
// 4. submit new task if it has more to recover
if (!invokersToReconnect.isEmpty()) {
checkConnectivity();
}
MetricsEventBus.publish(RegistryEvent.refreshDirectoryEvent(
applicationModel, getSummary(), getDirectoryMeta()));
},
reconnectTaskPeriod,
TimeUnit.MILLISECONDS);
}
MetricsEventBus.publish(
RegistryEvent.refreshDirectoryEvent(applicationModel, getSummary(), getDirectoryMeta()));
}
/**
* Refresh invokers from total invokers
* 1. all the invokers in need to reconnect list should be removed in the valid invokers list
* 2. all the invokers in disabled invokers list should be removed in the valid invokers list
* 3. all the invokers disappeared from total invokers should be removed in the need to reconnect list
* 4. all the invokers disappeared from total invokers should be removed in the disabled invokers list
*/
public void refreshInvoker() {
if (invokersInitialized) {
refreshInvokerInternal();
}
MetricsEventBus.publish(
RegistryEvent.refreshDirectoryEvent(applicationModel, getSummary(), getDirectoryMeta()));
}
protected Map<String, String> getDirectoryMeta() {
return Collections.emptyMap();
}
private synchronized void refreshInvokerInternal() {
BitList<Invoker<T>> copiedInvokers = invokers.clone();
refreshInvokers(copiedInvokers, invokersToReconnect);
refreshInvokers(copiedInvokers, disabledInvokers);
validInvokers = copiedInvokers;
}
private void refreshInvokers(BitList<Invoker<T>> targetInvokers, Collection<Invoker<T>> invokersToRemove) {
List<Invoker<T>> needToRemove = new LinkedList<>();
for (Invoker<T> tInvoker : invokersToRemove) {
if (targetInvokers.contains(tInvoker)) {
targetInvokers.remove(tInvoker);
} else {
needToRemove.add(tInvoker);
}
}
invokersToRemove.removeAll(needToRemove);
}
@Override
public void addDisabledInvoker(Invoker<T> invoker) {
if (invokers.contains(invoker)) {
disabledInvokers.add(invoker);
removeValidInvoker(invoker);
logger.info("Disable service address: " + invoker.getUrl() + ".");
}
MetricsEventBus.publish(
RegistryEvent.refreshDirectoryEvent(applicationModel, getSummary(), getDirectoryMeta()));
}
@Override
public void recoverDisabledInvoker(Invoker<T> invoker) {
if (disabledInvokers.remove(invoker)) {
try {
addValidInvoker(invoker);
logger.info("Recover service address: " + invoker.getUrl() + " from disabled list.");
} catch (Throwable ignore) {
}
}
MetricsEventBus.publish(
RegistryEvent.refreshDirectoryEvent(applicationModel, getSummary(), getDirectoryMeta()));
}
protected final void refreshRouter(BitList<Invoker<T>> newlyInvokers, Runnable switchAction) {
try {
routerChain.setInvokers(newlyInvokers.clone(), switchAction);
} catch (Throwable t) {
logger.error(
LoggerCodeConstants.INTERNAL_ERROR,
"",
"",
"Error occurred when refreshing router chain. " + "The addresses from notification: "
+ newlyInvokers.stream()
.map(Invoker::getUrl)
.map(URL::getAddress)
.collect(Collectors.joining(", ")),
t);
throw t;
}
}
/**
* for ut only
*/
@Deprecated
public Semaphore getCheckConnectivityPermit() {
return checkConnectivityPermit;
}
/**
* for ut only
*/
@Deprecated
public ScheduledFuture<?> getConnectivityCheckFuture() {
return connectivityCheckFuture;
}
public BitList<Invoker<T>> getInvokers() {
// return clone to avoid being modified.
return invokers.clone();
}
public BitList<Invoker<T>> getValidInvokers() {
// return clone to avoid being modified.
return validInvokers.clone();
}
public List<Invoker<T>> getInvokersToReconnect() {
return invokersToReconnect;
}
public Set<Invoker<T>> getDisabledInvokers() {
return disabledInvokers;
}
protected void setInvokers(BitList<Invoker<T>> invokers) {
this.invokers = invokers;
refreshInvokerInternal();
this.invokersInitialized = true;
MetricsEventBus.publish(
RegistryEvent.refreshDirectoryEvent(applicationModel, getSummary(), getDirectoryMeta()));
}
protected void destroyInvokers() {
// set empty instead of clearing to support concurrent access.
this.invokers = BitList.emptyList();
this.validInvokers = BitList.emptyList();
this.invokersInitialized = false;
}
private boolean addValidInvoker(Invoker<T> invoker) {
boolean result;
synchronized (this.validInvokers) {
result = this.validInvokers.add(invoker);
}
MetricsEventBus.publish(
RegistryEvent.refreshDirectoryEvent(applicationModel, getSummary(), getDirectoryMeta()));
return result;
}
private boolean removeValidInvoker(Invoker<T> invoker) {
boolean result;
synchronized (this.validInvokers) {
result = this.validInvokers.remove(invoker);
}
MetricsEventBus.publish(
RegistryEvent.refreshDirectoryEvent(applicationModel, getSummary(), getDirectoryMeta()));
return result;
}
protected abstract List<Invoker<T>> doList(
SingleRouterChain<T> singleRouterChain, BitList<Invoker<T>> invokers, Invocation invocation)
throws RpcException;
protected String joinValidInvokerAddresses() {
BitList<Invoker<T>> validInvokers = getValidInvokers().clone();
if (validInvokers.isEmpty()) {
return "empty";
}
return validInvokers.stream()
.limit(5)
.map(Invoker::getUrl)
.map(URL::getAddress)
.collect(Collectors.joining(","));
}
private Map<MetricsKey, Map<String, Integer>> getSummary() {
Map<MetricsKey, Map<String, Integer>> summaryMap = new HashMap<>();
summaryMap.put(MetricsKey.DIRECTORY_METRIC_NUM_VALID, groupByServiceKey(getValidInvokers()));
summaryMap.put(MetricsKey.DIRECTORY_METRIC_NUM_DISABLE, groupByServiceKey(getDisabledInvokers()));
summaryMap.put(MetricsKey.DIRECTORY_METRIC_NUM_TO_RECONNECT, groupByServiceKey(getInvokersToReconnect()));
summaryMap.put(MetricsKey.DIRECTORY_METRIC_NUM_ALL, groupByServiceKey(getInvokers()));
return summaryMap;
}
private Map<String, Integer> groupByServiceKey(Collection<Invoker<T>> invokers) {
return Collections.singletonMap(getConsumerUrl().getServiceKey(), invokers.size());
}
@Override
public String toString() {
return "Directory(" + "invokers: "
+ invokers.size() + "["
+ invokers.stream()
.map(Invoker::getUrl)
.map(URL::getAddress)
.limit(3)
.collect(Collectors.joining(", "))
+ "]" + ", validInvokers: "
+ validInvokers.size() + "["
+ validInvokers.stream()
.map(Invoker::getUrl)
.map(URL::getAddress)
.limit(3)
.collect(Collectors.joining(", "))
+ "]" + ", invokersToReconnect: "
+ invokersToReconnect.size() + "["
+ invokersToReconnect.stream()
.map(Invoker::getUrl)
.map(URL::getAddress)
.limit(3)
.collect(Collectors.joining(", "))
+ "]" + ')';
}
}
| 7,842 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/BooleanArrayMerger.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.merger;
import org.apache.dubbo.common.utils.ArrayUtils;
import org.apache.dubbo.rpc.cluster.Merger;
public class BooleanArrayMerger implements Merger<boolean[]> {
@Override
public boolean[] merge(boolean[]... items) {
if (ArrayUtils.isEmpty(items)) {
return new boolean[0];
}
int totalLen = 0;
for (boolean[] array : items) {
if (array != null) {
totalLen += array.length;
}
}
boolean[] result = new boolean[totalLen];
int index = 0;
for (boolean[] array : items) {
if (array != null) {
System.arraycopy(array, 0, result, index, array.length);
index += array.length;
}
}
return result;
}
}
| 7,843 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/ByteArrayMerger.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.merger;
import org.apache.dubbo.common.utils.ArrayUtils;
import org.apache.dubbo.rpc.cluster.Merger;
public class ByteArrayMerger implements Merger<byte[]> {
@Override
public byte[] merge(byte[]... items) {
if (ArrayUtils.isEmpty(items)) {
return new byte[0];
}
int total = 0;
for (byte[] array : items) {
if (array != null) {
total += array.length;
}
}
byte[] result = new byte[total];
int index = 0;
for (byte[] array : items) {
if (array != null) {
System.arraycopy(array, 0, result, index, array.length);
index += array.length;
}
}
return result;
}
}
| 7,844 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/IntArrayMerger.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.merger;
import org.apache.dubbo.common.utils.ArrayUtils;
import org.apache.dubbo.rpc.cluster.Merger;
import java.util.Arrays;
import java.util.Objects;
public class IntArrayMerger implements Merger<int[]> {
@Override
public int[] merge(int[]... items) {
if (ArrayUtils.isEmpty(items)) {
return new int[0];
}
return Arrays.stream(items)
.filter(Objects::nonNull)
.flatMapToInt(Arrays::stream)
.toArray();
}
}
| 7,845 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/ListMerger.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.merger;
import org.apache.dubbo.common.utils.ArrayUtils;
import org.apache.dubbo.rpc.cluster.Merger;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ListMerger implements Merger<List<?>> {
@Override
public List<Object> merge(List<?>... items) {
if (ArrayUtils.isEmpty(items)) {
return Collections.emptyList();
}
return Stream.of(items)
.filter(Objects::nonNull)
.flatMap(Collection::stream)
.collect(Collectors.toList());
}
}
| 7,846 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/LongArrayMerger.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.merger;
import org.apache.dubbo.common.utils.ArrayUtils;
import org.apache.dubbo.rpc.cluster.Merger;
import java.util.Arrays;
import java.util.Objects;
public class LongArrayMerger implements Merger<long[]> {
@Override
public long[] merge(long[]... items) {
if (ArrayUtils.isEmpty(items)) {
return new long[0];
}
return Arrays.stream(items)
.filter(Objects::nonNull)
.flatMapToLong(Arrays::stream)
.toArray();
}
}
| 7,847 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/DoubleArrayMerger.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.merger;
import org.apache.dubbo.common.utils.ArrayUtils;
import org.apache.dubbo.rpc.cluster.Merger;
import java.util.Arrays;
import java.util.Objects;
public class DoubleArrayMerger implements Merger<double[]> {
@Override
public double[] merge(double[]... items) {
if (ArrayUtils.isEmpty(items)) {
return new double[0];
}
return Arrays.stream(items)
.filter(Objects::nonNull)
.flatMapToDouble(Arrays::stream)
.toArray();
}
}
| 7,848 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/ArrayMerger.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.merger;
import org.apache.dubbo.common.utils.ArrayUtils;
import org.apache.dubbo.rpc.cluster.Merger;
import java.lang.reflect.Array;
public class ArrayMerger implements Merger<Object[]> {
public static final ArrayMerger INSTANCE = new ArrayMerger();
@Override
public Object[] merge(Object[]... items) {
if (ArrayUtils.isEmpty(items)) {
return new Object[0];
}
int i = 0;
while (i < items.length && items[i] == null) {
i++;
}
if (i == items.length) {
return new Object[0];
}
Class<?> type = items[i].getClass().getComponentType();
int totalLen = 0;
for (; i < items.length; i++) {
if (items[i] == null) {
continue;
}
Class<?> itemType = items[i].getClass().getComponentType();
if (itemType != type) {
throw new IllegalArgumentException("Arguments' types are different");
}
totalLen += items[i].length;
}
if (totalLen == 0) {
return new Object[0];
}
Object result = Array.newInstance(type, totalLen);
int index = 0;
for (Object[] array : items) {
if (array != null) {
System.arraycopy(array, 0, result, index, array.length);
index += array.length;
}
}
return (Object[]) result;
}
}
| 7,849 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/ShortArrayMerger.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.merger;
import org.apache.dubbo.common.utils.ArrayUtils;
import org.apache.dubbo.rpc.cluster.Merger;
public class ShortArrayMerger implements Merger<short[]> {
@Override
public short[] merge(short[]... items) {
if (ArrayUtils.isEmpty(items)) {
return new short[0];
}
int total = 0;
for (short[] array : items) {
if (array != null) {
total += array.length;
}
}
short[] result = new short[total];
int index = 0;
for (short[] array : items) {
if (array != null) {
System.arraycopy(array, 0, result, index, array.length);
index += array.length;
}
}
return result;
}
}
| 7,850 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/MergerFactory.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.merger;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.TypeUtils;
import org.apache.dubbo.rpc.cluster.Merger;
import org.apache.dubbo.rpc.model.ScopeModel;
import org.apache.dubbo.rpc.model.ScopeModelAware;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_FAILED_LOAD_MERGER;
public class MergerFactory implements ScopeModelAware {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MergerFactory.class);
private ConcurrentMap<Class<?>, Merger<?>> MERGER_CACHE = new ConcurrentHashMap<Class<?>, Merger<?>>();
private ScopeModel scopeModel;
@Override
public void setScopeModel(ScopeModel scopeModel) {
this.scopeModel = scopeModel;
}
/**
* Find the merger according to the returnType class, the merger will
* merge an array of returnType into one
*
* @param returnType the merger will return this type
* @return the merger which merges an array of returnType into one, return null if not exist
* @throws IllegalArgumentException if returnType is null
*/
public <T> Merger<T> getMerger(Class<T> returnType) {
if (returnType == null) {
throw new IllegalArgumentException("returnType is null");
}
if (CollectionUtils.isEmptyMap(MERGER_CACHE)) {
loadMergers();
}
Merger merger = MERGER_CACHE.get(returnType);
if (merger == null && returnType.isArray()) {
merger = ArrayMerger.INSTANCE;
}
return merger;
}
private void loadMergers() {
Set<String> names = scopeModel.getExtensionLoader(Merger.class).getSupportedExtensions();
for (String name : names) {
Merger m = scopeModel.getExtensionLoader(Merger.class).getExtension(name);
Class<?> actualTypeArg = getActualTypeArgument(m.getClass());
if (actualTypeArg == null) {
logger.warn(
CLUSTER_FAILED_LOAD_MERGER,
"load merger config failed",
"",
"Failed to get actual type argument from merger "
+ m.getClass().getName());
continue;
}
MERGER_CACHE.putIfAbsent(actualTypeArg, m);
}
}
/**
* get merger's actual type argument (same as return type)
* @param mergerCls
* @return
*/
private Class<?> getActualTypeArgument(Class<? extends Merger> mergerCls) {
Class<?> superClass = mergerCls;
while (superClass != Object.class) {
Type[] interfaceTypes = superClass.getGenericInterfaces();
ParameterizedType mergerType;
for (Type it : interfaceTypes) {
if (it instanceof ParameterizedType
&& (mergerType = ((ParameterizedType) it)).getRawType() == Merger.class) {
Type typeArg = mergerType.getActualTypeArguments()[0];
return TypeUtils.getRawClass(typeArg);
}
}
superClass = superClass.getSuperclass();
}
return null;
}
}
| 7,851 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/FloatArrayMerger.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.merger;
import org.apache.dubbo.common.utils.ArrayUtils;
import org.apache.dubbo.rpc.cluster.Merger;
public class FloatArrayMerger implements Merger<float[]> {
@Override
public float[] merge(float[]... items) {
if (ArrayUtils.isEmpty(items)) {
return new float[0];
}
int total = 0;
for (float[] array : items) {
if (array != null) {
total += array.length;
}
}
float[] result = new float[total];
int index = 0;
for (float[] array : items) {
if (array != null) {
System.arraycopy(array, 0, result, index, array.length);
index += array.length;
}
}
return result;
}
}
| 7,852 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/MapMerger.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.merger;
import org.apache.dubbo.common.utils.ArrayUtils;
import org.apache.dubbo.rpc.cluster.Merger;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Stream;
public class MapMerger implements Merger<Map<?, ?>> {
@Override
public Map<?, ?> merge(Map<?, ?>... items) {
if (ArrayUtils.isEmpty(items)) {
return Collections.emptyMap();
}
Map<Object, Object> result = new HashMap<Object, Object>();
Stream.of(items).filter(Objects::nonNull).forEach(result::putAll);
return result;
}
}
| 7,853 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/CharArrayMerger.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.merger;
import org.apache.dubbo.common.utils.ArrayUtils;
import org.apache.dubbo.rpc.cluster.Merger;
public class CharArrayMerger implements Merger<char[]> {
@Override
public char[] merge(char[]... items) {
if (ArrayUtils.isEmpty(items)) {
return new char[0];
}
int total = 0;
for (char[] array : items) {
if (array != null) {
total += array.length;
}
}
char[] result = new char[total];
int index = 0;
for (char[] array : items) {
if (array != null) {
System.arraycopy(array, 0, result, index, array.length);
index += array.length;
}
}
return result;
}
}
| 7,854 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/SetMerger.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.merger;
import org.apache.dubbo.common.utils.ArrayUtils;
import org.apache.dubbo.rpc.cluster.Merger;
import java.util.Collections;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Stream;
public class SetMerger implements Merger<Set<?>> {
@Override
public Set<Object> merge(Set<?>... items) {
if (ArrayUtils.isEmpty(items)) {
return Collections.emptySet();
}
Set<Object> result = new HashSet<Object>();
Stream.of(items).filter(Objects::nonNull).forEach(result::addAll);
return result;
}
}
| 7,855 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvoker.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.Version;
import org.apache.dubbo.common.config.Configuration;
import org.apache.dubbo.common.config.ConfigurationUtils;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.profiler.ProfilerSwitch;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.InvocationProfilerUtils;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcServiceContext;
import org.apache.dubbo.rpc.cluster.ClusterInvoker;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.cluster.LoadBalance;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ScopeModelUtil;
import org.apache.dubbo.rpc.support.RpcUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_LOADBALANCE;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_RESELECT_COUNT;
import static org.apache.dubbo.common.constants.CommonConstants.ENABLE_CONNECTIVITY_VALIDATION;
import static org.apache.dubbo.common.constants.CommonConstants.LOADBALANCE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.RESELECT_COUNT;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_FAILED_RESELECT_INVOKERS;
import static org.apache.dubbo.rpc.cluster.Constants.CLUSTER_AVAILABLE_CHECK_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.CLUSTER_STICKY_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.DEFAULT_CLUSTER_AVAILABLE_CHECK;
import static org.apache.dubbo.rpc.cluster.Constants.DEFAULT_CLUSTER_STICKY;
/**
* AbstractClusterInvoker
*/
public abstract class AbstractClusterInvoker<T> implements ClusterInvoker<T> {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(AbstractClusterInvoker.class);
protected Directory<T> directory;
protected boolean availableCheck;
private volatile int reselectCount = DEFAULT_RESELECT_COUNT;
private volatile boolean enableConnectivityValidation = true;
private final AtomicBoolean destroyed = new AtomicBoolean(false);
private volatile Invoker<T> stickyInvoker = null;
public AbstractClusterInvoker() {}
public AbstractClusterInvoker(Directory<T> directory) {
this(directory, directory.getUrl());
}
public AbstractClusterInvoker(Directory<T> directory, URL url) {
if (directory == null) {
throw new IllegalArgumentException("service directory == null");
}
this.directory = directory;
// sticky: invoker.isAvailable() should always be checked before using when availablecheck is true.
this.availableCheck = url.getParameter(CLUSTER_AVAILABLE_CHECK_KEY, DEFAULT_CLUSTER_AVAILABLE_CHECK);
Configuration configuration = ConfigurationUtils.getGlobalConfiguration(url.getOrDefaultModuleModel());
this.reselectCount = configuration.getInt(RESELECT_COUNT, DEFAULT_RESELECT_COUNT);
this.enableConnectivityValidation = configuration.getBoolean(ENABLE_CONNECTIVITY_VALIDATION, true);
}
@Override
public Class<T> getInterface() {
return getDirectory().getInterface();
}
@Override
public URL getUrl() {
return getDirectory().getConsumerUrl();
}
@Override
public URL getRegistryUrl() {
return getDirectory().getUrl();
}
@Override
public boolean isAvailable() {
Invoker<T> invoker = stickyInvoker;
if (invoker != null) {
return invoker.isAvailable();
}
return getDirectory().isAvailable();
}
@Override
public Directory<T> getDirectory() {
return directory;
}
@Override
public void destroy() {
if (destroyed.compareAndSet(false, true)) {
getDirectory().destroy();
}
}
@Override
public boolean isDestroyed() {
return destroyed.get();
}
/**
* Select a invoker using loadbalance policy.</br>
* a) Firstly, select an invoker using loadbalance. If this invoker is in previously selected list, or,
* if this invoker is unavailable, then continue step b (reselect), otherwise return the first selected invoker</br>
* <p>
* b) Reselection, the validation rule for reselection: selected > available. This rule guarantees that
* the selected invoker has the minimum chance to be one in the previously selected list, and also
* guarantees this invoker is available.
*
* @param loadbalance load balance policy
* @param invocation invocation
* @param invokers invoker candidates
* @param selected exclude selected invokers or not
* @return the invoker which will final to do invoke.
* @throws RpcException exception
*/
protected Invoker<T> select(
LoadBalance loadbalance, Invocation invocation, List<Invoker<T>> invokers, List<Invoker<T>> selected)
throws RpcException {
if (CollectionUtils.isEmpty(invokers)) {
return null;
}
String methodName = invocation == null ? StringUtils.EMPTY_STRING : RpcUtils.getMethodName(invocation);
boolean sticky =
invokers.get(0).getUrl().getMethodParameter(methodName, CLUSTER_STICKY_KEY, DEFAULT_CLUSTER_STICKY);
// ignore overloaded method
if (stickyInvoker != null && !invokers.contains(stickyInvoker)) {
stickyInvoker = null;
}
// ignore concurrency problem
if (sticky && stickyInvoker != null && (selected == null || !selected.contains(stickyInvoker))) {
if (availableCheck && stickyInvoker.isAvailable()) {
return stickyInvoker;
}
}
Invoker<T> invoker = doSelect(loadbalance, invocation, invokers, selected);
if (sticky) {
stickyInvoker = invoker;
}
return invoker;
}
private Invoker<T> doSelect(
LoadBalance loadbalance, Invocation invocation, List<Invoker<T>> invokers, List<Invoker<T>> selected)
throws RpcException {
if (CollectionUtils.isEmpty(invokers)) {
return null;
}
if (invokers.size() == 1) {
Invoker<T> tInvoker = invokers.get(0);
checkShouldInvalidateInvoker(tInvoker);
return tInvoker;
}
Invoker<T> invoker = loadbalance.select(invokers, getUrl(), invocation);
// If the `invoker` is in the `selected` or invoker is unavailable && availablecheck is true, reselect.
boolean isSelected = selected != null && selected.contains(invoker);
boolean isUnavailable = availableCheck && !invoker.isAvailable() && getUrl() != null;
if (isUnavailable) {
invalidateInvoker(invoker);
}
if (isSelected || isUnavailable) {
try {
Invoker<T> rInvoker = reselect(loadbalance, invocation, invokers, selected, availableCheck);
if (rInvoker != null) {
invoker = rInvoker;
} else {
// Check the index of current selected invoker, if it's not the last one, choose the one at index+1.
int index = invokers.indexOf(invoker);
try {
// Avoid collision
invoker = invokers.get((index + 1) % invokers.size());
} catch (Exception e) {
logger.warn(
CLUSTER_FAILED_RESELECT_INVOKERS,
"select invokers exception",
"",
e.getMessage() + " may because invokers list dynamic change, ignore.",
e);
}
}
} catch (Throwable t) {
logger.error(
CLUSTER_FAILED_RESELECT_INVOKERS,
"failed to reselect invokers",
"",
"cluster reselect fail reason is :" + t.getMessage()
+ " if can not solve, you can set cluster.availablecheck=false in url",
t);
}
}
return invoker;
}
/**
* Reselect, use invokers not in `selected` first, if all invokers are in `selected`,
* just pick an available one using loadbalance policy.
*
* @param loadbalance load balance policy
* @param invocation invocation
* @param invokers invoker candidates
* @param selected exclude selected invokers or not
* @param availableCheck check invoker available if true
* @return the reselect result to do invoke
* @throws RpcException exception
*/
private Invoker<T> reselect(
LoadBalance loadbalance,
Invocation invocation,
List<Invoker<T>> invokers,
List<Invoker<T>> selected,
boolean availableCheck)
throws RpcException {
// Allocating one in advance, this list is certain to be used.
List<Invoker<T>> reselectInvokers = new ArrayList<>(Math.min(invokers.size(), reselectCount));
// 1. Try picking some invokers not in `selected`.
// 1.1. If all selectable invokers' size is smaller than reselectCount, just add all
// 1.2. If all selectable invokers' size is greater than reselectCount, randomly select reselectCount.
// The result size of invokers might smaller than reselectCount due to disAvailable or de-duplication
// (might be zero).
// This means there is probable that reselectInvokers is empty however all invoker list may contain
// available invokers.
// Use reselectCount can reduce retry times if invokers' size is huge, which may lead to long time
// hang up.
if (reselectCount >= invokers.size()) {
for (Invoker<T> invoker : invokers) {
// check if available
if (availableCheck && !invoker.isAvailable()) {
// add to invalidate invoker
invalidateInvoker(invoker);
continue;
}
if (selected == null || !selected.contains(invoker)) {
reselectInvokers.add(invoker);
}
}
} else {
for (int i = 0; i < reselectCount; i++) {
// select one randomly
Invoker<T> invoker = invokers.get(ThreadLocalRandom.current().nextInt(invokers.size()));
// check if available
if (availableCheck && !invoker.isAvailable()) {
// add to invalidate invoker
invalidateInvoker(invoker);
continue;
}
// de-duplication
if (selected == null || !selected.contains(invoker) || !reselectInvokers.contains(invoker)) {
reselectInvokers.add(invoker);
}
}
}
// 2. Use loadBalance to select one (all the reselectInvokers are available)
if (!reselectInvokers.isEmpty()) {
return loadbalance.select(reselectInvokers, getUrl(), invocation);
}
// 3. reselectInvokers is empty. Unable to find at least one available invoker.
// Re-check all the selected invokers. If some in the selected list are available, add to reselectInvokers.
if (selected != null) {
for (Invoker<T> invoker : selected) {
if ((invoker.isAvailable()) // available first
&& !reselectInvokers.contains(invoker)) {
reselectInvokers.add(invoker);
}
}
}
// 4. If reselectInvokers is not empty after re-check.
// Pick an available invoker using loadBalance policy
if (!reselectInvokers.isEmpty()) {
return loadbalance.select(reselectInvokers, getUrl(), invocation);
}
// 5. No invoker match, return null.
return null;
}
private void checkShouldInvalidateInvoker(Invoker<T> invoker) {
if (availableCheck && !invoker.isAvailable()) {
invalidateInvoker(invoker);
}
}
private void invalidateInvoker(Invoker<T> invoker) {
if (enableConnectivityValidation) {
if (getDirectory() != null) {
getDirectory().addInvalidateInvoker(invoker);
}
}
}
@Override
public Result invoke(final Invocation invocation) throws RpcException {
checkWhetherDestroyed();
// binding attachments into invocation.
// Map<String, Object> contextAttachments = RpcContext.getClientAttachment().getObjectAttachments();
// if (contextAttachments != null && contextAttachments.size() != 0) {
// ((RpcInvocation) invocation).addObjectAttachmentsIfAbsent(contextAttachments);
// }
InvocationProfilerUtils.enterDetailProfiler(invocation, () -> "Router route.");
List<Invoker<T>> invokers = list(invocation);
InvocationProfilerUtils.releaseDetailProfiler(invocation);
checkInvokers(invokers, invocation);
LoadBalance loadbalance = initLoadBalance(invokers, invocation);
RpcUtils.attachInvocationIdIfAsync(getUrl(), invocation);
InvocationProfilerUtils.enterDetailProfiler(
invocation, () -> "Cluster " + this.getClass().getName() + " invoke.");
try {
return doInvoke(invocation, invokers, loadbalance);
} finally {
InvocationProfilerUtils.releaseDetailProfiler(invocation);
}
}
protected void checkWhetherDestroyed() {
if (destroyed.get()) {
throw new RpcException(
"Rpc cluster invoker for " + getInterface() + " on consumer " + NetUtils.getLocalHost()
+ " use dubbo version " + Version.getVersion()
+ " is now destroyed! Can not invoke any more.");
}
}
@Override
public String toString() {
return getInterface() + " -> " + getUrl().toString();
}
protected void checkInvokers(List<Invoker<T>> invokers, Invocation invocation) {
if (CollectionUtils.isEmpty(invokers)) {
throw new RpcException(
RpcException.NO_INVOKER_AVAILABLE_AFTER_FILTER,
"Failed to invoke the method "
+ RpcUtils.getMethodName(invocation) + " in the service "
+ getInterface().getName()
+ ". No provider available for the service "
+ getDirectory().getConsumerUrl().getServiceKey()
+ " from registry " + getDirectory()
+ " on the consumer " + NetUtils.getLocalHost()
+ " using the dubbo version " + Version.getVersion()
+ ". Please check if the providers have been started and registered.");
}
}
protected Result invokeWithContext(Invoker<T> invoker, Invocation invocation) {
Invoker<T> originInvoker = setContext(invoker);
Result result;
try {
if (ProfilerSwitch.isEnableSimpleProfiler()) {
InvocationProfilerUtils.enterProfiler(
invocation,
"Invoker invoke. Target Address: " + invoker.getUrl().getAddress());
}
setRemote(invoker, invocation);
result = invoker.invoke(invocation);
} finally {
clearContext(originInvoker);
InvocationProfilerUtils.releaseSimpleProfiler(invocation);
}
return result;
}
/**
* Set the remoteAddress and remoteApplicationName so that filter can get them.
*
*/
private void setRemote(Invoker<?> invoker, Invocation invocation) {
invocation.addInvokedInvoker(invoker);
RpcServiceContext serviceContext = RpcContext.getServiceContext();
serviceContext.setRemoteAddress(invoker.getUrl().toInetSocketAddress());
serviceContext.setRemoteApplicationName(invoker.getUrl().getRemoteApplication());
}
/**
* When using a thread pool to fork a child thread, ThreadLocal cannot be passed.
* In this scenario, please use the invokeWithContextAsync method.
*
* @return
*/
protected Result invokeWithContextAsync(Invoker<T> invoker, Invocation invocation, URL consumerUrl) {
Invoker<T> originInvoker = setContext(invoker, consumerUrl);
Result result;
try {
result = invoker.invoke(invocation);
} finally {
clearContext(originInvoker);
}
return result;
}
protected abstract Result doInvoke(Invocation invocation, List<Invoker<T>> invokers, LoadBalance loadbalance)
throws RpcException;
protected List<Invoker<T>> list(Invocation invocation) throws RpcException {
return getDirectory().list(invocation);
}
/**
* Init LoadBalance.
* <p>
* if invokers is not empty, init from the first invoke's url and invocation
* if invokes is empty, init a default LoadBalance(RandomLoadBalance)
* </p>
*
* @param invokers invokers
* @param invocation invocation
* @return LoadBalance instance. if not need init, return null.
*/
protected LoadBalance initLoadBalance(List<Invoker<T>> invokers, Invocation invocation) {
ApplicationModel applicationModel = ScopeModelUtil.getApplicationModel(invocation.getModuleModel());
if (CollectionUtils.isNotEmpty(invokers)) {
return applicationModel
.getExtensionLoader(LoadBalance.class)
.getExtension(invokers.get(0)
.getUrl()
.getMethodParameter(
RpcUtils.getMethodName(invocation), LOADBALANCE_KEY, DEFAULT_LOADBALANCE));
} else {
return applicationModel.getExtensionLoader(LoadBalance.class).getExtension(DEFAULT_LOADBALANCE);
}
}
private Invoker<T> setContext(Invoker<T> invoker) {
return setContext(invoker, null);
}
private Invoker<T> setContext(Invoker<T> invoker, URL consumerUrl) {
RpcServiceContext context = RpcContext.getServiceContext();
Invoker<?> originInvoker = context.getInvoker();
context.setInvoker(invoker)
.setConsumerUrl(
null != consumerUrl
? consumerUrl
: RpcContext.getServiceContext().getConsumerUrl());
return (Invoker<T>) originInvoker;
}
private void clearContext(Invoker<T> invoker) {
// do nothing
RpcContext context = RpcContext.getServiceContext();
context.setInvoker(invoker);
}
}
| 7,856 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailsafeCluster.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.support;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.cluster.support.wrapper.AbstractCluster;
/**
* {@link FailsafeClusterInvoker}
*
*/
public class FailsafeCluster extends AbstractCluster {
public static final String NAME = "failsafe";
@Override
public <T> AbstractClusterInvoker<T> doJoin(Directory<T> directory) throws RpcException {
return new FailsafeClusterInvoker<>(directory);
}
}
| 7,857 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailfastCluster.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.support;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.cluster.support.wrapper.AbstractCluster;
/**
* {@link FailfastClusterInvoker}
*
*/
public class FailfastCluster extends AbstractCluster {
public static final String NAME = "failfast";
@Override
public <T> AbstractClusterInvoker<T> doJoin(Directory<T> directory) throws RpcException {
return new FailfastClusterInvoker<>(directory);
}
}
| 7,858 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailoverCluster.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.support;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.cluster.support.wrapper.AbstractCluster;
/**
* {@link FailoverClusterInvoker}
*
*/
public class FailoverCluster extends AbstractCluster {
public static final String NAME = "failover";
@Override
public <T> AbstractClusterInvoker<T> doJoin(Directory<T> directory) throws RpcException {
return new FailoverClusterInvoker<>(directory);
}
}
| 7,859 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/AvailableClusterInvoker.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.support;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.cluster.LoadBalance;
import java.util.List;
/**
* AvailableClusterInvoker
*
*/
public class AvailableClusterInvoker<T> extends AbstractClusterInvoker<T> {
public AvailableClusterInvoker(Directory<T> directory) {
super(directory);
}
@Override
public Result doInvoke(Invocation invocation, List<Invoker<T>> invokers, LoadBalance loadbalance)
throws RpcException {
for (Invoker<T> invoker : invokers) {
if (invoker.isAvailable()) {
return invokeWithContext(invoker, invocation);
}
}
throw new RpcException("No provider available in " + invokers);
}
}
| 7,860 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvoker.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.support;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.ConfigUtils;
import org.apache.dubbo.rpc.AsyncRpcResult;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.cluster.LoadBalance;
import org.apache.dubbo.rpc.cluster.Merger;
import org.apache.dubbo.rpc.cluster.merger.MergerFactory;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ScopeModelUtil;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_FAILED_GROUP_MERGE;
import static org.apache.dubbo.rpc.Constants.ASYNC_KEY;
import static org.apache.dubbo.rpc.Constants.MERGER_KEY;
/**
* @param <T>
*/
@SuppressWarnings("unchecked")
public class MergeableClusterInvoker<T> extends AbstractClusterInvoker<T> {
private static final ErrorTypeAwareLogger log =
LoggerFactory.getErrorTypeAwareLogger(MergeableClusterInvoker.class);
public MergeableClusterInvoker(Directory<T> directory) {
super(directory);
}
@Override
protected Result doInvoke(Invocation invocation, List<Invoker<T>> invokers, LoadBalance loadbalance)
throws RpcException {
String merger = getUrl().getMethodParameter(invocation.getMethodName(), MERGER_KEY);
if (ConfigUtils.isEmpty(merger)) { // If a method doesn't have a merger, only invoke one Group
for (final Invoker<T> invoker : invokers) {
if (invoker.isAvailable()) {
try {
return invokeWithContext(invoker, invocation);
} catch (RpcException e) {
if (e.isNoInvokerAvailableAfterFilter()) {
log.debug("No available provider for service" + getUrl().getServiceKey() + " on group "
+ invoker.getUrl().getGroup() + ", will continue to try another group.");
} else {
throw e;
}
}
}
}
return invokeWithContext(invokers.iterator().next(), invocation);
}
Class<?> returnType;
try {
returnType = getInterface()
.getMethod(invocation.getMethodName(), invocation.getParameterTypes())
.getReturnType();
} catch (NoSuchMethodException e) {
returnType = null;
}
Map<String, Result> results = new HashMap<>();
for (final Invoker<T> invoker : invokers) {
RpcInvocation subInvocation = new RpcInvocation(invocation, invoker);
subInvocation.setAttachment(ASYNC_KEY, "true");
results.put(invoker.getUrl().getServiceKey(), invokeWithContext(invoker, subInvocation));
}
Object result;
List<Result> resultList = new ArrayList<>(results.size());
for (Map.Entry<String, Result> entry : results.entrySet()) {
Result asyncResult = entry.getValue();
try {
Result r = asyncResult.get(Integer.MAX_VALUE, TimeUnit.MILLISECONDS);
if (r.hasException()) {
log.error(
CLUSTER_FAILED_GROUP_MERGE,
"Invoke " + getGroupDescFromServiceKey(entry.getKey()) + " failed: "
+ r.getException().getMessage(),
"",
r.getException().getMessage());
} else {
resultList.add(r);
}
} catch (Exception e) {
throw new RpcException("Failed to invoke service " + entry.getKey() + ": " + e.getMessage(), e);
}
}
if (resultList.isEmpty()) {
return AsyncRpcResult.newDefaultAsyncResult(invocation);
} else if (resultList.size() == 1) {
return AsyncRpcResult.newDefaultAsyncResult(resultList.get(0).getValue(), invocation);
}
if (returnType == void.class) {
return AsyncRpcResult.newDefaultAsyncResult(invocation);
}
if (merger.startsWith(".")) {
merger = merger.substring(1);
Method method;
try {
method = returnType.getMethod(merger, returnType);
} catch (NoSuchMethodException | NullPointerException e) {
throw new RpcException("Can not merge result because missing method [ " + merger + " ] in class [ "
+ returnType.getName() + " ]");
}
if (!Modifier.isPublic(method.getModifiers())) {
method.setAccessible(true);
}
result = resultList.remove(0).getValue();
try {
if (method.getReturnType() != void.class
&& method.getReturnType().isAssignableFrom(result.getClass())) {
for (Result r : resultList) {
result = method.invoke(result, r.getValue());
}
} else {
for (Result r : resultList) {
method.invoke(result, r.getValue());
}
}
} catch (Exception e) {
throw new RpcException("Can not merge result: " + e.getMessage(), e);
}
} else {
Merger resultMerger;
ApplicationModel applicationModel = ScopeModelUtil.getApplicationModel(
invocation.getModuleModel().getApplicationModel());
if (ConfigUtils.isDefault(merger)) {
resultMerger = applicationModel
.getBeanFactory()
.getBean(MergerFactory.class)
.getMerger(returnType);
} else {
resultMerger = applicationModel.getExtensionLoader(Merger.class).getExtension(merger);
}
if (resultMerger != null) {
List<Object> rets = new ArrayList<>(resultList.size());
for (Result r : resultList) {
rets.add(r.getValue());
}
result = resultMerger.merge(rets.toArray((Object[]) Array.newInstance(returnType, 0)));
} else {
throw new RpcException("There is no merger to merge result.");
}
}
return AsyncRpcResult.newDefaultAsyncResult(result, invocation);
}
@Override
public Class<T> getInterface() {
return directory.getInterface();
}
@Override
public boolean isAvailable() {
return directory.isAvailable();
}
@Override
public void destroy() {
directory.destroy();
}
private String getGroupDescFromServiceKey(String key) {
int index = key.indexOf("/");
if (index > 0) {
return "group [ " + key.substring(0, index) + " ]";
}
return key;
}
}
| 7,861 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/BroadcastCluster.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.support;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.cluster.support.wrapper.AbstractCluster;
/**
* BroadcastCluster
*
*/
public class BroadcastCluster extends AbstractCluster {
@Override
public <T> AbstractClusterInvoker<T> doJoin(Directory<T> directory) throws RpcException {
return new BroadcastClusterInvoker<>(directory);
}
}
| 7,862 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailoverClusterInvoker.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.support;
import org.apache.dubbo.common.Version;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.cluster.LoadBalance;
import org.apache.dubbo.rpc.support.RpcUtils;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_RETRIES;
import static org.apache.dubbo.common.constants.CommonConstants.RETRIES_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_FAILED_MULTIPLE_RETRIES;
/**
* When invoke fails, log the initial error and retry other invokers (retry n times, which means at most n different invokers will be invoked)
* Note that retry causes latency.
* <p>
* <a href="http://en.wikipedia.org/wiki/Failover">Failover</a>
*
*/
public class FailoverClusterInvoker<T> extends AbstractClusterInvoker<T> {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(FailoverClusterInvoker.class);
public FailoverClusterInvoker(Directory<T> directory) {
super(directory);
}
@Override
@SuppressWarnings({"unchecked", "rawtypes"})
public Result doInvoke(Invocation invocation, final List<Invoker<T>> invokers, LoadBalance loadbalance)
throws RpcException {
List<Invoker<T>> copyInvokers = invokers;
String methodName = RpcUtils.getMethodName(invocation);
int len = calculateInvokeTimes(methodName);
// retry loop.
RpcException le = null; // last exception.
List<Invoker<T>> invoked = new ArrayList<Invoker<T>>(copyInvokers.size()); // invoked invokers.
Set<String> providers = new HashSet<String>(len);
for (int i = 0; i < len; i++) {
// Reselect before retry to avoid a change of candidate `invokers`.
// NOTE: if `invokers` changed, then `invoked` also lose accuracy.
if (i > 0) {
checkWhetherDestroyed();
copyInvokers = list(invocation);
// check again
checkInvokers(copyInvokers, invocation);
}
Invoker<T> invoker = select(loadbalance, invocation, copyInvokers, invoked);
invoked.add(invoker);
RpcContext.getServiceContext().setInvokers((List) invoked);
boolean success = false;
try {
Result result = invokeWithContext(invoker, invocation);
if (le != null && logger.isWarnEnabled()) {
logger.warn(
CLUSTER_FAILED_MULTIPLE_RETRIES,
"failed to retry do invoke",
"",
"Although retry the method " + methodName
+ " in the service " + getInterface().getName()
+ " was successful by the provider "
+ invoker.getUrl().getAddress()
+ ", but there have been failed providers " + providers
+ " (" + providers.size() + "/" + copyInvokers.size()
+ ") from the registry "
+ directory.getUrl().getAddress()
+ " on the consumer " + NetUtils.getLocalHost()
+ " using the dubbo version " + Version.getVersion() + ". Last error is: "
+ le.getMessage(),
le);
}
success = true;
return result;
} catch (RpcException e) {
if (e.isBiz()) { // biz exception.
throw e;
}
le = e;
} catch (Throwable e) {
le = new RpcException(e.getMessage(), e);
} finally {
if (!success) {
providers.add(invoker.getUrl().getAddress());
}
}
}
throw new RpcException(
le.getCode(),
"Failed to invoke the method "
+ methodName + " in the service " + getInterface().getName()
+ ". Tried " + len + " times of the providers " + providers
+ " (" + providers.size() + "/" + copyInvokers.size()
+ ") from the registry " + directory.getUrl().getAddress()
+ " on the consumer " + NetUtils.getLocalHost() + " using the dubbo version "
+ Version.getVersion() + ". Last error is: "
+ le.getMessage(),
le.getCause() != null ? le.getCause() : le);
}
private int calculateInvokeTimes(String methodName) {
int len = getUrl().getMethodParameter(methodName, RETRIES_KEY, DEFAULT_RETRIES) + 1;
RpcContext rpcContext = RpcContext.getClientAttachment();
Object retry = rpcContext.getObjectAttachment(RETRIES_KEY);
if (retry instanceof Number) {
len = ((Number) retry).intValue() + 1;
rpcContext.removeAttachment(RETRIES_KEY);
}
if (len <= 0) {
len = 1;
}
return len;
}
}
| 7,863 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailbackClusterInvoker.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.timer.HashedWheelTimer;
import org.apache.dubbo.common.timer.Timeout;
import org.apache.dubbo.common.timer.Timer;
import org.apache.dubbo.common.timer.TimerTask;
import org.apache.dubbo.common.utils.NamedThreadFactory;
import org.apache.dubbo.rpc.AsyncRpcResult;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.cluster.LoadBalance;
import org.apache.dubbo.rpc.support.RpcUtils;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_FAILBACK_TIMES;
import static org.apache.dubbo.common.constants.CommonConstants.RETRIES_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_FAILED_INVOKE_SERVICE;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_TIMER_RETRY_FAILED;
import static org.apache.dubbo.rpc.cluster.Constants.DEFAULT_FAILBACK_TASKS;
import static org.apache.dubbo.rpc.cluster.Constants.FAIL_BACK_TASKS_KEY;
/**
* When fails, record failure requests and schedule for retry on a regular interval.
* Especially useful for services of notification.
*
* <a href="http://en.wikipedia.org/wiki/Failback">Failback</a>
*/
public class FailbackClusterInvoker<T> extends AbstractClusterInvoker<T> {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(FailbackClusterInvoker.class);
private static final long RETRY_FAILED_PERIOD = 5;
/**
* Number of retries obtained from the configuration, don't contain the first invoke.
*/
private final int retries;
private final int failbackTasks;
private volatile Timer failTimer;
public FailbackClusterInvoker(Directory<T> directory) {
super(directory);
int retriesConfig = getUrl().getParameter(RETRIES_KEY, DEFAULT_FAILBACK_TIMES);
if (retriesConfig < 0) {
retriesConfig = DEFAULT_FAILBACK_TIMES;
}
int failbackTasksConfig = getUrl().getParameter(FAIL_BACK_TASKS_KEY, DEFAULT_FAILBACK_TASKS);
if (failbackTasksConfig <= 0) {
failbackTasksConfig = DEFAULT_FAILBACK_TASKS;
}
retries = retriesConfig;
failbackTasks = failbackTasksConfig;
}
private void addFailed(
LoadBalance loadbalance,
Invocation invocation,
List<Invoker<T>> invokers,
Invoker<T> lastInvoker,
URL consumerUrl) {
if (failTimer == null) {
synchronized (this) {
if (failTimer == null) {
failTimer = new HashedWheelTimer(
new NamedThreadFactory("failback-cluster-timer", true),
1,
TimeUnit.SECONDS,
32,
failbackTasks);
}
}
}
RetryTimerTask retryTimerTask = new RetryTimerTask(
loadbalance, invocation, invokers, lastInvoker, retries, RETRY_FAILED_PERIOD, consumerUrl);
try {
failTimer.newTimeout(retryTimerTask, RETRY_FAILED_PERIOD, TimeUnit.SECONDS);
} catch (Throwable e) {
logger.error(
CLUSTER_TIMER_RETRY_FAILED,
"add newTimeout exception",
"",
"Failback background works error, invocation->" + invocation + ", exception: " + e.getMessage(),
e);
}
}
@Override
protected Result doInvoke(Invocation invocation, List<Invoker<T>> invokers, LoadBalance loadbalance)
throws RpcException {
Invoker<T> invoker = null;
URL consumerUrl = RpcContext.getServiceContext().getConsumerUrl();
try {
invoker = select(loadbalance, invocation, invokers, null);
// Asynchronous call method must be used here, because failback will retry in the background.
// Then the serviceContext will be cleared after the call is completed.
return invokeWithContextAsync(invoker, invocation, consumerUrl);
} catch (Throwable e) {
logger.error(
CLUSTER_FAILED_INVOKE_SERVICE,
"Failback to invoke method and start to retries",
"",
"Failback to invoke method " + RpcUtils.getMethodName(invocation)
+ ", wait for retry in background. Ignored exception: "
+ e.getMessage() + ", ",
e);
if (retries > 0) {
addFailed(loadbalance, invocation, invokers, invoker, consumerUrl);
}
return AsyncRpcResult.newDefaultAsyncResult(null, null, invocation); // ignore
}
}
@Override
public void destroy() {
super.destroy();
if (failTimer != null) {
failTimer.stop();
}
}
/**
* RetryTimerTask
*/
private class RetryTimerTask implements TimerTask {
private final Invocation invocation;
private final LoadBalance loadbalance;
private final List<Invoker<T>> invokers;
private final long tick;
private Invoker<T> lastInvoker;
private URL consumerUrl;
/**
* Number of retries obtained from the configuration, don't contain the first invoke.
*/
private final int retries;
/**
* Number of retried.
*/
private int retriedTimes = 0;
RetryTimerTask(
LoadBalance loadbalance,
Invocation invocation,
List<Invoker<T>> invokers,
Invoker<T> lastInvoker,
int retries,
long tick,
URL consumerUrl) {
this.loadbalance = loadbalance;
this.invocation = invocation;
this.invokers = invokers;
this.retries = retries;
this.tick = tick;
this.lastInvoker = lastInvoker;
this.consumerUrl = consumerUrl;
}
@Override
public void run(Timeout timeout) {
try {
logger.info("Attempt to retry to invoke method " + RpcUtils.getMethodName(invocation)
+ ". The total will retry " + retries + " times, the current is the " + retriedTimes
+ " retry");
Invoker<T> retryInvoker =
select(loadbalance, invocation, invokers, Collections.singletonList(lastInvoker));
lastInvoker = retryInvoker;
invokeWithContextAsync(retryInvoker, invocation, consumerUrl);
} catch (Throwable e) {
logger.error(
CLUSTER_FAILED_INVOKE_SERVICE,
"Failed retry to invoke method",
"",
"Failed retry to invoke method " + RpcUtils.getMethodName(invocation) + ", waiting again.",
e);
if ((++retriedTimes) >= retries) {
logger.error(
CLUSTER_FAILED_INVOKE_SERVICE,
"Failed retry to invoke method and retry times exceed threshold",
"",
"Failed retry times exceed threshold (" + retries + "), We have to abandon, invocation->"
+ invocation,
e);
} else {
rePut(timeout);
}
}
}
private void rePut(Timeout timeout) {
if (timeout == null) {
return;
}
Timer timer = timeout.timer();
if (timer.isStop() || timeout.isCancelled()) {
return;
}
timer.newTimeout(timeout.task(), tick, TimeUnit.SECONDS);
}
}
}
| 7,864 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ClusterUtils.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.cluster.ProviderURLMergeProcessor;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ScopeModelAware;
import java.util.Map;
import static org.apache.dubbo.common.constants.CommonConstants.URL_MERGE_PROCESSOR_KEY;
/**
* ClusterUtils
*/
public class ClusterUtils implements ScopeModelAware {
private ApplicationModel applicationModel;
@Override
public void setApplicationModel(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
}
public URL mergeUrl(URL remoteUrl, Map<String, String> localMap) {
String ump = localMap.get(URL_MERGE_PROCESSOR_KEY);
ProviderURLMergeProcessor providerUrlMergeProcessor;
if (StringUtils.isNotEmpty(ump)) {
providerUrlMergeProcessor = applicationModel
.getExtensionLoader(ProviderURLMergeProcessor.class)
.getExtension(ump);
} else {
providerUrlMergeProcessor = applicationModel
.getExtensionLoader(ProviderURLMergeProcessor.class)
.getExtension("default");
}
return providerUrlMergeProcessor.mergeUrl(remoteUrl, localMap);
}
public Map<String, String> mergeLocalParams(Map<String, String> localMap) {
String ump = localMap.get(URL_MERGE_PROCESSOR_KEY);
ProviderURLMergeProcessor providerUrlMergeProcessor;
if (StringUtils.isNotEmpty(ump)) {
providerUrlMergeProcessor = applicationModel
.getExtensionLoader(ProviderURLMergeProcessor.class)
.getExtension(ump);
} else {
providerUrlMergeProcessor = applicationModel
.getExtensionLoader(ProviderURLMergeProcessor.class)
.getExtension("default");
}
return providerUrlMergeProcessor.mergeLocalParams(localMap);
}
}
| 7,865 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailsafeClusterInvoker.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.support;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.rpc.AsyncRpcResult;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.cluster.LoadBalance;
import java.util.List;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_ERROR_RESPONSE;
/**
* When invoke fails, log the error message and ignore this error by returning an empty Result.
* Usually used to write audit logs and other operations
*
* <a href="http://en.wikipedia.org/wiki/Fail-safe">Fail-safe</a>
*
*/
public class FailsafeClusterInvoker<T> extends AbstractClusterInvoker<T> {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(FailsafeClusterInvoker.class);
public FailsafeClusterInvoker(Directory<T> directory) {
super(directory);
}
@Override
public Result doInvoke(Invocation invocation, List<Invoker<T>> invokers, LoadBalance loadbalance)
throws RpcException {
try {
Invoker<T> invoker = select(loadbalance, invocation, invokers, null);
return invokeWithContext(invoker, invocation);
} catch (Throwable e) {
logger.error(
CLUSTER_ERROR_RESPONSE,
"Failsafe for provider exception",
"",
"Failsafe ignore exception: " + e.getMessage(),
e);
return AsyncRpcResult.newDefaultAsyncResult(null, null, invocation); // ignore
}
}
}
| 7,866 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailbackCluster.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.support;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.cluster.support.wrapper.AbstractCluster;
/**
* {@link FailbackClusterInvoker}
*
*/
public class FailbackCluster extends AbstractCluster {
public static final String NAME = "failback";
@Override
public <T> AbstractClusterInvoker<T> doJoin(Directory<T> directory) throws RpcException {
return new FailbackClusterInvoker<>(directory);
}
}
| 7,867 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailfastClusterInvoker.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.support;
import org.apache.dubbo.common.Version;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.cluster.LoadBalance;
import org.apache.dubbo.rpc.support.RpcUtils;
import java.util.List;
/**
* Execute exactly once, which means this policy will throw an exception immediately in case of an invocation error.
* Usually used for non-idempotent write operations
*
* <a href="http://en.wikipedia.org/wiki/Fail-fast">Fail-fast</a>
*/
public class FailfastClusterInvoker<T> extends AbstractClusterInvoker<T> {
public FailfastClusterInvoker(Directory<T> directory) {
super(directory);
}
@Override
public Result doInvoke(Invocation invocation, List<Invoker<T>> invokers, LoadBalance loadbalance)
throws RpcException {
Invoker<T> invoker = select(loadbalance, invocation, invokers, null);
try {
return invokeWithContext(invoker, invocation);
} catch (Throwable e) {
if (e instanceof RpcException && ((RpcException) e).isBiz()) { // biz exception.
throw (RpcException) e;
}
throw new RpcException(
e instanceof RpcException ? ((RpcException) e).getCode() : 0,
"Failfast invoke providers " + invoker.getUrl() + " "
+ loadbalance.getClass().getSimpleName()
+ " for service " + getInterface().getName()
+ " method " + RpcUtils.getMethodName(invocation) + " on consumer "
+ NetUtils.getLocalHost()
+ " use dubbo version " + Version.getVersion()
+ ", but no luck to perform the invocation. Last error is: " + e.getMessage(),
e.getCause() != null ? e.getCause() : e);
}
}
}
| 7,868 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/BroadcastClusterInvoker.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.cluster.LoadBalance;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_ERROR_RESPONSE;
/**
* BroadcastClusterInvoker
*/
public class BroadcastClusterInvoker<T> extends AbstractClusterInvoker<T> {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(BroadcastClusterInvoker.class);
private static final String BROADCAST_FAIL_PERCENT_KEY = "broadcast.fail.percent";
private static final int MAX_BROADCAST_FAIL_PERCENT = 100;
private static final int MIN_BROADCAST_FAIL_PERCENT = 0;
public BroadcastClusterInvoker(Directory<T> directory) {
super(directory);
}
@Override
@SuppressWarnings({"unchecked", "rawtypes"})
public Result doInvoke(final Invocation invocation, List<Invoker<T>> invokers, LoadBalance loadbalance)
throws RpcException {
RpcContext.getServiceContext().setInvokers((List) invokers);
RpcException exception = null;
Result result = null;
URL url = getUrl();
// The value range of broadcast.fail.threshold must be 0~100.
// 100 means that an exception will be thrown last, and 0 means that as long as an exception occurs, it will be
// thrown.
// see https://github.com/apache/dubbo/pull/7174
int broadcastFailPercent = url.getParameter(BROADCAST_FAIL_PERCENT_KEY, MAX_BROADCAST_FAIL_PERCENT);
if (broadcastFailPercent < MIN_BROADCAST_FAIL_PERCENT || broadcastFailPercent > MAX_BROADCAST_FAIL_PERCENT) {
logger.info(String.format(
"The value corresponding to the broadcast.fail.percent parameter must be between 0 and 100. "
+ "The current setting is %s, which is reset to 100.",
broadcastFailPercent));
broadcastFailPercent = MAX_BROADCAST_FAIL_PERCENT;
}
int failThresholdIndex = invokers.size() * broadcastFailPercent / MAX_BROADCAST_FAIL_PERCENT;
int failIndex = 0;
for (int i = 0, invokersSize = invokers.size(); i < invokersSize; i++) {
Invoker<T> invoker = invokers.get(i);
RpcContext.RestoreContext restoreContext = new RpcContext.RestoreContext();
try {
RpcInvocation subInvocation = new RpcInvocation(
invocation.getTargetServiceUniqueName(),
invocation.getServiceModel(),
invocation.getMethodName(),
invocation.getServiceName(),
invocation.getProtocolServiceKey(),
invocation.getParameterTypes(),
invocation.getArguments(),
invocation.copyObjectAttachments(),
invocation.getInvoker(),
Collections.synchronizedMap(new HashMap<>(invocation.getAttributes())),
invocation instanceof RpcInvocation ? ((RpcInvocation) invocation).getInvokeMode() : null);
result = invokeWithContext(invoker, subInvocation);
if (null != result && result.hasException()) {
Throwable resultException = result.getException();
if (null != resultException) {
exception = getRpcException(result.getException());
logger.warn(
CLUSTER_ERROR_RESPONSE,
"provider return error response",
"",
exception.getMessage(),
exception);
failIndex++;
if (failIndex == failThresholdIndex) {
break;
}
}
}
} catch (Throwable e) {
exception = getRpcException(e);
logger.warn(
CLUSTER_ERROR_RESPONSE,
"provider return error response",
"",
exception.getMessage(),
exception);
failIndex++;
if (failIndex == failThresholdIndex) {
break;
}
} finally {
if (i != invokersSize - 1) {
restoreContext.restore();
}
}
}
if (exception != null) {
if (failIndex == failThresholdIndex) {
if (logger.isDebugEnabled()) {
logger.debug(String.format(
"The number of BroadcastCluster call failures has reached the threshold %s",
failThresholdIndex));
}
} else {
if (logger.isDebugEnabled()) {
logger.debug(String.format(
"The number of BroadcastCluster call failures has not reached the threshold %s, fail size is %s",
failThresholdIndex, failIndex));
}
}
throw exception;
}
return result;
}
private RpcException getRpcException(Throwable throwable) {
RpcException rpcException;
if (throwable instanceof RpcException) {
rpcException = (RpcException) throwable;
} else {
rpcException = new RpcException(throwable.getMessage(), throwable);
}
return rpcException;
}
}
| 7,869 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/AvailableCluster.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.support;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.cluster.support.wrapper.AbstractCluster;
/**
* AvailableCluster
*
*/
public class AvailableCluster extends AbstractCluster {
public static final String NAME = "available";
@Override
public <T> AbstractClusterInvoker<T> doJoin(Directory<T> directory) throws RpcException {
return new AvailableClusterInvoker<>(directory);
}
}
| 7,870 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/MergeableCluster.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.support;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.cluster.support.wrapper.AbstractCluster;
public class MergeableCluster extends AbstractCluster {
public static final String NAME = "mergeable";
@Override
public <T> AbstractClusterInvoker<T> doJoin(Directory<T> directory) throws RpcException {
return new MergeableClusterInvoker<T>(directory);
}
}
| 7,871 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ForkingClusterInvoker.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.threadlocal.NamedInternalThreadFactory;
import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.cluster.LoadBalance;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT;
import static org.apache.dubbo.common.constants.CommonConstants.FORKS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.DEFAULT_FORKS;
/**
* NOTICE! This implementation does not work well with async call.
* <p>
* Invoke a specific number of invokers concurrently, usually used for demanding real-time operations, but need to waste more service resources.
*
* <a href="http://en.wikipedia.org/wiki/Fork_(topology)">Fork</a>
*/
public class ForkingClusterInvoker<T> extends AbstractClusterInvoker<T> {
/**
* Use {@link NamedInternalThreadFactory} to produce {@link org.apache.dubbo.common.threadlocal.InternalThread}
* which with the use of {@link org.apache.dubbo.common.threadlocal.InternalThreadLocal} in {@link RpcContext}.
*/
private final ExecutorService executor;
public ForkingClusterInvoker(Directory<T> directory) {
super(directory);
executor = directory
.getUrl()
.getOrDefaultFrameworkModel()
.getBeanFactory()
.getBean(FrameworkExecutorRepository.class)
.getSharedExecutor();
}
@Override
@SuppressWarnings({"unchecked", "rawtypes"})
public Result doInvoke(final Invocation invocation, List<Invoker<T>> invokers, LoadBalance loadbalance)
throws RpcException {
try {
final List<Invoker<T>> selected;
final int forks = getUrl().getParameter(FORKS_KEY, DEFAULT_FORKS);
final int timeout = getUrl().getParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT);
if (forks <= 0 || forks >= invokers.size()) {
selected = invokers;
} else {
selected = new ArrayList<>(forks);
while (selected.size() < forks) {
Invoker<T> invoker = select(loadbalance, invocation, invokers, selected);
if (!selected.contains(invoker)) {
// Avoid add the same invoker several times.
selected.add(invoker);
}
}
}
RpcContext.getServiceContext().setInvokers((List) selected);
final AtomicInteger count = new AtomicInteger();
final BlockingQueue<Object> ref = new LinkedBlockingQueue<>(1);
selected.forEach(invoker -> {
URL consumerUrl = RpcContext.getServiceContext().getConsumerUrl();
CompletableFuture.<Object>supplyAsync(
() -> {
if (ref.size() > 0) {
return null;
}
return invokeWithContextAsync(invoker, invocation, consumerUrl);
},
executor)
.whenComplete((v, t) -> {
if (t == null) {
ref.offer(v);
} else {
int value = count.incrementAndGet();
if (value >= selected.size()) {
ref.offer(t);
}
}
});
});
try {
Object ret = ref.poll(timeout, TimeUnit.MILLISECONDS);
if (ret instanceof Throwable) {
Throwable e = ret instanceof CompletionException
? ((CompletionException) ret).getCause()
: (Throwable) ret;
throw new RpcException(
e instanceof RpcException ? ((RpcException) e).getCode() : RpcException.UNKNOWN_EXCEPTION,
"Failed to forking invoke provider " + selected
+ ", but no luck to perform the invocation. " + "Last error is: " + e.getMessage(),
e.getCause() != null ? e.getCause() : e);
}
return (Result) ret;
} catch (InterruptedException e) {
throw new RpcException(
"Failed to forking invoke provider " + selected + ", "
+ "but no luck to perform the invocation. Last error is: " + e.getMessage(),
e);
}
} finally {
// clear attachments which is binding to current thread.
RpcContext.getClientAttachment().clearAttachments();
}
}
}
| 7,872 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ForkingCluster.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.support;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.cluster.support.wrapper.AbstractCluster;
/**
* {@link ForkingClusterInvoker}
*
*/
public class ForkingCluster extends AbstractCluster {
public static final String NAME = "forking";
@Override
public <T> AbstractClusterInvoker<T> doJoin(Directory<T> directory) throws RpcException {
return new ForkingClusterInvoker<>(directory);
}
}
| 7,873 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/ScopeClusterInvoker.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.support.wrapper;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.url.component.DubboServiceAddressURL;
import org.apache.dubbo.common.url.component.ServiceConfigURL;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.rpc.Exporter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.Cluster;
import org.apache.dubbo.rpc.cluster.ClusterInvoker;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.cluster.directory.StaticDirectory;
import org.apache.dubbo.rpc.listener.ExporterChangeListener;
import org.apache.dubbo.rpc.listener.InjvmExporterListener;
import org.apache.dubbo.rpc.support.RpcUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.apache.dubbo.common.constants.CommonConstants.BROADCAST_CLUSTER;
import static org.apache.dubbo.common.constants.CommonConstants.CLUSTER_KEY;
import static org.apache.dubbo.rpc.Constants.GENERIC_KEY;
import static org.apache.dubbo.rpc.Constants.LOCAL_PROTOCOL;
import static org.apache.dubbo.rpc.Constants.SCOPE_KEY;
import static org.apache.dubbo.rpc.Constants.SCOPE_LOCAL;
import static org.apache.dubbo.rpc.Constants.SCOPE_REMOTE;
import static org.apache.dubbo.rpc.cluster.Constants.PEER_KEY;
/**
* ScopeClusterInvoker is a cluster invoker which handles the invocation logic of a single service in a specific scope.
* <p>
* It selects between local and remote invoker at runtime.
*
* @param <T> the type of service interface
*/
public class ScopeClusterInvoker<T> implements ClusterInvoker<T>, ExporterChangeListener {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ScopeClusterInvoker.class);
private final Object createLock = new Object();
private Protocol protocolSPI;
private final Directory<T> directory;
private final Invoker<T> invoker;
private final AtomicBoolean isExported;
private volatile Invoker<T> injvmInvoker;
private volatile InjvmExporterListener injvmExporterListener;
private boolean peerFlag;
private boolean injvmFlag;
public ScopeClusterInvoker(Directory<T> directory, Invoker<T> invoker) {
this.directory = directory;
this.invoker = invoker;
this.isExported = new AtomicBoolean(false);
init();
}
@Override
public URL getUrl() {
return directory.getConsumerUrl();
}
@Override
public URL getRegistryUrl() {
return directory.getUrl();
}
@Override
public Directory<T> getDirectory() {
return directory;
}
@Override
public boolean isDestroyed() {
return directory.isDestroyed();
}
@Override
public boolean isAvailable() {
if (peerFlag || isBroadcast()) {
// If it's a point-to-point direct connection or broadcasting, it should be called remotely.
return invoker.isAvailable();
}
if (injvmFlag && isForceLocal()) {
// If it's a local call, it should be called locally.
return isExported.get();
}
if (injvmFlag && isExported.get()) {
// If allow local call, check if local exported first
return true;
}
return invoker.isAvailable();
}
@Override
public void destroy() {
if (injvmExporterListener != null) {
injvmExporterListener.removeExporterChangeListener(this, getUrl().getServiceKey());
}
destroyInjvmInvoker();
this.invoker.destroy();
}
@Override
public Class<T> getInterface() {
return directory.getInterface();
}
/**
* Checks if the current ScopeClusterInvoker is exported to the local JVM and invokes the corresponding Invoker.
* If it's not exported locally, then it delegates the invocation to the original Invoker.
*
* @param invocation the invocation to be performed
* @return the result of the invocation
* @throws RpcException if there was an error during the invocation
*/
@Override
public Result invoke(Invocation invocation) throws RpcException {
// When broadcasting, it should be called remotely.
if (isBroadcast()) {
if (logger.isDebugEnabled()) {
logger.debug("Performing broadcast call for method: " + RpcUtils.getMethodName(invocation)
+ " of service: " + getUrl().getServiceKey());
}
return invoker.invoke(invocation);
}
if (peerFlag) {
if (logger.isDebugEnabled()) {
logger.debug("Performing point-to-point call for method: " + RpcUtils.getMethodName(invocation)
+ " of service: " + getUrl().getServiceKey());
}
// If it's a point-to-point direct connection, invoke the original Invoker
return invoker.invoke(invocation);
}
if (isInjvmExported()) {
if (logger.isDebugEnabled()) {
logger.debug("Performing local JVM call for method: " + RpcUtils.getMethodName(invocation)
+ " of service: " + getUrl().getServiceKey());
}
// If it's exported to the local JVM, invoke the corresponding Invoker
return injvmInvoker.invoke(invocation);
}
if (logger.isDebugEnabled()) {
logger.debug("Performing remote call for method: " + RpcUtils.getMethodName(invocation) + " of service: "
+ getUrl().getServiceKey());
}
// Otherwise, delegate the invocation to the original Invoker
return invoker.invoke(invocation);
}
private boolean isBroadcast() {
return BROADCAST_CLUSTER.equalsIgnoreCase(getUrl().getParameter(CLUSTER_KEY));
}
@Override
public void onExporterChangeExport(Exporter<?> exporter) {
if (isExported.get()) {
return;
}
if (getUrl().getServiceKey().equals(exporter.getInvoker().getUrl().getServiceKey())
&& exporter.getInvoker().getUrl().getProtocol().equalsIgnoreCase(LOCAL_PROTOCOL)) {
createInjvmInvoker(exporter);
isExported.compareAndSet(false, true);
}
}
@Override
public void onExporterChangeUnExport(Exporter<?> exporter) {
if (getUrl().getServiceKey().equals(exporter.getInvoker().getUrl().getServiceKey())
&& exporter.getInvoker().getUrl().getProtocol().equalsIgnoreCase(LOCAL_PROTOCOL)) {
destroyInjvmInvoker();
isExported.compareAndSet(true, false);
}
}
public Invoker<?> getInvoker() {
return invoker;
}
/**
* Initializes the ScopeClusterInvoker instance.
*/
private void init() {
Boolean peer = (Boolean) getUrl().getAttribute(PEER_KEY);
String isInjvm = getUrl().getParameter(LOCAL_PROTOCOL);
// When the point-to-point direct connection is directly connected,
// the initialization is directly ended
if (peer != null && peer) {
peerFlag = true;
return;
}
// Check if the service has been exported through Injvm protocol
if (injvmInvoker == null
&& LOCAL_PROTOCOL.equalsIgnoreCase(getRegistryUrl().getProtocol())) {
injvmInvoker = invoker;
isExported.compareAndSet(false, true);
injvmFlag = true;
return;
}
// Check if the service has been exported through Injvm protocol or the SCOPE_LOCAL parameter is set
if (Boolean.TRUE.toString().equalsIgnoreCase(isInjvm)
|| SCOPE_LOCAL.equalsIgnoreCase(getUrl().getParameter(SCOPE_KEY))) {
injvmFlag = true;
} else if (isInjvm == null) {
injvmFlag = isNotRemoteOrGeneric();
}
protocolSPI = getUrl().getApplicationModel()
.getExtensionLoader(Protocol.class)
.getAdaptiveExtension();
injvmExporterListener =
getUrl().getOrDefaultFrameworkModel().getBeanFactory().getBean(InjvmExporterListener.class);
injvmExporterListener.addExporterChangeListener(this, getUrl().getServiceKey());
}
/**
* Check if the service is a generalized call or the SCOPE_REMOTE parameter is set
*
* @return boolean
*/
private boolean isNotRemoteOrGeneric() {
return !SCOPE_REMOTE.equalsIgnoreCase(getUrl().getParameter(SCOPE_KEY))
&& !getUrl().getParameter(GENERIC_KEY, false);
}
/**
* Checks whether the current ScopeClusterInvoker is exported to the local JVM and returns a boolean value.
*
* @return true if the ScopeClusterInvoker is exported to the local JVM, false otherwise
* @throws RpcException if there was an error during the invocation
*/
private boolean isInjvmExported() {
Boolean localInvoke = RpcContext.getServiceContext().getLocalInvoke();
boolean isExportedValue = isExported.get();
boolean localOnce = (localInvoke != null && localInvoke);
// Determine whether this call is local
if (isExportedValue && localOnce) {
return true;
}
// Determine whether this call is remote
if (localInvoke != null && !localInvoke) {
return false;
}
// When calling locally, determine whether it does not meet the requirements
if (!isExportedValue && (isForceLocal() || localOnce)) {
// If it's supposed to be exported to the local JVM ,but it's not, throw an exception
throw new RpcException(
"Local service for " + getUrl().getServiceInterface() + " has not been exposed yet!");
}
return isExportedValue && injvmFlag;
}
private boolean isForceLocal() {
return SCOPE_LOCAL.equalsIgnoreCase(getUrl().getParameter(SCOPE_KEY))
|| Boolean.TRUE.toString().equalsIgnoreCase(getUrl().getParameter(LOCAL_PROTOCOL));
}
/**
* Creates a new Invoker for the current ScopeClusterInvoker and exports it to the local JVM.
*/
private void createInjvmInvoker(Exporter<?> exporter) {
if (injvmInvoker == null) {
synchronized (createLock) {
if (injvmInvoker == null) {
URL url = new ServiceConfigURL(
LOCAL_PROTOCOL,
NetUtils.getLocalHost(),
getUrl().getPort(),
getInterface().getName(),
getUrl().getParameters());
url = url.setScopeModel(getUrl().getScopeModel());
url = url.setServiceModel(getUrl().getServiceModel());
DubboServiceAddressURL consumerUrl = new DubboServiceAddressURL(
url.getUrlAddress(),
url.getUrlParam(),
exporter.getInvoker().getUrl(),
null);
Invoker<?> invoker = protocolSPI.refer(getInterface(), consumerUrl);
List<Invoker<?>> invokers = new ArrayList<>();
invokers.add(invoker);
injvmInvoker = Cluster.getCluster(url.getScopeModel(), Cluster.DEFAULT, false)
.join(new StaticDirectory(url, invokers), true);
}
}
}
}
/**
* Destroy the existing InjvmInvoker.
*/
private void destroyInjvmInvoker() {
if (injvmInvoker != null) {
injvmInvoker.destroy();
injvmInvoker = null;
}
}
@Override
public String toString() {
return "ScopeClusterInvoker{" + "directory="
+ directory + ", isExported="
+ isExported + ", peerFlag="
+ peerFlag + ", injvmFlag="
+ injvmFlag + '}';
}
}
| 7,874 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvoker.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.support.wrapper;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.ConfigUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.AsyncRpcResult;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.InvokeMode;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.ClusterInvoker;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.protocol.dubbo.FutureAdapter;
import org.apache.dubbo.rpc.support.MockInvoker;
import org.apache.dubbo.rpc.support.RpcUtils;
import java.util.List;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_FAILED_MOCK_REQUEST;
import static org.apache.dubbo.rpc.Constants.MOCK_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.FORCE_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.INVOCATION_NEED_MOCK;
public class MockClusterInvoker<T> implements ClusterInvoker<T> {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MockClusterInvoker.class);
private static final boolean setFutureWhenSync =
Boolean.parseBoolean(System.getProperty(CommonConstants.SET_FUTURE_IN_SYNC_MODE, "true"));
private final Directory<T> directory;
private final Invoker<T> invoker;
public MockClusterInvoker(Directory<T> directory, Invoker<T> invoker) {
this.directory = directory;
this.invoker = invoker;
}
@Override
public URL getUrl() {
return directory.getConsumerUrl();
}
@Override
public URL getRegistryUrl() {
return directory.getUrl();
}
@Override
public Directory<T> getDirectory() {
return directory;
}
@Override
public boolean isDestroyed() {
return directory.isDestroyed();
}
@Override
public boolean isAvailable() {
return directory.isAvailable();
}
@Override
public void destroy() {
this.invoker.destroy();
}
@Override
public Class<T> getInterface() {
return directory.getInterface();
}
@Override
public Result invoke(Invocation invocation) throws RpcException {
Result result;
String value = getUrl().getMethodParameter(
RpcUtils.getMethodName(invocation), MOCK_KEY, Boolean.FALSE.toString())
.trim();
if (ConfigUtils.isEmpty(value)) {
// no mock
result = this.invoker.invoke(invocation);
} else if (value.startsWith(FORCE_KEY)) {
if (logger.isWarnEnabled()) {
logger.warn(
CLUSTER_FAILED_MOCK_REQUEST,
"force mock",
"",
"force-mock: " + RpcUtils.getMethodName(invocation) + " force-mock enabled , url : "
+ getUrl());
}
// force:direct mock
result = doMockInvoke(invocation, null);
} else {
// fail-mock
try {
result = this.invoker.invoke(invocation);
// fix:#4585
if (result.getException() != null && result.getException() instanceof RpcException) {
RpcException rpcException = (RpcException) result.getException();
if (rpcException.isBiz()) {
throw rpcException;
} else {
result = doMockInvoke(invocation, rpcException);
}
}
} catch (RpcException e) {
if (e.isBiz()) {
throw e;
}
if (logger.isWarnEnabled()) {
logger.warn(
CLUSTER_FAILED_MOCK_REQUEST,
"failed to mock invoke",
"",
"fail-mock: " + RpcUtils.getMethodName(invocation) + " fail-mock enabled , url : "
+ getUrl(),
e);
}
result = doMockInvoke(invocation, e);
}
}
return result;
}
@SuppressWarnings({"unchecked", "rawtypes"})
private Result doMockInvoke(Invocation invocation, RpcException e) {
Result result;
Invoker<T> mockInvoker;
RpcInvocation rpcInvocation = (RpcInvocation) invocation;
rpcInvocation.setInvokeMode(RpcUtils.getInvokeMode(getUrl(), invocation));
List<Invoker<T>> mockInvokers = selectMockInvoker(invocation);
if (CollectionUtils.isEmpty(mockInvokers)) {
mockInvoker = (Invoker<T>) new MockInvoker(getUrl(), directory.getInterface());
} else {
mockInvoker = mockInvokers.get(0);
}
try {
result = mockInvoker.invoke(invocation);
} catch (RpcException mockException) {
if (mockException.isBiz()) {
result = AsyncRpcResult.newDefaultAsyncResult(mockException.getCause(), invocation);
} else {
throw new RpcException(
mockException.getCode(), getMockExceptionMessage(e, mockException), mockException.getCause());
}
} catch (Throwable me) {
throw new RpcException(getMockExceptionMessage(e, me), me.getCause());
}
if (setFutureWhenSync || rpcInvocation.getInvokeMode() != InvokeMode.SYNC) {
// set server context
RpcContext.getServiceContext()
.setFuture(new FutureAdapter<>(((AsyncRpcResult) result).getResponseFuture()));
}
return result;
}
private String getMockExceptionMessage(Throwable t, Throwable mt) {
String msg = "mock error : " + mt.getMessage();
if (t != null) {
msg = msg + ", invoke error is :" + StringUtils.toString(t);
}
return msg;
}
/**
* Return MockInvoker
* Contract:
* directory.list() will return a list of normal invokers if Constants.INVOCATION_NEED_MOCK is absent or not true in invocation, otherwise, a list of mock invokers will return.
* if directory.list() returns more than one mock invoker, only one of them will be used.
*
* @param invocation
* @return
*/
private List<Invoker<T>> selectMockInvoker(Invocation invocation) {
List<Invoker<T>> invokers = null;
// TODO generic invoker?
if (invocation instanceof RpcInvocation) {
// Note the implicit contract (although the description is added to the interface declaration, but
// extensibility is a problem. The practice placed in the attachment needs to be improved)
invocation.setAttachment(INVOCATION_NEED_MOCK, Boolean.TRUE.toString());
// directory will return a list of normal invokers if Constants.INVOCATION_NEED_MOCK is absent or not true
// in invocation, otherwise, a list of mock invokers will return.
try {
RpcContext.getServiceContext().setConsumerUrl(getUrl());
invokers = directory.list(invocation);
} catch (RpcException e) {
if (logger.isInfoEnabled()) {
logger.info(
"Exception when try to invoke mock. Get mock invokers error for service:"
+ getUrl().getServiceInterface() + ", method:" + RpcUtils.getMethodName(invocation)
+ ", will construct a new mock with 'new MockInvoker()'.",
e);
}
}
}
return invokers;
}
@Override
public String toString() {
return "invoker :" + this.invoker + ",directory: " + this.directory;
}
}
| 7,875 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/AbstractCluster.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.support.wrapper;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.ConfigurationUtils;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.Cluster;
import org.apache.dubbo.rpc.cluster.ClusterInvoker;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.cluster.LoadBalance;
import org.apache.dubbo.rpc.cluster.filter.FilterChainBuilder;
import org.apache.dubbo.rpc.cluster.filter.InvocationInterceptorBuilder;
import org.apache.dubbo.rpc.cluster.interceptor.ClusterInterceptor;
import org.apache.dubbo.rpc.cluster.support.AbstractClusterInvoker;
import org.apache.dubbo.rpc.model.ScopeModelUtil;
import java.util.List;
import static org.apache.dubbo.common.constants.CommonConstants.CLUSTER_INTERCEPTOR_COMPATIBLE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.INVOCATION_INTERCEPTOR_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.REFERENCE_FILTER_KEY;
public abstract class AbstractCluster implements Cluster {
private <T> Invoker<T> buildClusterInterceptors(AbstractClusterInvoker<T> clusterInvoker) {
AbstractClusterInvoker<T> last = buildInterceptorInvoker(new ClusterFilterInvoker<>(clusterInvoker));
if (Boolean.parseBoolean(ConfigurationUtils.getProperty(
clusterInvoker.getDirectory().getConsumerUrl().getScopeModel(),
CLUSTER_INTERCEPTOR_COMPATIBLE_KEY,
"false"))) {
return build27xCompatibleClusterInterceptors(clusterInvoker, last);
}
return last;
}
@Override
public <T> Invoker<T> join(Directory<T> directory, boolean buildFilterChain) throws RpcException {
if (buildFilterChain) {
return buildClusterInterceptors(doJoin(directory));
} else {
return doJoin(directory);
}
}
private <T> AbstractClusterInvoker<T> buildInterceptorInvoker(AbstractClusterInvoker<T> invoker) {
List<InvocationInterceptorBuilder> builders = ScopeModelUtil.getApplicationModel(
invoker.getUrl().getScopeModel())
.getExtensionLoader(InvocationInterceptorBuilder.class)
.getActivateExtensions();
if (CollectionUtils.isEmpty(builders)) {
return invoker;
}
return new InvocationInterceptorInvoker<>(invoker, builders);
}
protected abstract <T> AbstractClusterInvoker<T> doJoin(Directory<T> directory) throws RpcException;
static class ClusterFilterInvoker<T> extends AbstractClusterInvoker<T> {
private final ClusterInvoker<T> filterInvoker;
public ClusterFilterInvoker(AbstractClusterInvoker<T> invoker) {
List<FilterChainBuilder> builders = ScopeModelUtil.getApplicationModel(
invoker.getUrl().getScopeModel())
.getExtensionLoader(FilterChainBuilder.class)
.getActivateExtensions();
if (CollectionUtils.isEmpty(builders)) {
filterInvoker = invoker;
} else {
ClusterInvoker<T> tmpInvoker = invoker;
for (FilterChainBuilder builder : builders) {
tmpInvoker = builder.buildClusterInvokerChain(
tmpInvoker, REFERENCE_FILTER_KEY, CommonConstants.CONSUMER);
}
filterInvoker = tmpInvoker;
}
}
@Override
public Result invoke(Invocation invocation) throws RpcException {
return filterInvoker.invoke(invocation);
}
@Override
public Directory<T> getDirectory() {
return filterInvoker.getDirectory();
}
@Override
public URL getRegistryUrl() {
return filterInvoker.getRegistryUrl();
}
@Override
public boolean isDestroyed() {
return filterInvoker.isDestroyed();
}
@Override
public URL getUrl() {
return filterInvoker.getUrl();
}
/**
* The only purpose is to build a interceptor chain, so the cluster related logic doesn't matter.
* Use ClusterInvoker<T> to replace AbstractClusterInvoker<T> in the future.
*/
@Override
protected Result doInvoke(Invocation invocation, List<Invoker<T>> invokers, LoadBalance loadbalance)
throws RpcException {
return null;
}
public ClusterInvoker<T> getFilterInvoker() {
return filterInvoker;
}
}
static class InvocationInterceptorInvoker<T> extends AbstractClusterInvoker<T> {
private ClusterInvoker<T> interceptorInvoker;
public InvocationInterceptorInvoker(
AbstractClusterInvoker<T> invoker, List<InvocationInterceptorBuilder> builders) {
ClusterInvoker<T> tmpInvoker = invoker;
for (InvocationInterceptorBuilder builder : builders) {
tmpInvoker = builder.buildClusterInterceptorChain(
tmpInvoker, INVOCATION_INTERCEPTOR_KEY, CommonConstants.CONSUMER);
}
interceptorInvoker = tmpInvoker;
}
@Override
public Result invoke(Invocation invocation) throws RpcException {
return interceptorInvoker.invoke(invocation);
}
@Override
public Directory<T> getDirectory() {
return interceptorInvoker.getDirectory();
}
@Override
public URL getRegistryUrl() {
return interceptorInvoker.getRegistryUrl();
}
@Override
public boolean isDestroyed() {
return interceptorInvoker.isDestroyed();
}
@Override
public URL getUrl() {
return interceptorInvoker.getUrl();
}
/**
* The only purpose is to build a interceptor chain, so the cluster related logic doesn't matter.
* Use ClusterInvoker<T> to replace AbstractClusterInvoker<T> in the future.
*/
@Override
protected Result doInvoke(Invocation invocation, List<Invoker<T>> invokers, LoadBalance loadbalance)
throws RpcException {
return null;
}
}
@Deprecated
private <T> ClusterInvoker<T> build27xCompatibleClusterInterceptors(
AbstractClusterInvoker<T> clusterInvoker, AbstractClusterInvoker<T> last) {
List<ClusterInterceptor> interceptors = ScopeModelUtil.getApplicationModel(
clusterInvoker.getUrl().getScopeModel())
.getExtensionLoader(ClusterInterceptor.class)
.getActivateExtensions();
if (!interceptors.isEmpty()) {
for (int i = interceptors.size() - 1; i >= 0; i--) {
final ClusterInterceptor interceptor = interceptors.get(i);
final AbstractClusterInvoker<T> next = last;
last = new InterceptorInvokerNode<>(clusterInvoker, interceptor, next);
}
}
return last;
}
@Deprecated
static class InterceptorInvokerNode<T> extends AbstractClusterInvoker<T> {
private final AbstractClusterInvoker<T> clusterInvoker;
private final ClusterInterceptor interceptor;
private final AbstractClusterInvoker<T> next;
public InterceptorInvokerNode(
AbstractClusterInvoker<T> clusterInvoker,
ClusterInterceptor interceptor,
AbstractClusterInvoker<T> next) {
this.clusterInvoker = clusterInvoker;
this.interceptor = interceptor;
this.next = next;
}
@Override
public Class<T> getInterface() {
return clusterInvoker.getInterface();
}
@Override
public URL getUrl() {
return clusterInvoker.getUrl();
}
@Override
public boolean isAvailable() {
return clusterInvoker.isAvailable();
}
@Override
public Result invoke(Invocation invocation) throws RpcException {
Result asyncResult;
try {
interceptor.before(next, invocation);
asyncResult = interceptor.intercept(next, invocation);
} catch (Exception e) {
// onError callback
if (interceptor instanceof ClusterInterceptor.Listener) {
ClusterInterceptor.Listener listener = (ClusterInterceptor.Listener) interceptor;
listener.onError(e, clusterInvoker, invocation);
}
throw e;
} finally {
interceptor.after(next, invocation);
}
return asyncResult.whenCompleteWithContext((r, t) -> {
// onResponse callback
if (interceptor instanceof ClusterInterceptor.Listener) {
ClusterInterceptor.Listener listener = (ClusterInterceptor.Listener) interceptor;
if (t == null) {
listener.onMessage(r, clusterInvoker, invocation);
} else {
listener.onError(t, clusterInvoker, invocation);
}
}
});
}
@Override
public void destroy() {
clusterInvoker.destroy();
}
@Override
public String toString() {
return clusterInvoker.toString();
}
@Override
protected Result doInvoke(Invocation invocation, List<Invoker<T>> invokers, LoadBalance loadbalance)
throws RpcException {
// The only purpose is to build an interceptor chain, so the cluster related logic doesn't matter.
return null;
}
}
}
| 7,876 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterWrapper.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.support.wrapper;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.Cluster;
import org.apache.dubbo.rpc.cluster.Directory;
/**
* mock impl
*
*/
public class MockClusterWrapper implements Cluster {
private final Cluster cluster;
public MockClusterWrapper(Cluster cluster) {
this.cluster = cluster;
}
@Override
public <T> Invoker<T> join(Directory<T> directory, boolean buildFilterChain) throws RpcException {
return new MockClusterInvoker<T>(directory, this.cluster.join(directory, buildFilterChain));
}
public Cluster getCluster() {
return cluster;
}
}
| 7,877 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/ScopeClusterWrapper.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.support.wrapper;
import org.apache.dubbo.common.extension.Wrapper;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.Cluster;
import org.apache.dubbo.rpc.cluster.Directory;
/**
* Introducing ScopeClusterInvoker section through Dubbo SPI mechanism
*/
@Wrapper(order = -1)
public class ScopeClusterWrapper implements Cluster {
private final Cluster cluster;
public ScopeClusterWrapper(Cluster cluster) {
this.cluster = cluster;
}
@Override
public <T> Invoker<T> join(Directory<T> directory, boolean buildFilterChain) throws RpcException {
return new ScopeClusterInvoker<>(directory, this.cluster.join(directory, buildFilterChain));
}
public Cluster getCluster() {
return cluster;
}
}
| 7,878 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/merger/DefaultProviderURLMergeProcessor.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.support.merger;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.rpc.cluster.ProviderURLMergeProcessor;
import java.util.HashMap;
import java.util.Map;
import static org.apache.dubbo.common.constants.CommonConstants.ALIVE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.CORE_THREADS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY_PREFIX;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.INVOKER_LISTENER_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.QUEUES_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.REFERENCE_FILTER_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.RELEASE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_APPLICATION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TAG_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREADPOOL_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
public class DefaultProviderURLMergeProcessor implements ProviderURLMergeProcessor {
@Override
public URL mergeUrl(URL remoteUrl, Map<String, String> localParametersMap) {
Map<String, String> map = new HashMap<>();
Map<String, String> remoteMap = remoteUrl.getParameters();
if (remoteMap != null && remoteMap.size() > 0) {
map.putAll(remoteMap);
// Remove configurations from provider, some items should be affected by provider.
map.remove(THREAD_NAME_KEY);
map.remove(DEFAULT_KEY_PREFIX + THREAD_NAME_KEY);
map.remove(THREADPOOL_KEY);
map.remove(DEFAULT_KEY_PREFIX + THREADPOOL_KEY);
map.remove(CORE_THREADS_KEY);
map.remove(DEFAULT_KEY_PREFIX + CORE_THREADS_KEY);
map.remove(THREADS_KEY);
map.remove(DEFAULT_KEY_PREFIX + THREADS_KEY);
map.remove(QUEUES_KEY);
map.remove(DEFAULT_KEY_PREFIX + QUEUES_KEY);
map.remove(ALIVE_KEY);
map.remove(DEFAULT_KEY_PREFIX + ALIVE_KEY);
map.remove(Constants.TRANSPORTER_KEY);
map.remove(DEFAULT_KEY_PREFIX + Constants.TRANSPORTER_KEY);
}
if (localParametersMap != null && localParametersMap.size() > 0) {
Map<String, String> copyOfLocalMap = new HashMap<>(localParametersMap);
if (map.containsKey(GROUP_KEY)) {
copyOfLocalMap.remove(GROUP_KEY);
}
if (map.containsKey(VERSION_KEY)) {
copyOfLocalMap.remove(VERSION_KEY);
}
if (map.containsKey(GENERIC_KEY)) {
copyOfLocalMap.remove(GENERIC_KEY);
}
copyOfLocalMap.remove(RELEASE_KEY);
copyOfLocalMap.remove(DUBBO_VERSION_KEY);
copyOfLocalMap.remove(METHODS_KEY);
copyOfLocalMap.remove(TIMESTAMP_KEY);
copyOfLocalMap.remove(TAG_KEY);
map.putAll(copyOfLocalMap);
if (remoteMap != null) {
map.put(REMOTE_APPLICATION_KEY, remoteMap.get(APPLICATION_KEY));
// Combine filters and listeners on Provider and Consumer
String remoteFilter = remoteMap.get(REFERENCE_FILTER_KEY);
String localFilter = copyOfLocalMap.get(REFERENCE_FILTER_KEY);
if (remoteFilter != null
&& remoteFilter.length() > 0
&& localFilter != null
&& localFilter.length() > 0) {
map.put(REFERENCE_FILTER_KEY, remoteFilter + "," + localFilter);
}
String remoteListener = remoteMap.get(INVOKER_LISTENER_KEY);
String localListener = copyOfLocalMap.get(INVOKER_LISTENER_KEY);
if (remoteListener != null
&& remoteListener.length() > 0
&& localListener != null
&& localListener.length() > 0) {
map.put(INVOKER_LISTENER_KEY, remoteListener + "," + localListener);
}
}
}
return remoteUrl.clearParameters().addParameters(map);
}
}
| 7,879 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/registry/ZoneAwareClusterInvoker.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.support.registry;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.ZoneDetector;
import org.apache.dubbo.rpc.cluster.ClusterInvoker;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.cluster.LoadBalance;
import org.apache.dubbo.rpc.cluster.support.AbstractClusterInvoker;
import java.util.List;
import java.util.stream.Collectors;
import static org.apache.dubbo.common.constants.CommonConstants.PREFERRED_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_ZONE;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_ZONE_FORCE;
import static org.apache.dubbo.common.constants.RegistryConstants.ZONE_KEY;
/**
* When there are more than one registry for subscription.
* <p>
* This extension provides a strategy to decide how to distribute traffics among them:
* 1. registry marked as 'preferred=true' has the highest priority.
* 2. check the zone the current request belongs, pick the registry that has the same zone first.
* 3. Evenly balance traffic between all registries based on each registry's weight.
*/
public class ZoneAwareClusterInvoker<T> extends AbstractClusterInvoker<T> {
private static final Logger logger = LoggerFactory.getLogger(ZoneAwareClusterInvoker.class);
private ZoneDetector zoneDetector;
public ZoneAwareClusterInvoker(Directory<T> directory) {
super(directory);
ExtensionLoader<ZoneDetector> loader =
directory.getConsumerUrl().getOrDefaultApplicationModel().getExtensionLoader(ZoneDetector.class);
if (loader.hasExtension("default")) {
zoneDetector = loader.getExtension("default");
}
}
@Override
@SuppressWarnings({"unchecked", "rawtypes"})
public Result doInvoke(Invocation invocation, final List<Invoker<T>> invokers, LoadBalance loadbalance)
throws RpcException {
// First, pick the invoker (XXXClusterInvoker) that comes from the local registry, distinguish by a 'preferred'
// key.
for (Invoker<T> invoker : invokers) {
ClusterInvoker<T> clusterInvoker = (ClusterInvoker<T>) invoker;
if (clusterInvoker.isAvailable() && clusterInvoker.getRegistryUrl().getParameter(PREFERRED_KEY, false)) {
return clusterInvoker.invoke(invocation);
}
}
RpcContext rpcContext = RpcContext.getClientAttachment();
String zone = rpcContext.getAttachment(REGISTRY_ZONE);
String force = rpcContext.getAttachment(REGISTRY_ZONE_FORCE);
if (StringUtils.isEmpty(zone) && zoneDetector != null) {
zone = zoneDetector.getZoneOfCurrentRequest(invocation);
force = zoneDetector.isZoneForcingEnabled(invocation, zone);
}
// providers in the registry with the same zone
if (StringUtils.isNotEmpty(zone)) {
for (Invoker<T> invoker : invokers) {
ClusterInvoker<T> clusterInvoker = (ClusterInvoker<T>) invoker;
if (clusterInvoker.isAvailable()
&& zone.equals(clusterInvoker.getRegistryUrl().getParameter(ZONE_KEY))) {
return clusterInvoker.invoke(invocation);
}
}
if (StringUtils.isNotEmpty(force) && "true".equalsIgnoreCase(force)) {
throw new IllegalStateException(
"No registry instance in zone or no available providers in the registry, zone: "
+ zone
+ ", registries: "
+ invokers.stream()
.map(invoker -> ((ClusterInvoker<T>) invoker)
.getRegistryUrl()
.toString())
.collect(Collectors.joining(",")));
}
}
// load balance among all registries, with registry weight count in.
Invoker<T> balancedInvoker = select(loadbalance, invocation, invokers, null);
if (balancedInvoker != null && balancedInvoker.isAvailable()) {
return balancedInvoker.invoke(invocation);
}
// If none of the invokers has a preferred signal or is picked by the loadbalancer, pick the first one
// available.
for (Invoker<T> invoker : invokers) {
ClusterInvoker<T> clusterInvoker = (ClusterInvoker<T>) invoker;
if (clusterInvoker.isAvailable()) {
return clusterInvoker.invoke(invocation);
}
}
throw new RpcException("No provider available in " + invokers);
}
}
| 7,880 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/registry/ZoneAwareCluster.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.support.registry;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.cluster.support.AbstractClusterInvoker;
import org.apache.dubbo.rpc.cluster.support.wrapper.AbstractCluster;
public class ZoneAwareCluster extends AbstractCluster {
public static final String NAME = "zone-aware";
@Override
protected <T> AbstractClusterInvoker<T> doJoin(Directory<T> directory) throws RpcException {
return new ZoneAwareClusterInvoker<T>(directory);
}
}
| 7,881 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/governance/GovernanceRuleRepository.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.governance;
import org.apache.dubbo.common.config.configcenter.ConfigurationListener;
import org.apache.dubbo.common.extension.SPI;
import static org.apache.dubbo.common.extension.ExtensionScope.MODULE;
@SPI(value = "default", scope = MODULE)
public interface GovernanceRuleRepository {
String DEFAULT_GROUP = "dubbo";
/**
* {@link #addListener(String, String, ConfigurationListener)}
*
* @param key the key to represent a configuration
* @param listener configuration listener
*/
default void addListener(String key, ConfigurationListener listener) {
addListener(key, DEFAULT_GROUP, listener);
}
/**
* {@link #removeListener(String, String, ConfigurationListener)}
*
* @param key the key to represent a configuration
* @param listener configuration listener
*/
default void removeListener(String key, ConfigurationListener listener) {
removeListener(key, DEFAULT_GROUP, listener);
}
/**
* Register a configuration listener for a specified key
* The listener only works for service governance purpose, so the target group would always be the value user
* specifies at startup or 'dubbo' by default. This method will only register listener, which means it will not
* trigger a notification that contains the current value.
*
* @param key the key to represent a configuration
* @param group the group where the key belongs to
* @param listener configuration listener
*/
void addListener(String key, String group, ConfigurationListener listener);
/**
* Stops one listener from listening to value changes in the specified key.
*
* @param key the key to represent a configuration
* @param group the group where the key belongs to
* @param listener configuration listener
*/
void removeListener(String key, String group, ConfigurationListener listener);
/**
* Get the governance rule mapped to the given key and the given group
*
* @param key the key to represent a configuration
* @param group the group where the key belongs to
* @return target configuration mapped to the given key and the given group
*/
default String getRule(String key, String group) {
return getRule(key, group, -1L);
}
/**
* Get the governance rule mapped to the given key and the given group. If the
* rule fails to return after timeout exceeds, IllegalStateException will be thrown.
*
* @param key the key to represent a configuration
* @param group the group where the key belongs to
* @param timeout timeout value for fetching the target config
* @return target configuration mapped to the given key and the given group, IllegalStateException will be thrown
* if timeout exceeds.
*/
String getRule(String key, String group, long timeout) throws IllegalStateException;
}
| 7,882 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/governance/DefaultGovernanceRuleRepositoryImpl.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.governance;
import org.apache.dubbo.common.config.configcenter.ConfigurationListener;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.rpc.model.ModuleModel;
public class DefaultGovernanceRuleRepositoryImpl implements GovernanceRuleRepository {
private final ModuleModel moduleModel;
public DefaultGovernanceRuleRepositoryImpl(ModuleModel moduleModel) {
this.moduleModel = moduleModel;
}
@Override
public void addListener(String key, String group, ConfigurationListener listener) {
DynamicConfiguration dynamicConfiguration = getDynamicConfiguration();
if (dynamicConfiguration != null) {
dynamicConfiguration.addListener(key, group, listener);
}
}
@Override
public void removeListener(String key, String group, ConfigurationListener listener) {
DynamicConfiguration dynamicConfiguration = getDynamicConfiguration();
if (dynamicConfiguration != null) {
dynamicConfiguration.removeListener(key, group, listener);
}
}
@Override
public String getRule(String key, String group, long timeout) throws IllegalStateException {
DynamicConfiguration dynamicConfiguration = getDynamicConfiguration();
if (dynamicConfiguration != null) {
return dynamicConfiguration.getConfig(key, group, timeout);
}
return null;
}
private DynamicConfiguration getDynamicConfiguration() {
return moduleModel.modelEnvironment().getDynamicConfiguration().orElse(null);
}
}
| 7,883 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/AbstractConfigurator.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.configurator;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.rpc.cluster.Configurator;
import org.apache.dubbo.rpc.cluster.configurator.parser.model.ConditionMatch;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE;
import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER;
import static org.apache.dubbo.common.constants.CommonConstants.ENABLED_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACES;
import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER;
import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.COMPATIBLE_CONFIG_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.CONFIG_VERSION_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.OVERRIDE_PROVIDERS_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.RULE_VERSION_V30;
import static org.apache.dubbo.rpc.cluster.configurator.parser.model.ConfiguratorConfig.MATCH_CONDITION;
/**
* AbstractConfigurator
*/
public abstract class AbstractConfigurator implements Configurator {
private static final Logger logger = LoggerFactory.getLogger(AbstractConfigurator.class);
private static final String TILDE = "~";
private final URL configuratorUrl;
public AbstractConfigurator(URL url) {
if (url == null) {
throw new IllegalArgumentException("configurator url == null");
}
this.configuratorUrl = url;
}
@Override
public URL getUrl() {
return configuratorUrl;
}
@Override
public URL configure(URL url) {
// If override url is not enabled or is invalid, just return.
if (!configuratorUrl.getParameter(ENABLED_KEY, true)
|| configuratorUrl.getHost() == null
|| url == null
|| url.getHost() == null) {
logger.info("Cannot apply configurator rule, the rule is disabled or is invalid: \n" + configuratorUrl);
return url;
}
String apiVersion = configuratorUrl.getParameter(CONFIG_VERSION_KEY);
if (StringUtils.isNotEmpty(apiVersion)) { // v2.7 or above
String currentSide = url.getSide();
String configuratorSide = configuratorUrl.getSide();
if (currentSide.equals(configuratorSide) && CONSUMER.equals(configuratorSide)) {
url = configureIfMatch(NetUtils.getLocalHost(), url);
} else if (currentSide.equals(configuratorSide) && PROVIDER.equals(configuratorSide)) {
url = configureIfMatch(url.getHost(), url);
}
}
/*
* This else branch is deprecated and is left only to keep compatibility with versions before 2.7.0
*/
else {
url = configureDeprecated(url);
}
return url;
}
@Deprecated
private URL configureDeprecated(URL url) {
// If override url has port, means it is a provider address. We want to control a specific provider with this
// override url, it may take effect on the specific provider instance or on consumers holding this provider
// instance.
if (configuratorUrl.getPort() != 0) {
if (url.getPort() == configuratorUrl.getPort()) {
return configureIfMatch(url.getHost(), url);
}
} else {
/*
* override url don't have a port, means the ip override url specify is a consumer address or 0.0.0.0.
* 1.If it is a consumer ip address, the intention is to control a specific consumer instance, it must takes effect at the consumer side, any provider received this override url should ignore.
* 2.If the ip is 0.0.0.0, this override url can be used on consumer, and also can be used on provider.
*/
if (url.getSide(PROVIDER).equals(CONSUMER)) {
// NetUtils.getLocalHost is the ip address consumer registered to registry.
return configureIfMatch(NetUtils.getLocalHost(), url);
} else if (url.getSide(CONSUMER).equals(PROVIDER)) {
// take effect on all providers, so address must be 0.0.0.0, otherwise it won't flow to this if branch
return configureIfMatch(ANYHOST_VALUE, url);
}
}
return url;
}
private URL configureIfMatch(String host, URL url) {
if (ANYHOST_VALUE.equals(configuratorUrl.getHost()) || host.equals(configuratorUrl.getHost())) {
if (isV27ConditionMatchOrUnset(url)) {
Set<String> conditionKeys = genConditionKeys();
String apiVersion = configuratorUrl.getParameter(CONFIG_VERSION_KEY);
if (apiVersion != null && apiVersion.startsWith(RULE_VERSION_V30)) {
ConditionMatch matcher = (ConditionMatch) configuratorUrl.getAttribute(MATCH_CONDITION);
if (matcher != null) {
if (matcher.isMatch(host, url)) {
return doConfigure(url, configuratorUrl.removeParameters(conditionKeys));
} else {
logger.debug("Cannot apply configurator rule, param mismatch, current params are " + url
+ ", params in rule is " + matcher);
}
} else {
return doConfigure(url, configuratorUrl.removeParameters(conditionKeys));
}
} else if (isDeprecatedConditionMatch(conditionKeys, url)) {
return doConfigure(url, configuratorUrl.removeParameters(conditionKeys));
}
}
} else {
logger.debug("Cannot apply configurator rule, host mismatch, current host is " + host + ", host in rule is "
+ configuratorUrl.getHost());
}
return url;
}
/**
* Check if v2.7 configurator rule is set and can be matched.
*
* @param url the configurator rule url
* @return true if v2.7 configurator rule is not set or the rule can be matched.
*/
private boolean isV27ConditionMatchOrUnset(URL url) {
String providers = configuratorUrl.getParameter(OVERRIDE_PROVIDERS_KEY);
if (StringUtils.isNotEmpty(providers)) {
boolean match = false;
String[] providerAddresses = providers.split(CommonConstants.COMMA_SEPARATOR);
for (String address : providerAddresses) {
if (address.equals(url.getAddress())
|| address.equals(ANYHOST_VALUE)
|| address.equals(ANYHOST_VALUE + CommonConstants.GROUP_CHAR_SEPARATOR + ANY_VALUE)
|| address.equals(ANYHOST_VALUE + CommonConstants.GROUP_CHAR_SEPARATOR + url.getPort())
|| address.equals(url.getHost())) {
match = true;
}
}
if (!match) {
logger.debug("Cannot apply configurator rule, provider address mismatch, current address "
+ url.getAddress() + ", address in rule is " + providers);
return false;
}
}
String configApplication = configuratorUrl.getApplication(configuratorUrl.getUsername());
String currentApplication = url.getApplication(url.getUsername());
if (configApplication != null
&& !ANY_VALUE.equals(configApplication)
&& !configApplication.equals(currentApplication)) {
logger.debug("Cannot apply configurator rule, application name mismatch, current application is "
+ currentApplication + ", application in rule is " + configApplication);
return false;
}
String configServiceKey = configuratorUrl.getServiceKey();
String currentServiceKey = url.getServiceKey();
if (!ANY_VALUE.equals(configServiceKey) && !configServiceKey.equals(currentServiceKey)) {
logger.debug("Cannot apply configurator rule, service mismatch, current service is " + currentServiceKey
+ ", service in rule is " + configServiceKey);
return false;
}
return true;
}
private boolean isDeprecatedConditionMatch(Set<String> conditionKeys, URL url) {
boolean result = true;
for (Map.Entry<String, String> entry : configuratorUrl.getParameters().entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
boolean startWithTilde = startWithTilde(key);
if (startWithTilde || APPLICATION_KEY.equals(key) || SIDE_KEY.equals(key)) {
if (startWithTilde) {
conditionKeys.add(key);
}
if (value != null
&& !ANY_VALUE.equals(value)
&& !value.equals(url.getParameter(startWithTilde ? key.substring(1) : key))) {
result = false;
break;
}
}
}
return result;
}
private Set<String> genConditionKeys() {
Set<String> conditionKeys = new HashSet<String>();
conditionKeys.add(CATEGORY_KEY);
conditionKeys.add(Constants.CHECK_KEY);
conditionKeys.add(DYNAMIC_KEY);
conditionKeys.add(ENABLED_KEY);
conditionKeys.add(GROUP_KEY);
conditionKeys.add(VERSION_KEY);
conditionKeys.add(APPLICATION_KEY);
conditionKeys.add(SIDE_KEY);
conditionKeys.add(CONFIG_VERSION_KEY);
conditionKeys.add(COMPATIBLE_CONFIG_KEY);
conditionKeys.add(INTERFACES);
return conditionKeys;
}
private boolean startWithTilde(String key) {
return StringUtils.isNotEmpty(key) && key.startsWith(TILDE);
}
protected abstract URL doConfigure(URL currentUrl, URL configUrl);
}
| 7,884 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/absent/AbsentConfigurator.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.configurator.absent;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.cluster.configurator.AbstractConfigurator;
/**
* AbsentConfigurator
*/
public class AbsentConfigurator extends AbstractConfigurator {
public AbsentConfigurator(URL url) {
super(url);
}
@Override
public URL doConfigure(URL currentUrl, URL configUrl) {
return currentUrl.addParametersIfAbsent(configUrl.getParameters());
}
}
| 7,885 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/absent/AbsentConfiguratorFactory.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.configurator.absent;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.cluster.Configurator;
import org.apache.dubbo.rpc.cluster.ConfiguratorFactory;
/**
* AbsentConfiguratorFactory
*
*/
public class AbsentConfiguratorFactory implements ConfiguratorFactory {
@Override
public Configurator getConfigurator(URL url) {
return new AbsentConfigurator(url);
}
}
| 7,886 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/override/OverrideConfiguratorFactory.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.configurator.override;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.cluster.Configurator;
import org.apache.dubbo.rpc.cluster.ConfiguratorFactory;
/**
* OverrideConfiguratorFactory
*
*/
public class OverrideConfiguratorFactory implements ConfiguratorFactory {
@Override
public Configurator getConfigurator(URL url) {
return new OverrideConfigurator(url);
}
}
| 7,887 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/override/OverrideConfigurator.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.configurator.override;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.rpc.cluster.configurator.AbstractConfigurator;
/**
* OverrideConfigurator
*/
public class OverrideConfigurator extends AbstractConfigurator {
public static final Logger logger = LoggerFactory.getLogger(OverrideConfigurator.class);
public OverrideConfigurator(URL url) {
super(url);
}
@Override
public URL doConfigure(URL currentUrl, URL configUrl) {
logger.info("Start overriding url " + currentUrl + " with override url " + configUrl);
return currentUrl.addParameters(configUrl.getParameters());
}
}
| 7,888 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParser.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.configurator.parser;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.cluster.configurator.parser.model.ConfigItem;
import org.apache.dubbo.rpc.cluster.configurator.parser.model.ConfiguratorConfig;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE;
import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER;
import static org.apache.dubbo.common.constants.RegistryConstants.APP_DYNAMIC_CONFIGURATORS_CATEGORY;
import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_CONFIGURATORS_CATEGORY;
import static org.apache.dubbo.rpc.cluster.Constants.OVERRIDE_PROVIDERS_KEY;
import static org.apache.dubbo.rpc.cluster.configurator.parser.model.ConfiguratorConfig.MATCH_CONDITION;
/**
* Config parser
*/
public class ConfigParser {
public static List<URL> parseConfigurators(String rawConfig) {
// compatible url JsonArray, such as [ "override://xxx", "override://xxx" ]
List<URL> compatibleUrls = parseJsonArray(rawConfig);
if (CollectionUtils.isNotEmpty(compatibleUrls)) {
return compatibleUrls;
}
List<URL> urls = new ArrayList<>();
ConfiguratorConfig configuratorConfig = parseObject(rawConfig);
String scope = configuratorConfig.getScope();
List<ConfigItem> items = configuratorConfig.getConfigs();
if (ConfiguratorConfig.SCOPE_APPLICATION.equals(scope)) {
items.forEach(item -> urls.addAll(appItemToUrls(item, configuratorConfig)));
} else {
// service scope by default.
items.forEach(item -> urls.addAll(serviceItemToUrls(item, configuratorConfig)));
}
return urls;
}
private static List<URL> parseJsonArray(String rawConfig) {
List<URL> urls = new ArrayList<>();
try {
List<String> list = JsonUtils.toJavaList(rawConfig, String.class);
if (!CollectionUtils.isEmpty(list)) {
list.forEach(u -> urls.add(URL.valueOf(u)));
}
} catch (Throwable t) {
return null;
}
return urls;
}
private static ConfiguratorConfig parseObject(String rawConfig) {
Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions()));
Map<String, Object> map = yaml.load(rawConfig);
return ConfiguratorConfig.parseFromMap(map);
}
private static List<URL> serviceItemToUrls(ConfigItem item, ConfiguratorConfig config) {
List<URL> urls = new ArrayList<>();
List<String> addresses = parseAddresses(item);
addresses.forEach(addr -> {
StringBuilder urlBuilder = new StringBuilder();
urlBuilder.append("override://").append(addr).append('/');
urlBuilder.append(appendService(config.getKey()));
urlBuilder.append(toParameterString(item));
parseEnabled(item, config, urlBuilder);
urlBuilder.append("&configVersion=").append(config.getConfigVersion());
List<String> apps = item.getApplications();
if (CollectionUtils.isNotEmpty(apps)) {
apps.forEach(app -> {
StringBuilder tmpUrlBuilder = new StringBuilder(urlBuilder);
urls.add(appendMatchCondition(
URL.valueOf(tmpUrlBuilder
.append("&application=")
.append(app)
.toString()),
item));
});
} else {
urls.add(appendMatchCondition(URL.valueOf(urlBuilder.toString()), item));
}
});
return urls;
}
private static List<URL> appItemToUrls(ConfigItem item, ConfiguratorConfig config) {
List<URL> urls = new ArrayList<>();
List<String> addresses = parseAddresses(item);
for (String addr : addresses) {
StringBuilder urlBuilder = new StringBuilder();
urlBuilder.append("override://").append(addr).append('/');
List<String> services = item.getServices();
if (services == null) {
services = new ArrayList<>();
}
if (services.isEmpty()) {
services.add("*");
}
for (String s : services) {
StringBuilder tmpUrlBuilder = new StringBuilder(urlBuilder);
tmpUrlBuilder.append(appendService(s));
tmpUrlBuilder.append(toParameterString(item));
tmpUrlBuilder.append("&application=").append(config.getKey());
parseEnabled(item, config, tmpUrlBuilder);
tmpUrlBuilder.append("&category=").append(APP_DYNAMIC_CONFIGURATORS_CATEGORY);
tmpUrlBuilder.append("&configVersion=").append(config.getConfigVersion());
urls.add(appendMatchCondition(URL.valueOf(tmpUrlBuilder.toString()), item));
}
}
return urls;
}
private static String toParameterString(ConfigItem item) {
StringBuilder sb = new StringBuilder();
sb.append("category=");
sb.append(DYNAMIC_CONFIGURATORS_CATEGORY);
if (item.getSide() != null) {
sb.append("&side=");
sb.append(item.getSide());
}
Map<String, String> parameters = item.getParameters();
if (CollectionUtils.isEmptyMap(parameters)) {
throw new IllegalStateException("Invalid configurator rule, please specify at least one parameter "
+ "you want to change in the rule.");
}
parameters.forEach((k, v) -> {
sb.append('&');
sb.append(k);
sb.append('=');
sb.append(v);
});
if (CollectionUtils.isNotEmpty(item.getProviderAddresses())) {
sb.append('&');
sb.append(OVERRIDE_PROVIDERS_KEY);
sb.append('=');
sb.append(CollectionUtils.join(item.getProviderAddresses(), ","));
} else if (PROVIDER.equals(item.getSide())) {
sb.append('&');
sb.append(OVERRIDE_PROVIDERS_KEY);
sb.append('=');
sb.append(CollectionUtils.join(parseAddresses(item), ","));
}
return sb.toString();
}
private static String appendService(String serviceKey) {
StringBuilder sb = new StringBuilder();
if (StringUtils.isEmpty(serviceKey)) {
throw new IllegalStateException("service field in configuration is null.");
}
String interfaceName = serviceKey;
int i = interfaceName.indexOf('/');
if (i > 0) {
sb.append("group=");
sb.append(interfaceName, 0, i);
sb.append('&');
interfaceName = interfaceName.substring(i + 1);
}
int j = interfaceName.indexOf(':');
if (j > 0) {
sb.append("version=");
sb.append(interfaceName.substring(j + 1));
sb.append('&');
interfaceName = interfaceName.substring(0, j);
}
sb.insert(0, interfaceName + "?");
return sb.toString();
}
private static void parseEnabled(ConfigItem item, ConfiguratorConfig config, StringBuilder urlBuilder) {
urlBuilder.append("&enabled=");
if (item.getType() == null || ConfigItem.GENERAL_TYPE.equals(item.getType())) {
urlBuilder.append(config.getEnabled());
} else {
urlBuilder.append(item.getEnabled());
}
}
private static List<String> parseAddresses(ConfigItem item) {
List<String> addresses = item.getAddresses();
if (addresses == null) {
addresses = new ArrayList<>();
}
if (addresses.isEmpty()) {
addresses.add(ANYHOST_VALUE);
}
return addresses;
}
private static URL appendMatchCondition(URL url, ConfigItem item) {
if (item.getMatch() != null) {
url = url.putAttribute(MATCH_CONDITION, item.getMatch());
}
return url;
}
}
| 7,889 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/model/ParamMatch.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.configurator.parser.model;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match.StringMatch;
public class ParamMatch {
private String key;
private StringMatch value;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public StringMatch getValue() {
return value;
}
public void setValue(StringMatch value) {
this.value = value;
}
public boolean isMatch(URL url) {
if (key == null || value == null) {
return false;
}
String input = url.getParameter(key);
return value.isMatch(input);
}
@Override
public String toString() {
return "ParamMatch{" + "key='" + key + '\'' + ", value='" + value + '\'' + '}';
}
}
| 7,890 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/model/ConditionMatch.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.configurator.parser.model;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match.AddressMatch;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match.ListStringMatch;
import java.util.List;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY;
public class ConditionMatch {
private AddressMatch address;
private AddressMatch providerAddress;
private ListStringMatch service;
private ListStringMatch app;
private List<ParamMatch> param;
public AddressMatch getAddress() {
return address;
}
public void setAddress(AddressMatch address) {
this.address = address;
}
public AddressMatch getProviderAddress() {
return providerAddress;
}
public void setProviderAddress(AddressMatch providerAddress) {
this.providerAddress = providerAddress;
}
public ListStringMatch getService() {
return service;
}
public void setService(ListStringMatch service) {
this.service = service;
}
public ListStringMatch getApp() {
return app;
}
public void setApp(ListStringMatch app) {
this.app = app;
}
public List<ParamMatch> getParam() {
return param;
}
public void setParam(List<ParamMatch> param) {
this.param = param;
}
public boolean isMatch(String host, URL url) {
if (getAddress() != null && !getAddress().isMatch(host)) {
return false;
}
if (getProviderAddress() != null && !getProviderAddress().isMatch(url.getAddress())) {
return false;
}
if (getService() != null && !getService().isMatch(url.getServiceKey())) {
return false;
}
if (getApp() != null && !getApp().isMatch(url.getParameter(APPLICATION_KEY))) {
return false;
}
if (getParam() != null) {
for (ParamMatch match : param) {
if (!match.isMatch(url)) {
return false;
}
}
}
return true;
}
@Override
public String toString() {
return "ConditionMatch{" + "address='"
+ address + '\'' + "providerAddress='"
+ providerAddress + '\'' + ", service='"
+ service + '\'' + ", app='"
+ app + '\'' + ", param='"
+ param + '\'' + '}';
}
}
| 7,891 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/model/ConfiguratorConfig.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.configurator.parser.model;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
*
*/
public class ConfiguratorConfig {
public static final String MATCH_CONDITION = "MATCH_CONDITION";
public static final String SCOPE_SERVICE = "service";
public static final String SCOPE_APPLICATION = "application";
public static final String CONFIG_VERSION_KEY = "configVersion";
public static final String SCOPE_KEY = "scope";
public static final String CONFIG_KEY = "key";
public static final String ENABLED_KEY = "enabled";
public static final String CONFIGS_KEY = "configs";
private String configVersion;
private String scope;
private String key;
private Boolean enabled = true;
private List<ConfigItem> configs;
@SuppressWarnings("unchecked")
public static ConfiguratorConfig parseFromMap(Map<String, Object> map) {
ConfiguratorConfig configuratorConfig = new ConfiguratorConfig();
configuratorConfig.setConfigVersion((String) map.get(CONFIG_VERSION_KEY));
configuratorConfig.setScope((String) map.get(SCOPE_KEY));
configuratorConfig.setKey((String) map.get(CONFIG_KEY));
Object enabled = map.get(ENABLED_KEY);
if (enabled != null) {
configuratorConfig.setEnabled(Boolean.parseBoolean(enabled.toString()));
}
Object configs = map.get(CONFIGS_KEY);
if (configs != null && List.class.isAssignableFrom(configs.getClass())) {
configuratorConfig.setConfigs(((List<Map<String, Object>>) configs)
.stream().map(ConfigItem::parseFromMap).collect(Collectors.toList()));
}
return configuratorConfig;
}
public String getConfigVersion() {
return configVersion;
}
public void setConfigVersion(String configVersion) {
this.configVersion = configVersion;
}
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public List<ConfigItem> getConfigs() {
return configs;
}
public void setConfigs(List<ConfigItem> configs) {
this.configs = configs;
}
}
| 7,892 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/model/ConfigItem.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.configurator.parser.model;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.PojoUtils;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_FAILED_RECEIVE_RULE;
/**
*
*/
public class ConfigItem {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ConfigItem.class);
public static final String GENERAL_TYPE = "general";
public static final String WEIGHT_TYPE = "weight";
public static final String BALANCING_TYPE = "balancing";
public static final String DISABLED_TYPE = "disabled";
public static final String CONFIG_ITEM_TYPE = "type";
public static final String ENABLED_KEY = "enabled";
public static final String ADDRESSES_KEY = "addresses";
public static final String PROVIDER_ADDRESSES_KEY = "providerAddresses";
public static final String SERVICES_KEY = "services";
public static final String APPLICATIONS_KEY = "applications";
public static final String PARAMETERS_KEY = "parameters";
public static final String MATCH_KEY = "match";
public static final String SIDE_KEY = "side";
private String type;
private Boolean enabled;
private List<String> addresses;
private List<String> providerAddresses;
private List<String> services;
private List<String> applications;
private Map<String, String> parameters;
private ConditionMatch match;
private String side;
@SuppressWarnings("unchecked")
public static ConfigItem parseFromMap(Map<String, Object> map) {
ConfigItem configItem = new ConfigItem();
configItem.setType((String) map.get(CONFIG_ITEM_TYPE));
Object enabled = map.get(ENABLED_KEY);
if (enabled != null) {
configItem.setEnabled(Boolean.parseBoolean(enabled.toString()));
}
Object addresses = map.get(ADDRESSES_KEY);
if (addresses != null && List.class.isAssignableFrom(addresses.getClass())) {
configItem.setAddresses(
((List<Object>) addresses).stream().map(String::valueOf).collect(Collectors.toList()));
}
Object providerAddresses = map.get(PROVIDER_ADDRESSES_KEY);
if (providerAddresses != null && List.class.isAssignableFrom(providerAddresses.getClass())) {
configItem.setProviderAddresses(((List<Object>) providerAddresses)
.stream().map(String::valueOf).collect(Collectors.toList()));
}
Object services = map.get(SERVICES_KEY);
if (services != null && List.class.isAssignableFrom(services.getClass())) {
configItem.setServices(
((List<Object>) services).stream().map(String::valueOf).collect(Collectors.toList()));
}
Object applications = map.get(APPLICATIONS_KEY);
if (applications != null && List.class.isAssignableFrom(applications.getClass())) {
configItem.setApplications(
((List<Object>) applications).stream().map(String::valueOf).collect(Collectors.toList()));
}
Object parameters = map.get(PARAMETERS_KEY);
if (parameters != null && Map.class.isAssignableFrom(parameters.getClass())) {
configItem.setParameters(((Map<String, Object>) parameters)
.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue()
.toString())));
}
try {
Object match = map.get(MATCH_KEY);
if (match != null && Map.class.isAssignableFrom(match.getClass())) {
configItem.setMatch(PojoUtils.mapToPojo((Map<String, Object>) match, ConditionMatch.class));
}
} catch (Throwable t) {
logger.error(
CLUSTER_FAILED_RECEIVE_RULE,
" Failed to parse dynamic configuration rule",
String.valueOf(map.get(MATCH_KEY)),
"Error occurred when parsing rule component.",
t);
}
configItem.setSide((String) map.get(SIDE_KEY));
return configItem;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public List<String> getAddresses() {
return addresses;
}
public void setAddresses(List<String> addresses) {
this.addresses = addresses;
}
public List<String> getServices() {
return services;
}
public void setServices(List<String> services) {
this.services = services;
}
public List<String> getApplications() {
return applications;
}
public void setApplications(List<String> applications) {
this.applications = applications;
}
public List<String> getProviderAddresses() {
return providerAddresses;
}
public void setProviderAddresses(List<String> providerAddresses) {
this.providerAddresses = providerAddresses;
}
public Map<String, String> getParameters() {
return parameters;
}
public void setParameters(Map<String, String> parameters) {
this.parameters = parameters;
}
public String getSide() {
return side;
}
public void setSide(String side) {
this.side = side;
}
public ConditionMatch getMatch() {
return match;
}
public void setMatch(ConditionMatch match) {
this.match = match;
}
}
| 7,893 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/FilterChainBuilder.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.filter;
import org.apache.dubbo.common.Experimental;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.rpc.AsyncRpcResult;
import org.apache.dubbo.rpc.BaseFilter;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.InvocationProfilerUtils;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.ListenableFilter;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.ClusterInvoker;
import org.apache.dubbo.rpc.cluster.Directory;
import java.util.List;
import java.util.stream.Collectors;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_EXECUTE_FILTER_EXCEPTION;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR;
import static org.apache.dubbo.common.extension.ExtensionScope.APPLICATION;
@SPI(value = "default", scope = APPLICATION)
public interface FilterChainBuilder {
/**
* build consumer/provider filter chain
*/
<T> Invoker<T> buildInvokerChain(final Invoker<T> invoker, String key, String group);
/**
* build consumer cluster filter chain
*/
<T> ClusterInvoker<T> buildClusterInvokerChain(final ClusterInvoker<T> invoker, String key, String group);
/**
* Works on provider side
*
* @param <T>
* @param <TYPE>
*/
class FilterChainNode<T, TYPE extends Invoker<T>, FILTER extends BaseFilter> implements Invoker<T> {
TYPE originalInvoker;
Invoker<T> nextNode;
FILTER filter;
public FilterChainNode(TYPE originalInvoker, Invoker<T> nextNode, FILTER filter) {
this.originalInvoker = originalInvoker;
this.nextNode = nextNode;
this.filter = filter;
}
public TYPE getOriginalInvoker() {
return originalInvoker;
}
@Override
public Class<T> getInterface() {
return originalInvoker.getInterface();
}
@Override
public URL getUrl() {
return originalInvoker.getUrl();
}
@Override
public boolean isAvailable() {
return originalInvoker.isAvailable();
}
@Override
public Result invoke(Invocation invocation) throws RpcException {
Result asyncResult;
try {
InvocationProfilerUtils.enterDetailProfiler(
invocation, () -> "Filter " + filter.getClass().getName() + " invoke.");
asyncResult = filter.invoke(nextNode, invocation);
} catch (Exception e) {
InvocationProfilerUtils.releaseDetailProfiler(invocation);
if (filter instanceof ListenableFilter) {
ListenableFilter listenableFilter = ((ListenableFilter) filter);
try {
Filter.Listener listener = listenableFilter.listener(invocation);
if (listener != null) {
listener.onError(e, originalInvoker, invocation);
}
} finally {
listenableFilter.removeListener(invocation);
}
} else if (filter instanceof FILTER.Listener) {
FILTER.Listener listener = (FILTER.Listener) filter;
listener.onError(e, originalInvoker, invocation);
}
throw e;
} finally {
}
return asyncResult.whenCompleteWithContext((r, t) -> {
InvocationProfilerUtils.releaseDetailProfiler(invocation);
if (filter instanceof ListenableFilter) {
ListenableFilter listenableFilter = ((ListenableFilter) filter);
Filter.Listener listener = listenableFilter.listener(invocation);
try {
if (listener != null) {
if (t == null) {
listener.onResponse(r, originalInvoker, invocation);
} else {
listener.onError(t, originalInvoker, invocation);
}
}
} finally {
listenableFilter.removeListener(invocation);
}
} else if (filter instanceof FILTER.Listener) {
FILTER.Listener listener = (FILTER.Listener) filter;
if (t == null) {
listener.onResponse(r, originalInvoker, invocation);
} else {
listener.onError(t, originalInvoker, invocation);
}
}
});
}
@Override
public void destroy() {
originalInvoker.destroy();
}
@Override
public String toString() {
return originalInvoker.toString();
}
}
/**
* Works on consumer side
*
* @param <T>
* @param <TYPE>
*/
class ClusterFilterChainNode<T, TYPE extends ClusterInvoker<T>, FILTER extends BaseFilter>
extends FilterChainNode<T, TYPE, FILTER> implements ClusterInvoker<T> {
public ClusterFilterChainNode(TYPE originalInvoker, Invoker<T> nextNode, FILTER filter) {
super(originalInvoker, nextNode, filter);
}
@Override
public URL getRegistryUrl() {
return getOriginalInvoker().getRegistryUrl();
}
@Override
public Directory<T> getDirectory() {
return getOriginalInvoker().getDirectory();
}
@Override
public boolean isDestroyed() {
return getOriginalInvoker().isDestroyed();
}
}
class CallbackRegistrationInvoker<T, FILTER extends BaseFilter> implements Invoker<T> {
private static final ErrorTypeAwareLogger LOGGER =
LoggerFactory.getErrorTypeAwareLogger(CallbackRegistrationInvoker.class);
final Invoker<T> filterInvoker;
final List<FILTER> filters;
public CallbackRegistrationInvoker(Invoker<T> filterInvoker, List<FILTER> filters) {
this.filterInvoker = filterInvoker;
this.filters = filters;
}
@Override
public Result invoke(Invocation invocation) throws RpcException {
Result asyncResult = filterInvoker.invoke(invocation);
asyncResult.whenCompleteWithContext((r, t) -> {
RuntimeException filterRuntimeException = null;
for (int i = filters.size() - 1; i >= 0; i--) {
FILTER filter = filters.get(i);
try {
InvocationProfilerUtils.releaseDetailProfiler(invocation);
if (filter instanceof ListenableFilter) {
ListenableFilter listenableFilter = ((ListenableFilter) filter);
Filter.Listener listener = listenableFilter.listener(invocation);
try {
if (listener != null) {
if (t == null) {
listener.onResponse(r, filterInvoker, invocation);
} else {
listener.onError(t, filterInvoker, invocation);
}
}
} finally {
listenableFilter.removeListener(invocation);
}
} else if (filter instanceof FILTER.Listener) {
FILTER.Listener listener = (FILTER.Listener) filter;
if (t == null) {
listener.onResponse(r, filterInvoker, invocation);
} else {
listener.onError(t, filterInvoker, invocation);
}
}
} catch (RuntimeException runtimeException) {
LOGGER.error(
CLUSTER_EXECUTE_FILTER_EXCEPTION,
"the custom filter is abnormal",
"",
String.format(
"Exception occurred while executing the %s filter named %s.",
i, filter.getClass().getSimpleName()));
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(String.format(
"Whole filter list is: %s",
filters.stream()
.map(tmpFilter ->
tmpFilter.getClass().getSimpleName())
.collect(Collectors.toList())));
}
filterRuntimeException = runtimeException;
t = runtimeException;
}
}
if (filterRuntimeException != null) {
throw filterRuntimeException;
}
});
return asyncResult;
}
public Invoker<T> getFilterInvoker() {
return filterInvoker;
}
@Override
public Class<T> getInterface() {
return filterInvoker.getInterface();
}
@Override
public URL getUrl() {
return filterInvoker.getUrl();
}
@Override
public boolean isAvailable() {
return filterInvoker.isAvailable();
}
@Override
public void destroy() {
filterInvoker.destroy();
}
}
class ClusterCallbackRegistrationInvoker<T, FILTER extends BaseFilter>
extends CallbackRegistrationInvoker<T, FILTER> implements ClusterInvoker<T> {
private ClusterInvoker<T> originalInvoker;
public ClusterCallbackRegistrationInvoker(
ClusterInvoker<T> originalInvoker, Invoker<T> filterInvoker, List<FILTER> filters) {
super(filterInvoker, filters);
this.originalInvoker = originalInvoker;
}
public ClusterInvoker<T> getOriginalInvoker() {
return originalInvoker;
}
@Override
public URL getRegistryUrl() {
return getOriginalInvoker().getRegistryUrl();
}
@Override
public Directory<T> getDirectory() {
return getOriginalInvoker().getDirectory();
}
@Override
public boolean isDestroyed() {
return getOriginalInvoker().isDestroyed();
}
}
@Experimental(
"Works for the same purpose as FilterChainNode, replace FilterChainNode with this one when proved stable enough")
class CopyOfFilterChainNode<T, TYPE extends Invoker<T>, FILTER extends BaseFilter> implements Invoker<T> {
private static final ErrorTypeAwareLogger LOGGER =
LoggerFactory.getErrorTypeAwareLogger(CopyOfFilterChainNode.class);
TYPE originalInvoker;
Invoker<T> nextNode;
FILTER filter;
public CopyOfFilterChainNode(TYPE originalInvoker, Invoker<T> nextNode, FILTER filter) {
this.originalInvoker = originalInvoker;
this.nextNode = nextNode;
this.filter = filter;
}
public TYPE getOriginalInvoker() {
return originalInvoker;
}
@Override
public Class<T> getInterface() {
return originalInvoker.getInterface();
}
@Override
public URL getUrl() {
return originalInvoker.getUrl();
}
@Override
public boolean isAvailable() {
return originalInvoker.isAvailable();
}
@Override
public Result invoke(Invocation invocation) throws RpcException {
Result asyncResult;
try {
InvocationProfilerUtils.enterDetailProfiler(
invocation, () -> "Filter " + filter.getClass().getName() + " invoke.");
asyncResult = filter.invoke(nextNode, invocation);
if (!(asyncResult instanceof AsyncRpcResult)) {
String msg =
"The result of filter invocation must be AsyncRpcResult. (If you want to recreate a result, please use AsyncRpcResult.newDefaultAsyncResult.) "
+ "Filter class: " + filter.getClass().getName() + ". Result class: "
+ asyncResult.getClass().getName() + ".";
LOGGER.error(INTERNAL_ERROR, "", "", msg);
throw new RpcException(msg);
}
} catch (Exception e) {
InvocationProfilerUtils.releaseDetailProfiler(invocation);
if (filter instanceof ListenableFilter) {
ListenableFilter listenableFilter = ((ListenableFilter) filter);
try {
Filter.Listener listener = listenableFilter.listener(invocation);
if (listener != null) {
listener.onError(e, originalInvoker, invocation);
}
} finally {
listenableFilter.removeListener(invocation);
}
} else if (filter instanceof FILTER.Listener) {
FILTER.Listener listener = (FILTER.Listener) filter;
listener.onError(e, originalInvoker, invocation);
}
throw e;
} finally {
}
return asyncResult;
}
@Override
public void destroy() {
originalInvoker.destroy();
}
@Override
public String toString() {
return originalInvoker.toString();
}
}
@Experimental(
"Works for the same purpose as ClusterFilterChainNode, replace ClusterFilterChainNode with this one when proved stable enough")
class CopyOfClusterFilterChainNode<T, TYPE extends ClusterInvoker<T>, FILTER extends BaseFilter>
extends CopyOfFilterChainNode<T, TYPE, FILTER> implements ClusterInvoker<T> {
public CopyOfClusterFilterChainNode(TYPE originalInvoker, Invoker<T> nextNode, FILTER filter) {
super(originalInvoker, nextNode, filter);
}
@Override
public URL getRegistryUrl() {
return getOriginalInvoker().getRegistryUrl();
}
@Override
public Directory<T> getDirectory() {
return getOriginalInvoker().getDirectory();
}
@Override
public boolean isDestroyed() {
return getOriginalInvoker().isDestroyed();
}
}
}
| 7,894 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/ProtocolFilterWrapper.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.filter;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.utils.UrlUtils;
import org.apache.dubbo.rpc.Exporter;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.ProtocolServer;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.model.ScopeModelUtil;
import java.util.List;
import static org.apache.dubbo.common.constants.CommonConstants.REFERENCE_FILTER_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.SERVICE_FILTER_KEY;
/**
* ListenerProtocol
*/
@Activate(order = 100)
public class ProtocolFilterWrapper implements Protocol {
private final Protocol protocol;
public ProtocolFilterWrapper(Protocol protocol) {
if (protocol == null) {
throw new IllegalArgumentException("protocol == null");
}
this.protocol = protocol;
}
@Override
public int getDefaultPort() {
return protocol.getDefaultPort();
}
@Override
public <T> Exporter<T> export(Invoker<T> invoker) throws RpcException {
if (UrlUtils.isRegistry(invoker.getUrl())) {
return protocol.export(invoker);
}
FilterChainBuilder builder = getFilterChainBuilder(invoker.getUrl());
return protocol.export(builder.buildInvokerChain(invoker, SERVICE_FILTER_KEY, CommonConstants.PROVIDER));
}
private <T> FilterChainBuilder getFilterChainBuilder(URL url) {
return ScopeModelUtil.getExtensionLoader(FilterChainBuilder.class, url.getScopeModel())
.getDefaultExtension();
}
@Override
public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException {
if (UrlUtils.isRegistry(url)) {
return protocol.refer(type, url);
}
FilterChainBuilder builder = getFilterChainBuilder(url);
return builder.buildInvokerChain(protocol.refer(type, url), REFERENCE_FILTER_KEY, CommonConstants.CONSUMER);
}
@Override
public void destroy() {
protocol.destroy();
}
@Override
public List<ProtocolServer> getServers() {
return protocol.getServers();
}
}
| 7,895 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/DefaultFilterChainBuilder.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.filter;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.extension.ExtensionDirector;
import org.apache.dubbo.common.extension.support.ActivateComparator;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.cluster.ClusterInvoker;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.apache.dubbo.rpc.model.ScopeModel;
import org.apache.dubbo.rpc.model.ScopeModelUtil;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
@Activate
public class DefaultFilterChainBuilder implements FilterChainBuilder {
/**
* build consumer/provider filter chain
*/
@Override
public <T> Invoker<T> buildInvokerChain(final Invoker<T> originalInvoker, String key, String group) {
Invoker<T> last = originalInvoker;
URL url = originalInvoker.getUrl();
List<ModuleModel> moduleModels = getModuleModelsFromUrl(url);
List<Filter> filters;
if (moduleModels != null && moduleModels.size() == 1) {
filters = ScopeModelUtil.getExtensionLoader(Filter.class, moduleModels.get(0))
.getActivateExtension(url, key, group);
} else if (moduleModels != null && moduleModels.size() > 1) {
filters = new ArrayList<>();
List<ExtensionDirector> directors = new ArrayList<>();
for (ModuleModel moduleModel : moduleModels) {
List<Filter> tempFilters = ScopeModelUtil.getExtensionLoader(Filter.class, moduleModel)
.getActivateExtension(url, key, group);
filters.addAll(tempFilters);
directors.add(moduleModel.getExtensionDirector());
}
filters = sortingAndDeduplication(filters, directors);
} else {
filters = ScopeModelUtil.getExtensionLoader(Filter.class, null).getActivateExtension(url, key, group);
}
if (!CollectionUtils.isEmpty(filters)) {
for (int i = filters.size() - 1; i >= 0; i--) {
final Filter filter = filters.get(i);
final Invoker<T> next = last;
last = new CopyOfFilterChainNode<>(originalInvoker, next, filter);
}
return new CallbackRegistrationInvoker<>(last, filters);
}
return last;
}
/**
* build consumer cluster filter chain
*/
@Override
public <T> ClusterInvoker<T> buildClusterInvokerChain(
final ClusterInvoker<T> originalInvoker, String key, String group) {
ClusterInvoker<T> last = originalInvoker;
URL url = originalInvoker.getUrl();
List<ModuleModel> moduleModels = getModuleModelsFromUrl(url);
List<ClusterFilter> filters;
if (moduleModels != null && moduleModels.size() == 1) {
filters = ScopeModelUtil.getExtensionLoader(ClusterFilter.class, moduleModels.get(0))
.getActivateExtension(url, key, group);
} else if (moduleModels != null && moduleModels.size() > 1) {
filters = new ArrayList<>();
List<ExtensionDirector> directors = new ArrayList<>();
for (ModuleModel moduleModel : moduleModels) {
List<ClusterFilter> tempFilters = ScopeModelUtil.getExtensionLoader(ClusterFilter.class, moduleModel)
.getActivateExtension(url, key, group);
filters.addAll(tempFilters);
directors.add(moduleModel.getExtensionDirector());
}
filters = sortingAndDeduplication(filters, directors);
} else {
filters =
ScopeModelUtil.getExtensionLoader(ClusterFilter.class, null).getActivateExtension(url, key, group);
}
if (!CollectionUtils.isEmpty(filters)) {
for (int i = filters.size() - 1; i >= 0; i--) {
final ClusterFilter filter = filters.get(i);
final Invoker<T> next = last;
last = new CopyOfClusterFilterChainNode<>(originalInvoker, next, filter);
}
return new ClusterCallbackRegistrationInvoker<>(originalInvoker, last, filters);
}
return last;
}
private <T> List<T> sortingAndDeduplication(List<T> filters, List<ExtensionDirector> directors) {
Map<Class<?>, T> filtersSet = new TreeMap<>(new ActivateComparator(directors));
for (T filter : filters) {
filtersSet.putIfAbsent(filter.getClass(), filter);
}
return new ArrayList<>(filtersSet.values());
}
/**
* When the application-level service registration and discovery strategy is adopted, the URL will be of type InstanceAddressURL,
* and InstanceAddressURL belongs to the application layer and holds the ApplicationModel,
* but the filter is at the module layer and holds the ModuleModel,
* so it needs to be based on the url in the ScopeModel type to parse out all the moduleModels held by the url
* to obtain the filter configuration.
*
* @param url URL
* @return All ModuleModels in the url
*/
private List<ModuleModel> getModuleModelsFromUrl(URL url) {
List<ModuleModel> moduleModels = null;
ScopeModel scopeModel = url.getScopeModel();
if (scopeModel instanceof ApplicationModel) {
moduleModels = ((ApplicationModel) scopeModel).getPubModuleModels();
} else if (scopeModel instanceof ModuleModel) {
moduleModels = new ArrayList<>();
moduleModels.add((ModuleModel) scopeModel);
}
return moduleModels;
}
}
| 7,896 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/InvocationInterceptorBuilder.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.filter;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.rpc.cluster.ClusterInvoker;
@SPI("default")
public interface InvocationInterceptorBuilder {
<T> ClusterInvoker<T> buildClusterInterceptorChain(final ClusterInvoker<T> invoker, String key, String group);
}
| 7,897 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/ClusterFilter.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.filter;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.rpc.BaseFilter;
@SPI(scope = ExtensionScope.MODULE)
public interface ClusterFilter extends BaseFilter {}
| 7,898 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/MetricsClusterFilter.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.filter.support;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.metrics.collector.DefaultMetricsCollector;
import org.apache.dubbo.metrics.event.MetricsDispatcher;
import org.apache.dubbo.metrics.event.MetricsEventBus;
import org.apache.dubbo.metrics.event.RequestEvent;
import org.apache.dubbo.metrics.model.MethodMetric;
import org.apache.dubbo.rpc.BaseFilter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.filter.ClusterFilter;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ScopeModelAware;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE;
@Activate(group = CONSUMER, onClass = "org.apache.dubbo.metrics.collector.DefaultMetricsCollector")
public class MetricsClusterFilter implements ClusterFilter, BaseFilter.Listener, ScopeModelAware {
private ApplicationModel applicationModel;
private DefaultMetricsCollector collector;
private String appName;
private MetricsDispatcher metricsDispatcher;
private boolean serviceLevel;
@Override
public void setApplicationModel(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
this.collector = applicationModel.getBeanFactory().getBean(DefaultMetricsCollector.class);
this.appName = applicationModel.tryGetApplicationName();
this.metricsDispatcher = applicationModel.getBeanFactory().getBean(MetricsDispatcher.class);
this.serviceLevel = MethodMetric.isServiceLevel(applicationModel);
}
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
return invoker.invoke(invocation);
}
@Override
public void onResponse(Result result, Invoker<?> invoker, Invocation invocation) {
handleMethodException(result.getException(), invocation);
}
@Override
public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) {
handleMethodException(t, invocation);
}
private void handleMethodException(Throwable t, Invocation invocation) {
if (collector == null || !collector.isCollectEnabled()) {
return;
}
if (t instanceof RpcException) {
RpcException e = (RpcException) t;
if (e.isForbidden()) {
MetricsEventBus.publish(RequestEvent.toRequestErrorEvent(
applicationModel,
appName,
metricsDispatcher,
invocation,
CONSUMER_SIDE,
e.getCode(),
serviceLevel));
}
}
}
}
| 7,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.