com.alibaba.csp.sentinel.slots.block.RuleConstant Java Examples

The following examples show how to use com.alibaba.csp.sentinel.slots.block.RuleConstant. 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: AuthorityRuleManagerTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Test
public void testLoadRules() {
    String resourceName = "testLoadRules";

    AuthorityRule rule = new AuthorityRule();
    rule.setResource(resourceName);
    rule.setLimitApp("a,b");
    rule.setStrategy(RuleConstant.AUTHORITY_WHITE);
    AuthorityRuleManager.loadRules(Collections.singletonList(rule));

    List<AuthorityRule> rules = AuthorityRuleManager.getRules();
    assertEquals(1, rules.size());
    assertEquals(rule, rules.get(0));

    AuthorityRuleManager.loadRules(Collections.singletonList(new AuthorityRule()));
    rules = AuthorityRuleManager.getRules();
    assertEquals(0, rules.size());
}
 
Example #2
Source File: ParamFlowQpsDemo.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
private static void initParamFlowRules() {
    // QPS mode, threshold is 5 for every frequent "hot spot" parameter in index 0 (the first arg).
    ParamFlowRule rule = new ParamFlowRule(RESOURCE_KEY)
        .setParamIdx(0)
        .setGrade(RuleConstant.FLOW_GRADE_QPS)
        //.setDurationInSec(3)
        //.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER)
        //.setMaxQueueingTimeMs(600)
        .setCount(5);

    // We can set threshold count for specific parameter value individually.
    // Here we add an exception item. That means: QPS threshold of entries with parameter `PARAM_B` (type: int)
    // in index 0 will be 10, rather than the global threshold (5).
    ParamFlowItem item = new ParamFlowItem().setObject(String.valueOf(PARAM_B))
        .setClassType(int.class.getName())
        .setCount(10);
    rule.setParamFlowItemList(Collections.singletonList(item));
    ParamFlowRuleManager.loadRules(Collections.singletonList(rule));
}
 
Example #3
Source File: ExceptionCountDegradeDemo.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
private static void initDegradeRule() {
    List<DegradeRule> rules = new ArrayList<DegradeRule>();
    DegradeRule rule = new DegradeRule();
    rule.setResource(KEY);
    // set limit exception count to 4
    rule.setCount(4);
    rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT);
    /**
     * When degrading by {@link RuleConstant#DEGRADE_GRADE_EXCEPTION_COUNT}, time window
     * less than 60 seconds will not work as expected. Because the exception count is
     * summed by minute, when a short time window elapsed, the degradation condition
     * may still be satisfied.
     */
    rule.setTimeWindow(10);
    rules.add(rule);
    DegradeRuleManager.loadRules(rules);
}
 
Example #4
Source File: AsyncEntryDemo.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
private static void initFlowRule() {
    // Rule 1 won't take effect as the limitApp doesn't match.
    FlowRule rule1 = new FlowRule()
        .setResource("test-another-sync-in-async")
        .setLimitApp("originB")
        .as(FlowRule.class)
        .setCount(4)
        .setGrade(RuleConstant.FLOW_GRADE_QPS);
    // Rule 2 will take effect.
    FlowRule rule2 = new FlowRule()
        .setResource("test-another-async")
        .setLimitApp("default")
        .as(FlowRule.class)
        .setCount(5)
        .setGrade(RuleConstant.FLOW_GRADE_QPS);
    List<FlowRule> ruleList = Arrays.asList(rule1, rule2);
    FlowRuleManager.loadRules(ruleList);
}
 
Example #5
Source File: PullConsumerDemo.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
private static void initFlowControlRule() {
    FlowRule rule = new FlowRule();
    rule.setResource(KEY);
    // Indicates the interval between two adjacent requests is 200 ms.
    rule.setCount(5);
    rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
    rule.setLimitApp("default");

    // Enable rate limiting (uniform). This can ensure fixed intervals between two adjacent calls.
    // In this example, intervals between two incoming calls (message consumption) will be 200 ms constantly.
    rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER);
    // If more requests are coming, they'll be put into the waiting queue.
    // The queue has a queueing timeout. Requests that may exceed the timeout will be immediately blocked.
    // In this example, the max timeout is 5s.
    rule.setMaxQueueingTimeMs(5 * 1000);
    FlowRuleManager.loadRules(Collections.singletonList(rule));
}
 
