Java Code Examples for com.alibaba.csp.sentinel.EntryType#IN

The following examples show how to use com.alibaba.csp.sentinel.EntryType#IN . 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: ParameterMetricStorageTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Test
public void testInitParamMetrics() {
    ParamFlowRule rule = new ParamFlowRule();
    rule.setParamIdx(1);
    int index = 1;
    String resourceName = "res-" + System.currentTimeMillis();
    ResourceWrapper resourceWrapper = new StringResourceWrapper(resourceName, EntryType.IN);

    assertNull(ParameterMetricStorage.getParamMetric(resourceWrapper));

    ParameterMetricStorage.initParamMetricsFor(resourceWrapper, rule);
    ParameterMetric metric = ParameterMetricStorage.getParamMetric(resourceWrapper);
    assertNotNull(metric);
    assertNotNull(metric.getRuleTimeCounterMap().get(rule));
    assertNotNull(metric.getThreadCountMap().get(index));

    // Duplicate init.
    ParameterMetricStorage.initParamMetricsFor(resourceWrapper, rule);
    assertSame(metric, ParameterMetricStorage.getParamMetric(resourceWrapper));

    ParamFlowRule rule2 = new ParamFlowRule();
    rule2.setParamIdx(1);
    assertSame(metric, ParameterMetricStorage.getParamMetric(resourceWrapper));
}
 
Example 2
Source File: ParamFlowCheckerTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Test
public void testPassLocalCheckForCollection() throws InterruptedException {
    final String resourceName = "testPassLocalCheckForCollection";
    final ResourceWrapper resourceWrapper = new StringResourceWrapper(resourceName, EntryType.IN);
    int paramIdx = 0;
    double globalThreshold = 1;

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

    String v1 = "a", v2 = "B", v3 = "Cc";
    List<String> list = Arrays.asList(v1, v2, v3);
    ParameterMetric metric = new ParameterMetric();
    ParameterMetricStorage.getMetricsMap().put(resourceWrapper.getName(), metric);
    metric.getRuleTimeCounterMap().put(rule, new ConcurrentLinkedHashMapWrapper<Object, AtomicLong>(4000));
    metric.getRuleTokenCounterMap().put(rule, new ConcurrentLinkedHashMapWrapper<Object, AtomicLong>(4000));

    assertTrue(ParamFlowChecker.passCheck(resourceWrapper, rule, 1, list));
    assertFalse(ParamFlowChecker.passCheck(resourceWrapper, rule, 1, list));
}
 
Example 3
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 4
Source File: ParameterMetricStorageTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Test
public void testInitParamMetrics() {
    ParamFlowRule rule = new ParamFlowRule();
    rule.setParamIdx(1);
    int index = 1;
    String resourceName = "res-" + System.currentTimeMillis();
    ResourceWrapper resourceWrapper = new StringResourceWrapper(resourceName, EntryType.IN);

    assertNull(ParameterMetricStorage.getParamMetric(resourceWrapper));

    ParameterMetricStorage.initParamMetricsFor(resourceWrapper, rule);
    ParameterMetric metric = ParameterMetricStorage.getParamMetric(resourceWrapper);
    assertNotNull(metric);
    assertNotNull(metric.getRuleTimeCounterMap().get(rule));
    assertNotNull(metric.getThreadCountMap().get(index));

    // Duplicate init.
    ParameterMetricStorage.initParamMetricsFor(resourceWrapper, rule);
    assertSame(metric, ParameterMetricStorage.getParamMetric(resourceWrapper));

    ParamFlowRule rule2 = new ParamFlowRule();
    rule2.setParamIdx(1);
    assertSame(metric, ParameterMetricStorage.getParamMetric(resourceWrapper));
}
 
Example 5
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 6
Source File: SentinelWebFluxFilter.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
private SentinelReactorTransformer<Void> buildSentinelTransformer(ServerWebExchange exchange, String finalPath) {
    String origin = Optional.ofNullable(WebFluxCallbackManager.getRequestOriginParser())
        .map(f -> f.apply(exchange))
        .orElse(EMPTY_ORIGIN);

    return new SentinelReactorTransformer<>(new EntryConfig(finalPath, ResourceTypeConstants.COMMON_WEB,
        EntryType.IN, new ContextConfig(finalPath, origin)));
}
 
