com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager Java Examples

The following examples show how to use com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager. 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: SpringCloudGatewayParamParserTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Test
public void testParseParametersNoParamItem() {
    // Mock a request.
    ServerWebExchange exchange = mock(ServerWebExchange.class);
    // Prepare gateway rules.
    Set<GatewayFlowRule> rules = new HashSet<>();
    String routeId1 = "my_test_route_A";
    rules.add(new GatewayFlowRule(routeId1)
        .setCount(5)
        .setIntervalSec(1)
    );
    GatewayRuleManager.loadRules(rules);

    Object[] params = paramParser.parseParameterFor(routeId1, exchange,
        e -> e.getResourceMode() == 0);
    assertThat(params.length).isEqualTo(1);
}
 
Example #2
Source File: SpringCloudGatewayParamParserTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Test
public void testParseParametersNoParamItem() {
    // Mock a request.
    ServerWebExchange exchange = mock(ServerWebExchange.class);
    // Prepare gateway rules.
    Set<GatewayFlowRule> rules = new HashSet<>();
    String routeId1 = "my_test_route_A";
    rules.add(new GatewayFlowRule(routeId1)
        .setCount(5)
        .setIntervalSec(1)
    );
    GatewayRuleManager.loadRules(rules);

    Object[] params = paramParser.parseParameterFor(routeId1, exchange,
        e -> e.getResourceMode() == 0);
    assertThat(params.length).isEqualTo(1);
}
 
Example #3
Source File: GatewayFlowSlot.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
private void checkGatewayParamFlow(ResourceWrapper resourceWrapper, int count, Object... args)
    throws BlockException {
    if (args == null) {
        return;
    }

    List<ParamFlowRule> rules = GatewayRuleManager.getConvertedParamRules(resourceWrapper.getName());
    if (rules == null || rules.isEmpty()) {
        return;
    }

    for (ParamFlowRule rule : rules) {
        // Initialize the parameter metrics.
        ParameterMetricStorage.initParamMetricsFor(resourceWrapper, rule);

        if (!ParamFlowChecker.passCheck(resourceWrapper, rule, count, args)) {
            String triggeredParam = "";
            if (args.length > rule.getParamIdx()) {
                Object value = args[rule.getParamIdx()];
                triggeredParam = String.valueOf(value);
            }
            throw new ParamFlowException(resourceWrapper.getName(), triggeredParam, rule);
        }
    }
}
 
Example #4
Source File: SentinelConfig.java    From lion with Apache License 2.0 6 votes vote down vote up
/**
 * 初始化限流规则(或在 dashboard 中配置)
 */
private void initGatewayRules() {
    Set<GatewayFlowRule> rules = new HashSet<>();
    rules.add(new GatewayFlowRule("lion-auth")
            // 限流阈值QPS
            .setCount(COUNT)
            // 统计时间窗口,单位是秒,默认是 1 秒
            .setIntervalSec(INTERVAL_SEC)
    );
    rules.add(new GatewayFlowRule("lion-demo-provider")
            .setCount(COUNT)
            .setIntervalSec(INTERVAL_SEC)
    );
    rules.add(new GatewayFlowRule("lion-demo-consumer")
            .setCount(COUNT)
            .setIntervalSec(INTERVAL_SEC)
    );
    GatewayRuleManager.loadRules(rules);
}
 
Example #5
Source File: UpdateGatewayRuleCommandHandler.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Override
public CommandResponse<String> handle(CommandRequest request) {
    String data = request.getParam("data");
    if (StringUtil.isBlank(data)) {
        return CommandResponse.ofFailure(new IllegalArgumentException("Bad data"));
    }
    try {
        data = URLDecoder.decode(data, "utf-8");
    } catch (Exception e) {
        RecordLog.info("Decode gateway rule data error", e);
        return CommandResponse.ofFailure(e, "decode gateway rule data error");
    }

    RecordLog.info(String.format("[API Server] Receiving rule change (type: gateway rule): %s", data));

    String result = SUCCESS_MSG;
 Set<GatewayFlowRule> flowRules = JSON.parseObject(data, new TypeReference<Set<GatewayFlowRule>>() {
 });
    GatewayRuleManager.loadRules(flowRules);
    if (!writeToDataSource(gatewayFlowWds, flowRules)) {
        result = WRITE_DS_FAILURE_MSG;
    }
    return CommandResponse.ofSuccess(result);
}
 
