com.alibaba.csp.sentinel.EntryType Java Examples

The following examples show how to use com.alibaba.csp.sentinel.EntryType. 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: 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 #2
Source File: AbstractSentinelInterceptor.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
    throws Exception {
    try {
        String resourceName = getResourceName(request);

        if (StringUtil.isNotEmpty(resourceName)) {
            // Parse the request origin using registered origin parser.
            String origin = parseOrigin(request);
            String contextName = getContextName(request);
            ContextUtil.enter(contextName, origin);
            Entry entry = SphU.entry(resourceName, ResourceTypeConstants.COMMON_WEB, EntryType.IN);

            setEntryInRequest(request, baseWebMvcConfig.getRequestAttributeName(), entry);
        }
        return true;
    } catch (BlockException e) {
        try {
            handleBlockException(request, response, e);
        } finally {
            ContextUtil.exit();
        }
        return false;
    }
}
 
Example #3
Source File: FreqParamFlowController.java    From sentinel-tutorial with Apache License 2.0 6 votes vote down vote up
/**
 * 热点参数限流
 */
@GetMapping("/freqParamFlowWithoutParam")
public @ResponseBody
String freqParamFlowWithoutParam(@RequestParam("uid") Long uid,@RequestParam("ip") Long ip) {
    Entry entry = null;
    String retVal;
    try{
        // 如果不传入任何参数,来查询热点参数限流的效果
        entry = SphU.entry(resourceName, EntryType.IN,1);
        retVal = "passed";
    }catch(BlockException e){
        retVal = "blocked";
    }finally {
        if(entry!=null){
            entry.exit();
        }
    }
    return retVal;
}
 
Example #4
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 #5
Source File: PullConsumerDemo.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
private static void doSomething(MessageExt message) {
    pool.submit(() -> {
        Entry entry = null;
        try {
            ContextUtil.enter(KEY);
            entry = SphU.entry(KEY, EntryType.OUT);

            // Your business logic here.
            System.out.printf("[%d][%s][Success: %d] Receive New Messages: %s %n", System.currentTimeMillis(),
                Thread.currentThread().getName(), SUCCESS_COUNT.addAndGet(1), new String(message.getBody()));
        } catch (BlockException ex) {
            // Blocked.
            System.out.println("Blocked: " + FAIL_COUNT.addAndGet(1));
        } finally {
            if (entry != null) {
                entry.exit();
            }
            ContextUtil.exit();
        }
    });
}
 
Example #6
Source File: ParamFlowQpsRunner.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {

    while (!stop) {
        Entry entry = null;
        T param = generateParam();
        try {
            entry = SphU.entry(resourceName, EntryType.IN, 1, param);
            // Add pass for parameter.
            passFor(param);
        } catch (BlockException e) {
            // block.incrementAndGet();
            blockFor(param);
        } catch (Exception ex) {
            // biz exception
            ex.printStackTrace();
        } finally {
            // total.incrementAndGet();
            if (entry != null) {
                entry.exit(1, param);
            }
        }

        sleep(ThreadLocalRandom.current().nextInt(0, 10));
    }
}
 
Example #7
Source File: ParamFlowQpsRunner.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {

    while (!stop) {
        Entry entry = null;
        T param = generateParam();
        try {
            entry = SphU.entry(resourceName, EntryType.IN, 1, param);
            // Add pass for parameter.
            passFor(param);
        } catch (BlockException e) {
            // block.incrementAndGet();
            blockFor(param);
        } catch (Exception ex) {
            // biz exception
            ex.printStackTrace();
        } finally {
            // total.incrementAndGet();
            if (entry != null) {
                entry.exit(1, param);
            }
        }

        sleep(ThreadLocalRandom.current().nextInt(0, 10));
    }
}
 
Example #8
Source File: DemoController.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@RequestMapping("/link")
@ResponseBody
public String link() throws BlockException {

    Entry entry = SphU.entry("head1", EntryType.IN);

    Entry entry1 = SphU.entry("head2", EntryType.IN);
    Entry entry2 = SphU.entry("head3", EntryType.IN);
    Entry entry3 = SphU.entry("head4", EntryType.IN);

    entry3.exit();
    entry2.exit();
    entry1.exit();
    entry.exit();
    return "successfully create a call link";
}
 