Example #6
Source File: PullConsumerDemo.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
private static void initFlowControlRule() {
    FlowRule rule = new FlowRule();
    rule.setResource(KEY);
    // Indicates the interval between two adjacent requests is 200 ms.
    rule.setCount(5);
    rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
    rule.setLimitApp("default");

    // Enable rate limiting (uniform). This can ensure fixed intervals between two adjacent calls.
    // In this example, intervals between two incoming calls (message consumption) will be 200 ms constantly.
    rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER);
    // If more requests are coming, they'll be put into the waiting queue.
    // The queue has a queueing timeout. Requests that may exceed the timeout will be immediately blocked.
    // In this example, the max timeout is 5s.
    rule.setMaxQueueingTimeMs(5 * 1000);
    FlowRuleManager.loadRules(Collections.singletonList(rule));
}
 
Example #7
Source File: AsyncEntryDemo.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
private static void initFlowRule() {
    // Rule 1 won't take effect as the limitApp doesn't match.
    FlowRule rule1 = new FlowRule()
        .setResource("test-another-sync-in-async")
        .setLimitApp("originB")
        .as(FlowRule.class)
        .setCount(4)
        .setGrade(RuleConstant.FLOW_GRADE_QPS);
    // Rule 2 will take effect.
    FlowRule rule2 = new FlowRule()
        .setResource("test-another-async")
        .setLimitApp("default")
        .as(FlowRule.class)
        .setCount(5)
        .setGrade(RuleConstant.FLOW_GRADE_QPS);
    List<FlowRule> ruleList = Arrays.asList(rule1, rule2);
    FlowRuleManager.loadRules(ruleList);
}
 
Example #8
Source File: GatewayRuleManager.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
public static boolean isValidRule(GatewayFlowRule rule) {
    if (rule == null || StringUtil.isBlank(rule.getResource()) || rule.getResourceMode() < 0
        || rule.getGrade() < 0 || rule.getCount() < 0 || rule.getBurst() < 0 || rule.getControlBehavior() < 0) {
        return false;
    }
    if (rule.getGrade() == RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER
        && rule.getMaxQueueingTimeoutMs() < 0) {
        return false;
    }
    if (rule.getIntervalSec() <= 0) {
        return false;
    }
    GatewayParamFlowItem item = rule.getParamItem();
    if (item != null) {
        return isValidParamItem(item);
    }
    return true;
}
 
Example #9
Source File: ParamFlowCheckerTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Test
public void testPassLocalCheckForArray() throws InterruptedException {
    final String resourceName = "testPassLocalCheckForArray";
    final ResourceWrapper resourceWrapper = new StringResourceWrapper(resourceName, EntryType.IN);
    int paramIdx = 0;
    double globalThreshold = 1;

    ParamFlowRule rule = new ParamFlowRule(resourceName).setParamIdx(paramIdx)
        .setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER).setCount(globalThreshold);

    TimeUtil.currentTimeMillis();

    String v1 = "a", v2 = "B", v3 = "Cc";
    Object arr = new String[] {v1, v2, v3};
    ParameterMetric metric = new ParameterMetric();
    ParameterMetricStorage.getMetricsMap().put(resourceWrapper.getName(), metric);
    metric.getRuleTimeCounterMap().put(rule, new ConcurrentLinkedHashMapWrapper<Object, AtomicLong>(4000));

    assertTrue(ParamFlowChecker.passCheck(resourceWrapper, rule, 1, arr));
    assertFalse(ParamFlowChecker.passCheck(resourceWrapper, rule, 1, arr));
}
 
Example #10
Source File: FlowPartialIntegrationTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Test
public void testFlowRule_other() {

    FlowRule flowRule = new FlowRule();
    flowRule.setResource("testOther");
    flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
    flowRule.setCount(0);
    flowRule.setLimitApp("other");
    FlowRuleManager.loadRules(Arrays.asList(flowRule));

    Entry e = null;
    try {
        e = SphU.entry("testOther");
    } catch (BlockException e1) {
        e1.printStackTrace();fail("Should had failed");
    }

    if (e != null) {
        e.exit();
    } else {
        fail("Should had failed");
    }
}
 