Example #6
Source File: GatewayParamParserTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Test
public void testParseParametersNoParamItem() {
    RequestItemParser<Object> itemParser = mock(RequestItemParser.class);
    GatewayParamParser<Object> parser = new GatewayParamParser<>(itemParser);
    // Create a fake request.
    Object request = new Object();
    // Prepare gateway rules.
    Set<GatewayFlowRule> rules = new HashSet<>();
    String routeId1 = "my_test_route_A";
    rules.add(new GatewayFlowRule(routeId1)
        .setCount(5)
        .setIntervalSec(1)
    );
    rules.add(new GatewayFlowRule(routeId1)
        .setCount(10)
        .setControlBehavior(2)
        .setMaxQueueingTimeoutMs(1000)
    );
    GatewayRuleManager.loadRules(rules);

    Object[] params = parser.parseParameterFor(routeId1, request, routeIdPredicate);
    assertThat(params.length).isEqualTo(1);
}
 
Example #7
Source File: GatewayFlowSlot.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
private void checkGatewayParamFlow(ResourceWrapper resourceWrapper, int count, Object... args)
    throws BlockException {
    if (args == null) {
        return;
    }

    List<ParamFlowRule> rules = GatewayRuleManager.getConvertedParamRules(resourceWrapper.getName());
    if (rules == null || rules.isEmpty()) {
        return;
    }

    for (ParamFlowRule rule : rules) {
        // Initialize the parameter metrics.
        ParameterMetricStorage.initParamMetricsFor(resourceWrapper, rule);

        if (!ParamFlowChecker.passCheck(resourceWrapper, rule, count, args)) {
            String triggeredParam = "";
            if (args.length > rule.getParamIdx()) {
                Object value = args[rule.getParamIdx()];
                triggeredParam = String.valueOf(value);
            }
            throw new ParamFlowException(resourceWrapper.getName(), triggeredParam, rule);
        }
    }
}
 
Example #8
Source File: UpdateGatewayRuleCommandHandler.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Override
public CommandResponse<String> handle(CommandRequest request) {
    String data = request.getParam("data");
    if (StringUtil.isBlank(data)) {
        return CommandResponse.ofFailure(new IllegalArgumentException("Bad data"));
    }
    try {
        data = URLDecoder.decode(data, "utf-8");
    } catch (Exception e) {
        RecordLog.info("Decode gateway rule data error", e);
        return CommandResponse.ofFailure(e, "decode gateway rule data error");
    }

    RecordLog.info(String.format("[API Server] Receiving rule change (type: gateway rule): %s", data));

    String result = SUCCESS_MSG;
    List<GatewayFlowRule> flowRules = JSONArray.parseArray(data, GatewayFlowRule.class);
    GatewayRuleManager.loadRules(new HashSet<>(flowRules));
    return CommandResponse.ofSuccess(result);
}
 
Example #9
Source File: GatewayParamParserTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Test
public void testParseParametersNoParamItem() {
    RequestItemParser<Object> itemParser = mock(RequestItemParser.class);
    GatewayParamParser<Object> parser = new GatewayParamParser<>(itemParser);
    // Create a fake request.
    Object request = new Object();
    // Prepare gateway rules.
    Set<GatewayFlowRule> rules = new HashSet<>();
    String routeId1 = "my_test_route_A";
    rules.add(new GatewayFlowRule(routeId1)
        .setCount(5)
        .setIntervalSec(1)
    );
    rules.add(new GatewayFlowRule(routeId1)
        .setCount(10)
        .setControlBehavior(2)
        .setMaxQueueingTimeoutMs(1000)
    );
    GatewayRuleManager.loadRules(rules);

    Object[] params = parser.parseParameterFor(routeId1, request, routeIdPredicate);
    assertThat(params.length).isEqualTo(1);
}
 