Example #9
Source File: FreqParamFlowController.java    From sentinel-tutorial with Apache License 2.0 6 votes vote down vote up
/**
 * 热点参数限流
 * 构造不同的uid的值,并且以不同的频率来请求该方法,查看效果
 */
@GetMapping("/freqParamFlow")
public @ResponseBody
String freqParamFlow(@RequestParam("uid") Long uid,@RequestParam("ip") Long ip) {
    Entry entry = null;
    String retVal;
    try{
        // 只对参数 uid 的值进行限流,参数 ip 的值不进行限制
        entry = SphU.entry(resourceName, EntryType.IN,1,uid);
        retVal = "passed";
    }catch(BlockException e){
        retVal = "blocked";
    }finally {
        if(entry!=null){
            entry.exit();
        }
    }
    return retVal;
}
 
Example #10
Source File: MetricExitCallbackTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Test
public void onExit() {
    FakeMetricExtension extension = new FakeMetricExtension();
    MetricExtensionProvider.addMetricExtension(extension);

    MetricExitCallback exitCallback = new MetricExitCallback();
    StringResourceWrapper resourceWrapper = new StringResourceWrapper("resource", EntryType.OUT);
    int count = 2;
    Object[] args = {"args1", "args2"};
    extension.rt = 20;
    extension.success = 6;
    extension.thread = 10;
    Context context = mock(Context.class);
    Entry entry = mock(Entry.class);
    when(entry.getError()).thenReturn(null);
    when(entry.getCreateTime()).thenReturn(TimeUtil.currentTimeMillis() - 100);
    when(context.getCurEntry()).thenReturn(entry);
    exitCallback.onExit(context, resourceWrapper, count, args);
    Assert.assertEquals(120, extension.rt, 10);
    Assert.assertEquals(extension.success, 6 + count);
    Assert.assertEquals(extension.thread, 10 - 1);
}
 
Example #11
Source File: FlowSlotTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Test(expected = FlowException.class)
@SuppressWarnings("unchecked")
public void testCheckFlowBlock() 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";
    FlowRule rule = new FlowRule(resA).setCount(10);
    FlowRuleManager.loadRules(Collections.singletonList(rule));

    when(checker.canPassCheck(any(FlowRule.class), any(Context.class), any(DefaultNode.class), anyInt(), anyBoolean()))
        .thenReturn(false);

    flowSlot.checkFlow(new StringResourceWrapper(resA, EntryType.IN), context, node, 1, false);
}
 
Example #12
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 #13
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 #14
Source File: ParamFlowCheckerTest.java    From Sentinel 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 #15
Source File: FlowSlotTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Test(expected = FlowException.class)
@SuppressWarnings("unchecked")
public void testCheckFlowBlock() 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";
    FlowRule rule = new FlowRule(resA).setCount(10);
    FlowRuleManager.loadRules(Collections.singletonList(rule));

    when(checker.canPassCheck(any(FlowRule.class), any(Context.class), any(DefaultNode.class), anyInt(), anyBoolean()))
        .thenReturn(false);

    flowSlot.checkFlow(new StringResourceWrapper(resA, EntryType.IN), context, node, 1, false);
}
 
Example #16
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 #17
Source File: ClusterBuilderSlot.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
/**
 * Get {@link ClusterNode} of the resource name.
 *
 * @param id resource name.
 * @return the {@link ClusterNode}.
 */
public static ClusterNode getClusterNode(String id) {
    if (id == null) {
        return null;
    }
    ClusterNode clusterNode = null;

    for (EntryType nodeType : EntryType.values()) {
        clusterNode = clusterNodeMap.get(new StringResourceWrapper(id, nodeType));
        if (clusterNode != null) {
            break;
        }
    }

    return clusterNode;
}
 
Example #18
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 #19
Source File: PullConsumerDemo.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
private static void doSomething(MessageExt message) {
    pool.submit(() -> {
        Entry entry = null;
        try {
            ContextUtil.enter(KEY);
            entry = SphU.entry(KEY, EntryType.OUT);

            // Your business logic here.
            System.out.printf("[%d][%s][Success: %d] Receive New Messages: %s %n", System.currentTimeMillis(),
                Thread.currentThread().getName(), SUCCESS_COUNT.addAndGet(1), new String(message.getBody()));
        } catch (BlockException ex) {
            // Blocked.
            System.out.println("Blocked: " + FAIL_COUNT.addAndGet(1));
        } finally {
            if (entry != null) {
                entry.exit();
            }
            ContextUtil.exit();
        }
    });
}
 
