com.alibaba.csp.sentinel.slots.clusterbuilder.ClusterBuilderSlot Java Examples

The following examples show how to use com.alibaba.csp.sentinel.slots.clusterbuilder.ClusterBuilderSlot. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MonoSentinelOperatorIntegrationTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Test
public void testEmitExceptionWhenFlowControlTriggered() {
    String resourceName = createResourceName("testEmitExceptionWhenFlowControlTriggered");
    FlowRuleManager.loadRules(Collections.singletonList(
        new FlowRule(resourceName).setCount(0)
    ));
    StepVerifier.create(Mono.error(new IllegalStateException("some"))
        .transform(new SentinelReactorTransformer<>(resourceName)))
        .expectError(BlockException.class)
        .verify();

    ClusterNode cn = ClusterBuilderSlot.getClusterNode(resourceName);
    assertNotNull(cn);
    assertEquals(0, cn.passQps(), 0.01);
    assertEquals(1, cn.blockRequest());

    FlowRuleManager.loadRules(new ArrayList<>());
}
 
Example #2
Source File: FetchSimpleClusterNodeCommandHandler.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Override
public CommandResponse<String> handle(CommandRequest request) {
    /*
     * type==notZero means nodes whose totalRequest <= 0 will be ignored.
     */
    String type = request.getParam("type");
    List<NodeVo> list = new ArrayList<NodeVo>();
    Map<ResourceWrapper, ClusterNode> map = ClusterBuilderSlot.getClusterNodeMap();
    if (map == null) {
        return CommandResponse.ofSuccess(JSONArray.toJSONString(list));
    }
    for (Map.Entry<ResourceWrapper, ClusterNode> entry : map.entrySet()) {
        if ("notZero".equalsIgnoreCase(type)) {
            if (entry.getValue().totalRequest() > 0) {
                list.add(NodeVo.fromClusterNode(entry.getKey(), entry.getValue()));
            }
        } else {
            list.add(NodeVo.fromClusterNode(entry.getKey(), entry.getValue()));
        }
    }
    return CommandResponse.ofSuccess(JSONArray.toJSONString(list));
}
 
Example #3
Source File: FlowRuleChecker.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
static Node selectReferenceNode(FlowRule rule, Context context, DefaultNode node) {
    String refResource = rule.getRefResource();
    int strategy = rule.getStrategy();

    if (StringUtil.isEmpty(refResource)) {
        return null;
    }

    if (strategy == RuleConstant.STRATEGY_RELATE) {
        return ClusterBuilderSlot.getClusterNode(refResource);
    }

    if (strategy == RuleConstant.STRATEGY_CHAIN) {
        if (!refResource.equals(context.getName())) {
            return null;
        }
        return node;
    }
    // No node.
    return null;
}
 
Example #4
Source File: ProviderFilterTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Test
public void testUrlPathParam() {
    String url = "/test/hello/{name}";
    String resourceName = "GET:" + url;

    String url1 = "/test/hello/abc";
    Response response1 = given().get(url1);
    response1.then().statusCode(200).body(equalTo("Hello abc !"));

    String url2 = "/test/hello/def";
    Response response2 = given().get(url2);
    response2.then().statusCode(200).body(equalTo("Hello def !"));

    ClusterNode cn = ClusterBuilderSlot.getClusterNode(resourceName);
    assertNotNull(cn);
    assertEquals(2, cn.passQps(), 0.01);

    assertNull(ClusterBuilderSlot.getClusterNode("GET:" + url1));
    assertNull(ClusterBuilderSlot.getClusterNode("GET:" + url2));
}
 
Example #5
Source File: SentinelJaxRsQuarkusAdapterTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetHello() {
    String url = "/test/hello";
    String resourceName = "GET:" + url;
    Response response = given().get(url);
    response.then().statusCode(200).body(equalTo(HELLO_STR));

    ClusterNode cn = ClusterBuilderSlot.getClusterNode(resourceName);
    assertNotNull(cn);
    assertEquals(1, cn.passQps(), 0.01);

    String context = "";
    for (Node n : Constants.ROOT.getChildList()) {
        if (n instanceof EntranceNode) {
            String id = ((EntranceNode) n).getId().getName();
            if (url.equals(id)) {
                context = ((EntranceNode) n).getId().getName();
            }
        }
    }
    assertEquals("", context);
}
 