Example #10
Source File: AbstractDataSourceProperties.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
public void postRegister(AbstractDataSource dataSource) {
	switch (this.getRuleType()) {
	case FLOW:
		FlowRuleManager.register2Property(dataSource.getProperty());
		break;
	case DEGRADE:
		DegradeRuleManager.register2Property(dataSource.getProperty());
		break;
	case PARAM_FLOW:
		ParamFlowRuleManager.register2Property(dataSource.getProperty());
		break;
	case SYSTEM:
		SystemRuleManager.register2Property(dataSource.getProperty());
		break;
	case AUTHORITY:
		AuthorityRuleManager.register2Property(dataSource.getProperty());
		break;
	case GW_FLOW:
		GatewayRuleManager.register2Property(dataSource.getProperty());
		break;
	case GW_API_GROUP:
		GatewayApiDefinitionManager.register2Property(dataSource.getProperty());
		break;
	default:
		break;
	}
}
 
Example #11
Source File: GatewayConfiguration.java    From spring-cloud-sofastack-samples with Apache License 2.0 5 votes vote down vote up
/**
 * rules
 */
private void initGatewayRules() {
    Set<GatewayFlowRule> rules = new HashSet<>();
    rules.add(new GatewayFlowRule("biz-web")
    // 限流阈值
        .setCount(10)
        // 统计时间窗口,单位是秒,默认是 1 秒
        .setIntervalSec(1));
    GatewayRuleManager.loadRules(rules);
}
 
Example #12
Source File: GatewayParamParserTest.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Test
public void testParseParametersWithEmptyItemPattern() {
    RequestItemParser<Object> itemParser = mock(RequestItemParser.class);
    GatewayParamParser<Object> paramParser = new GatewayParamParser<>(itemParser);
    // Create a fake request.
    Object request = new Object();
    // Prepare gateway rules.
    Set<GatewayFlowRule> rules = new HashSet<>();
    final String routeId = "my_test_route_DS(*H";
    final String headerName = "X-Sentinel-Flag";
    GatewayFlowRule routeRule1 = new GatewayFlowRule(routeId)
        .setCount(10)
        .setIntervalSec(2)
        .setParamItem(new GatewayParamFlowItem()
            .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HEADER)
            .setFieldName(headerName)
            .setPattern("")
            .setMatchStrategy(SentinelGatewayConstants.PARAM_MATCH_STRATEGY_EXACT)
        );
    rules.add(routeRule1);
    GatewayRuleManager.loadRules(rules);

    mockSingleHeader(itemParser, headerName, "Sent1nel");
    Object[] params = paramParser.parseParameterFor(routeId, request, routeIdPredicate);
    assertThat(params.length).isEqualTo(1);
    // Empty pattern should not take effect.
    assertThat(params[routeRule1.getParamItem().getIndex()]).isEqualTo("Sent1nel");
}
 
