Search in sources :

Example 11 with GatewayParamFlowItemEntity

use of com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.GatewayParamFlowItemEntity in project RuoYi-Cloud-Plus by JavaLionLi.

the class GatewayFlowRuleController method addFlowRule.

@PostMapping("/new.json")
@AuthAction(AuthService.PrivilegeType.WRITE_RULE)
public Result<GatewayFlowRuleEntity> addFlowRule(@RequestBody AddFlowRuleReqVo reqVo) {
    String app = reqVo.getApp();
    if (StringUtil.isBlank(app)) {
        return Result.ofFail(-1, "app can't be null or empty");
    }
    GatewayFlowRuleEntity entity = new GatewayFlowRuleEntity();
    entity.setApp(app.trim());
    String ip = reqVo.getIp();
    if (StringUtil.isBlank(ip)) {
        return Result.ofFail(-1, "ip can't be null or empty");
    }
    entity.setIp(ip.trim());
    Integer port = reqVo.getPort();
    if (port == null) {
        return Result.ofFail(-1, "port can't be null");
    }
    entity.setPort(port);
    // API类型, Route ID或API分组
    Integer resourceMode = reqVo.getResourceMode();
    if (resourceMode == null) {
        return Result.ofFail(-1, "resourceMode can't be null");
    }
    if (!Arrays.asList(RESOURCE_MODE_ROUTE_ID, RESOURCE_MODE_CUSTOM_API_NAME).contains(resourceMode)) {
        return Result.ofFail(-1, "invalid resourceMode: " + resourceMode);
    }
    entity.setResourceMode(resourceMode);
    // API名称
    String resource = reqVo.getResource();
    if (StringUtil.isBlank(resource)) {
        return Result.ofFail(-1, "resource can't be null or empty");
    }
    entity.setResource(resource.trim());
    // 针对请求属性
    GatewayParamFlowItemVo paramItem = reqVo.getParamItem();
    if (paramItem != null) {
        GatewayParamFlowItemEntity itemEntity = new GatewayParamFlowItemEntity();
        entity.setParamItem(itemEntity);
        // 参数属性 0-ClientIP 1-Remote Host 2-Header 3-URL参数 4-Cookie
        Integer parseStrategy = paramItem.getParseStrategy();
        if (!Arrays.asList(PARAM_PARSE_STRATEGY_CLIENT_IP, PARAM_PARSE_STRATEGY_HOST, PARAM_PARSE_STRATEGY_HEADER, PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE).contains(parseStrategy)) {
            return Result.ofFail(-1, "invalid parseStrategy: " + parseStrategy);
        }
        itemEntity.setParseStrategy(paramItem.getParseStrategy());
        // 当参数属性为2-Header 3-URL参数 4-Cookie时,参数名称必填
        if (Arrays.asList(PARAM_PARSE_STRATEGY_HEADER, PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE).contains(parseStrategy)) {
            // 参数名称
            String fieldName = paramItem.getFieldName();
            if (StringUtil.isBlank(fieldName)) {
                return Result.ofFail(-1, "fieldName can't be null or empty");
            }
            itemEntity.setFieldName(paramItem.getFieldName());
        }
        String pattern = paramItem.getPattern();
        // 如果匹配串不为空,验证匹配模式
        if (StringUtil.isNotEmpty(pattern)) {
            itemEntity.setPattern(pattern);
            Integer matchStrategy = paramItem.getMatchStrategy();
            if (!Arrays.asList(PARAM_MATCH_STRATEGY_EXACT, PARAM_MATCH_STRATEGY_CONTAINS, PARAM_MATCH_STRATEGY_REGEX).contains(matchStrategy)) {
                return Result.ofFail(-1, "invalid matchStrategy: " + matchStrategy);
            }
            itemEntity.setMatchStrategy(matchStrategy);
        }
    }
    // 阈值类型 0-线程数 1-QPS
    Integer grade = reqVo.getGrade();
    if (grade == null) {
        return Result.ofFail(-1, "grade can't be null");
    }
    if (!Arrays.asList(FLOW_GRADE_THREAD, FLOW_GRADE_QPS).contains(grade)) {
        return Result.ofFail(-1, "invalid grade: " + grade);
    }
    entity.setGrade(grade);
    // QPS阈值
    Double count = reqVo.getCount();
    if (count == null) {
        return Result.ofFail(-1, "count can't be null");
    }
    if (count < 0) {
        return Result.ofFail(-1, "count should be at lease zero");
    }
    entity.setCount(count);
    // 间隔
    Long interval = reqVo.getInterval();
    if (interval == null) {
        return Result.ofFail(-1, "interval can't be null");
    }
    if (interval <= 0) {
        return Result.ofFail(-1, "interval should be greater than zero");
    }
    entity.setInterval(interval);
    // 间隔单位
    Integer intervalUnit = reqVo.getIntervalUnit();
    if (intervalUnit == null) {
        return Result.ofFail(-1, "intervalUnit can't be null");
    }
    if (!Arrays.asList(INTERVAL_UNIT_SECOND, INTERVAL_UNIT_MINUTE, INTERVAL_UNIT_HOUR, INTERVAL_UNIT_DAY).contains(intervalUnit)) {
        return Result.ofFail(-1, "Invalid intervalUnit: " + intervalUnit);
    }
    entity.setIntervalUnit(intervalUnit);
    // 流控方式 0-快速失败 2-匀速排队
    Integer controlBehavior = reqVo.getControlBehavior();
    if (controlBehavior == null) {
        return Result.ofFail(-1, "controlBehavior can't be null");
    }
    if (!Arrays.asList(CONTROL_BEHAVIOR_DEFAULT, CONTROL_BEHAVIOR_RATE_LIMITER).contains(controlBehavior)) {
        return Result.ofFail(-1, "invalid controlBehavior: " + controlBehavior);
    }
    entity.setControlBehavior(controlBehavior);
    if (CONTROL_BEHAVIOR_DEFAULT == controlBehavior) {
        // 0-快速失败, 则Burst size必填
        Integer burst = reqVo.getBurst();
        if (burst == null) {
            return Result.ofFail(-1, "burst can't be null");
        }
        if (burst < 0) {
            return Result.ofFail(-1, "invalid burst: " + burst);
        }
        entity.setBurst(burst);
    } else if (CONTROL_BEHAVIOR_RATE_LIMITER == controlBehavior) {
        // 1-匀速排队, 则超时时间必填
        Integer maxQueueingTimeoutMs = reqVo.getMaxQueueingTimeoutMs();
        if (maxQueueingTimeoutMs == null) {
            return Result.ofFail(-1, "maxQueueingTimeoutMs can't be null");
        }
        if (maxQueueingTimeoutMs < 0) {
            return Result.ofFail(-1, "invalid maxQueueingTimeoutMs: " + maxQueueingTimeoutMs);
        }
        entity.setMaxQueueingTimeoutMs(maxQueueingTimeoutMs);
    }
    Date date = new Date();
    entity.setGmtCreate(date);
    entity.setGmtModified(date);
    try {
        entity = repository.save(entity);
    } catch (Throwable throwable) {
        logger.error("add gateway flow rule error:", throwable);
        return Result.ofThrowable(-1, throwable);
    }
    if (!publishRules(app, ip, port)) {
        logger.warn("publish gateway flow rules fail after add");
    }
    return Result.ofSuccess(entity);
}
Also used : GatewayFlowRuleEntity(com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.GatewayFlowRuleEntity) GatewayParamFlowItemVo(com.alibaba.csp.sentinel.dashboard.domain.vo.gateway.rule.GatewayParamFlowItemVo) GatewayParamFlowItemEntity(com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.GatewayParamFlowItemEntity) Date(java.util.Date) AuthAction(com.alibaba.csp.sentinel.dashboard.auth.AuthAction)