Example 7
Source File: ParamFlowCheckerTest.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Test
public void testHotParamCheckerPassCheckExceedArgs() {
    final String resourceName = "testHotParamCheckerPassCheckExceedArgs";
    final ResourceWrapper resourceWrapper = new StringResourceWrapper(resourceName, EntryType.IN);
    int paramIdx = 1;

    ParamFlowRule rule = new ParamFlowRule();
    rule.setResource(resourceName);
    rule.setCount(10);
    rule.setParamIdx(paramIdx);

    assertTrue("The rule will pass if the paramIdx exceeds provided args",
            ParamFlowChecker.passCheck(resourceWrapper, rule, 1, "abc"));
}
 
Example 8
Source File: ContextUtil.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
protected static Context trueEnter(String name, String origin) {
    Context context = contextHolder.get();
    if (context == null) {
        Map<String, DefaultNode> localCacheNameMap = contextNameNodeMap;
        DefaultNode node = localCacheNameMap.get(name);
        if (node == null) {
            if (localCacheNameMap.size() > Constants.MAX_CONTEXT_NAME_SIZE) {
                setNullContext();
                return NULL_CONTEXT;
            } else {
                try {
                    LOCK.lock();
                    node = contextNameNodeMap.get(name);
                    if (node == null) {
                        if (contextNameNodeMap.size() > Constants.MAX_CONTEXT_NAME_SIZE) {
                            setNullContext();
                            return NULL_CONTEXT;
                        } else {
                            node = new EntranceNode(new StringResourceWrapper(name, EntryType.IN), null);
                            // Add entrance node.
                            Constants.ROOT.addChild(node);

                            Map<String, DefaultNode> newMap = new HashMap<>(contextNameNodeMap.size() + 1);
                            newMap.putAll(contextNameNodeMap);
                            newMap.put(name, node);
                            contextNameNodeMap = newMap;
                        }
                    }
                } finally {
                    LOCK.unlock();
                }
            }
        }
        context = new Context(node, name);
        context.setOrigin(origin);
        contextHolder.set(context);
    }

    return context;
}
 
Example 9
Source File: StatisticSlot.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@Override
public void exit(Context context, ResourceWrapper resourceWrapper, int count, Object... args) {
    DefaultNode node = (DefaultNode)context.getCurNode();

    if (context.getCurEntry().getError() == null) {
        // Calculate response time (max RT is TIME_DROP_VALVE).
        long rt = TimeUtil.currentTimeMillis() - context.getCurEntry().getCreateTime();
        if (rt > Constants.TIME_DROP_VALVE) {
            rt = Constants.TIME_DROP_VALVE;
        }

        // Record response time and success count.
        node.addRtAndSuccess(rt, count);
        if (context.getCurEntry().getOriginNode() != null) {
            context.getCurEntry().getOriginNode().addRtAndSuccess(rt, count);
        }

        node.decreaseThreadNum();

        if (context.getCurEntry().getOriginNode() != null) {
            context.getCurEntry().getOriginNode().decreaseThreadNum();
        }

        if (resourceWrapper.getType() == EntryType.IN) {
            Constants.ENTRY_NODE.addRtAndSuccess(rt, count);
            Constants.ENTRY_NODE.decreaseThreadNum();
        }
    } else {
        // Error may happen.
    }

    // Handle exit event with registered exit callback handlers.
    Collection<ProcessorSlotExitCallback> exitCallbacks = StatisticSlotCallbackRegistry.getExitCallbacks();
    for (ProcessorSlotExitCallback handler : exitCallbacks) {
        handler.onExit(context, resourceWrapper, count, args);
    }

    fireExit(context, resourceWrapper, count);
}
 
Example 10
Source File: ParamFlowCheckerTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@Test
public void testSingleValueCheckQpsWithExceptionItems() throws InterruptedException {
    final String resourceName = "testSingleValueCheckQpsWithExceptionItems";
    final ResourceWrapper resourceWrapper = new StringResourceWrapper(resourceName, EntryType.IN);
    TimeUtil.currentTimeMillis();
    int paramIdx = 0;

    long globalThreshold = 5L;
    int thresholdB = 0;
    int thresholdD = 7;

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

    String valueA = "valueA";
    String valueB = "valueB";
    String valueC = "valueC";
    String valueD = "valueD";

    // Directly set parsed map for test.
    Map<Object, Integer> map = new HashMap<Object, Integer>();
    map.put(valueB, thresholdB);
    map.put(valueD, thresholdD);
    rule.setParsedHotItems(map);

    ParameterMetric metric = new ParameterMetric();
    ParameterMetricStorage.getMetricsMap().put(resourceWrapper.getName(), metric);
    metric.getRuleTimeCounterMap().put(rule, new ConcurrentLinkedHashMapWrapper<Object, AtomicLong>(4000));

    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertFalse(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueB));
    TimeUnit.SECONDS.sleep(3);
}
 