Example #13
Source File: GatewayParamParserTest.java    From Sentinel with Apache License 2.0 4 votes vote down vote up
@Test
public void testParseParametersWithItemPatternMatching() {
    RequestItemParser<Object> itemParser = mock(RequestItemParser.class);
    GatewayParamParser<Object> paramParser = new GatewayParamParser<>(itemParser);
    // Create a fake request.
    Object request = new Object();

    // Prepare gateway rules.
    Set<GatewayFlowRule> rules = new HashSet<>();
    final String routeId1 = "my_test_route_F&@";
    final String api1 = "my_test_route_E5K";
    final String headerName = "X-Sentinel-Flag";
    final String paramName = "p";

    String nameEquals = "Wow";
    String nameContains = "warn";
    String valueRegex = "\\d+";
    GatewayFlowRule routeRule1 = new GatewayFlowRule(routeId1)
        .setCount(10)
        .setIntervalSec(1)
        .setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER)
        .setMaxQueueingTimeoutMs(600)
        .setParamItem(new GatewayParamFlowItem()
            .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HEADER)
            .setFieldName(headerName)
            .setPattern(nameEquals)
            .setMatchStrategy(SentinelGatewayConstants.PARAM_MATCH_STRATEGY_EXACT)
        );
    GatewayFlowRule routeRule2 = new GatewayFlowRule(routeId1)
        .setCount(20)
        .setIntervalSec(1)
        .setBurst(5)
        .setParamItem(new GatewayParamFlowItem()
            .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)
            .setFieldName(paramName)
            .setPattern(nameContains)
            .setMatchStrategy(SentinelGatewayConstants.PARAM_MATCH_STRATEGY_CONTAINS)
        );
    GatewayFlowRule apiRule1 = new GatewayFlowRule(api1)
        .setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_CUSTOM_API_NAME)
        .setCount(5)
        .setIntervalSec(1)
        .setParamItem(new GatewayParamFlowItem()
            .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)
            .setFieldName(paramName)
            .setPattern(valueRegex)
            .setMatchStrategy(SentinelGatewayConstants.PARAM_MATCH_STRATEGY_REGEX)
        );
    rules.add(routeRule1);
    rules.add(routeRule2);
    rules.add(apiRule1);
    GatewayRuleManager.loadRules(rules);

    mockSingleHeader(itemParser, headerName, nameEquals);
    mockSingleUrlParam(itemParser, paramName, nameContains);
    Object[] params = paramParser.parseParameterFor(routeId1, request, routeIdPredicate);
    assertThat(params.length).isEqualTo(2);
    assertThat(params[routeRule1.getParamItem().getIndex()]).isEqualTo(nameEquals);
    assertThat(params[routeRule2.getParamItem().getIndex()]).isEqualTo(nameContains);

    mockSingleHeader(itemParser, headerName, nameEquals + "_foo");
    mockSingleUrlParam(itemParser, paramName, nameContains + "_foo");
    params = paramParser.parseParameterFor(routeId1, request, routeIdPredicate);
    assertThat(params.length).isEqualTo(2);
    assertThat(params[routeRule1.getParamItem().getIndex()])
        .isEqualTo(SentinelGatewayConstants.GATEWAY_NOT_MATCH_PARAM);
    assertThat(params[routeRule2.getParamItem().getIndex()])
        .isEqualTo(nameContains + "_foo");

    mockSingleHeader(itemParser, headerName, "foo");
    mockSingleUrlParam(itemParser, paramName, "foo");
    params = paramParser.parseParameterFor(routeId1, request, routeIdPredicate);
    assertThat(params.length).isEqualTo(2);
    assertThat(params[routeRule1.getParamItem().getIndex()])
        .isEqualTo(SentinelGatewayConstants.GATEWAY_NOT_MATCH_PARAM);
    assertThat(params[routeRule2.getParamItem().getIndex()])
        .isEqualTo(SentinelGatewayConstants.GATEWAY_NOT_MATCH_PARAM);

    mockSingleUrlParam(itemParser, paramName, "23");
    params = paramParser.parseParameterFor(api1, request, apiNamePredicate);
    assertThat(params.length).isEqualTo(1);
    assertThat(params[apiRule1.getParamItem().getIndex()]).isEqualTo("23");

    mockSingleUrlParam(itemParser, paramName, "some233");
    params = paramParser.parseParameterFor(api1, request, apiNamePredicate);
    assertThat(params.length).isEqualTo(1);
    assertThat(params[apiRule1.getParamItem().getIndex()])
        .isEqualTo(SentinelGatewayConstants.GATEWAY_NOT_MATCH_PARAM);
}
 
Example #14
Source File: GatewayParamParserTest.java    From Sentinel with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() {
    GatewayApiDefinitionManager.loadApiDefinitions(new HashSet<ApiDefinition>());
    GatewayRuleManager.loadRules(new HashSet<GatewayFlowRule>());
    GatewayRegexCache.clear();
}
 
Example #15
Source File: GatewayParamParserTest.java    From Sentinel with Apache License 2.0 4 votes vote down vote up
@After
public void tearDown() {
    GatewayApiDefinitionManager.loadApiDefinitions(new HashSet<ApiDefinition>());
    GatewayRuleManager.loadRules(new HashSet<GatewayFlowRule>());
    GatewayRegexCache.clear();
}
 
Example #16
Source File: RulesWebFluxController.java    From spring-cloud-alibaba with Apache License 2.0 4 votes vote down vote up
@GetMapping("/gateway")
public Mono<Set<GatewayFlowRule>> apiGateway() {
	return Mono.just(GatewayRuleManager.getRules());
}
 
Example #17
Source File: GetGatewayRuleCommandHandler.java    From Sentinel with Apache License 2.0 4 votes vote down vote up
@Override
public CommandResponse<String> handle(CommandRequest request) {
    return CommandResponse.ofSuccess(JSON.toJSONString(GatewayRuleManager.getRules()));
}
 
