com.alibaba.csp.sentinel.node.DefaultNode Java Examples

The following examples show how to use com.alibaba.csp.sentinel.node.DefaultNode. 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: FlowRuleChecker.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
private static boolean applyTokenResult(/*@NonNull*/ TokenResult result, FlowRule rule, Context context,
                                                     DefaultNode node,
                                                     int acquireCount, boolean prioritized) {
    switch (result.getStatus()) {
        case TokenResultStatus.OK:
            return true;
        case TokenResultStatus.SHOULD_WAIT:
            // Wait for next tick.
            try {
                Thread.sleep(result.getWaitInMs());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return true;
        case TokenResultStatus.NO_RULE_EXISTS:
        case TokenResultStatus.BAD_REQUEST:
        case TokenResultStatus.FAIL:
        case TokenResultStatus.TOO_MANY_REQUEST:
            return fallbackToLocalOrPass(rule, context, node, acquireCount, prioritized);
        case TokenResultStatus.BLOCKED:
        default:
            return false;
    }
}
 
Example #2
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 #3
Source File: FlowSlotTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testCheckFlowPass() throws Exception {
    FlowRuleChecker checker = mock(FlowRuleChecker.class);
    FlowSlot flowSlot = new FlowSlot(checker);
    Context context = mock(Context.class);
    DefaultNode node = mock(DefaultNode.class);
    doCallRealMethod().when(checker).checkFlow(any(Function.class), any(ResourceWrapper.class), any(Context.class),
        any(DefaultNode.class), anyInt(), anyBoolean());

    String resA = "resAK";
    String resB = "resBK";
    FlowRule rule1 = new FlowRule(resA).setCount(10);
    FlowRule rule2 = new FlowRule(resB).setCount(10);
    // Here we only load rules for resA.
    FlowRuleManager.loadRules(Collections.singletonList(rule1));

    when(checker.canPassCheck(eq(rule1), any(Context.class), any(DefaultNode.class), anyInt(), anyBoolean()))
        .thenReturn(true);
    when(checker.canPassCheck(eq(rule2), any(Context.class), any(DefaultNode.class), anyInt(), anyBoolean()))
        .thenReturn(false);

    flowSlot.checkFlow(new StringResourceWrapper(resA, EntryType.IN), context, node, 1, false);
    flowSlot.checkFlow(new StringResourceWrapper(resB, EntryType.IN), context, node, 1, false);
}
 
Example #4
Source File: FlowRuleChecker.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
private static boolean passClusterCheck(FlowRule rule, Context context, DefaultNode node, int acquireCount,
                                        boolean prioritized) {
    try {
        TokenService clusterService = pickClusterService();
        if (clusterService == null) {
            return fallbackToLocalOrPass(rule, context, node, acquireCount, prioritized);
        }
        long flowId = rule.getClusterConfig().getFlowId();
        TokenResult result = clusterService.requestToken(flowId, acquireCount, prioritized);
        return applyTokenResult(result, rule, context, node, acquireCount, prioritized);
        // If client is absent, then fallback to local mode.
    } catch (Throwable ex) {
        RecordLog.warn("[FlowRuleChecker] Request cluster token unexpected failed", ex);
    }
    // Fallback to local flow control when token client or server for this rule is not available.
    // If fallback is not enabled, then directly pass.
    return fallbackToLocalOrPass(rule, context, node, acquireCount, prioritized);
}
 
Example #5
Source File: FlowRuleCheckerTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Test
public void testCustomOriginFlowSelectNode() {
    String origin = "appA";
    String limitAppB = "appB";

    DefaultNode node = mock(DefaultNode.class);
    DefaultNode originNode = mock(DefaultNode.class);
    ClusterNode cn = mock(ClusterNode.class);
    when(node.getClusterNode()).thenReturn(cn);
    Context context = mock(Context.class);
    when(context.getOrigin()).thenReturn(origin);
    when(context.getOriginNode()).thenReturn(originNode);

    FlowRule rule = new FlowRule("testCustomOriginFlowSelectNode").setCount(1);
    rule.setLimitApp(origin);
    // Origin matches, return the origin node.
    assertEquals(originNode, FlowRuleChecker.selectNodeByRequesterAndStrategy(rule, context, node));

    rule.setLimitApp(limitAppB);
    // Origin mismatch, no node found.
    assertNull(FlowRuleChecker.selectNodeByRequesterAndStrategy(rule, context, node));
}
 
Example #6
Source File: FlowSlotTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testCheckFlowPass() throws Exception {
    FlowRuleChecker checker = mock(FlowRuleChecker.class);
    FlowSlot flowSlot = new FlowSlot(checker);
    Context context = mock(Context.class);
    DefaultNode node = mock(DefaultNode.class);
    doCallRealMethod().when(checker).checkFlow(any(Function.class), any(ResourceWrapper.class), any(Context.class),
        any(DefaultNode.class), anyInt(), anyBoolean());

    String resA = "resAK";
    String resB = "resBK";
    FlowRule rule1 = new FlowRule(resA).setCount(10);
    FlowRule rule2 = new FlowRule(resB).setCount(10);
    // Here we only load rules for resA.
    FlowRuleManager.loadRules(Collections.singletonList(rule1));

    when(checker.canPassCheck(eq(rule1), any(Context.class), any(DefaultNode.class), anyInt(), anyBoolean()))
        .thenReturn(true);
    when(checker.canPassCheck(eq(rule2), any(Context.class), any(DefaultNode.class), anyInt(), anyBoolean()))
        .thenReturn(false);

    flowSlot.checkFlow(new StringResourceWrapper(resA, EntryType.IN), context, node, 1, false);
    flowSlot.checkFlow(new StringResourceWrapper(resB, EntryType.IN), context, node, 1, false);
}
 
Example #7
Source File: FlowRuleCheckerTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Test
public void testOtherOriginFlowSelectNode() {
    String originA = "appA";
    String originB = "appB";

    DefaultNode node = mock(DefaultNode.class);
    DefaultNode originNode = mock(DefaultNode.class);
    ClusterNode cn = mock(ClusterNode.class);
    when(node.getClusterNode()).thenReturn(cn);
    Context context = mock(Context.class);
    when(context.getOriginNode()).thenReturn(originNode);

    FlowRule ruleA = new FlowRule("testOtherOriginFlowSelectNode").setCount(1);
    ruleA.setLimitApp(originA);
    FlowRule ruleB = new FlowRule("testOtherOriginFlowSelectNode").setCount(2);
    ruleB.setLimitApp(RuleConstant.LIMIT_APP_OTHER);
    FlowRuleManager.loadRules(Arrays.asList(ruleA, ruleB));

    // Origin matches other, return the origin node.
    when(context.getOrigin()).thenReturn(originB);
    assertEquals(originNode, FlowRuleChecker.selectNodeByRequesterAndStrategy(ruleB, context, node));

    // Origin matches limitApp of an existing rule, so no nodes are selected.
    when(context.getOrigin()).thenReturn(originA);
    assertNull(FlowRuleChecker.selectNodeByRequesterAndStrategy(ruleB, context, node));
}
 
Example #8
Source File: FetchTreeCommandHandler.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
private void visitTree(int level, DefaultNode node, /*@NonNull*/ StringBuilder sb) {
    for (int i = 0; i < level; ++i) {
        sb.append("-");
    }
    if (!(node instanceof EntranceNode)) {
        sb.append(String.format("%s(t:%s pq:%s bq:%s tq:%s rt:%s prq:%s 1mp:%s 1mb:%s 1mt:%s)",
            node.getId().getShowName(), node.curThreadNum(), node.passQps(),
            node.blockQps(), node.totalQps(), node.avgRt(), node.successQps(),
            node.totalRequest() - node.blockRequest(), node.blockRequest(),
            node.totalRequest())).append("\n");
    } else {
        sb.append(String.format("EntranceNode: %s(t:%s pq:%s bq:%s tq:%s rt:%s prq:%s 1mp:%s 1mb:%s 1mt:%s)",
            node.getId().getShowName(), node.curThreadNum(), node.passQps(),
            node.blockQps(), node.totalQps(), node.avgRt(), node.successQps(),
            node.totalRequest() - node.blockRequest(), node.blockRequest(),
            node.totalRequest())).append("\n");
    }
    for (Node n : node.getChildList()) {
        DefaultNode dn = (DefaultNode)n;
        visitTree(level + 1, dn, sb);
    }
}
 
Example #9
Source File: FetchTreeCommandHandler.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
private void visitTree(int level, DefaultNode node, /*@NonNull*/ StringBuilder sb) {
    for (int i = 0; i < level; ++i) {
        sb.append("-");
    }
    if (!(node instanceof EntranceNode)) {
        sb.append(String.format("%s(t:%s pq:%s bq:%s tq:%s rt:%s prq:%s 1mp:%s 1mb:%s 1mt:%s)",
            node.getId().getShowName(), node.curThreadNum(), node.passQps(),
            node.blockQps(), node.totalQps(), node.avgRt(), node.successQps(),
            node.totalRequest() - node.blockRequest(), node.blockRequest(),
            node.totalRequest())).append("\n");
    } else {
        sb.append(String.format("EntranceNode: %s(t:%s pq:%s bq:%s tq:%s rt:%s prq:%s 1mp:%s 1mb:%s 1mt:%s)",
            node.getId().getShowName(), node.curThreadNum(), node.passQps(),
            node.blockQps(), node.totalQps(), node.avgRt(), node.successQps(),
            node.totalRequest() - node.blockRequest(), node.blockRequest(),
            node.totalRequest())).append("\n");
    }
    for (Node n : node.getChildList()) {
        DefaultNode dn = (DefaultNode)n;
        visitTree(level + 1, dn, sb);
    }
}
 
Example #10
Source File: ClusterNodeBuilderTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@Test
public void clusterNodeBuilder_normal() throws Exception {
    ContextUtil.enter("entry1", "caller1");

    Entry nodeA = SphU.entry("nodeA");

    Node curNode = nodeA.getCurNode();
    assertSame(curNode.getClass(), DefaultNode.class);
    DefaultNode dN = (DefaultNode)curNode;
    assertTrue(dN.getClusterNode().getOriginCountMap().containsKey("caller1"));
    assertSame(nodeA.getOriginNode(), dN.getClusterNode().getOrCreateOriginNode("caller1"));

    if (nodeA != null) {
        nodeA.exit();
    }
    ContextUtil.exit();

    ContextUtil.enter("entry4", "caller2");

    nodeA = SphU.entry("nodeA");

    curNode = nodeA.getCurNode();
    assertSame(curNode.getClass(), DefaultNode.class);
    DefaultNode dN1 = (DefaultNode)curNode;
    assertTrue(dN1.getClusterNode().getOriginCountMap().containsKey("caller2"));
    assertNotSame(dN1, dN);

    if (nodeA != null) {
        nodeA.exit();
    }
    ContextUtil.exit();
}
 
Example #11
Source File: FlowRuleCheckerTest.java    From Sentinel 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 #12
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 #13
Source File: FlowRuleCheckerTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@Test
public void testSelectNodeForEmptyReference() {
    DefaultNode node = mock(DefaultNode.class);
    Context context = mock(Context.class);

    FlowRule rule = new FlowRule("testSelectNodeForEmptyReference")
        .setCount(1)
        .setStrategy(RuleConstant.STRATEGY_CHAIN);
    assertNull(FlowRuleChecker.selectReferenceNode(rule, context, node));
}
 
Example #14
Source File: GatewayFlowSlot.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Override
public void entry(Context context, ResourceWrapper resource, DefaultNode node, int count,
                  boolean prioritized, Object... args) throws Throwable {
    checkGatewayParamFlow(resource, count, args);

    fireEntry(context, resource, node, count, prioritized, args);
}
 
Example #15
Source File: FlowRuleTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@Test
public void testFlowRule_strategy() {

    FlowRule flowRule = new FlowRule();
    flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
    flowRule.setCount(1);
    flowRule.setLimitApp("default");
    flowRule.setStrategy(RuleConstant.STRATEGY_CHAIN);
    DefaultController defaultController = new DefaultController(1, flowRule.getGrade());
    flowRule.setRater(defaultController);
    flowRule.setRefResource("entry1");

    Context context = mock(Context.class);
    DefaultNode dn = mock(DefaultNode.class);

    when(context.getName()).thenReturn("entry1");
    when(dn.passQps()).thenReturn(1d);
    assertFalse(flowRule.passCheck(context, dn, 1));

    when(context.getName()).thenReturn("entry2");
    assertTrue(flowRule.passCheck(context, dn, 1));

    // Strategy == relate
    flowRule.setStrategy(RuleConstant.STRATEGY_CHAIN);
    ClusterNode cn = mock(ClusterNode.class);
    assertTrue(flowRule.passCheck(context, dn, 1));
}
 
Example #16
Source File: FlowRuleTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@Test
public void testFlowRule_grade() {

    FlowRule flowRule = new FlowRule();
    flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
    flowRule.setCount(1);
    flowRule.setLimitApp("default");
    flowRule.setStrategy(RuleConstant.STRATEGY_DIRECT);

    DefaultController defaultController = new DefaultController(1, flowRule.getGrade());
    flowRule.setRater(defaultController);

    Context context = mock(Context.class);
    DefaultNode node = mock(DefaultNode.class);
    ClusterNode cn = mock(ClusterNode.class);

    when(context.getOrigin()).thenReturn("");
    when(node.getClusterNode()).thenReturn(cn);
    when(cn.passQps()).thenReturn(1d);

    assertFalse(flowRule.passCheck(context, node, 1));

    flowRule.setGrade(RuleConstant.FLOW_GRADE_THREAD);
    defaultController = new DefaultController(1, flowRule.getGrade());
    flowRule.setRater(defaultController);
    when(cn.curThreadNum()).thenReturn(1);
    assertTrue(!flowRule.passCheck(context, node, 1));
}
 
Example #17
Source File: FlowRuleCheckerTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@Test
public void testPassCheckSelectEmptyNodeSuccess() {
    FlowRule rule = new FlowRule("abc").setCount(1);
    rule.setLimitApp("abc");

    DefaultNode node = mock(DefaultNode.class);
    Context context = mock(Context.class);
    when(context.getOrigin()).thenReturn("def");

    FlowRuleChecker checker = new FlowRuleChecker();
    assertTrue(checker.canPassCheck(rule, context, node, 1));
}
 
Example #18
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 #19
Source File: FlowRuleCheckerTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultLimitAppFlowSelectNode() {
    DefaultNode node = mock(DefaultNode.class);
    ClusterNode cn = mock(ClusterNode.class);
    when(node.getClusterNode()).thenReturn(cn);
    Context context = mock(Context.class);

    // limitApp: default
    FlowRule rule = new FlowRule("testDefaultLimitAppFlowSelectNode").setCount(1);
    assertEquals(cn, FlowRuleChecker.selectNodeByRequesterAndStrategy(rule, context, node));
}
 
Example #20
Source File: DegradeTest.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Test
public void testExceptionCountModeDegrade() throws Throwable {
    String key = "test_degrade_exception_count";
    ClusterNode cn = mock(ClusterNode.class);
    when(cn.totalException()).thenReturn(10L);
    ClusterBuilderSlot.getClusterNodeMap().put(new StringResourceWrapper(key, EntryType.IN), cn);

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

    DegradeRule rule = new DegradeRule();
    rule.setCount(4);
    rule.setResource(key);
    rule.setTimeWindow(2);
    rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT);

    when(cn.totalException()).thenReturn(4L);

    // Will fail.
    assertFalse(rule.passCheck(context, node, 1));

    // Restore from the degrade timeout.
    TimeUnit.MILLISECONDS.sleep(2200);

    when(cn.totalException()).thenReturn(0L);
    // Will pass.
    assertTrue(rule.passCheck(context, node, 1));
}
 