Example #6
Source File: SentinelGrpcClientInterceptorTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Test
public void testGrpcClientInterceptor() throws Exception {
    final int port = 19328;

    configureFlowRule(threshold);
    server.start(port, false);

    FooServiceClient client = new FooServiceClient("localhost", port, new SentinelGrpcClientInterceptor());

    assertTrue(sendRequest(client));
    ClusterNode clusterNode = ClusterBuilderSlot.getClusterNode(resourceName, EntryType.OUT);
    assertNotNull(clusterNode);
    assertEquals(1, clusterNode.totalRequest() - clusterNode.blockRequest());

    // Not allowed to pass.
    configureFlowRule(0);

    // The second request will be blocked.
    assertFalse(sendRequest(client));
    assertEquals(1, clusterNode.blockRequest());

    server.stop();
}
 
Example #7
Source File: ClientFilterTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Test
public void testServerReturn400() {
    final String url = "/test/400";
    final String resourceName = "GET:" + url;
    Response response = SentinelJaxRsClientTemplate.execute(resourceName, new Supplier<Response>() {
        @Override
        public Response get() {
            return client.target(host).path(url).request()
                    .get();
        }
    });
    assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());
    assertEquals("test return 400", response.readEntity(String.class));


    ClusterNode cn = ClusterBuilderSlot.getClusterNode(resourceName);
    assertNotNull(cn);
    assertEquals(1, cn.passQps(), 0.01);
}
 
Example #8
Source File: SentinelGrpcServerInterceptorTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Test
public void testGrpcServerInterceptor() throws Exception {
    final int port = 19329;
    client = new FooServiceClient("localhost", port);

    configureFlowRule(threshold);
    server.start(port, true);

    assertTrue(sendRequest());
    ClusterNode clusterNode = ClusterBuilderSlot.getClusterNode(resourceName, EntryType.IN);
    assertNotNull(clusterNode);
    assertEquals(1, clusterNode.totalRequest() - clusterNode.blockRequest());

    // Not allowed to pass.
    configureFlowRule(0);

    // The second request will be blocked.
    assertFalse(sendRequest());
    assertEquals(1, clusterNode.blockRequest());

    server.stop();
}
 
Example #9
Source File: ClientFilterTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@AfterClass
public static void shutdown() {
    ctx.close();

    Context context = ContextUtil.getContext();
    if (context != null) {
        context.setCurEntry(null);
        ContextUtil.exit();
    }

    Constants.ROOT.removeChildList();

    ClusterBuilderSlot.getClusterNodeMap().clear();

    // Clear chainMap in CtSph
    try {
        Method resetChainMapMethod = CtSph.class.getDeclaredMethod("resetChainMap");
        resetChainMapMethod.setAccessible(true);
        resetChainMapMethod.invoke(null);
    } catch (Exception e) {
        // Empty
    }
}
 
Example #10
Source File: CommonFilterContextTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Test
public void testCommonFilterMiscellaneous() throws Exception {
    String url = "/hello";
    this.mvc.perform(get(url))
            .andExpect(status().isOk())
            .andExpect(content().string(HELLO_STR));

    ClusterNode cn = ClusterBuilderSlot.getClusterNode(url);
    assertNotNull(cn);
    assertEquals(1, cn.passQps(), 0.01);
    String context = "";
    for (Node n : Constants.ROOT.getChildList()) {
        if (n instanceof EntranceNode) {
            String id = ((EntranceNode) n).getId().getName();
            if (url.equals(id)) {
                context = ((EntranceNode) n).getId().getName();
            }
        }
    }
    assertEquals(url, context);
}
 
Example #11
Source File: CommonFilterTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Test
public void testCommonFilterMiscellaneous() throws Exception {
    String url = "/hello";
    this.mvc.perform(get(url))
        .andExpect(status().isOk())
        .andExpect(content().string(HELLO_STR));

    ClusterNode cn = ClusterBuilderSlot.getClusterNode(url);
    assertNotNull(cn);
    assertEquals(1, cn.passQps(), 0.01);

    testCommonBlockAndRedirectBlockPage(url, cn);

    // Test for url cleaner.
    testUrlCleaner();

    testCustomOriginParser();
}
 