Example #18
Source File: RulesController.java    From spring-cloud-alibaba with Apache License 2.0 4 votes vote down vote up
@GetMapping("/gateway")
public Set<GatewayFlowRule> apiGateway() {
	return GatewayRuleManager.getRules();
}
 
Example #19
Source File: SentinelGatewayFilterTest.java    From Sentinel with Apache License 2.0 4 votes vote down vote up
@After
public void tearDown() {
    GatewayApiDefinitionManager.loadApiDefinitions(new HashSet<>());
    GatewayRuleManager.loadRules(new HashSet<>());
}
 
Example #20
Source File: GatewayConfiguration.java    From Sentinel with Apache License 2.0 4 votes vote down vote up
private void initGatewayRules() {
    Set<GatewayFlowRule> rules = new HashSet<>();
    rules.add(new GatewayFlowRule("aliyun_route")
        .setCount(10)
        .setIntervalSec(1)
    );
    rules.add(new GatewayFlowRule("aliyun_route")
        .setCount(2)
        .setIntervalSec(2)
        .setBurst(2)
        .setParamItem(new GatewayParamFlowItem()
            .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_CLIENT_IP)
        )
    );
    rules.add(new GatewayFlowRule("httpbin_route")
        .setCount(10)
        .setIntervalSec(1)
        .setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER)
        .setMaxQueueingTimeoutMs(600)
        .setParamItem(new GatewayParamFlowItem()
            .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HEADER)
            .setFieldName("X-Sentinel-Flag")
        )
    );
    rules.add(new GatewayFlowRule("httpbin_route")
        .setCount(1)
        .setIntervalSec(1)
        .setParamItem(new GatewayParamFlowItem()
            .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)
            .setFieldName("pa")
        )
    );
    rules.add(new GatewayFlowRule("httpbin_route")
        .setCount(2)
        .setIntervalSec(30)
        .setParamItem(new GatewayParamFlowItem()
            .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)
            .setFieldName("type")
            .setPattern("warn")
            .setMatchStrategy(SentinelGatewayConstants.PARAM_MATCH_STRATEGY_CONTAINS)
        )
    );

    rules.add(new GatewayFlowRule("some_customized_api")
        .setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_CUSTOM_API_NAME)
        .setCount(5)
        .setIntervalSec(1)
        .setParamItem(new GatewayParamFlowItem()
            .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)
            .setFieldName("pn")
        )
    );
    GatewayRuleManager.loadRules(rules);
}
 
Example #21
Source File: SentinelGatewayFilterTest.java    From Sentinel with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() {
    GatewayApiDefinitionManager.loadApiDefinitions(new HashSet<>());
    GatewayRuleManager.loadRules(new HashSet<>());
}
 
Example #22
Source File: SpringCloudGatewayParamParserTest.java    From Sentinel with Apache License 2.0 4 votes vote down vote up
@After
public void tearDown() {
    GatewayApiDefinitionManager.loadApiDefinitions(new HashSet<>());
    GatewayRuleManager.loadRules(new HashSet<>());
}
 
Example #23
Source File: SpringCloudGatewayParamParserTest.java    From Sentinel with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() {
    GatewayApiDefinitionManager.loadApiDefinitions(new HashSet<>());
    GatewayRuleManager.loadRules(new HashSet<>());
}
 