Example #11
Source File: DegradeRuleManager.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
public static boolean isValidRule(DegradeRule rule) {
    boolean baseValid = rule != null && !StringUtil.isBlank(rule.getResource())
        && rule.getCount() >= 0 && rule.getTimeWindow() > 0;
    if (!baseValid) {
        return false;
    }
    int maxAllowedRt = SentinelConfig.statisticMaxRt();
    if (rule.getGrade() == RuleConstant.DEGRADE_GRADE_RT) {
        if (rule.getRtSlowRequestAmount() <= 0) {
            return false;
        }
        // Warn for RT mode that exceeds the {@code TIME_DROP_VALVE}.
        if (rule.getCount() > maxAllowedRt) {
            RecordLog.warn(String.format("[DegradeRuleManager] WARN: setting large RT threshold (%.1f ms)"
                    + " in RT mode will not take effect since it exceeds the max allowed value (%d ms)",
                rule.getCount(), maxAllowedRt));
        }
    }

    // Check exception ratio mode.
    if (rule.getGrade() == RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO) {
        return rule.getCount() <= 1 && rule.getMinRequestAmount() > 0;
    }
    return true;
}
 
Example #12
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 #13
Source File: SentinelConverterTests.java    From spring-cloud-alibaba with Apache License 2.0 6 votes vote down vote up
@Test
public void testJsonConverter() {
	JsonConverter jsonConverter = new JsonConverter(objectMapper, FlowRule.class);
	List<FlowRule> flowRules = (List<FlowRule>) jsonConverter
			.convert(readFileContent("classpath: flowrule.json"));

	assertThat(flowRules.size()).isEqualTo(1);
	assertThat(flowRules.get(0).getResource()).isEqualTo("resource");
	assertThat(flowRules.get(0).getLimitApp()).isEqualTo("default");
	assertThat(String.valueOf(flowRules.get(0).getCount())).isEqualTo("1.0");
	assertThat(flowRules.get(0).getControlBehavior())
			.isEqualTo(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);
	assertThat(flowRules.get(0).getStrategy())
			.isEqualTo(RuleConstant.STRATEGY_DIRECT);
	assertThat(flowRules.get(0).getGrade()).isEqualTo(RuleConstant.FLOW_GRADE_QPS);
}
 
Example #14
Source File: AuthoritySlotTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Test(expected = AuthorityException.class)
public void testCheckAuthorityNoExceptionItemsWhiteFail() throws Exception {
    String origin = "appA";
    String resourceName = "testCheckAuthorityNoExceptionItemsWhiteFail";
    ResourceWrapper resourceWrapper = new StringResourceWrapper(resourceName, EntryType.IN);
    ContextUtil.enter("entrance", origin);
    try {
        AuthorityRule ruleB = new AuthorityRule()
            .setResource(resourceName)
            .setLimitApp("appB, appE")
            .as(AuthorityRule.class)
            .setStrategy(RuleConstant.AUTHORITY_WHITE);

        AuthorityRuleManager.loadRules(Collections.singletonList(ruleB));
        authoritySlot.checkBlackWhiteAuthority(resourceWrapper, ContextUtil.getContext());
    } finally {
        ContextUtil.exit();
    }
}
 
Example #15
Source File: AuthoritySlotTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Test(expected = AuthorityException.class)
public void testCheckAuthorityNoExceptionItemsWhiteFail() throws Exception {
    String origin = "appA";
    String resourceName = "testCheckAuthorityNoExceptionItemsWhiteFail";
    ResourceWrapper resourceWrapper = new StringResourceWrapper(resourceName, EntryType.IN);
    ContextUtil.enter("entrance", origin);
    try {
        AuthorityRule ruleB = new AuthorityRule()
            .setResource(resourceName)
            .setLimitApp("appB, appE")
            .as(AuthorityRule.class)
            .setStrategy(RuleConstant.AUTHORITY_WHITE);

        AuthorityRuleManager.loadRules(Collections.singletonList(ruleB));
        authoritySlot.checkBlackWhiteAuthority(resourceWrapper, ContextUtil.getContext());
    } finally {
        ContextUtil.exit();
    }
}
 
Example #16
Source File: AuthoritySlotTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Test(expected = AuthorityException.class)
public void testCheckAuthorityNoExceptionItemsBlackFail() throws Exception {
    String origin = "appA";
    String resourceName = "testCheckAuthorityNoExceptionItemsBlackFail";
    ResourceWrapper resourceWrapper = new StringResourceWrapper(resourceName, EntryType.IN);
    ContextUtil.enter("entrance", origin);
    try {
        AuthorityRule ruleA = new AuthorityRule()
            .setResource(resourceName)
            .setLimitApp(origin + ",appC")
            .as(AuthorityRule.class)
            .setStrategy(RuleConstant.AUTHORITY_BLACK);

        AuthorityRuleManager.loadRules(Collections.singletonList(ruleA));
        authoritySlot.checkBlackWhiteAuthority(resourceWrapper, ContextUtil.getContext());
    } finally {
        ContextUtil.exit();
    }
}
 