Example #21
Source File: AsyncEntryIntegrationTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
private DefaultNode queryInvocationTree(boolean check) {
    DefaultNode root = Constants.ROOT;
    DefaultNode entranceNode = shouldHasChildFor(root, contextName, check);
    DefaultNode testTopNode = shouldHasChildFor(entranceNode, "test-top", check);
    DefaultNode testAsyncNode = shouldHasChildFor(testTopNode, "test-async", check);
    shouldHasChildFor(testTopNode, "test-sync", check);
    shouldHasChildFor(testAsyncNode, "test-sync-in-async", check);
    DefaultNode anotherAsyncInAsyncNode = shouldHasChildFor(testAsyncNode, "test-another-async", check);
    return shouldHasChildFor(anotherAsyncInAsyncNode, "test-another-in-async", check);
}
 
Example #22
Source File: AsyncEntryIntegrationTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@Test
public void testAsyncEntryUnderSyncEntry() throws Exception {
    // Expected invocation chain:
    // EntranceNode: machine-root
    // -EntranceNode: async-context
    // --test-top
    // ---test-async
    // ----test-sync-in-async
    // ----test-another-async
    // -----test-another-in-async
    // ---test-sync
    ContextUtil.enter(contextName, origin);
    Entry entry = null;
    try {
        entry = SphU.entry("test-top");
        doAsyncThenSync();
    } catch (BlockException ex) {
        ex.printStackTrace();
    } finally {
        if (entry != null) {
            entry.exit();
        }
        ContextUtil.exit();
    }

    // we keep the original timeout of 15 seconds although the test should
    // complete in less than 3 seconds
    await().timeout(15, TimeUnit.SECONDS)
        .until(new Callable<DefaultNode>() {
            @Override
            public DefaultNode call() throws Exception {
                return queryInvocationTree(false);
            }
        }, CoreMatchers.notNullValue());

    queryInvocationTree(true);
}
 