Example #24
Source File: SpringCloudGatewayParamParserTest.java    From Sentinel with Apache License 2.0 4 votes vote down vote up
@Test
public void testParseParametersWithItems() {
    // Mock a request.
    ServerWebExchange exchange = mock(ServerWebExchange.class);
    ServerHttpRequest request = mock(ServerHttpRequest.class);
    when(exchange.getRequest()).thenReturn(request);
    RequestPath requestPath = mock(RequestPath.class);
    when(request.getPath()).thenReturn(requestPath);

    // Prepare gateway rules.
    Set<GatewayFlowRule> rules = new HashSet<>();
    String routeId1 = "my_test_route_A";
    String api1 = "my_test_route_B";
    String headerName = "X-Sentinel-Flag";
    String paramName = "p";
    GatewayFlowRule routeRule1 = new GatewayFlowRule(routeId1)
        .setCount(2)
        .setIntervalSec(2)
        .setBurst(2)
        .setParamItem(new GatewayParamFlowItem()
            .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_CLIENT_IP)
        );
    GatewayFlowRule routeRule2 = new GatewayFlowRule(routeId1)
        .setCount(10)
        .setIntervalSec(1)
        .setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER)
        .setMaxQueueingTimeoutMs(600)
        .setParamItem(new GatewayParamFlowItem()
            .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HEADER)
            .setFieldName(headerName)
        );
    GatewayFlowRule routeRule3 = new GatewayFlowRule(routeId1)
        .setCount(20)
        .setIntervalSec(1)
        .setBurst(5)
        .setParamItem(new GatewayParamFlowItem()
            .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)
            .setFieldName(paramName)
        );
    GatewayFlowRule routeRule4 = new GatewayFlowRule(routeId1)
        .setCount(120)
        .setIntervalSec(10)
        .setBurst(30)
        .setParamItem(new GatewayParamFlowItem()
            .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HOST)
        );
    GatewayFlowRule apiRule1 = new GatewayFlowRule(api1)
        .setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_CUSTOM_API_NAME)
        .setCount(5)
        .setIntervalSec(1)
        .setParamItem(new GatewayParamFlowItem()
            .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)
            .setFieldName(paramName)
        );
    rules.add(routeRule1);
    rules.add(routeRule2);
    rules.add(routeRule3);
    rules.add(routeRule4);
    rules.add(apiRule1);
    GatewayRuleManager.loadRules(rules);

    String expectedHost = "hello.test.sentinel";
    String expectedAddress = "66.77.88.99";
    String expectedHeaderValue1 = "Sentinel";
    String expectedUrlParamValue1 = "17";
    mockClientHostAddress(request, expectedAddress);
    Map<String, String> expectedHeaders = new HashMap<String, String>() {{
        put(headerName, expectedHeaderValue1); put("Host", expectedHost);
    }};
    mockHeaders(request, expectedHeaders);
    mockSingleUrlParam(request, paramName, expectedUrlParamValue1);
    Object[] params = paramParser.parseParameterFor(routeId1, exchange, e -> e.getResourceMode() == 0);
    assertThat(params.length).isEqualTo(4);
    assertThat(params[routeRule1.getParamItem().getIndex()]).isEqualTo(expectedAddress);
    assertThat(params[routeRule2.getParamItem().getIndex()]).isEqualTo(expectedHeaderValue1);
    assertThat(params[routeRule3.getParamItem().getIndex()]).isEqualTo(expectedUrlParamValue1);
    assertThat(params[routeRule4.getParamItem().getIndex()]).isEqualTo(expectedHost);

    assertThat(paramParser.parseParameterFor(api1, exchange, e -> e.getResourceMode() == 0).length).isZero();

    String expectedUrlParamValue2 = "fs";
    mockSingleUrlParam(request, paramName, expectedUrlParamValue2);
    params = paramParser.parseParameterFor(api1, exchange, e -> e.getResourceMode() == 1);
    assertThat(params.length).isEqualTo(1);
    assertThat(params[apiRule1.getParamItem().getIndex()]).isEqualTo(expectedUrlParamValue2);
}
 
Example #25
Source File: GatewayRuleConfig.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 4 votes vote down vote up
private void initGatewayRules() {
    Set<GatewayFlowRule> rules = new HashSet<>();
    rules.add(new GatewayFlowRule("aliyun-product-route")
        .setCount(10)
        .setIntervalSec(1)
    );
    rules.add(new GatewayFlowRule("aliyun-product-route")
        .setCount(2)
        .setIntervalSec(2)
        .setBurst(2)
        .setParamItem(new GatewayParamFlowItem()
            .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_CLIENT_IP)
        )
    );
    rules.add(new GatewayFlowRule("another-route-httpbin")
        .setCount(10)
        .setIntervalSec(1)
        .setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER)
        .setMaxQueueingTimeoutMs(600)
        .setParamItem(new GatewayParamFlowItem()
            .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HEADER)
            .setFieldName("X-Sentinel-Flag")
        )
    );
    rules.add(new GatewayFlowRule("another-route-httpbin")
        .setCount(1)
        .setIntervalSec(1)
        .setParamItem(new GatewayParamFlowItem()
            .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)
            .setFieldName("pa")
        )
    );

    rules.add(new GatewayFlowRule("some_customized_api")
        .setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_CUSTOM_API_NAME)
        .setCount(5)
        .setIntervalSec(1)
        .setParamItem(new GatewayParamFlowItem()
            .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)
            .setFieldName("pn")
        )
    );
    GatewayRuleManager.loadRules(rules);
}
 