Example 11
Source File: AuthoritySlotTest.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Test
public void testCheckAuthorityNoExceptionItemsSuccess() throws Exception {
    String origin = "appA";
    String resourceName = "testCheckAuthorityNoExceptionItemsSuccess";
    ResourceWrapper resourceWrapper = new StringResourceWrapper(resourceName, EntryType.IN);
    ContextUtil.enter("entrance", origin);
    try {
        AuthorityRule ruleA = new AuthorityRule()
            .setResource(resourceName)
            .setLimitApp(origin + ",appB")
            .as(AuthorityRule.class)
            .setStrategy(RuleConstant.AUTHORITY_WHITE);

        AuthorityRuleManager.loadRules(Collections.singletonList(ruleA));
        authoritySlot.checkBlackWhiteAuthority(resourceWrapper, ContextUtil.getContext());

        AuthorityRule ruleB = new AuthorityRule()
            .setResource(resourceName)
            .setLimitApp("appD")
            .as(AuthorityRule.class)
            .setStrategy(RuleConstant.AUTHORITY_BLACK);

        AuthorityRuleManager.loadRules(Collections.singletonList(ruleB));
        authoritySlot.checkBlackWhiteAuthority(resourceWrapper, ContextUtil.getContext());
    } finally {
        ContextUtil.exit();
    }
}
 
Example 12
Source File: ParamFlowCheckerTest.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Test
public void testSingleValueCheckQpsWithExceptionItems() throws InterruptedException {
    final String resourceName = "testSingleValueCheckQpsWithExceptionItems";
    final ResourceWrapper resourceWrapper = new StringResourceWrapper(resourceName, EntryType.IN);
    TimeUtil.currentTimeMillis();
    int paramIdx = 0;

    long globalThreshold = 5L;
    int thresholdB = 0;
    int thresholdD = 7;

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

    String valueA = "valueA";
    String valueB = "valueB";
    String valueC = "valueC";
    String valueD = "valueD";

    // Directly set parsed map for test.
    Map<Object, Integer> map = new HashMap<Object, Integer>();
    map.put(valueB, thresholdB);
    map.put(valueD, thresholdD);
    rule.setParsedHotItems(map);

    ParameterMetric metric = new ParameterMetric();
    ParameterMetricStorage.getMetricsMap().put(resourceWrapper.getName(), metric);
    metric.getRuleTimeCounterMap().put(rule, new ConcurrentLinkedHashMapWrapper<Object, AtomicLong>(4000));

    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertFalse(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueB));
    TimeUnit.SECONDS.sleep(3);
}
 
Example 13
Source File: ParamFlowDefaultCheckerTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@Test
public void testCheckQpsWithLongIntervalAndHighThreshold() {
    // This test case is intended to avoid number overflow.
    final String resourceName = "testCheckQpsWithLongIntervalAndHighThreshold";
    final ResourceWrapper resourceWrapper = new StringResourceWrapper(resourceName, EntryType.IN);
    int paramIdx = 0;

    // Set a large threshold.
    long threshold = 25000L;

    ParamFlowRule rule = new ParamFlowRule(resourceName)
        .setCount(threshold)
        .setParamIdx(paramIdx);

    String valueA = "valueA";
    ParameterMetric metric = new ParameterMetric();
    ParameterMetricStorage.getMetricsMap().put(resourceWrapper.getName(), metric);
    metric.getRuleTimeCounterMap().put(rule, new ConcurrentLinkedHashMapWrapper<Object, AtomicLong>(4000));
    metric.getRuleTokenCounterMap().put(rule,
        new ConcurrentLinkedHashMapWrapper<Object, AtomicLong>(4000));

    // We mock the time directly to avoid unstable behaviour.
    setCurrentMillis(System.currentTimeMillis());

    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));

    // 24 hours passed.
    // This can make `toAddCount` larger that Integer.MAX_VALUE.
    sleep(1000 * 60 * 60 * 24);
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));

    // 48 hours passed.
    sleep(1000 * 60 * 60 * 48);
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
}
 