Example 12 with GatewayParamFlowItemEntity

use of com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.GatewayParamFlowItemEntity in project RuoYi-Cloud-Plus by JavaLionLi.

the class GatewayFlowRuleController method updateFlowRule.

@PostMapping("/save.json")
@AuthAction(AuthService.PrivilegeType.WRITE_RULE)
public Result<GatewayFlowRuleEntity> updateFlowRule(@RequestBody UpdateFlowRuleReqVo reqVo) {
    String app = reqVo.getApp();
    if (StringUtil.isBlank(app)) {
        return Result.ofFail(-1, "app can't be null or empty");
    }
    Long id = reqVo.getId();
    if (id == null) {
        return Result.ofFail(-1, "id can't be null");
    }
    GatewayFlowRuleEntity entity = repository.findById(id);
    if (entity == null) {
        return Result.ofFail(-1, "gateway flow rule does not exist, id=" + id);
    }
    // 针对请求属性
    GatewayParamFlowItemVo paramItem = reqVo.getParamItem();
    if (paramItem != null) {
        GatewayParamFlowItemEntity itemEntity = new GatewayParamFlowItemEntity();
        entity.setParamItem(itemEntity);
        // 参数属性 0-ClientIP 1-Remote Host 2-Header 3-URL参数 4-Cookie
        Integer parseStrategy = paramItem.getParseStrategy();
        if (!Arrays.asList(PARAM_PARSE_STRATEGY_CLIENT_IP, PARAM_PARSE_STRATEGY_HOST, PARAM_PARSE_STRATEGY_HEADER, PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE).contains(parseStrategy)) {
            return Result.ofFail(-1, "invalid parseStrategy: " + parseStrategy);
        }
        itemEntity.setParseStrategy(paramItem.getParseStrategy());
        // 当参数属性为2-Header 3-URL参数 4-Cookie时,参数名称必填
        if (Arrays.asList(PARAM_PARSE_STRATEGY_HEADER, PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE).contains(parseStrategy)) {
            // 参数名称
            String fieldName = paramItem.getFieldName();
            if (StringUtil.isBlank(fieldName)) {
                return Result.ofFail(-1, "fieldName can't be null or empty");
            }
            itemEntity.setFieldName(paramItem.getFieldName());
        }
        String pattern = paramItem.getPattern();
        // 如果匹配串不为空,验证匹配模式
        if (StringUtil.isNotEmpty(pattern)) {
            itemEntity.setPattern(pattern);
            Integer matchStrategy = paramItem.getMatchStrategy();
            if (!Arrays.asList(PARAM_MATCH_STRATEGY_EXACT, PARAM_MATCH_STRATEGY_CONTAINS, PARAM_MATCH_STRATEGY_REGEX).contains(matchStrategy)) {
                return Result.ofFail(-1, "invalid matchStrategy: " + matchStrategy);
            }
            itemEntity.setMatchStrategy(matchStrategy);
        }
    } else {
        entity.setParamItem(null);
    }
    // 阈值类型 0-线程数 1-QPS
    Integer grade = reqVo.getGrade();
    if (grade == null) {
        return Result.ofFail(-1, "grade can't be null");
    }
    if (!Arrays.asList(FLOW_GRADE_THREAD, FLOW_GRADE_QPS).contains(grade)) {
        return Result.ofFail(-1, "invalid grade: " + grade);
    }
    entity.setGrade(grade);
    // QPS阈值
    Double count = reqVo.getCount();
    if (count == null) {
        return Result.ofFail(-1, "count can't be null");
    }
    if (count < 0) {
        return Result.ofFail(-1, "count should be at lease zero");
    }
    entity.setCount(count);
    // 间隔
    Long interval = reqVo.getInterval();
    if (interval == null) {
        return Result.ofFail(-1, "interval can't be null");
    }
    if (interval <= 0) {
        return Result.ofFail(-1, "interval should be greater than zero");
    }
    entity.setInterval(interval);
    // 间隔单位
    Integer intervalUnit = reqVo.getIntervalUnit();
    if (intervalUnit == null) {
        return Result.ofFail(-1, "intervalUnit can't be null");
    }
    if (!Arrays.asList(INTERVAL_UNIT_SECOND, INTERVAL_UNIT_MINUTE, INTERVAL_UNIT_HOUR, INTERVAL_UNIT_DAY).contains(intervalUnit)) {
        return Result.ofFail(-1, "Invalid intervalUnit: " + intervalUnit);
    }
    entity.setIntervalUnit(intervalUnit);
    // 流控方式 0-快速失败 2-匀速排队
    Integer controlBehavior = reqVo.getControlBehavior();
    if (controlBehavior == null) {
        return Result.ofFail(-1, "controlBehavior can't be null");
    }
    if (!Arrays.asList(CONTROL_BEHAVIOR_DEFAULT, CONTROL_BEHAVIOR_RATE_LIMITER).contains(controlBehavior)) {
        return Result.ofFail(-1, "invalid controlBehavior: " + controlBehavior);
    }
    entity.setControlBehavior(controlBehavior);
    if (CONTROL_BEHAVIOR_DEFAULT == controlBehavior) {
        // 0-快速失败, 则Burst size必填
        Integer burst = reqVo.getBurst();
        if (burst == null) {
            return Result.ofFail(-1, "burst can't be null");
        }
        if (burst < 0) {
            return Result.ofFail(-1, "invalid burst: " + burst);
        }
        entity.setBurst(burst);
    } else if (CONTROL_BEHAVIOR_RATE_LIMITER == controlBehavior) {
        // 2-匀速排队, 则超时时间必填
        Integer maxQueueingTimeoutMs = reqVo.getMaxQueueingTimeoutMs();
        if (maxQueueingTimeoutMs == null) {
            return Result.ofFail(-1, "maxQueueingTimeoutMs can't be null");
        }
        if (maxQueueingTimeoutMs < 0) {
            return Result.ofFail(-1, "invalid maxQueueingTimeoutMs: " + maxQueueingTimeoutMs);
        }
        entity.setMaxQueueingTimeoutMs(maxQueueingTimeoutMs);
    }
    Date date = new Date();
    entity.setGmtModified(date);
    try {
        entity = repository.save(entity);
    } catch (Throwable throwable) {
        logger.error("update gateway flow rule error:", throwable);
        return Result.ofThrowable(-1, throwable);
    }
    if (!publishRules(app, entity.getIp(), entity.getPort())) {
        logger.warn("publish gateway flow rules fail after update");
    }
    return Result.ofSuccess(entity);
}
Also used : GatewayFlowRuleEntity(com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.GatewayFlowRuleEntity) GatewayParamFlowItemVo(com.alibaba.csp.sentinel.dashboard.domain.vo.gateway.rule.GatewayParamFlowItemVo) GatewayParamFlowItemEntity(com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.GatewayParamFlowItemEntity) Date(java.util.Date) AuthAction(com.alibaba.csp.sentinel.dashboard.auth.AuthAction)