Example #26
Source File: GatewayRuleConfig.java    From Sentinel with Apache License 2.0 4 votes vote down vote up
private void initGatewayRules() {
    Set<GatewayFlowRule> rules = new HashSet<>();
    rules.add(new GatewayFlowRule("images")
        .setCount(10)
        .setIntervalSec(1)
    );
    rules.add(new GatewayFlowRule("images")
        .setCount(2)
        .setIntervalSec(2)
        .setBurst(2)
        .setParamItem(new GatewayParamFlowItem()
            .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_CLIENT_IP)
        )
    );
    rules.add(new GatewayFlowRule("comments")
        .setCount(3)
        .setIntervalSec(1)
        .setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER)
        .setMaxQueueingTimeoutMs(6000)
        .setParamItem(new GatewayParamFlowItem()
            .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HEADER)
            .setFieldName("X-Sentinel-Flag")
        )
    );
    rules.add(new GatewayFlowRule("comments")
        .setCount(1)
        .setIntervalSec(1)
        .setParamItem(new GatewayParamFlowItem()
            .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)
            .setFieldName("pa")
        )
    );

    rules.add(new GatewayFlowRule("some_customized_api")
        .setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_CUSTOM_API_NAME)
        .setCount(5)
        .setIntervalSec(1)
        .setParamItem(new GatewayParamFlowItem()
            .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)
            .setFieldName("pn")
        )
    );
    GatewayRuleManager.loadRules(rules);
}
 
Example #27
Source File: GatewayRuleConfig.java    From Sentinel with Apache License 2.0 4 votes vote down vote up
private void initGatewayRules() {
    Set<GatewayFlowRule> rules = new HashSet<>();
    rules.add(new GatewayFlowRule("aliyun-product-route")
        .setCount(10)
        .setIntervalSec(1)
    );
    rules.add(new GatewayFlowRule("aliyun-product-route")
        .setCount(2)
        .setIntervalSec(2)
        .setBurst(2)
        .setParamItem(new GatewayParamFlowItem()
            .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_CLIENT_IP)
        )
    );
    rules.add(new GatewayFlowRule("another-route-httpbin")
        .setCount(10)
        .setIntervalSec(1)
        .setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER)
        .setMaxQueueingTimeoutMs(600)
        .setParamItem(new GatewayParamFlowItem()
            .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HEADER)
            .setFieldName("X-Sentinel-Flag")
        )
    );
    rules.add(new GatewayFlowRule("another-route-httpbin")
        .setCount(1)
        .setIntervalSec(1)
        .setParamItem(new GatewayParamFlowItem()
            .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)
            .setFieldName("pa")
        )
    );

    rules.add(new GatewayFlowRule("some_customized_api")
        .setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_CUSTOM_API_NAME)
        .setCount(5)
        .setIntervalSec(1)
        .setParamItem(new GatewayParamFlowItem()
            .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)
            .setFieldName("pn")
        )
    );
    GatewayRuleManager.loadRules(rules);
}
 
Example #28
Source File: GatewayParamParserTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 4 votes vote down vote up
@After
public void tearDown() {
    GatewayApiDefinitionManager.loadApiDefinitions(new HashSet<ApiDefinition>());
    GatewayRuleManager.loadRules(new HashSet<GatewayFlowRule>());
    GatewayRegexCache.clear();
}
 
Example #29
Source File: GatewayParamParserTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() {
    GatewayApiDefinitionManager.loadApiDefinitions(new HashSet<ApiDefinition>());
    GatewayRuleManager.loadRules(new HashSet<GatewayFlowRule>());
    GatewayRegexCache.clear();
}
 