Example #12
Source File: FluxSentinelOperatorTestIntegrationTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Test
public void testEmitMultipleValuesWhenFlowControlTriggered() {
    String resourceName = createResourceName("testEmitMultipleValuesWhenFlowControlTriggered");
    FlowRuleManager.loadRules(Collections.singletonList(
        new FlowRule(resourceName).setCount(0)
    ));
    StepVerifier.create(Flux.just(1, 3, 5)
        .map(e -> e * 2)
        .transform(new SentinelReactorTransformer<>(resourceName)))
        .expectError(BlockException.class)
        .verify();

    ClusterNode cn = ClusterBuilderSlot.getClusterNode(resourceName);
    assertNotNull(cn);
    assertEquals(0, cn.passQps(), 0.01);
    assertEquals(1, cn.blockRequest());

    FlowRuleManager.loadRules(new ArrayList<>());
}
 
Example #13
Source File: ClientFilterTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Test
public void testClientFallback() {
    final String url = "/test/hello";
    final String resourceName = "GET:" + url;
    configureRulesFor(resourceName, 0);

    Response response = SentinelJaxRsClientTemplate.execute(resourceName, new Supplier<Response>() {
        @Override
        public Response get() {
            return client.target(host).path(url).request()
                    .get();
        }
    });
    assertEquals(javax.ws.rs.core.Response.Status.TOO_MANY_REQUESTS.getStatusCode(), response.getStatus());
    assertEquals("Blocked by Sentinel (flow limiting)", response.readEntity(String.class));


    ClusterNode cn = ClusterBuilderSlot.getClusterNode(resourceName);
    assertNotNull(cn);
    assertEquals(0, cn.passQps(), 0.01);
}
 
Example #14
Source File: SentinelAnnotationInterceptorIntegrationTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Test
public void testDefaultFallbackWithSingleParam() {
    assertThat(fooService.anotherFoo(1)).isEqualTo("Hello for 1");
    String resourceName = "apiAnotherFooWithDefaultFallback";
    ClusterNode cn = ClusterBuilderSlot.getClusterNode(resourceName);
    assertThat(cn).isNotNull();
    assertThat(cn.passQps()).isPositive();

    // Default fallback should take effect.
    assertThat(fooService.anotherFoo(5758)).isEqualTo(FooUtil.FALLBACK_DEFAULT_RESULT);
    assertThat(cn.exceptionQps()).isPositive();
    assertThat(cn.blockQps()).isZero();

    FlowRuleManager.loadRules(Collections.singletonList(
            new FlowRule(resourceName).setCount(0)
    ));
    // Default fallback should also take effect for BlockException.
    assertThat(fooService.anotherFoo(5758)).isEqualTo(FooUtil.FALLBACK_DEFAULT_RESULT);
    assertThat(cn.blockQps()).isPositive();
}
 
Example #15
Source File: MonoSentinelOperatorIntegrationTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Test
public void testEmitSingleValueWhenFlowControlTriggered() {
    String resourceName = createResourceName("testEmitSingleValueWhenFlowControlTriggered");
    FlowRuleManager.loadRules(Collections.singletonList(
        new FlowRule(resourceName).setCount(0)
    ));
    StepVerifier.create(Mono.just(1)
        .map(e -> e * 2)
        .transform(new SentinelReactorTransformer<>(resourceName)))
        .expectError(BlockException.class)
        .verify();

    ClusterNode cn = ClusterBuilderSlot.getClusterNode(resourceName);
    assertNotNull(cn);
    assertEquals(0, cn.passQps(), 0.01);
    assertEquals(1, cn.blockRequest());

    FlowRuleManager.loadRules(new ArrayList<>());
}
 
Example #16
Source File: ReactorSphUTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Test
public void testReactorEntryNormalWhenFlowControlTriggered() {
    String resourceName = createResourceName("testReactorEntryNormalWhenFlowControlTriggered");
    FlowRuleManager.loadRules(Collections.singletonList(
        new FlowRule(resourceName).setCount(0)
    ));
    StepVerifier.create(ReactorSphU.entryWith(resourceName, Mono.just(60))
        .subscribeOn(Schedulers.elastic())
        .map(e -> e * 3))
        .expectError(BlockException.class)
        .verify();

    ClusterNode cn = ClusterBuilderSlot.getClusterNode(resourceName);
    assertNotNull(cn);
    assertEquals(0, cn.passQps(), 0.01);
    assertEquals(1, cn.blockRequest());

    FlowRuleManager.loadRules(new ArrayList<>());
}
 