Example #17
Source File: PaceFlowDemo.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
private static void initPaceFlowRule() {
    List<FlowRule> rules = new ArrayList<FlowRule>();
    FlowRule rule1 = new FlowRule();
    rule1.setResource(KEY);
    rule1.setCount(count);
    rule1.setGrade(RuleConstant.FLOW_GRADE_QPS);
    rule1.setLimitApp("default");
    /*
     * CONTROL_BEHAVIOR_RATE_LIMITER means requests more than threshold will be queueing in the queue,
     * until the queueing time is more than {@link FlowRule#maxQueueingTimeMs}, the requests will be rejected.
     */
    rule1.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER);
    rule1.setMaxQueueingTimeMs(20 * 1000);

    rules.add(rule1);
    FlowRuleManager.loadRules(rules);
}
 
Example #18
Source File: FlowRuleComparatorTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Test
public void testFlowRuleComparator() {
    FlowRule ruleA = new FlowRule("abc")
        .setCount(10);
    ruleA.setLimitApp(RuleConstant.LIMIT_APP_DEFAULT);
    FlowRule ruleB = new FlowRule("abc");
    ruleB.setLimitApp("originA");
    FlowRule ruleC = new FlowRule("abc");
    ruleC.setLimitApp("originB");
    FlowRule ruleD = new FlowRule("abc");
    ruleD.setLimitApp(RuleConstant.LIMIT_APP_OTHER);
    FlowRule ruleE = new FlowRule("abc")
        .setCount(20);
    ruleE.setLimitApp(RuleConstant.LIMIT_APP_DEFAULT);

    List<FlowRule> list = Arrays.asList(ruleA, ruleB, ruleC, ruleD, ruleE);
    FlowRuleComparator comparator = new FlowRuleComparator();
    Collections.sort(list, comparator);
    List<FlowRule> expected = Arrays.asList(ruleB, ruleC, ruleD, ruleA, ruleE);
    assertOrderEqual(expected.size(), expected, list);
}
 
Example #19
Source File: FlowPartialIntegrationTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Test
public void testFlowRule_other() {

    FlowRule flowRule = new FlowRule();
    flowRule.setResource("testOther");
    flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
    flowRule.setCount(0);
    flowRule.setLimitApp("other");
    FlowRuleManager.loadRules(Arrays.asList(flowRule));

    Entry e = null;
    try {
        e = SphU.entry("testOther");
    } catch (BlockException e1) {
        e1.printStackTrace();fail("Should had failed");
    }

    if (e != null) {
        e.exit();
    } else {
        fail("Should had failed");
    }
}
 
Example #20
Source File: FlowRuleCheckerTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Test
public void testSelectReferenceNodeForContextEntrance() {
    String contextName = "good_context";

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

    FlowRule rule = new FlowRule("testSelectReferenceNodeForContextEntrance")
        .setCount(1)
        .setStrategy(RuleConstant.STRATEGY_CHAIN)
        .setRefResource(contextName);

    when(context.getName()).thenReturn(contextName);
    assertEquals(node, FlowRuleChecker.selectReferenceNode(rule, context, node));

    when(context.getName()).thenReturn("other_context");
    assertNull(FlowRuleChecker.selectReferenceNode(rule, context, node));
}
 
Example #21
Source File: ParamFlowCheckerTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Test
public void testPassLocalCheckForArray() throws InterruptedException {
    final String resourceName = "testPassLocalCheckForArray";
    final ResourceWrapper resourceWrapper = new StringResourceWrapper(resourceName, EntryType.IN);
    int paramIdx = 0;
    double globalThreshold = 1;

    ParamFlowRule rule = new ParamFlowRule(resourceName).setParamIdx(paramIdx)
            .setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER).setCount(globalThreshold);

    TimeUtil.currentTimeMillis();

    String v1 = "a", v2 = "B", v3 = "Cc";
    Object arr = new String[]{v1, v2, v3};
    ParameterMetric metric = new ParameterMetric();
    ParameterMetricStorage.getMetricsMap().put(resourceWrapper.getName(), metric);
    metric.getRuleTimeCounterMap().put(rule, new ConcurrentLinkedHashMapWrapper<Object, AtomicLong>(4000));

    assertTrue(ParamFlowChecker.passCheck(resourceWrapper, rule, 1, arr));
    assertFalse(ParamFlowChecker.passCheck(resourceWrapper, rule, 1, arr));
}
 