Example #30
Source File: GatewayParamParserTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 4 votes vote down vote up
@Test
public void testParseParametersWithItemPatternMatching() {
    RequestItemParser<Object> itemParser = mock(RequestItemParser.class);
    GatewayParamParser<Object> paramParser = new GatewayParamParser<>(itemParser);
    // Create a fake request.
    Object request = new Object();

    // Prepare gateway rules.
    Set<GatewayFlowRule> rules = new HashSet<>();
    final String routeId1 = "my_test_route_F&@";
    final String api1 = "my_test_route_E5K";
    final String headerName = "X-Sentinel-Flag";
    final String paramName = "p";

    String nameEquals = "Wow";
    String nameContains = "warn";
    String valueRegex = "\\d+";
    GatewayFlowRule routeRule1 = new GatewayFlowRule(routeId1)
        .setCount(10)
        .setIntervalSec(1)
        .setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER)
        .setMaxQueueingTimeoutMs(600)
        .setParamItem(new GatewayParamFlowItem()
            .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HEADER)
            .setFieldName(headerName)
            .setPattern(nameEquals)
            .setMatchStrategy(SentinelGatewayConstants.PARAM_MATCH_STRATEGY_EXACT)
        );
    GatewayFlowRule routeRule2 = new GatewayFlowRule(routeId1)
        .setCount(20)
        .setIntervalSec(1)
        .setBurst(5)
        .setParamItem(new GatewayParamFlowItem()
            .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)
            .setFieldName(paramName)
            .setPattern(nameContains)
            .setMatchStrategy(SentinelGatewayConstants.PARAM_MATCH_STRATEGY_CONTAINS)
        );
    GatewayFlowRule apiRule1 = new GatewayFlowRule(api1)
        .setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_CUSTOM_API_NAME)
        .setCount(5)
        .setIntervalSec(1)
        .setParamItem(new GatewayParamFlowItem()
            .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)
            .setFieldName(paramName)
            .setPattern(valueRegex)
            .setMatchStrategy(SentinelGatewayConstants.PARAM_MATCH_STRATEGY_REGEX)
        );
    rules.add(routeRule1);
    rules.add(routeRule2);
    rules.add(apiRule1);
    GatewayRuleManager.loadRules(rules);

    mockSingleHeader(itemParser, headerName, nameEquals);
    mockSingleUrlParam(itemParser, paramName, nameContains);
    Object[] params = paramParser.parseParameterFor(routeId1, request, routeIdPredicate);
    assertThat(params.length).isEqualTo(2);
    assertThat(params[routeRule1.getParamItem().getIndex()]).isEqualTo(nameEquals);
    assertThat(params[routeRule2.getParamItem().getIndex()]).isEqualTo(nameContains);

    mockSingleHeader(itemParser, headerName, nameEquals + "_foo");
    mockSingleUrlParam(itemParser, paramName, nameContains + "_foo");
    params = paramParser.parseParameterFor(routeId1, request, routeIdPredicate);
    assertThat(params.length).isEqualTo(2);
    assertThat(params[routeRule1.getParamItem().getIndex()])
        .isEqualTo(SentinelGatewayConstants.GATEWAY_NOT_MATCH_PARAM);
    assertThat(params[routeRule2.getParamItem().getIndex()])
        .isEqualTo(nameContains + "_foo");

    mockSingleHeader(itemParser, headerName, "foo");
    mockSingleUrlParam(itemParser, paramName, "foo");
    params = paramParser.parseParameterFor(routeId1, request, routeIdPredicate);
    assertThat(params.length).isEqualTo(2);
    assertThat(params[routeRule1.getParamItem().getIndex()])
        .isEqualTo(SentinelGatewayConstants.GATEWAY_NOT_MATCH_PARAM);
    assertThat(params[routeRule2.getParamItem().getIndex()])
        .isEqualTo(SentinelGatewayConstants.GATEWAY_NOT_MATCH_PARAM);

    mockSingleUrlParam(itemParser, paramName, "23");
    params = paramParser.parseParameterFor(api1, request, apiNamePredicate);
    assertThat(params.length).isEqualTo(1);
    assertThat(params[apiRule1.getParamItem().getIndex()]).isEqualTo("23");

    mockSingleUrlParam(itemParser, paramName, "some233");
    params = paramParser.parseParameterFor(api1, request, apiNamePredicate);
    assertThat(params.length).isEqualTo(1);
    assertThat(params[apiRule1.getParamItem().getIndex()])
        .isEqualTo(SentinelGatewayConstants.GATEWAY_NOT_MATCH_PARAM);
}