Example #17
Source File: SentinelAnnotationIntegrationTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Test
public void testDefaultFallbackWithSingleParam() {
    assertThat(fooService.anotherFoo(1)).isEqualTo("Hello for 1");
    String resourceName = "apiAnotherFooWithDefaultFallback";
    ClusterNode cn = ClusterBuilderSlot.getClusterNode(resourceName);
    assertThat(cn).isNotNull();
    assertThat(cn.passQps()).isPositive();

    // Default fallback should take effect.
    assertThat(fooService.anotherFoo(5758)).isEqualTo(FooUtil.FALLBACK_DEFAULT_RESULT);
    assertThat(cn.exceptionQps()).isPositive();
    assertThat(cn.blockQps()).isZero();

    FlowRuleManager.loadRules(Collections.singletonList(
        new FlowRule(resourceName).setCount(0)
    ));
    // Default fallback should also take effect for BlockException.
    assertThat(fooService.anotherFoo(5758)).isEqualTo(FooUtil.FALLBACK_DEFAULT_RESULT);
    assertThat(cn.blockQps()).isPositive();
}
 
Example #18
Source File: FlowRuleChecker.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
static Node selectReferenceNode(FlowRule rule, Context context, DefaultNode node) {
    String refResource = rule.getRefResource();
    int strategy = rule.getStrategy();

    if (StringUtil.isEmpty(refResource)) {
        return null;
    }

    if (strategy == RuleConstant.STRATEGY_RELATE) {
        return ClusterBuilderSlot.getClusterNode(refResource);
    }

    if (strategy == RuleConstant.STRATEGY_CHAIN) {
        if (!refResource.equals(context.getName())) {
            return null;
        }
        return node;
    }
    // No node.
    return null;
}
 
Example #19
Source File: SentinelWebFluxIntegrationTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Test
public void testCustomizedIgnoreUrlCleaner() throws Exception {
    final String fooPrefix = "/foo/";
    String url1 = fooPrefix + 1;
    WebFluxCallbackManager.setUrlCleaner(((exchange, originUrl) -> {
        if (originUrl.startsWith(fooPrefix)) {
            return "";
        }
        return originUrl;
    }));
    this.webClient.get()
            .uri(url1)
            .exchange()
            .expectStatus().isOk()
            .expectBody(String.class).isEqualTo("Hello 1");

    assertNull(ClusterBuilderSlot.getClusterNode(url1));
    WebFluxCallbackManager.resetUrlCleaner();
}
 
Example #20
Source File: ClientFilterTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Test
public void testServerReturn500() {
    final String url = "/test/ex";
    final String resourceName = "GET:" + url;
    Response response = SentinelJaxRsClientTemplate.execute(resourceName, new Supplier<Response>() {
        @Override
        public Response get() {
            return client.target(host).path(url).request()
                    .get();
        }
    });
    assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatus());
    assertEquals("test exception mapper", response.readEntity(String.class));


    ClusterNode cn = ClusterBuilderSlot.getClusterNode(resourceName);
    assertNotNull(cn);
    assertEquals(1, cn.passQps(), 0.01);
}
 
Example #21
Source File: SentinelAnnotationIntegrationTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Test
public void testClassLevelDefaultFallbackWithSingleParam() {
    assertThat(barService.anotherBar(1)).isEqualTo("Hello for 1");
    String resourceName = "apiAnotherBarWithDefaultFallback";
    ClusterNode cn = ClusterBuilderSlot.getClusterNode(resourceName);
    assertThat(cn).isNotNull();
    assertThat(cn.passQps()).isPositive();

    assertThat(barService.doSomething(1)).isEqualTo("do something");
    String resourceName1 = "com.alibaba.csp.sentinel.annotation.aspectj.integration.service.BarService:doSomething(int)";
    ClusterNode cn1 = ClusterBuilderSlot.getClusterNode(resourceName1);
    assertThat(cn1).isNotNull();
    assertThat(cn1.passQps()).isPositive();

    assertThat(barService.anotherBar(5758)).isEqualTo("eee...");
    assertThat(cn.exceptionQps()).isPositive();
    assertThat(cn.blockQps()).isZero();

    assertThat(barService.doSomething(5758)).isEqualTo("GlobalFallback:doFallback");
    assertThat(cn1.exceptionQps()).isPositive();
    assertThat(cn1.blockQps()).isZero();
}
 