Example #22
Source File: DefaultController.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Override
public boolean canPass(Node node, int acquireCount, boolean prioritized) {
    int curCount = avgUsedTokens(node);
    if (curCount + acquireCount > count) {
        if (prioritized && grade == RuleConstant.FLOW_GRADE_QPS) {
            long currentTime;
            long waitInMs;
            currentTime = TimeUtil.currentTimeMillis();
            waitInMs = node.tryOccupyNext(currentTime, acquireCount, count);
            if (waitInMs < OccupyTimeoutProperty.getOccupyTimeout()) {
                node.addWaitingRequest(currentTime + waitInMs, acquireCount);
                node.addOccupiedPass(acquireCount);
                sleep(waitInMs);

                // PriorityWaitException indicates that the request will pass after waiting for {@link @waitInMs}.
                throw new PriorityWaitException(waitInMs);
            }
        }
        return false;
    }
    return true;
}
 
Example #23
Source File: FlowRuleUtil.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
private static TrafficShapingController generateRater(/*@Valid*/ FlowRule rule) {
    if (rule.getGrade() == RuleConstant.FLOW_GRADE_QPS) {
        switch (rule.getControlBehavior()) {
            case RuleConstant.CONTROL_BEHAVIOR_WARM_UP:
                return new WarmUpController(rule.getCount(), rule.getWarmUpPeriodSec(),
                    ColdFactorProperty.coldFactor);
            case RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER:
                return new RateLimiterController(rule.getMaxQueueingTimeMs(), rule.getCount());
            case RuleConstant.CONTROL_BEHAVIOR_WARM_UP_RATE_LIMITER:
                return new WarmUpRateLimiterController(rule.getCount(), rule.getWarmUpPeriodSec(),
                    rule.getMaxQueueingTimeMs(), ColdFactorProperty.coldFactor);
            case RuleConstant.CONTROL_BEHAVIOR_DEFAULT:
            default:
                // Default mode or unknown mode: default traffic shaping controller (fast-reject).
        }
    }
    return new DefaultController(rule.getCount(), rule.getGrade());
}
 
Example #24
Source File: ParameterMetricTest.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Test
public void testInitAndClearParameterMetric() {
    // Create a parameter metric for resource "abc".
    ParameterMetric metric = new ParameterMetric();

    ParamFlowRule rule = new ParamFlowRule("abc")
        .setParamIdx(1);
    metric.initialize(rule);
    CacheMap<Object, AtomicInteger> threadCountMap = metric.getThreadCountMap().get(rule.getParamIdx());
    assertNotNull(threadCountMap);
    CacheMap<Object, AtomicLong> timeRecordMap = metric.getRuleTimeCounter(rule);
    assertNotNull(timeRecordMap);
    metric.initialize(rule);
    assertSame(threadCountMap, metric.getThreadCountMap().get(rule.getParamIdx()));
    assertSame(timeRecordMap, metric.getRuleTimeCounter(rule));

    ParamFlowRule rule2 = new ParamFlowRule("abc")
        .setParamIdx(1);
    metric.initialize(rule2);
    CacheMap<Object, AtomicLong> timeRecordMap2 = metric.getRuleTimeCounter(rule2);
    assertSame(timeRecordMap, timeRecordMap2);

    rule2.setParamIdx(2);
    metric.initialize(rule2);
    assertNotSame(timeRecordMap2, metric.getRuleTimeCounter(rule2));

    ParamFlowRule rule3 = new ParamFlowRule("abc")
        .setParamIdx(1)
        .setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER);
    metric.initialize(rule3);
    assertNotSame(timeRecordMap, metric.getRuleTimeCounter(rule3));

    metric.clear();
    assertEquals(0, metric.getThreadCountMap().size());
    assertEquals(0, metric.getRuleTimeCounterMap().size());
    assertEquals(0, metric.getRuleTokenCounterMap().size());
}
 