Example #23
Source File: MetricEntryCallback.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Override
public void onBlocked(BlockException ex, Context context, ResourceWrapper resourceWrapper,
                      DefaultNode param, int count, Object... args) {
    for (MetricExtension m : MetricExtensionProvider.getMetricExtensions()) {
        m.addBlock(resourceWrapper.getName(), count, context.getOrigin(), ex, args);
    }
}
 
Example #24
Source File: FlowRuleTest.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Test
public void testFlowRule_grade() {

    FlowRule flowRule = new FlowRule();
    flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
    flowRule.setCount(1);
    flowRule.setLimitApp("default");
    flowRule.setStrategy(RuleConstant.STRATEGY_DIRECT);

    DefaultController defaultController = new DefaultController(1, flowRule.getGrade());
    flowRule.setRater(defaultController);

    Context context = mock(Context.class);
    DefaultNode node = mock(DefaultNode.class);
    ClusterNode cn = mock(ClusterNode.class);

    when(context.getOrigin()).thenReturn("");
    when(node.getClusterNode()).thenReturn(cn);
    when(cn.passQps()).thenReturn(1d);

    assertFalse(flowRule.passCheck(context, node, 1));

    flowRule.setGrade(RuleConstant.FLOW_GRADE_THREAD);
    defaultController = new DefaultController(1, flowRule.getGrade());
    flowRule.setRater(defaultController);
    when(cn.curThreadNum()).thenReturn(1);
    assertTrue(!flowRule.passCheck(context, node, 1));
}
 