Example 14
Source File: ParamFlowSlotTest.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Test
public void testEntryWhenParamFlowRuleNotExists() throws Throwable {
    String resourceName = "testEntryWhenParamFlowRuleNotExists";
    ResourceWrapper resourceWrapper = new StringResourceWrapper(resourceName, EntryType.IN);
    paramFlowSlot.entry(null, resourceWrapper, null, 1, false, "abc");
    // The parameter metric instance will not be created.
    assertNull(ParameterMetricStorage.getParamMetric(resourceWrapper));
}
 
Example 15
Source File: ParamFlowDefaultCheckerTest.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Test
public void testParamFlowDefaultCheckSingleQps() {
    final String resourceName = "testParamFlowDefaultCheckSingleQps";
    final ResourceWrapper resourceWrapper = new StringResourceWrapper(resourceName, EntryType.IN);
    int paramIdx = 0;

    long threshold = 5L;

    ParamFlowRule rule = new ParamFlowRule();
    rule.setResource(resourceName);
    rule.setCount(threshold);
    rule.setParamIdx(paramIdx);

    String valueA = "valueA";
    ParameterMetric metric = new ParameterMetric();
    ParameterMetricStorage.getMetricsMap().put(resourceWrapper.getName(), metric);
    metric.getRuleTimeCounterMap().put(rule, new ConcurrentLinkedHashMapWrapper<Object, AtomicLong>(4000));
    metric.getRuleTokenCounterMap().put(rule,
        new ConcurrentLinkedHashMapWrapper<Object, AtomicLong>(4000));

    // We mock the time directly to avoid unstable behaviour.
    setCurrentMillis(System.currentTimeMillis());

    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertFalse(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));

    sleep(3000);
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertFalse(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
}
 
Example 16
Source File: ParamFlowSlotTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@Test
public void testNegativeParamIdx() throws Throwable {
    String resourceName = "testNegativeParamIdx";
    ResourceWrapper resourceWrapper = new StringResourceWrapper(resourceName, EntryType.IN);
    ParamFlowRule rule = new ParamFlowRule(resourceName)
        .setCount(1)
        .setParamIdx(-1);
    ParamFlowRuleManager.loadRules(Collections.singletonList(rule));
    paramFlowSlot.entry(null, resourceWrapper, null, 1, false, "abc", "def", "ghi");
    assertEquals(2, rule.getParamIdx().longValue());

    rule.setParamIdx(-1);
    ParamFlowRuleManager.loadRules(Collections.singletonList(rule));
    paramFlowSlot.entry(null, resourceWrapper, null, 1, false, null);
    // Null args will not trigger conversion.
    assertEquals(-1, rule.getParamIdx().intValue());

    rule.setParamIdx(-100);
    ParamFlowRuleManager.loadRules(Collections.singletonList(rule));
    paramFlowSlot.entry(null, resourceWrapper, null, 1, false, "abc", "def", "ghi");
    assertEquals(100, rule.getParamIdx().longValue());

    rule.setParamIdx(0);
    ParamFlowRuleManager.loadRules(Collections.singletonList(rule));
    paramFlowSlot.entry(null, resourceWrapper, null, 1, false, "abc", "def", "ghi");
    assertEquals(0, rule.getParamIdx().longValue());
}
 
Example 17
Source File: ParamFlowThrottleRateLimitingCheckerTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 4 votes vote down vote up
@Test
public void testSingleValueThrottleCheckQps() throws Exception {
    final String resourceName = "testSingleValueThrottleCheckQps";
    final ResourceWrapper resourceWrapper = new StringResourceWrapper(resourceName, EntryType.IN);
    int paramIdx = 0;
    TimeUtil.currentTimeMillis();

    long threshold = 5L;

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

    String valueA = "valueA";
    ParameterMetric metric = new ParameterMetric();
    ParameterMetricStorage.getMetricsMap().put(resourceWrapper.getName(), metric);
    metric.getRuleTimeCounterMap().put(rule, new ConcurrentLinkedHashMapWrapper<Object, AtomicLong>(4000));

    long currentTime = TimeUtil.currentTimeMillis();
    long endTime = currentTime + rule.getDurationInSec() * 1000;
    int successCount = 0;
    while (currentTime <= endTime - 10) {
        if (ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA)) {
            successCount++;
        }
        currentTime = TimeUtil.currentTimeMillis();
    }
    assertEquals(successCount, threshold);

    System.out.println("testSingleValueThrottleCheckQps: sleep for 3 seconds");
    TimeUnit.SECONDS.sleep(3);

    currentTime = TimeUtil.currentTimeMillis();
    endTime = currentTime + rule.getDurationInSec() * 1000;
    successCount = 0;
    while (currentTime <= endTime - 10) {
        if (ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA)) {
            successCount++;
        }
        currentTime = TimeUtil.currentTimeMillis();
    }
    assertEquals(successCount, threshold);
}
 