Example #22
Source File: FluxSentinelOperatorTestIntegrationTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Test
public void testEmitMultipleValuesWhenFlowControlTriggered() {
    String resourceName = createResourceName("testEmitMultipleValuesWhenFlowControlTriggered");
    FlowRuleManager.loadRules(Collections.singletonList(
        new FlowRule(resourceName).setCount(0)
    ));
    StepVerifier.create(Flux.just(1, 3, 5)
        .map(e -> e * 2)
        .transform(new SentinelReactorTransformer<>(resourceName)))
        .expectError(BlockException.class)
        .verify();

    ClusterNode cn = ClusterBuilderSlot.getClusterNode(resourceName);
    assertNotNull(cn);
    assertEquals(0, cn.passQps(), 0.01);
    assertEquals(1, cn.blockRequest());

    FlowRuleManager.loadRules(new ArrayList<>());
}
 
Example #23
Source File: SentinelAnnotationIntegrationTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Test
public void testDefaultFallbackWithSingleParam() {
    assertThat(fooService.anotherFoo(1)).isEqualTo("Hello for 1");
    String resourceName = "apiAnotherFooWithDefaultFallback";
    ClusterNode cn = ClusterBuilderSlot.getClusterNode(resourceName);
    assertThat(cn).isNotNull();
    assertThat(cn.passQps()).isPositive();

    // Default fallback should take effect.
    assertThat(fooService.anotherFoo(5758)).isEqualTo(FooUtil.FALLBACK_DEFAULT_RESULT);
    assertThat(cn.exceptionQps()).isPositive();
    assertThat(cn.blockQps()).isZero();

    FlowRuleManager.loadRules(Collections.singletonList(
        new FlowRule(resourceName).setCount(0)
    ));
    // Default fallback should also take effect for BlockException.
    assertThat(fooService.anotherFoo(5758)).isEqualTo(FooUtil.FALLBACK_DEFAULT_RESULT);
    assertThat(cn.blockQps()).isPositive();
}
 
Example #24
Source File: CommonFilterTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
private void testUrlExclusion() throws Exception {
    final String excludePrefix = "/exclude/";
    String url = excludePrefix + 1;
    WebCallbackManager.setUrlCleaner(new UrlCleaner() {
        @Override
        public String clean(String originUrl) {
            if(originUrl.startsWith(excludePrefix)) {
                return "";
            }
            return originUrl;
        }
    });
    this.mvc.perform(get(url).accept(MediaType.TEXT_PLAIN))
            .andExpect(status().isOk())
            .andExpect(content().string("Exclude 1"));
    assertNull(ClusterBuilderSlot.getClusterNode(url));
    WebCallbackManager.setUrlCleaner(new DefaultUrlCleaner());
}
 
Example #25
Source File: FlowRuleCheckerTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@Test
public void testSelectNodeForRelateReference() {
    String refResource = "testSelectNodeForRelateReference_refResource";

    DefaultNode node = mock(DefaultNode.class);
    ClusterNode refCn = mock(ClusterNode.class);
    ClusterBuilderSlot.getClusterNodeMap().put(new StringResourceWrapper(refResource, EntryType.IN), refCn);
    Context context = mock(Context.class);

    FlowRule rule = new FlowRule("testSelectNodeForRelateReference")
        .setCount(1)
        .setStrategy(RuleConstant.STRATEGY_RELATE)
        .setRefResource(refResource);
    assertEquals(refCn, FlowRuleChecker.selectReferenceNode(rule, context, node));
}
 