Example #25
Source File: Tracer.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
private static void traceExceptionToNode(Throwable t, int count, Entry entry, DefaultNode curNode) {
    if (curNode == null) {
        return;
    }
    for (MetricExtension m : MetricExtensionProvider.getMetricExtensions()) {
        m.addException(entry.getResourceWrapper().getName(), count, t);
    }

    // clusterNode can be null when Constants.ON is false.
    ClusterNode clusterNode = curNode.getClusterNode();
    if (clusterNode == null) {
        return;
    }
    clusterNode.trace(t, count);
}
 
Example #26
Source File: Tracer.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
/**
 * Trace provided {@link Throwable} and add exception count to provided entry.
 *
 * @param e     exception to record
 * @param count exception count to add
 * @since 1.4.2
 */
public static void traceEntry(Throwable e, int count, Entry entry) {
    if (!shouldTrace(e)) {
        return;
    }
    if (entry == null || entry.getCurNode() == null) {
        return;
    }

    DefaultNode curNode = (DefaultNode)entry.getCurNode();
    traceExceptionToNode(e, count, entry, curNode);
}
 
Example #27
Source File: Tracer.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
/**
 * Trace provided {@link Throwable} and add exception count to current entry in provided context.
 *
 * @param e     exception to record
 * @param count exception count to add
 * @since 1.4.2
 */
