├── src
├── main
│ ├── resources
│ │ └── META-INF
│ │ │ └── dubbo
│ │ │ └── org.apache.dubbo.rpc.Filter
│ └── java
│ │ └── com
│ │ └── alibaba
│ │ └── csp
│ │ └── sentinel
│ │ └── adapter
│ │ └── dubbo
│ │ ├── fallback
│ │ ├── DefaultDubboFallback.java
│ │ ├── DubboFallback.java
│ │ └── DubboFallbackRegistry.java
│ │ ├── DubboAppContextFilter.java
│ │ ├── DubboUtils.java
│ │ ├── SentinelDubboConsumerFilter.java
│ │ └── SentinelDubboProviderFilter.java
└── test
│ ├── java
│ └── com
│ │ └── alibaba
│ │ └── csp
│ │ └── sentinel
│ │ ├── adapter
│ │ └── dubbo
│ │ │ ├── provider
│ │ │ ├── DemoService.java
│ │ │ └── impl
│ │ │ │ └── DemoServiceImpl.java
│ │ │ ├── fallback
│ │ │ └── DubboFallbackRegistryTest.java
│ │ │ ├── DubboAppContextFilterTest.java
│ │ │ ├── DubboUtilsTest.java
│ │ │ ├── SentinelDubboConsumerFilterTest.java
│ │ │ └── SentinelDubboProviderFilterTest.java
│ │ └── BaseTest.java
│ └── resources
│ ├── spring-dubbo-consumer-filter.xml
│ └── spring-dubbo-provider-filter.xml
├── .gitignore
├── pom.xml
├── README.md
└── LICENSE
/src/main/resources/META-INF/dubbo/org.apache.dubbo.rpc.Filter:
--------------------------------------------------------------------------------
1 | sentinel.dubbo.provider.filter=com.alibaba.csp.sentinel.adapter.dubbo.SentinelDubboProviderFilter
2 | sentinel.dubbo.consumer.filter=com.alibaba.csp.sentinel.adapter.dubbo.SentinelDubboConsumerFilter
3 | dubbo.application.context.name.filter=com.alibaba.csp.sentinel.adapter.dubbo.DubboAppContextFilter
4 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # IntelliJ project files
2 | .idea/
3 | *.iml
4 | out
5 | gen
6 |
7 | # Maven
8 | target/
9 | pom.xml.tag
10 | pom.xml.releaseBackup
11 | pom.xml.versionsBackup
12 | pom.xml.next
13 | release.properties
14 | dependency-reduced-pom.xml
15 | buildNumber.properties
16 | .mvn/timing.properties
17 | !/.mvn/wrapper/maven-wrapper.jar
18 |
19 | # Eclipse
20 | .classpath
21 | .settings/
22 | .project
23 |
24 | # System related
25 | *.DS_Store
26 | Thumbs.db
27 |
--------------------------------------------------------------------------------
/src/test/java/com/alibaba/csp/sentinel/adapter/dubbo/provider/DemoService.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 1999-2018 Alibaba Group Holding Ltd.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.alibaba.csp.sentinel.adapter.dubbo.provider;
17 |
18 | /**
19 | * @author leyou
20 | */
21 | public interface DemoService {
22 | String sayHello(String name, int n);
23 | }
24 |
--------------------------------------------------------------------------------
/src/test/resources/spring-dubbo-consumer-filter.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/src/test/resources/spring-dubbo-provider-filter.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/src/test/java/com/alibaba/csp/sentinel/adapter/dubbo/provider/impl/DemoServiceImpl.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 1999-2018 Alibaba Group Holding Ltd.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.alibaba.csp.sentinel.adapter.dubbo.provider.impl;
17 |
18 | import com.alibaba.csp.sentinel.adapter.dubbo.provider.DemoService;
19 |
20 | /**
21 | * @author leyou
22 | */
23 | public class DemoServiceImpl implements DemoService {
24 | public String sayHello(String name, int n) {
25 | return "Hello " + name + ", " + n;
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/com/alibaba/csp/sentinel/adapter/dubbo/fallback/DefaultDubboFallback.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 1999-2018 Alibaba Group Holding Ltd.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.alibaba.csp.sentinel.adapter.dubbo.fallback;
17 |
18 | import com.alibaba.csp.sentinel.slots.block.BlockException;
19 | import com.alibaba.csp.sentinel.slots.block.SentinelRpcException;
20 |
21 | import org.apache.dubbo.rpc.Invocation;
22 | import org.apache.dubbo.rpc.Invoker;
23 | import org.apache.dubbo.rpc.Result;
24 |
25 | /**
26 | * @author Eric Zhao
27 | */
28 | public class DefaultDubboFallback implements DubboFallback {
29 |
30 | @Override
31 | public Result handle(Invoker> invoker, Invocation invocation, BlockException ex) {
32 | // Just wrap and throw the exception.
33 | throw new SentinelRpcException(ex);
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/test/java/com/alibaba/csp/sentinel/BaseTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 1999-2018 Alibaba Group Holding Ltd.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.alibaba.csp.sentinel;
17 |
18 | import com.alibaba.csp.sentinel.slots.clusterbuilder.ClusterBuilderSlot;
19 |
20 | import org.apache.dubbo.rpc.RpcContext;
21 |
22 | /**
23 | * Base test class, provide common methods for subClass
24 | * The package is same as CtSph, to call CtSph.resetChainMap() method for test
25 | *
26 | * Note: Only for test. DO NOT USE IN PRODUCTION!
27 | *
28 | * @author cdfive
29 | */
30 | public class BaseTest {
31 |
32 | /**
33 | * Clean up resources for context, clusterNodeMap, processorSlotChainMap
34 | */
35 | protected static void cleanUpAll() {
36 | RpcContext.removeContext();
37 | ClusterBuilderSlot.getClusterNodeMap().clear();
38 | CtSph.resetChainMap();
39 | }
40 | }
--------------------------------------------------------------------------------
/src/main/java/com/alibaba/csp/sentinel/adapter/dubbo/fallback/DubboFallback.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 1999-2018 Alibaba Group Holding Ltd.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.alibaba.csp.sentinel.adapter.dubbo.fallback;
17 |
18 | import com.alibaba.csp.sentinel.slots.block.BlockException;
19 |
20 | import org.apache.dubbo.rpc.Invocation;
21 | import org.apache.dubbo.rpc.Invoker;
22 | import org.apache.dubbo.rpc.Result;
23 |
24 | /**
25 | * Fallback handler for Dubbo services.
26 | *
27 | * @author Eric Zhao
28 | */
29 | @FunctionalInterface
30 | public interface DubboFallback {
31 |
32 | /**
33 | * Handle the block exception and provide fallback result.
34 | *
35 | * @param invoker Dubbo invoker
36 | * @param invocation Dubbo invocation
37 | * @param ex block exception
38 | * @return fallback result
39 | */
40 | Result handle(Invoker> invoker, Invocation invocation, BlockException ex);
41 | }
42 |
--------------------------------------------------------------------------------
/src/main/java/com/alibaba/csp/sentinel/adapter/dubbo/DubboAppContextFilter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 1999-2018 Alibaba Group Holding Ltd.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.alibaba.csp.sentinel.adapter.dubbo;
17 |
18 | import org.apache.dubbo.common.Constants;
19 | import org.apache.dubbo.common.extension.Activate;
20 | import org.apache.dubbo.rpc.Filter;
21 | import org.apache.dubbo.rpc.Invocation;
22 | import org.apache.dubbo.rpc.Invoker;
23 | import org.apache.dubbo.rpc.Result;
24 | import org.apache.dubbo.rpc.RpcContext;
25 | import org.apache.dubbo.rpc.RpcException;
26 |
27 | /**
28 | * Puts current consumer's application name in the attachment of each invocation.
29 | *
30 | * @author Eric Zhao
31 | */
32 | @Activate(group = "consumer")
33 | public class DubboAppContextFilter implements Filter {
34 |
35 | @Override
36 | public Result invoke(Invoker> invoker, Invocation invocation) throws RpcException {
37 | String application = invoker.getUrl().getParameter(Constants.APPLICATION_KEY);
38 | if (application != null) {
39 | RpcContext.getContext().setAttachment(DubboUtils.SENTINEL_DUBBO_APPLICATION_KEY, application);
40 | }
41 | return invoker.invoke(invocation);
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 |
7 | com.alibaba.csp
8 | sentinel-apache-dubbo-adapter
9 | 1.6.0
10 | jar
11 |
12 |
13 | 1.8
14 | 1.8
15 |
16 | 1.6.0
17 | 2.7.22
18 |
19 | 4.12
20 | 2.21.0
21 |
22 |
23 |
24 |
25 | com.alibaba.csp
26 | sentinel-core
27 | ${sentinel.version}
28 |
29 |
30 | org.apache.dubbo
31 | dubbo
32 | ${apache.dubbo.version}
33 | provided
34 |
35 |
36 |
37 | junit
38 | junit
39 | ${junit.version}
40 | test
41 |
42 |
43 | org.mockito
44 | mockito-core
45 | ${mockito.version}
46 | test
47 |
48 |
49 | com.alibaba
50 | fastjson
51 | 1.2.57
52 | test
53 |
54 |
55 |
56 |
--------------------------------------------------------------------------------
/src/main/java/com/alibaba/csp/sentinel/adapter/dubbo/DubboUtils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 1999-2018 Alibaba Group Holding Ltd.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.alibaba.csp.sentinel.adapter.dubbo;
17 |
18 | import org.apache.dubbo.rpc.Invocation;
19 | import org.apache.dubbo.rpc.Invoker;
20 |
21 | /**
22 | * @author Eric Zhao
23 | */
24 | public final class DubboUtils {
25 |
26 | public static final String SENTINEL_DUBBO_APPLICATION_KEY = "dubboApplication";
27 |
28 | public static String getApplication(Invocation invocation, String defaultValue) {
29 | if (invocation == null || invocation.getAttachments() == null) {
30 | throw new IllegalArgumentException("Bad invocation instance");
31 | }
32 | return invocation.getAttachment(SENTINEL_DUBBO_APPLICATION_KEY, defaultValue);
33 | }
34 |
35 | public static String getResourceName(Invoker> invoker, Invocation invocation) {
36 | StringBuilder buf = new StringBuilder(64);
37 | buf.append(invoker.getInterface().getName())
38 | .append(":")
39 | .append(invocation.getMethodName())
40 | .append("(");
41 | boolean isFirst = true;
42 | for (Class> clazz : invocation.getParameterTypes()) {
43 | if (!isFirst) {
44 | buf.append(",");
45 | }
46 | buf.append(clazz.getName());
47 | isFirst = false;
48 | }
49 | buf.append(")");
50 | return buf.toString();
51 | }
52 |
53 | private DubboUtils() {}
54 | }
55 |
--------------------------------------------------------------------------------
/src/test/java/com/alibaba/csp/sentinel/adapter/dubbo/fallback/DubboFallbackRegistryTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 1999-2018 Alibaba Group Holding Ltd.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.alibaba.csp.sentinel.adapter.dubbo.fallback;
17 |
18 | import com.alibaba.csp.sentinel.slots.block.BlockException;
19 | import com.alibaba.csp.sentinel.slots.block.SentinelRpcException;
20 | import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
21 |
22 | import org.apache.dubbo.rpc.Result;
23 | import org.apache.dubbo.rpc.RpcResult;
24 | import org.junit.Assert;
25 | import org.junit.Test;
26 |
27 | /**
28 | * @author Eric Zhao
29 | */
30 | public class DubboFallbackRegistryTest {
31 |
32 | @Test(expected = SentinelRpcException.class)
33 | public void testDefaultFallback() {
34 | // Test for default.
35 | BlockException ex = new FlowException("xxx");
36 | DubboFallbackRegistry.getConsumerFallback()
37 | .handle(null, null, ex);
38 | }
39 |
40 | @Test
41 | public void testCustomFallback() {
42 | BlockException ex = new FlowException("xxx");
43 | DubboFallbackRegistry.setConsumerFallback(
44 | (invoker, invocation, e) -> new RpcResult("Error: " + e.getClass().getName()));
45 | Result result = DubboFallbackRegistry.getConsumerFallback()
46 | .handle(null, null, ex);
47 | Assert.assertFalse("The invocation should not fail", result.hasException());
48 | Assert.assertEquals("Error: " + ex.getClass().getName(), result.getValue());
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/src/main/java/com/alibaba/csp/sentinel/adapter/dubbo/fallback/DubboFallbackRegistry.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 1999-2018 Alibaba Group Holding Ltd.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.alibaba.csp.sentinel.adapter.dubbo.fallback;
17 |
18 | import com.alibaba.csp.sentinel.util.AssertUtil;
19 |
20 | /**
21 | *
Global fallback registry for Dubbo.
22 | *
23 | *
24 | * Note: Circuit breaking is mainly designed for consumer. The provider should not
25 | * give fallback result in most circumstances.
26 | *
27 | *
28 | * @author Eric Zhao
29 | */
30 | public final class DubboFallbackRegistry {
31 |
32 | private static volatile DubboFallback consumerFallback = new DefaultDubboFallback();
33 | private static volatile DubboFallback providerFallback = new DefaultDubboFallback();
34 |
35 | public static DubboFallback getConsumerFallback() {
36 | return consumerFallback;
37 | }
38 |
39 | public static void setConsumerFallback(DubboFallback consumerFallback) {
40 | AssertUtil.notNull(consumerFallback, "consumerFallback cannot be null");
41 | DubboFallbackRegistry.consumerFallback = consumerFallback;
42 | }
43 |
44 | public static DubboFallback getProviderFallback() {
45 | return providerFallback;
46 | }
47 |
48 | public static void setProviderFallback(DubboFallback providerFallback) {
49 | AssertUtil.notNull(providerFallback, "providerFallback cannot be null");
50 | DubboFallbackRegistry.providerFallback = providerFallback;
51 | }
52 |
53 | private DubboFallbackRegistry() {}
54 | }
55 |
--------------------------------------------------------------------------------
/src/test/java/com/alibaba/csp/sentinel/adapter/dubbo/DubboAppContextFilterTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 1999-2018 Alibaba Group Holding Ltd.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.alibaba.csp.sentinel.adapter.dubbo;
17 |
18 | import com.alibaba.csp.sentinel.BaseTest;
19 | import com.alibaba.csp.sentinel.adapter.dubbo.DubboAppContextFilter;
20 | import com.alibaba.csp.sentinel.adapter.dubbo.DubboUtils;
21 |
22 | import org.apache.dubbo.common.URL;
23 | import org.apache.dubbo.rpc.Invocation;
24 | import org.apache.dubbo.rpc.Invoker;
25 | import org.apache.dubbo.rpc.RpcContext;
26 | import org.junit.After;
27 | import org.junit.Before;
28 | import org.junit.Test;
29 |
30 | import static org.junit.Assert.assertEquals;
31 | import static org.junit.Assert.assertNull;
32 | import static org.mockito.Mockito.mock;
33 | import static org.mockito.Mockito.verify;
34 | import static org.mockito.Mockito.when;
35 |
36 | /**
37 | * @author cdfive
38 | */
39 | public class DubboAppContextFilterTest extends BaseTest {
40 |
41 | private DubboAppContextFilter filter = new DubboAppContextFilter();
42 |
43 | @Before
44 | public void setUp() {
45 | cleanUpAll();
46 | }
47 |
48 | @After
49 | public void cleanUp() {
50 | cleanUpAll();
51 | }
52 |
53 | @Test
54 | public void testInvokeApplicationKey() {
55 | Invoker invoker = mock(Invoker.class);
56 | Invocation invocation = mock(Invocation.class);
57 | URL url = URL.valueOf("test://test:111/test?application=serviceA");
58 | when(invoker.getUrl()).thenReturn(url);
59 |
60 | filter.invoke(invoker, invocation);
61 | verify(invoker).invoke(invocation);
62 |
63 | String application = RpcContext.getContext().getAttachment(DubboUtils.SENTINEL_DUBBO_APPLICATION_KEY);
64 | assertEquals("serviceA", application);
65 | }
66 |
67 | @Test
68 | public void testInvokeNullApplicationKey() {
69 | Invoker invoker = mock(Invoker.class);
70 | Invocation invocation = mock(Invocation.class);
71 | URL url = URL.valueOf("test://test:111/test?application=");
72 | when(invoker.getUrl()).thenReturn(url);
73 |
74 | filter.invoke(invoker, invocation);
75 | verify(invoker).invoke(invocation);
76 |
77 | String application = RpcContext.getContext().getAttachment(DubboUtils.SENTINEL_DUBBO_APPLICATION_KEY);
78 | assertNull(application);
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/src/test/java/com/alibaba/csp/sentinel/adapter/dubbo/DubboUtilsTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 1999-2018 Alibaba Group Holding Ltd.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.alibaba.csp.sentinel.adapter.dubbo;
17 |
18 | import java.lang.reflect.Method;
19 | import java.util.HashMap;
20 |
21 | import com.alibaba.csp.sentinel.adapter.dubbo.DubboUtils;
22 | import com.alibaba.csp.sentinel.adapter.dubbo.provider.DemoService;
23 |
24 | import org.apache.dubbo.rpc.Invocation;
25 | import org.apache.dubbo.rpc.Invoker;
26 | import org.junit.Test;
27 |
28 | import static org.junit.Assert.assertEquals;
29 | import static org.junit.Assert.fail;
30 | import static org.mockito.Mockito.mock;
31 | import static org.mockito.Mockito.verify;
32 | import static org.mockito.Mockito.when;
33 |
34 | /**
35 | * @author cdfive
36 | */
37 | public class DubboUtilsTest {
38 |
39 | @Test
40 | public void testGetApplication() {
41 | Invocation invocation = mock(Invocation.class);
42 | when(invocation.getAttachments()).thenReturn(new HashMap<>());
43 | when(invocation.getAttachment(DubboUtils.SENTINEL_DUBBO_APPLICATION_KEY, ""))
44 | .thenReturn("consumerA");
45 |
46 | String application = DubboUtils.getApplication(invocation, "");
47 | verify(invocation).getAttachment(DubboUtils.SENTINEL_DUBBO_APPLICATION_KEY, "");
48 |
49 | assertEquals("consumerA", application);
50 | }
51 |
52 | @Test(expected = IllegalArgumentException.class)
53 | public void testGetApplicationNoAttachments() {
54 | Invocation invocation = mock(Invocation.class);
55 | when(invocation.getAttachments()).thenReturn(null);
56 | when(invocation.getAttachment(DubboUtils.SENTINEL_DUBBO_APPLICATION_KEY, ""))
57 | .thenReturn("consumerA");
58 |
59 | DubboUtils.getApplication(invocation, "");
60 |
61 | fail("No attachments in invocation, IllegalArgumentException should be thrown!");
62 | }
63 |
64 | @Test
65 | public void testGetResourceName() {
66 | Invoker invoker = mock(Invoker.class);
67 | when(invoker.getInterface()).thenReturn(DemoService.class);
68 |
69 | Invocation invocation = mock(Invocation.class);
70 | Method method = DemoService.class.getMethods()[0];
71 | when(invocation.getMethodName()).thenReturn(method.getName());
72 | when(invocation.getParameterTypes()).thenReturn(method.getParameterTypes());
73 |
74 | String resourceName = DubboUtils.getResourceName(invoker, invocation);
75 |
76 | assertEquals("com.alibaba.csp.sentinel.adapter.dubbo.provider.DemoService:sayHello(java.lang.String,int)", resourceName);
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/src/main/java/com/alibaba/csp/sentinel/adapter/dubbo/SentinelDubboConsumerFilter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 1999-2018 Alibaba Group Holding Ltd.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.alibaba.csp.sentinel.adapter.dubbo;
17 |
18 | import com.alibaba.csp.sentinel.Entry;
19 | import com.alibaba.csp.sentinel.EntryType;
20 | import com.alibaba.csp.sentinel.SphU;
21 | import com.alibaba.csp.sentinel.Tracer;
22 | import com.alibaba.csp.sentinel.adapter.dubbo.fallback.DubboFallbackRegistry;
23 | import com.alibaba.csp.sentinel.log.RecordLog;
24 | import com.alibaba.csp.sentinel.slots.block.BlockException;
25 |
26 | import org.apache.dubbo.common.extension.Activate;
27 | import org.apache.dubbo.rpc.Filter;
28 | import org.apache.dubbo.rpc.Invocation;
29 | import org.apache.dubbo.rpc.Invoker;
30 | import org.apache.dubbo.rpc.Result;
31 | import org.apache.dubbo.rpc.RpcException;
32 |
33 | /**
34 | * Dubbo service consumer filter for Sentinel. Auto activated by default.
35 | *
36 | * If you want to disable the consumer filter, you can configure:
37 | *
38 | * <dubbo:consumer filter="-sentinel.dubbo.consumer.filter"/>
39 | *
40 | *
41 | * @author Carpenter Lee
42 | * @author Eric Zhao
43 | */
44 | @Activate(group = "consumer")
45 | public class SentinelDubboConsumerFilter implements Filter {
46 |
47 | public SentinelDubboConsumerFilter() {
48 | RecordLog.info("Sentinel Apache Dubbo consumer filter initialized");
49 | }
50 |
51 | @Override
52 | public Result invoke(Invoker> invoker, Invocation invocation) throws RpcException {
53 | Entry interfaceEntry = null;
54 | Entry methodEntry = null;
55 | try {
56 | String resourceName = DubboUtils.getResourceName(invoker, invocation);
57 | interfaceEntry = SphU.entry(invoker.getInterface().getName(), EntryType.OUT);
58 | methodEntry = SphU.entry(resourceName, EntryType.OUT);
59 |
60 | Result result = invoker.invoke(invocation);
61 | if (result.hasException()) {
62 | Throwable e = result.getException();
63 | // Record common exception.
64 | Tracer.traceEntry(e, interfaceEntry);
65 | Tracer.traceEntry(e, methodEntry);
66 | }
67 | return result;
68 | } catch (BlockException e) {
69 | return DubboFallbackRegistry.getConsumerFallback().handle(invoker, invocation, e);
70 | } catch (RpcException e) {
71 | Tracer.traceEntry(e, interfaceEntry);
72 | Tracer.traceEntry(e, methodEntry);
73 | throw e;
74 | } finally {
75 | if (methodEntry != null) {
76 | methodEntry.exit();
77 | }
78 | if (interfaceEntry != null) {
79 | interfaceEntry.exit();
80 | }
81 | }
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Sentinel Apache Dubbo Adapter
2 |
3 | > Note: 中文文档请见[此处](https://github.com/alibaba/Sentinel/wiki/主流框架的适配#dubbo)。
4 |
5 | Sentinel Dubbo Adapter provides service consumer filter and provider filter
6 | for [Apache Dubbo](https://dubbo.apache.org/en-us/) services.
7 |
8 | **Note: This adapter only supports Apache Dubbo 2.7.x and above.** For legacy `com.alibaba:dubbo` 2.6.x,
9 | please use `sentinel-dubbo-adapter` module instead.
10 |
11 | To use Sentinel Dubbo Adapter, you can simply add the following dependency to your `pom.xml`:
12 |
13 | ```xml
14 |
15 | com.alibaba.csp
16 | sentinel-apache-dubbo-adapter
17 | x.y.z
18 |
19 | ```
20 |
21 | The Sentinel filters are **enabled by default**. Once you add the dependency,
22 | the Dubbo services and methods will become protected resources in Sentinel,
23 | which can leverage Sentinel's flow control and guard ability when rules are configured.
24 | Demos can be found in [sentinel-demo-dubbo](https://github.com/alibaba/Sentinel/tree/master/sentinel-demo/sentinel-demo-dubbo).
25 |
26 | If you don't want the filters enabled, you can manually disable them. For example:
27 |
28 | ```xml
29 |
30 |
31 |
32 | ```
33 |
34 | For more details of Dubbo filter, see [here](http://dubbo.apache.org/en-us/docs/dev/impls/filter.html).
35 |
36 | ## Dubbo resources
37 |
38 | The resource for Dubbo services has two granularities: service interface and service method.
39 |
40 | - Service interface:resourceName format is `interfaceName`,e.g. `com.alibaba.csp.sentinel.demo.dubbo.FooService`
41 | - Service method:resourceName format is `interfaceName:methodSignature`,e.g. `com.alibaba.csp.sentinel.demo.dubbo.FooService:sayHello(java.lang.String)`
42 |
43 | ## Flow control based on caller
44 |
45 | In many circumstances, it's also significant to control traffic flow based on the **caller**.
46 | For example, assuming that there are two services A and B, both of them initiate remote call requests to the service provider.
47 | If we want to limit the calls from service B only, we can set the `limitApp` of flow rule as the identifier of service B (e.g. service name).
48 |
49 | Sentinel Dubbo Adapter will automatically resolve the Dubbo consumer's *application name* as the caller's name (`origin`),
50 | and will bring the caller's name when doing resource protection.
51 | If `limitApp` of flow rules is not configured (`default`), flow control will take effects on all callers.
52 | If `limitApp` of a flow rule is configured with a caller, then the corresponding flow rule will only take effect on the specific caller.
53 |
54 | > Note: Dubbo consumer does not provide its Dubbo application name when doing RPC,
55 | so developers should manually put the application name into *attachment* at consumer side,
56 | then extract it at provider side. Sentinel Dubbo Adapter has implemented a filter (`DubboAppContextFilter`)
57 | where consumer can carry application name information to provider automatically.
58 | If the consumer does not use Sentinel Dubbo Adapter but requires flow control based on caller, developers can manually put the application name into attachment with the key `dubboApplication`.
59 |
60 | ## Global fallback
61 |
62 | Sentinel Dubbo Adapter supports global fallback configuration.
63 | The global fallback will handle exceptions and give replacement result when blocked by
64 | flow control, degrade or system load protection. You can implement your own `DubboFallback` interface
65 | and then register to `DubboFallbackRegistry`. If no fallback is configured, Sentinel will wrap the `BlockException`
66 | then directly throw it out.
67 |
68 | Besides, we can also leverage [Dubbo mock mechanism](http://dubbo.apache.org/en-us/docs/user/demos/local-mock.html) to provide fallback implementation of degraded Dubbo services.
--------------------------------------------------------------------------------
/src/main/java/com/alibaba/csp/sentinel/adapter/dubbo/SentinelDubboProviderFilter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 1999-2018 Alibaba Group Holding Ltd.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.alibaba.csp.sentinel.adapter.dubbo;
17 |
18 | import com.alibaba.csp.sentinel.Entry;
19 | import com.alibaba.csp.sentinel.EntryType;
20 | import com.alibaba.csp.sentinel.SphU;
21 | import com.alibaba.csp.sentinel.Tracer;
22 | import com.alibaba.csp.sentinel.adapter.dubbo.fallback.DubboFallbackRegistry;
23 | import com.alibaba.csp.sentinel.context.ContextUtil;
24 | import com.alibaba.csp.sentinel.log.RecordLog;
25 | import com.alibaba.csp.sentinel.slots.block.BlockException;
26 |
27 | import org.apache.dubbo.common.extension.Activate;
28 | import org.apache.dubbo.rpc.Filter;
29 | import org.apache.dubbo.rpc.Invocation;
30 | import org.apache.dubbo.rpc.Invoker;
31 | import org.apache.dubbo.rpc.Result;
32 | import org.apache.dubbo.rpc.RpcException;
33 |
34 | /**
35 | * Apache Dubbo service provider filter that enables integration with Sentinel. Auto activated by default.
36 | * Note: this only works for Apache Dubbo 2.7.x or above version.
37 | *
38 | * If you want to disable the provider filter, you can configure:
39 | *
40 | * <dubbo:provider filter="-sentinel.dubbo.provider.filter"/>
41 | *
42 | *
43 | * @author Carpenter Lee
44 | * @author Eric Zhao
45 | */
46 | @Activate(group = "provider")
47 | public class SentinelDubboProviderFilter implements Filter {
48 |
49 | public SentinelDubboProviderFilter() {
50 | RecordLog.info("Sentinel Apache Dubbo provider filter initialized");
51 | }
52 |
53 | @Override
54 | public Result invoke(Invoker> invoker, Invocation invocation) throws RpcException {
55 | // Get origin caller.
56 | String application = DubboUtils.getApplication(invocation, "");
57 |
58 | Entry interfaceEntry = null;
59 | Entry methodEntry = null;
60 | try {
61 | String resourceName = DubboUtils.getResourceName(invoker, invocation);
62 | String interfaceName = invoker.getInterface().getName();
63 | // Only need to create entrance context at provider side, as context will take effect
64 | // at entrance of invocation chain only (for inbound traffic).
65 | ContextUtil.enter(resourceName, application);
66 | interfaceEntry = SphU.entry(interfaceName, EntryType.IN);
67 | methodEntry = SphU.entry(resourceName, EntryType.IN, 1, invocation.getArguments());
68 |
69 | Result result = invoker.invoke(invocation);
70 | if (result.hasException()) {
71 | Throwable e = result.getException();
72 | // Record common exception.
73 | Tracer.traceEntry(e, interfaceEntry);
74 | Tracer.traceEntry(e, methodEntry);
75 | }
76 | return result;
77 | } catch (BlockException e) {
78 | return DubboFallbackRegistry.getProviderFallback().handle(invoker, invocation, e);
79 | } catch (RpcException e) {
80 | Tracer.traceEntry(e, interfaceEntry);
81 | Tracer.traceEntry(e, methodEntry);
82 | throw e;
83 | } finally {
84 | if (methodEntry != null) {
85 | methodEntry.exit(1, invocation.getArguments());
86 | }
87 | if (interfaceEntry != null) {
88 | interfaceEntry.exit();
89 | }
90 | ContextUtil.exit();
91 | }
92 | }
93 | }
94 |
--------------------------------------------------------------------------------
/src/test/java/com/alibaba/csp/sentinel/adapter/dubbo/SentinelDubboConsumerFilterTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 1999-2018 Alibaba Group Holding Ltd.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.alibaba.csp.sentinel.adapter.dubbo;
17 |
18 | import java.lang.reflect.Method;
19 | import java.util.Map;
20 | import java.util.Set;
21 |
22 | import com.alibaba.csp.sentinel.BaseTest;
23 | import com.alibaba.csp.sentinel.Constants;
24 | import com.alibaba.csp.sentinel.Entry;
25 | import com.alibaba.csp.sentinel.EntryType;
26 | import com.alibaba.csp.sentinel.adapter.dubbo.DubboUtils;
27 | import com.alibaba.csp.sentinel.adapter.dubbo.SentinelDubboConsumerFilter;
28 | import com.alibaba.csp.sentinel.adapter.dubbo.provider.DemoService;
29 | import com.alibaba.csp.sentinel.context.Context;
30 | import com.alibaba.csp.sentinel.context.ContextUtil;
31 | import com.alibaba.csp.sentinel.node.ClusterNode;
32 | import com.alibaba.csp.sentinel.node.DefaultNode;
33 | import com.alibaba.csp.sentinel.node.Node;
34 | import com.alibaba.csp.sentinel.node.StatisticNode;
35 | import com.alibaba.csp.sentinel.slotchain.ResourceWrapper;
36 |
37 | import org.apache.dubbo.rpc.Invocation;
38 | import org.apache.dubbo.rpc.Invoker;
39 | import org.apache.dubbo.rpc.Result;
40 | import org.junit.After;
41 | import org.junit.Before;
42 | import org.junit.Test;
43 |
44 | import static org.junit.Assert.assertEquals;
45 | import static org.junit.Assert.assertNotNull;
46 | import static org.junit.Assert.assertNotSame;
47 | import static org.junit.Assert.assertNull;
48 | import static org.junit.Assert.assertSame;
49 | import static org.mockito.Mockito.mock;
50 | import static org.mockito.Mockito.verify;
51 | import static org.mockito.Mockito.when;
52 |
53 | /**
54 | * @author cdfive
55 | */
56 | public class SentinelDubboConsumerFilterTest extends BaseTest {
57 |
58 | private SentinelDubboConsumerFilter filter = new SentinelDubboConsumerFilter();
59 |
60 | @Before
61 | public void setUp() {
62 | cleanUpAll();
63 | }
64 |
65 | @After
66 | public void cleanUp() {
67 | cleanUpAll();
68 | }
69 |
70 | @Test
71 | public void testInvoke() {
72 | final Invoker invoker = mock(Invoker.class);
73 | when(invoker.getInterface()).thenReturn(DemoService.class);
74 |
75 | final Invocation invocation = mock(Invocation.class);
76 | Method method = DemoService.class.getMethods()[0];
77 | when(invocation.getMethodName()).thenReturn(method.getName());
78 | when(invocation.getParameterTypes()).thenReturn(method.getParameterTypes());
79 |
80 | final Result result = mock(Result.class);
81 | when(result.hasException()).thenReturn(false);
82 | when(invoker.invoke(invocation)).thenAnswer(invocationOnMock -> {
83 | verifyInvocationStructure(invoker, invocation);
84 | return result;
85 | });
86 |
87 | filter.invoke(invoker, invocation);
88 | verify(invoker).invoke(invocation);
89 |
90 | Context context = ContextUtil.getContext();
91 | assertNull(context);
92 | }
93 |
94 | /**
95 | * Simply verify invocation structure in memory:
96 | * EntranceNode(defaultContextName)
97 | * --InterfaceNode(interfaceName)
98 | * ----MethodNode(resourceName)
99 | */
100 | private void verifyInvocationStructure(Invoker invoker, Invocation invocation) {
101 | Context context = ContextUtil.getContext();
102 | assertNotNull(context);
103 |
104 | // As not call ContextUtil.enter(resourceName, application) in SentinelDubboConsumerFilter, use default context
105 | // In actual project, a consumer is usually also a provider, the context will be created by SentinelDubboProviderFilter
106 | // If consumer is on the top of Dubbo RPC invocation chain, use default context
107 | String resourceName = DubboUtils.getResourceName(invoker, invocation);
108 | assertEquals(Constants.CONTEXT_DEFAULT_NAME, context.getName());
109 | assertEquals("", context.getOrigin());
110 |
111 | DefaultNode entranceNode = context.getEntranceNode();
112 | ResourceWrapper entranceResource = entranceNode.getId();
113 | assertEquals(Constants.CONTEXT_DEFAULT_NAME, entranceResource.getName());
114 | assertSame(EntryType.IN, entranceResource.getType());
115 |
116 | // As SphU.entry(interfaceName, EntryType.OUT);
117 | Set childList = entranceNode.getChildList();
118 | assertEquals(1, childList.size());
119 | DefaultNode interfaceNode = (DefaultNode) childList.iterator().next();
120 | ResourceWrapper interfaceResource = interfaceNode.getId();
121 | assertEquals(DemoService.class.getName(), interfaceResource.getName());
122 | assertSame(EntryType.OUT, interfaceResource.getType());
123 |
124 | // As SphU.entry(resourceName, EntryType.OUT);
125 | childList = interfaceNode.getChildList();
126 | assertEquals(1, childList.size());
127 | DefaultNode methodNode = (DefaultNode) childList.iterator().next();
128 | ResourceWrapper methodResource = methodNode.getId();
129 | assertEquals(resourceName, methodResource.getName());
130 | assertSame(EntryType.OUT, methodResource.getType());
131 |
132 | // Verify curEntry
133 | Entry curEntry = context.getCurEntry();
134 | assertSame(methodNode, curEntry.getCurNode());
135 | assertSame(interfaceNode, curEntry.getLastNode());
136 | assertNull(curEntry.getOriginNode());// As context origin is not "", no originNode should be created in curEntry
137 |
138 | // Verify clusterNode
139 | ClusterNode methodClusterNode = methodNode.getClusterNode();
140 | ClusterNode interfaceClusterNode = interfaceNode.getClusterNode();
141 | assertNotSame(methodClusterNode, interfaceClusterNode);// Different resource->Different ProcessorSlot->Different ClusterNode
142 |
143 | // As context origin is "", the StatisticNode should not be created in originCountMap of ClusterNode
144 | Map methodOriginCountMap = methodClusterNode.getOriginCountMap();
145 | assertEquals(0, methodOriginCountMap.size());
146 |
147 | Map interfaceOriginCountMap = interfaceClusterNode.getOriginCountMap();
148 | assertEquals(0, interfaceOriginCountMap.size());
149 | }
150 | }
151 |
--------------------------------------------------------------------------------
/src/test/java/com/alibaba/csp/sentinel/adapter/dubbo/SentinelDubboProviderFilterTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 1999-2018 Alibaba Group Holding Ltd.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.alibaba.csp.sentinel.adapter.dubbo;
17 |
18 | import java.lang.reflect.Method;
19 | import java.util.Map;
20 | import java.util.Set;
21 |
22 | import com.alibaba.csp.sentinel.BaseTest;
23 | import com.alibaba.csp.sentinel.Entry;
24 | import com.alibaba.csp.sentinel.EntryType;
25 | import com.alibaba.csp.sentinel.adapter.dubbo.DubboUtils;
26 | import com.alibaba.csp.sentinel.adapter.dubbo.SentinelDubboProviderFilter;
27 | import com.alibaba.csp.sentinel.adapter.dubbo.provider.DemoService;
28 | import com.alibaba.csp.sentinel.context.Context;
29 | import com.alibaba.csp.sentinel.context.ContextUtil;
30 | import com.alibaba.csp.sentinel.node.ClusterNode;
31 | import com.alibaba.csp.sentinel.node.DefaultNode;
32 | import com.alibaba.csp.sentinel.node.Node;
33 | import com.alibaba.csp.sentinel.node.StatisticNode;
34 | import com.alibaba.csp.sentinel.slotchain.ResourceWrapper;
35 |
36 | import org.apache.dubbo.rpc.Invocation;
37 | import org.apache.dubbo.rpc.Invoker;
38 | import org.apache.dubbo.rpc.Result;
39 | import org.junit.After;
40 | import org.junit.Before;
41 | import org.junit.Test;
42 |
43 | import static org.junit.Assert.assertEquals;
44 | import static org.junit.Assert.assertNotNull;
45 | import static org.junit.Assert.assertNotSame;
46 | import static org.junit.Assert.assertNull;
47 | import static org.junit.Assert.assertSame;
48 | import static org.junit.Assert.assertTrue;
49 | import static org.mockito.Mockito.mock;
50 | import static org.mockito.Mockito.verify;
51 | import static org.mockito.Mockito.when;
52 |
53 | /**
54 | * @author cdfive
55 | */
56 | public class SentinelDubboProviderFilterTest extends BaseTest {
57 |
58 | private SentinelDubboProviderFilter filter = new SentinelDubboProviderFilter();
59 |
60 | @Before
61 | public void setUp() {
62 | cleanUpAll();
63 | }
64 |
65 | @After
66 | public void cleanUp() {
67 | cleanUpAll();
68 | }
69 |
70 | @Test
71 | public void testInvoke() {
72 | final String originApplication = "consumerA";
73 |
74 | final Invoker invoker = mock(Invoker.class);
75 | when(invoker.getInterface()).thenReturn(DemoService.class);
76 |
77 | final Invocation invocation = mock(Invocation.class);
78 | Method method = DemoService.class.getMethods()[0];
79 | when(invocation.getMethodName()).thenReturn(method.getName());
80 | when(invocation.getParameterTypes()).thenReturn(method.getParameterTypes());
81 | when(invocation.getAttachment(DubboUtils.SENTINEL_DUBBO_APPLICATION_KEY, ""))
82 | .thenReturn(originApplication);
83 |
84 | final Result result = mock(Result.class);
85 | when(result.hasException()).thenReturn(false);
86 | when(invoker.invoke(invocation)).thenAnswer(invocationOnMock -> {
87 | verifyInvocationStructure(originApplication, invoker, invocation);
88 | return result;
89 | });
90 |
91 | filter.invoke(invoker, invocation);
92 | verify(invoker).invoke(invocation);
93 |
94 | Context context = ContextUtil.getContext();
95 | assertNull(context);
96 | }
97 |
98 | /**
99 | * Simply verify invocation structure in memory:
100 | * EntranceNode(resourceName)
101 | * --InterfaceNode(interfaceName)
102 | * ----MethodNode(resourceName)
103 | */
104 | private void verifyInvocationStructure(String originApplication, Invoker invoker, Invocation invocation) {
105 | Context context = ContextUtil.getContext();
106 | assertNotNull(context);
107 |
108 | // As ContextUtil.enter(resourceName, application) in SentinelDubboProviderFilter
109 | String resourceName = DubboUtils.getResourceName(invoker, invocation);
110 | assertEquals(resourceName, context.getName());
111 | assertEquals(originApplication, context.getOrigin());
112 |
113 | DefaultNode entranceNode = context.getEntranceNode();
114 | ResourceWrapper entranceResource = entranceNode.getId();
115 | assertEquals(resourceName, entranceResource.getName());
116 | assertSame(EntryType.IN, entranceResource.getType());
117 |
118 | // As SphU.entry(interfaceName, EntryType.IN);
119 | Set childList = entranceNode.getChildList();
120 | assertEquals(1, childList.size());
121 | DefaultNode interfaceNode = (DefaultNode) childList.iterator().next();
122 | ResourceWrapper interfaceResource = interfaceNode.getId();
123 | assertEquals(DemoService.class.getName(), interfaceResource.getName());
124 | assertSame(EntryType.IN, interfaceResource.getType());
125 |
126 | // As SphU.entry(resourceName, EntryType.IN, 1, invocation.getArguments());
127 | childList = interfaceNode.getChildList();
128 | assertEquals(1, childList.size());
129 | DefaultNode methodNode = (DefaultNode) childList.iterator().next();
130 | ResourceWrapper methodResource = methodNode.getId();
131 | assertEquals(resourceName, methodResource.getName());
132 | assertSame(EntryType.IN, methodResource.getType());
133 |
134 | // Verify curEntry
135 | Entry curEntry = context.getCurEntry();
136 | assertSame(methodNode, curEntry.getCurNode());
137 | assertSame(interfaceNode, curEntry.getLastNode());
138 | assertNotNull(curEntry.getOriginNode());// As context origin is not "", originNode should be created
139 |
140 | // Verify clusterNode
141 | ClusterNode methodClusterNode = methodNode.getClusterNode();
142 | ClusterNode interfaceClusterNode = interfaceNode.getClusterNode();
143 | assertNotSame(methodClusterNode, interfaceClusterNode);// Different resource->Different ProcessorSlot->Different ClusterNode
144 |
145 | // As context origin is not "", the StatisticNode should be created in originCountMap of ClusterNode
146 | Map methodOriginCountMap = methodClusterNode.getOriginCountMap();
147 | assertEquals(1, methodOriginCountMap.size());
148 | assertTrue(methodOriginCountMap.containsKey(originApplication));
149 |
150 | Map interfaceOriginCountMap = interfaceClusterNode.getOriginCountMap();
151 | assertEquals(1, interfaceOriginCountMap.size());
152 | assertTrue(interfaceOriginCountMap.containsKey(originApplication));
153 | }
154 | }
155 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------