Example #26
Source File: ReactorSphUTest.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Test
public void testReactorEntryWithBizException() {
    String resourceName = createResourceName("testReactorEntryWithBizException");
    StepVerifier.create(ReactorSphU.entryWith(resourceName, Mono.error(new IllegalStateException())))
        .expectError(IllegalStateException.class)
        .verify();

    ClusterNode cn = ClusterBuilderSlot.getClusterNode(resourceName);
    assertNotNull(cn);
    assertEquals(1, cn.passQps(), 0.01);
    assertEquals(1, cn.totalException());
}
 
Example #27
Source File: SentinelGrpcServerInterceptorTest.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Test
public void testGrpcServerInterceptor() throws Exception {
    final int port = 19329;
    server.start(port, true);
    client = new FooServiceClient("localhost", port);

    configureFlowRule(Integer.MAX_VALUE);
    assertTrue(sendRequest(FooRequest.newBuilder().setName("Sentinel").setId(666).build()));
    ClusterNode clusterNode = ClusterBuilderSlot.getClusterNode(resourceName, EntryType.IN);
    assertNotNull(clusterNode);
    assertEquals(1, clusterNode.totalPass());

    // Not allowed to pass.
    configureFlowRule(0);
    // The second request will be blocked.
    assertFalse(sendRequest(FooRequest.newBuilder().setName("Sentinel").setId(666).build()));
    assertEquals(1, clusterNode.blockRequest());

    configureFlowRule(Integer.MAX_VALUE);
    assertFalse(sendRequest(FooRequest.newBuilder().setName("Sentinel").setId(-1).build()));
    assertEquals(1, clusterNode.totalException());

    configureFlowRule(Integer.MAX_VALUE);
    assertTrue(sendRequest(FooRequest.newBuilder().setName("Sentinel").setId(-2).build()));
    assertTrue(clusterNode.avgRt() >= 1000);

    server.stop();
}
 
Example #28
Source File: DefaultSlotChainBuilder.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@Override
public ProcessorSlotChain build() {
    ProcessorSlotChain chain = new DefaultProcessorSlotChain();
    chain.addLast(new NodeSelectorSlot());
    chain.addLast(new ClusterBuilderSlot());
    chain.addLast(new LogSlot());
    chain.addLast(new StatisticSlot());
    chain.addLast(new SystemSlot());
    chain.addLast(new AuthoritySlot());
    chain.addLast(new FlowSlot());
    chain.addLast(new DegradeSlot());

    return chain;
}
 
Example #29
Source File: DegradeTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@Test
public void testAverageRtDegrade() throws InterruptedException {
    String key = "test_degrade_average_rt";
    ClusterNode cn = mock(ClusterNode.class);
    ClusterBuilderSlot.getClusterNodeMap().put(new StringResourceWrapper(key, EntryType.IN), cn);

    Context context = mock(Context.class);
    DefaultNode node = mock(DefaultNode.class);
    when(node.getClusterNode()).thenReturn(cn);
    when(cn.avgRt()).thenReturn(2d);

    int rtSlowRequestAmount = 10;
    DegradeRule rule = new DegradeRule();
    rule.setCount(1);
    rule.setResource(key);
    rule.setTimeWindow(2);
    rule.setGrade(RuleConstant.DEGRADE_GRADE_RT);
    rule.setRtSlowRequestAmount(rtSlowRequestAmount);

    //Will true
    for (int i = 0; i < rtSlowRequestAmount - 1; i++) {
        assertTrue(rule.passCheck(context, node, 1));
    }

    // The third time will fail.
    assertFalse(rule.passCheck(context, node, 1));
    assertFalse(rule.passCheck(context, node, 1));

    // Restore.
    TimeUnit.MILLISECONDS.sleep(2200);
    assertTrue(rule.passCheck(context, node, 1));
}
 
Example #30
Source File: SampleCountProperty.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
/**
 * Update the {@link #SAMPLE_COUNT}. All {@link ClusterNode}s will be reset if newSampleCount
 * is different from {@link #SAMPLE_COUNT}.
 *
 * @param newSampleCount New sample count to set. This value must be divisor of 1000.
 */
public static void updateSampleCount(int newSampleCount) {
    if (newSampleCount != SAMPLE_COUNT) {
        SAMPLE_COUNT = newSampleCount;
        ClusterBuilderSlot.resetClusterNodes();
    }
    RecordLog.info("SAMPLE_COUNT updated to: " + SAMPLE_COUNT);
}