Example #25
Source File: SentinelFeignTests.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
	FlowRule rule1 = new FlowRule();
	rule1.setGrade(RuleConstant.FLOW_GRADE_QPS);
	rule1.setCount(0);
	rule1.setResource("GET:http://test-service/echo/{str}");
	rule1.setLimitApp("default");
	rule1.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);
	rule1.setStrategy(RuleConstant.STRATEGY_DIRECT);
	FlowRule rule2 = new FlowRule();
	rule2.setGrade(RuleConstant.FLOW_GRADE_QPS);
	rule2.setCount(0);
	rule2.setResource("GET:http://foo-service/echo/{str}");
	rule2.setLimitApp("default");
	rule2.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);
	rule2.setStrategy(RuleConstant.STRATEGY_DIRECT);
	FlowRule rule3 = new FlowRule();
	rule3.setGrade(RuleConstant.FLOW_GRADE_QPS);
	rule3.setCount(0);
	rule3.setResource("GET:http://bar-service/bar");
	rule3.setLimitApp("default");
	rule3.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);
	rule3.setStrategy(RuleConstant.STRATEGY_DIRECT);
	FlowRule rule4 = new FlowRule();
	rule4.setGrade(RuleConstant.FLOW_GRADE_QPS);
	rule4.setCount(0);
	rule4.setResource("GET:http://baz-service/baz");
	rule4.setLimitApp("default");
	rule4.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);
	rule4.setStrategy(RuleConstant.STRATEGY_DIRECT);
	FlowRuleManager.loadRules(Arrays.asList(rule1, rule2, rule3, rule4));
}
 
Example #26
Source File: FlowQpsDemo.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
private static void initFlowQpsRule() {
    List<FlowRule> rules = new ArrayList<FlowRule>();
    FlowRule rule1 = new FlowRule();
    rule1.setResource(KEY);
    // set limit qps to 20
    rule1.setCount(20);
    rule1.setGrade(RuleConstant.FLOW_GRADE_QPS);
    rule1.setLimitApp("default");
    rules.add(rule1);
    FlowRuleManager.loadRules(rules);
}
 
Example #27
Source File: AuthorityRuleChecker.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
static boolean passCheck(AuthorityRule rule, Context context) {
    String requester = context.getOrigin();

    // Empty origin or empty limitApp will pass.
    if (StringUtil.isEmpty(requester) || StringUtil.isEmpty(rule.getLimitApp())) {
        return true;
    }

    // Do exact match with origin name.
    int pos = rule.getLimitApp().indexOf(requester);
    boolean contain = pos > -1;

    if (contain) {
        boolean exactlyMatch = false;
        String[] appArray = rule.getLimitApp().split(",");
        for (String app : appArray) {
            if (requester.equals(app)) {
                exactlyMatch = true;
                break;
            }
        }

        contain = exactlyMatch;
    }

    int strategy = rule.getStrategy();
    if (strategy == RuleConstant.AUTHORITY_BLACK && contain) {
        return false;
    }

    if (strategy == RuleConstant.AUTHORITY_WHITE && !contain) {
        return false;
    }

    return true;
}
 
Example #28
Source File: FlowRuleChecker.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
static Node selectNodeByRequesterAndStrategy(/*@NonNull*/ FlowRule rule, Context context, DefaultNode node) {
    // The limit app should not be empty.
    String limitApp = rule.getLimitApp();
    int strategy = rule.getStrategy();
    String origin = context.getOrigin();

    if (limitApp.equals(origin) && filterOrigin(origin)) {
        if (strategy == RuleConstant.STRATEGY_DIRECT) {
            // Matches limit origin, return origin statistic node.
            return context.getOriginNode();
        }

        return selectReferenceNode(rule, context, node);
    } else if (RuleConstant.LIMIT_APP_DEFAULT.equals(limitApp)) {
        if (strategy == RuleConstant.STRATEGY_DIRECT) {
            // Return the cluster node.
            return node.getClusterNode();
        }

        return selectReferenceNode(rule, context, node);
    } else if (RuleConstant.LIMIT_APP_OTHER.equals(limitApp)
        && FlowRuleManager.isOtherOrigin(origin, rule.getResource())) {
        if (strategy == RuleConstant.STRATEGY_DIRECT) {
            return context.getOriginNode();
        }

        return selectReferenceNode(rule, context, node);
    }

    return null;
}
 
Example #29
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 #30
Source File: AuthorityDemo.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
private static void initBlackRules() {
    AuthorityRule rule = new AuthorityRule();
    rule.setResource(RESOURCE_NAME);
    rule.setStrategy(RuleConstant.AUTHORITY_BLACK);
    rule.setLimitApp("appA,appB");
    AuthorityRuleManager.loadRules(Collections.singletonList(rule));
}