Example 18
Source File: ParamFlowDefaultCheckerTest.java    From Sentinel with Apache License 2.0 4 votes vote down vote up
@Test
public void testParamFlowDefaultCheckSingleQpsWithBurst() throws InterruptedException {
    final String resourceName = "testParamFlowDefaultCheckSingleQpsWithBurst";
    final ResourceWrapper resourceWrapper = new StringResourceWrapper(resourceName, EntryType.IN);
    int paramIdx = 0;

    long threshold = 5L;

    ParamFlowRule rule = new ParamFlowRule();
    rule.setResource(resourceName);
    rule.setCount(threshold);
    rule.setParamIdx(paramIdx);
    rule.setBurstCount(3);

    String valueA = "valueA";
    ParameterMetric metric = new ParameterMetric();
    ParameterMetricStorage.getMetricsMap().put(resourceWrapper.getName(), metric);
    metric.getRuleTimeCounterMap().put(rule, new ConcurrentLinkedHashMapWrapper<Object, AtomicLong>(4000));
    metric.getRuleTokenCounterMap().put(rule,
        new ConcurrentLinkedHashMapWrapper<Object, AtomicLong>(4000));

    // We mock the time directly to avoid unstable behaviour.
    setCurrentMillis(System.currentTimeMillis());

    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertFalse(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));

    sleep(1002);
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertFalse(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));

    sleep(1002);
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertFalse(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));

    sleep(2000);
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertFalse(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));

    sleep(1002);
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertFalse(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
}
 
Example 19
Source File: ContextUtil.java    From Sentinel with Apache License 2.0 4 votes vote down vote up
private static void initDefaultContext() {
    String defaultContextName = Constants.CONTEXT_DEFAULT_NAME;
    EntranceNode node = new EntranceNode(new StringResourceWrapper(defaultContextName, EntryType.IN), null);
    Constants.ROOT.addChild(node);
    contextNameNodeMap.put(defaultContextName, node);
}
 
Example 20
Source File: ParamFlowCheckerTest.java    From Sentinel with Apache License 2.0 4 votes vote down vote up
@Test
public void testSingleValueCheckThreadCountWithExceptionItems() {
    final String resourceName = "testSingleValueCheckThreadCountWithExceptionItems";
    final ResourceWrapper resourceWrapper = new StringResourceWrapper(resourceName, EntryType.IN);
    int paramIdx = 0;

    long globalThreshold = 5L;
    int thresholdB = 3;
    int thresholdD = 7;

    ParamFlowRule rule = new ParamFlowRule(resourceName).setCount(globalThreshold).setParamIdx(paramIdx)
            .setGrade(RuleConstant.FLOW_GRADE_THREAD);

    String valueA = "valueA";
    String valueB = "valueB";
    String valueC = "valueC";
    String valueD = "valueD";

    // Directly set parsed map for test.
    Map<Object, Integer> map = new HashMap<Object, Integer>();
    map.put(valueB, thresholdB);
    map.put(valueD, thresholdD);
    rule.setParsedHotItems(map);

    ParameterMetric metric = mock(ParameterMetric.class);
    when(metric.getThreadCount(paramIdx, valueA)).thenReturn(globalThreshold - 1);
    when(metric.getThreadCount(paramIdx, valueB)).thenReturn(globalThreshold - 1);
    when(metric.getThreadCount(paramIdx, valueC)).thenReturn(globalThreshold - 1);
    when(metric.getThreadCount(paramIdx, valueD)).thenReturn(globalThreshold + 1);
    ParameterMetricStorage.getMetricsMap().put(resourceWrapper.getName(), metric);

    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertFalse(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueB));
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueC));
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueD));

    when(metric.getThreadCount(paramIdx, valueA)).thenReturn(globalThreshold);
    when(metric.getThreadCount(paramIdx, valueB)).thenReturn(thresholdB - 1L);
    when(metric.getThreadCount(paramIdx, valueC)).thenReturn(globalThreshold + 1);
    when(metric.getThreadCount(paramIdx, valueD)).thenReturn(globalThreshold - 1).thenReturn((long) thresholdD);

    assertFalse(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA));
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueB));
    assertFalse(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueC));
    assertTrue(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueD));
    assertFalse(ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueD));
}