Example 13 with GatewayParamFlowItemEntity

use of com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.GatewayParamFlowItemEntity in project Sentinel by alibaba.

the class GatewayFlowRuleControllerTest method testDeleteFlowRule.

@Test
public void testDeleteFlowRule() throws Exception {
    String path = "/gateway/flow/delete.json";
    // Add one entity into memory repository for delete
    GatewayFlowRuleEntity addEntity = new GatewayFlowRuleEntity();
    addEntity.setId(1L);
    addEntity.setApp(TEST_APP);
    addEntity.setIp(TEST_IP);
    addEntity.setPort(TEST_PORT);
    addEntity.setResource("httpbin_route");
    addEntity.setResourceMode(RESOURCE_MODE_ROUTE_ID);
    addEntity.setGrade(FLOW_GRADE_QPS);
    addEntity.setCount(5D);
    addEntity.setInterval(30L);
    addEntity.setIntervalUnit(GatewayFlowRuleEntity.INTERVAL_UNIT_SECOND);
    addEntity.setControlBehavior(CONTROL_BEHAVIOR_DEFAULT);
    addEntity.setBurst(0);
    addEntity.setMaxQueueingTimeoutMs(0);
    Date date = new Date();
    date = DateUtils.addSeconds(date, -1);
    addEntity.setGmtCreate(date);
    addEntity.setGmtModified(date);
    GatewayParamFlowItemEntity addItemEntity = new GatewayParamFlowItemEntity();
    addEntity.setParamItem(addItemEntity);
    addItemEntity.setParseStrategy(PARAM_PARSE_STRATEGY_CLIENT_IP);
    repository.save(addEntity);
    given(sentinelApiClient.modifyGatewayFlowRules(eq(TEST_APP), eq(TEST_IP), eq(TEST_PORT), any())).willReturn(true);
    MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post(path);
    requestBuilder.param("id", String.valueOf(addEntity.getId()));
    // Do controller logic
    MvcResult mvcResult = mockMvc.perform(requestBuilder).andExpect(MockMvcResultMatchers.status().isOk()).andDo(MockMvcResultHandlers.print()).andReturn();
    // Verify the modifyGatewayFlowRules method has been called
    verify(sentinelApiClient).modifyGatewayFlowRules(eq(TEST_APP), eq(TEST_IP), eq(TEST_PORT), any());
    // Verify the result
    Result<Long> result = JSONObject.parseObject(mvcResult.getResponse().getContentAsString(), new TypeReference<Result<Long>>() {
    });
    assertTrue(result.isSuccess());
    assertEquals(addEntity.getId(), result.getData());
    // Now no entities in memory
    List<GatewayFlowRuleEntity> entitiesInMem = repository.findAllByApp(TEST_APP);
    assertEquals(0, entitiesInMem.size());
}
Also used : GatewayFlowRuleEntity(com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.GatewayFlowRuleEntity) MockHttpServletRequestBuilder(org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder) GatewayParamFlowItemEntity(com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.GatewayParamFlowItemEntity) MvcResult(org.springframework.test.web.servlet.MvcResult) Date(java.util.Date) Result(com.alibaba.csp.sentinel.dashboard.domain.Result) MvcResult(org.springframework.test.web.servlet.MvcResult) WebMvcTest(org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest) NoAuthConfigurationTest(com.alibaba.csp.sentinel.dashboard.config.NoAuthConfigurationTest) Test(org.junit.Test)