Example #20
Source File: SentinelZuulPreFilter.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
private void doSentinelEntry(String resourceName, final int resType, RequestContext requestContext,
                             Deque<EntryHolder> holders) throws BlockException {
    Object[] params = paramParser.parseParameterFor(resourceName, requestContext,
        new Predicate<GatewayFlowRule>() {
            @Override
            public boolean test(GatewayFlowRule r) {
                return r.getResourceMode() == resType;
            }
        });
    AsyncEntry entry = SphU.asyncEntry(resourceName, ResourceTypeConstants.COMMON_API_GATEWAY,
            EntryType.IN, params);
    EntryHolder holder = new EntryHolder(entry, params);
    holders.push(holder);
}
 
Example #21
Source File: MonoSentinelOperatorIntegrationTest.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Test
public void testTransformMonoWithSentinelContextEnter() {
    String resourceName = createResourceName("testTransformMonoWithSentinelContextEnter");
    String contextName = "test_reactive_context";
    String origin = "originA";
    FlowRuleManager.loadRules(Collections.singletonList(
        new FlowRule(resourceName).setCount(0).setLimitApp(origin).as(FlowRule.class)
    ));
    StepVerifier.create(Mono.just(2)
        .transform(new SentinelReactorTransformer<>(
            // Customized context with origin.
            new EntryConfig(resourceName, EntryType.OUT, new ContextConfig(contextName, origin))))
    )
        .expectError(BlockException.class)
        .verify();

    ClusterNode cn = ClusterBuilderSlot.getClusterNode(resourceName);
    assertNotNull(cn);
    assertEquals(0, cn.passQps(), 0.01);
    assertEquals(1, cn.blockRequest());
    assertTrue(Constants.ROOT.getChildList()
        .stream()
        .filter(node -> node instanceof EntranceNode)
        .map(e -> (EntranceNode)e)
        .anyMatch(e -> e.getId().getName().equals(contextName))
    );

    FlowRuleManager.loadRules(new ArrayList<>());
}
 
Example #22
Source File: ContextUtil.java    From Sentinel 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 {
                LOCK.lock();
                try {
                    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 #23
Source File: SentinelConfigBuilder.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
@Override
public SentinelCircuitBreakerConfiguration build() {
	Assert.hasText(resourceName, "resourceName cannot be empty");
	List<DegradeRule> rules = Optional.ofNullable(this.rules)
			.orElse(new ArrayList<>());

	EntryType entryType = Optional.ofNullable(this.entryType).orElse(EntryType.OUT);
	return new SentinelCircuitBreakerConfiguration()
			.setResourceName(this.resourceName).setEntryType(entryType)
			.setRules(rules);
}
 
Example #24
Source File: ParamFlowSlotTest.java    From Sentinel 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 #25
Source File: AuthoritySlotTest.java    From Sentinel-Dashboard-Nacos 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 #26
Source File: StatisticSlot.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Override
public void exit(Context context, ResourceWrapper resourceWrapper, int count, Object... args) {
    Node node = context.getCurNode();

    if (context.getCurEntry().getBlockError() == null) {
        // Calculate response time (use completeStatTime as the time of completion).
        long completeStatTime = TimeUtil.currentTimeMillis();
        context.getCurEntry().setCompleteTimestamp(completeStatTime);
        long rt = completeStatTime - context.getCurEntry().getCreateTimestamp();

        Throwable error = context.getCurEntry().getError();

        // Record response time and success count.
        recordCompleteFor(node, count, rt, error);
        recordCompleteFor(context.getCurEntry().getOriginNode(), count, rt, error);
        if (resourceWrapper.getEntryType() == EntryType.IN) {
            recordCompleteFor(Constants.ENTRY_NODE, count, rt, error);
        }
    }

    // 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 #27
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 #28
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 #29
Source File: ParamFlowCheckerTest.java    From Sentinel-Dashboard-Nacos 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 #30
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));
}