public static void traceContext(Throwable e, int count, Context context) {
    if (!shouldTrace(e)) {
        return;
    }
    if (context == null) {
        return;
    }

    DefaultNode curNode = (DefaultNode)context.getCurNode();
    traceExceptionToNode(e, count, context.getCurEntry(), curNode);
}
 
Example #28
Source File: FlowRuleCheckerTest.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultLimitAppFlowSelectNode() {
    DefaultNode node = mock(DefaultNode.class);
    ClusterNode cn = mock(ClusterNode.class);
    when(node.getClusterNode()).thenReturn(cn);
    Context context = mock(Context.class);

    // limitApp: default
    FlowRule rule = new FlowRule("testDefaultLimitAppFlowSelectNode").setCount(1);
    assertEquals(cn, FlowRuleChecker.selectNodeByRequesterAndStrategy(rule, context, node));
}
 
Example #29
Source File: FlowRuleCheckerTest.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Test
public void testPassCheckSelectEmptyNodeSuccess() {
    FlowRule rule = new FlowRule("abc").setCount(1);
    rule.setLimitApp("abc");

    DefaultNode node = mock(DefaultNode.class);
    Context context = mock(Context.class);
    when(context.getOrigin()).thenReturn("def");

    FlowRuleChecker checker = new FlowRuleChecker();
    assertTrue(checker.canPassCheck(rule, context, node, 1));
}
 
Example #30
Source File: DegradeTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@Test
public void testExceptionCountModeDegrade() throws Throwable {
    String key = "test_degrade_exception_count";
    ClusterNode cn = mock(ClusterNode.class);
    when(cn.totalException()).thenReturn(10L);
    ClusterBuilderSlot.getClusterNodeMap().put(new StringResourceWrapper(key, EntryType.IN), cn);

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

    DegradeRule rule = new DegradeRule();
    rule.setCount(4);
    rule.setResource(key);
    rule.setTimeWindow(2);
    rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT);

    when(cn.totalException()).thenReturn(4L);

    // Will fail.
    assertFalse(rule.passCheck(context, node, 1));

    // Restore from the degrade timeout.
    TimeUnit.MILLISECONDS.sleep(2200);

    when(cn.totalException()).thenReturn(0L);
    // Will pass.
    assertTrue(rule.passCheck(context, node, 1));
}