Example 14 with GatewayParamFlowItemEntity

use of com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.GatewayParamFlowItemEntity in project Sentinel by alibaba.

the class GatewayFlowRuleControllerTest method testUpdateFlowRule.

@Test
public void testUpdateFlowRule() throws Exception {
    String path = "/gateway/flow/save.json";
    // Add one entity into memory repository for update
    GatewayFlowRuleEntity addEntity = new GatewayFlowRuleEntity();
    addEntity.setId(1L);
    addEntity.setApp(TEST_APP);
    addEntity.setIp(TEST_IP);
    addEntity.setPort(TEST_PORT);
    addEntity.setResource("httpbin_route");
    addEntity.setResourceMode(RESOURCE_MODE_ROUTE_ID);
    addEntity.setGrade(FLOW_GRADE_QPS);
    addEntity.setCount(5D);
    addEntity.setInterval(30L);
    addEntity.setIntervalUnit(GatewayFlowRuleEntity.INTERVAL_UNIT_SECOND);
    addEntity.setControlBehavior(CONTROL_BEHAVIOR_DEFAULT);
    addEntity.setBurst(0);
    addEntity.setMaxQueueingTimeoutMs(0);
    Date date = new Date();
    // To make the gmtModified different when do update
    date = DateUtils.addSeconds(date, -1);
    addEntity.setGmtCreate(date);
    addEntity.setGmtModified(date);
    GatewayParamFlowItemEntity addItemEntity = new GatewayParamFlowItemEntity();
    addEntity.setParamItem(addItemEntity);
    addItemEntity.setParseStrategy(PARAM_PARSE_STRATEGY_CLIENT_IP);
    repository.save(addEntity);
    UpdateFlowRuleReqVo reqVo = new UpdateFlowRuleReqVo();
    reqVo.setId(addEntity.getId());
    reqVo.setApp(TEST_APP);
    reqVo.setGrade(FLOW_GRADE_QPS);
    reqVo.setCount(6D);
    reqVo.setInterval(2L);
    reqVo.setIntervalUnit(GatewayFlowRuleEntity.INTERVAL_UNIT_MINUTE);
    reqVo.setControlBehavior(CONTROL_BEHAVIOR_RATE_LIMITER);
    reqVo.setMaxQueueingTimeoutMs(500);
    GatewayParamFlowItemVo itemVo = new GatewayParamFlowItemVo();
    reqVo.setParamItem(itemVo);
    itemVo.setParseStrategy(PARAM_PARSE_STRATEGY_URL_PARAM);
    itemVo.setFieldName("pa");
    given(sentinelApiClient.modifyGatewayFlowRules(eq(TEST_APP), eq(TEST_IP), eq(TEST_PORT), any())).willReturn(true);
    MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post(path);
    requestBuilder.content(JSON.toJSONString(reqVo)).contentType(MediaType.APPLICATION_JSON);
    // Do controller logic
    MvcResult mvcResult = mockMvc.perform(requestBuilder).andExpect(MockMvcResultMatchers.status().isOk()).andDo(MockMvcResultHandlers.print()).andReturn();
    // Verify the modifyGatewayFlowRules method has been called
    verify(sentinelApiClient).modifyGatewayFlowRules(eq(TEST_APP), eq(TEST_IP), eq(TEST_PORT), any());
    Result<GatewayFlowRuleEntity> result = JSONObject.parseObject(mvcResult.getResponse().getContentAsString(), new TypeReference<Result<GatewayFlowRuleEntity>>() {
    });
    assertTrue(result.isSuccess());
    GatewayFlowRuleEntity entity = result.getData();
    assertNotNull(entity);
    assertEquals(RESOURCE_MODE_ROUTE_ID, entity.getResourceMode().intValue());
    assertEquals("httpbin_route", entity.getResource());
    assertEquals(6D, entity.getCount().doubleValue(), 0);
    assertEquals(2L, entity.getInterval().longValue());
    assertEquals(GatewayFlowRuleEntity.INTERVAL_UNIT_MINUTE, entity.getIntervalUnit().intValue());
    assertEquals(CONTROL_BEHAVIOR_RATE_LIMITER, entity.getControlBehavior().intValue());
    assertEquals(0, entity.getBurst().intValue());
    assertEquals(500, entity.getMaxQueueingTimeoutMs().intValue());
    assertEquals(date, entity.getGmtCreate());
    // To make sure gmtModified has been set and it's different from gmtCreate
    assertNotNull(entity.getGmtModified());
    assertNotEquals(entity.getGmtCreate(), entity.getGmtModified());
    // Verify the entity which is update in memory repository
    GatewayParamFlowItemEntity itemEntity = entity.getParamItem();
    assertEquals(PARAM_PARSE_STRATEGY_URL_PARAM, itemEntity.getParseStrategy().intValue());
    assertEquals("pa", itemEntity.getFieldName());
}
Also used : UpdateFlowRuleReqVo(com.alibaba.csp.sentinel.dashboard.domain.vo.gateway.rule.UpdateFlowRuleReqVo) GatewayFlowRuleEntity(com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.GatewayFlowRuleEntity) MockHttpServletRequestBuilder(org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder) GatewayParamFlowItemVo(com.alibaba.csp.sentinel.dashboard.domain.vo.gateway.rule.GatewayParamFlowItemVo) GatewayParamFlowItemEntity(com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.GatewayParamFlowItemEntity) MvcResult(org.springframework.test.web.servlet.MvcResult) Date(java.util.Date) Result(com.alibaba.csp.sentinel.dashboard.domain.Result) MvcResult(org.springframework.test.web.servlet.MvcResult) WebMvcTest(org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest) NoAuthConfigurationTest(com.alibaba.csp.sentinel.dashboard.config.NoAuthConfigurationTest) Test(org.junit.Test)

Example 15 with GatewayParamFlowItemEntity

use of com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.GatewayParamFlowItemEntity in project Sentinel by alibaba.

the class GatewayFlowRuleController method addFlowRule.

@PostMapping("/new.json")
@AuthAction(AuthService.PrivilegeType.WRITE_RULE)
public Result<GatewayFlowRuleEntity> addFlowRule(@RequestBody AddFlowRuleReqVo reqVo) {
    String app = reqVo.getApp();
    if (StringUtil.isBlank(app)) {
        return Result.ofFail(-1, "app can't be null or empty");
    }
    GatewayFlowRuleEntity entity = new GatewayFlowRuleEntity();
    entity.setApp(app.trim());
    String ip = reqVo.getIp();
    if (StringUtil.isBlank(ip)) {
        return Result.ofFail(-1, "ip can't be null or empty");
    }
    entity.setIp(ip.trim());
    Integer port = reqVo.getPort();
    if (port == null) {
        return Result.ofFail(-1, "port can't be null");
    }
    entity.setPort(port);
    // API类型, Route ID或API分组
    Integer resourceMode = reqVo.getResourceMode();
    if (resourceMode == null) {
        return Result.ofFail(-1, "resourceMode can't be null");
    }
    if (!Arrays.asList(RESOURCE_MODE_ROUTE_ID, RESOURCE_MODE_CUSTOM_API_NAME).contains(resourceMode)) {
        return Result.ofFail(-1, "invalid resourceMode: " + resourceMode);
    }
    entity.setResourceMode(resourceMode);
    // API名称
    String resource = reqVo.getResource();
    if (StringUtil.isBlank(resource)) {
        return Result.ofFail(-1, "resource can't be null or empty");
    }
    entity.setResource(resource.trim());
    // 针对请求属性
    GatewayParamFlowItemVo paramItem = reqVo.getParamItem();
    if (paramItem != null) {
        GatewayParamFlowItemEntity itemEntity = new GatewayParamFlowItemEntity();
        entity.setParamItem(itemEntity);
        // 参数属性 0-ClientIP 1-Remote Host 2-Header 3-URL参数 4-Cookie
        Integer parseStrategy = paramItem.getParseStrategy();
        if (!Arrays.asList(PARAM_PARSE_STRATEGY_CLIENT_IP, PARAM_PARSE_STRATEGY_HOST, PARAM_PARSE_STRATEGY_HEADER, PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE).contains(parseStrategy)) {
            return Result.ofFail(-1, "invalid parseStrategy: " + parseStrategy);
        }
        itemEntity.setParseStrategy(paramItem.getParseStrategy());
        // 当参数属性为2-Header 3-URL参数 4-Cookie时,参数名称必填
        if (Arrays.asList(PARAM_PARSE_STRATEGY_HEADER, PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE).contains(parseStrategy)) {
            // 参数名称
            String fieldName = paramItem.getFieldName();
            if (StringUtil.isBlank(fieldName)) {
                return Result.ofFail(-1, "fieldName can't be null or empty");
            }
            itemEntity.setFieldName(paramItem.getFieldName());
        }
        String pattern = paramItem.getPattern();
        // 如果匹配串不为空,验证匹配模式
        if (StringUtil.isNotEmpty(pattern)) {
            itemEntity.setPattern(pattern);
            Integer matchStrategy = paramItem.getMatchStrategy();
            if (!Arrays.asList(PARAM_MATCH_STRATEGY_EXACT, PARAM_MATCH_STRATEGY_CONTAINS, PARAM_MATCH_STRATEGY_REGEX).contains(matchStrategy)) {
                return Result.ofFail(-1, "invalid matchStrategy: " + matchStrategy);
            }
            itemEntity.setMatchStrategy(matchStrategy);
        }
    }
    // 阈值类型 0-线程数 1-QPS
    Integer grade = reqVo.getGrade();
    if (grade == null) {
        return Result.ofFail(-1, "grade can't be null");
    }
    if (!Arrays.asList(FLOW_GRADE_THREAD, FLOW_GRADE_QPS).contains(grade)) {
        return Result.ofFail(-1, "invalid grade: " + grade);
    }
    entity.setGrade(grade);
    // QPS阈值
    Double count = reqVo.getCount();
    if (count == null) {
        return Result.ofFail(-1, "count can't be null");
    }
    if (count < 0) {
        return Result.ofFail(-1, "count should be at lease zero");
    }
    entity.setCount(count);
    // 间隔
    Long interval = reqVo.getInterval();
    if (interval == null) {
        return Result.ofFail(-1, "interval can't be null");
    }
    if (interval <= 0) {
        return Result.ofFail(-1, "interval should be greater than zero");
    }
    entity.setInterval(interval);
    // 间隔单位
    Integer intervalUnit = reqVo.getIntervalUnit();
    if (intervalUnit == null) {
        return Result.ofFail(-1, "intervalUnit can't be null");
    }
    if (!Arrays.asList(INTERVAL_UNIT_SECOND, INTERVAL_UNIT_MINUTE, INTERVAL_UNIT_HOUR, INTERVAL_UNIT_DAY).contains(intervalUnit)) {
        return Result.ofFail(-1, "Invalid intervalUnit: " + intervalUnit);
    }
    entity.setIntervalUnit(intervalUnit);
    // 流控方式 0-快速失败 2-匀速排队
    Integer controlBehavior = reqVo.getControlBehavior();
    if (controlBehavior == null) {
        return Result.ofFail(-1, "controlBehavior can't be null");
    }
    if (!Arrays.asList(CONTROL_BEHAVIOR_DEFAULT, CONTROL_BEHAVIOR_RATE_LIMITER).contains(controlBehavior)) {
        return Result.ofFail(-1, "invalid controlBehavior: " + controlBehavior);
    }
    entity.setControlBehavior(controlBehavior);
    if (CONTROL_BEHAVIOR_DEFAULT == controlBehavior) {
        // 0-快速失败, 则Burst size必填
        Integer burst = reqVo.getBurst();
        if (burst == null) {
            return Result.ofFail(-1, "burst can't be null");
        }
        if (burst < 0) {
            return Result.ofFail(-1, "invalid burst: " + burst);
        }
        entity.setBurst(burst);
    } else if (CONTROL_BEHAVIOR_RATE_LIMITER == controlBehavior) {
        // 1-匀速排队, 则超时时间必填
        Integer maxQueueingTimeoutMs = reqVo.getMaxQueueingTimeoutMs();
        if (maxQueueingTimeoutMs == null) {
            return Result.ofFail(-1, "maxQueueingTimeoutMs can't be null");
        }
        if (maxQueueingTimeoutMs < 0) {
            return Result.ofFail(-1, "invalid maxQueueingTimeoutMs: " + maxQueueingTimeoutMs);
        }
        entity.setMaxQueueingTimeoutMs(maxQueueingTimeoutMs);
    }
    Date date = new Date();
    entity.setGmtCreate(date);
    entity.setGmtModified(date);
    try {
        entity = repository.save(entity);
    } catch (Throwable throwable) {
        logger.error("add gateway flow rule error:", throwable);
        return Result.ofThrowable(-1, throwable);
    }
    if (!publishRules(app, ip, port)) {
        logger.warn("publish gateway flow rules fail after add");
    }
    return Result.ofSuccess(entity);
}
Also used : GatewayFlowRuleEntity(com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.GatewayFlowRuleEntity) GatewayParamFlowItemVo(com.alibaba.csp.sentinel.dashboard.domain.vo.gateway.rule.GatewayParamFlowItemVo) GatewayParamFlowItemEntity(com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.GatewayParamFlowItemEntity) Date(java.util.Date) AuthAction(com.alibaba.csp.sentinel.dashboard.auth.AuthAction)

Aggregations

GatewayFlowRuleEntity (com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.GatewayFlowRuleEntity)16 GatewayParamFlowItemEntity (com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.GatewayParamFlowItemEntity)16 Date (java.util.Date)14 GatewayParamFlowItemVo (com.alibaba.csp.sentinel.dashboard.domain.vo.gateway.rule.GatewayParamFlowItemVo)12 AuthAction (com.alibaba.csp.sentinel.dashboard.auth.AuthAction)10 Result (com.alibaba.csp.sentinel.dashboard.domain.Result)6 Test (org.junit.Test)6 WebMvcTest (org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest)6 MvcResult (org.springframework.test.web.servlet.MvcResult)6 MockHttpServletRequestBuilder (org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder)6 NoAuthConfigurationTest (com.alibaba.csp.sentinel.dashboard.config.NoAuthConfigurationTest)3 UpdateFlowRuleReqVo (com.alibaba.csp.sentinel.dashboard.domain.vo.gateway.rule.UpdateFlowRuleReqVo)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2