use of com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.ApiDefinitionEntity in project Sentinel by alibaba.
the class GatewayApiController method addApi.
@PostMapping("/new.json")
@AuthAction(AuthService.PrivilegeType.WRITE_RULE)
public Result<ApiDefinitionEntity> addApi(HttpServletRequest request, @RequestBody AddApiReqVo reqVo) {
String app = reqVo.getApp();
if (StringUtil.isBlank(app)) {
return Result.ofFail(-1, "app can't be null or empty");
}
ApiDefinitionEntity entity = new ApiDefinitionEntity();
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名称
String apiName = reqVo.getApiName();
if (StringUtil.isBlank(apiName)) {
return Result.ofFail(-1, "apiName can't be null or empty");
}
entity.setApiName(apiName.trim());
// 匹配规则列表
List<ApiPredicateItemVo> predicateItems = reqVo.getPredicateItems();
if (CollectionUtils.isEmpty(predicateItems)) {
return Result.ofFail(-1, "predicateItems can't empty");
}
List<ApiPredicateItemEntity> predicateItemEntities = new ArrayList<>();
for (ApiPredicateItemVo predicateItem : predicateItems) {
ApiPredicateItemEntity predicateItemEntity = new ApiPredicateItemEntity();
// 匹配模式
Integer matchStrategy = predicateItem.getMatchStrategy();
if (!Arrays.asList(URL_MATCH_STRATEGY_EXACT, URL_MATCH_STRATEGY_PREFIX, URL_MATCH_STRATEGY_REGEX).contains(matchStrategy)) {
return Result.ofFail(-1, "invalid matchStrategy: " + matchStrategy);
}
predicateItemEntity.setMatchStrategy(matchStrategy);
// 匹配串
String pattern = predicateItem.getPattern();
if (StringUtil.isBlank(pattern)) {
return Result.ofFail(-1, "pattern can't be null or empty");
}
predicateItemEntity.setPattern(pattern);
predicateItemEntities.add(predicateItemEntity);
}
entity.setPredicateItems(new LinkedHashSet<>(predicateItemEntities));
// 检查API名称不能重复
List<ApiDefinitionEntity> allApis = repository.findAllByMachine(MachineInfo.of(app.trim(), ip.trim(), port));
if (allApis.stream().map(o -> o.getApiName()).anyMatch(o -> o.equals(apiName.trim()))) {
return Result.ofFail(-1, "apiName exists: " + apiName);
}
Date date = new Date();
entity.setGmtCreate(date);
entity.setGmtModified(date);
try {
entity = repository.save(entity);
} catch (Throwable throwable) {
logger.error("add gateway api error:", throwable);
return Result.ofThrowable(-1, throwable);
}
if (!publishApis(app, ip, port)) {
logger.warn("publish gateway apis fail after add");
}
return Result.ofSuccess(entity);
}
use of com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.ApiDefinitionEntity in project Sentinel by alibaba.
the class GatewayApiController method updateApi.
@PostMapping("/save.json")
@AuthAction(AuthService.PrivilegeType.WRITE_RULE)
public Result<ApiDefinitionEntity> updateApi(@RequestBody UpdateApiReqVo 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");
}
ApiDefinitionEntity entity = repository.findById(id);
if (entity == null) {
return Result.ofFail(-1, "api does not exist, id=" + id);
}
// 匹配规则列表
List<ApiPredicateItemVo> predicateItems = reqVo.getPredicateItems();
if (CollectionUtils.isEmpty(predicateItems)) {
return Result.ofFail(-1, "predicateItems can't empty");
}
List<ApiPredicateItemEntity> predicateItemEntities = new ArrayList<>();
for (ApiPredicateItemVo predicateItem : predicateItems) {
ApiPredicateItemEntity predicateItemEntity = new ApiPredicateItemEntity();
// 匹配模式
int matchStrategy = predicateItem.getMatchStrategy();
if (!Arrays.asList(URL_MATCH_STRATEGY_EXACT, URL_MATCH_STRATEGY_PREFIX, URL_MATCH_STRATEGY_REGEX).contains(matchStrategy)) {
return Result.ofFail(-1, "Invalid matchStrategy: " + matchStrategy);
}
predicateItemEntity.setMatchStrategy(matchStrategy);
// 匹配串
String pattern = predicateItem.getPattern();
if (StringUtil.isBlank(pattern)) {
return Result.ofFail(-1, "pattern can't be null or empty");
}
predicateItemEntity.setPattern(pattern);
predicateItemEntities.add(predicateItemEntity);
}
entity.setPredicateItems(new LinkedHashSet<>(predicateItemEntities));
Date date = new Date();
entity.setGmtModified(date);
try {
entity = repository.save(entity);
} catch (Throwable throwable) {
logger.error("update gateway api error:", throwable);
return Result.ofThrowable(-1, throwable);
}
if (!publishApis(app, entity.getIp(), entity.getPort())) {
logger.warn("publish gateway apis fail after update");
}
return Result.ofSuccess(entity);
}
use of com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.ApiDefinitionEntity in project Sentinel by alibaba.
the class SentinelApiClient method fetchApis.
public CompletableFuture<List<ApiDefinitionEntity>> fetchApis(String app, String ip, int port) {
if (StringUtil.isBlank(ip) || port <= 0) {
return AsyncUtils.newFailedFuture(new IllegalArgumentException("Invalid parameter"));
}
try {
return executeCommand(ip, port, FETCH_GATEWAY_API_PATH, false).thenApply(r -> {
List<ApiDefinitionEntity> entities = JSON.parseArray(r, ApiDefinitionEntity.class);
if (entities != null) {
for (ApiDefinitionEntity entity : entities) {
entity.setApp(app);
entity.setIp(ip);
entity.setPort(port);
}
}
return entities;
});
} catch (Exception ex) {
logger.warn("Error when fetching gateway apis", ex);
return AsyncUtils.newFailedFuture(ex);
}
}
use of com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.ApiDefinitionEntity in project Sentinel by alibaba.
the class GatewayApiControllerTest method testQueryApis.
@Test
public void testQueryApis() throws Exception {
String path = "/gateway/api/list.json";
List<ApiDefinitionEntity> entities = new ArrayList<>();
// Mock two entities
ApiDefinitionEntity entity = new ApiDefinitionEntity();
entity.setId(1L);
entity.setApp(TEST_APP);
entity.setIp(TEST_IP);
entity.setPort(TEST_PORT);
entity.setApiName("foo");
Date date = new Date();
entity.setGmtCreate(date);
entity.setGmtModified(date);
Set<ApiPredicateItemEntity> itemEntities = new LinkedHashSet<>();
entity.setPredicateItems(itemEntities);
ApiPredicateItemEntity itemEntity = new ApiPredicateItemEntity();
itemEntity.setPattern("/aaa");
itemEntity.setMatchStrategy(URL_MATCH_STRATEGY_EXACT);
itemEntities.add(itemEntity);
entities.add(entity);
ApiDefinitionEntity entity2 = new ApiDefinitionEntity();
entity2.setId(2L);
entity2.setApp(TEST_APP);
entity2.setIp(TEST_IP);
entity2.setPort(TEST_PORT);
entity2.setApiName("biz");
entity.setGmtCreate(date);
entity.setGmtModified(date);
Set<ApiPredicateItemEntity> itemEntities2 = new LinkedHashSet<>();
entity2.setPredicateItems(itemEntities2);
ApiPredicateItemEntity itemEntity2 = new ApiPredicateItemEntity();
itemEntity2.setPattern("/bbb");
itemEntity2.setMatchStrategy(URL_MATCH_STRATEGY_PREFIX);
itemEntities2.add(itemEntity2);
entities.add(entity2);
CompletableFuture<List<ApiDefinitionEntity>> completableFuture = mock(CompletableFuture.class);
given(completableFuture.get()).willReturn(entities);
given(sentinelApiClient.fetchApis(TEST_APP, TEST_IP, TEST_PORT)).willReturn(completableFuture);
MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get(path);
requestBuilder.param("app", TEST_APP);
requestBuilder.param("ip", TEST_IP);
requestBuilder.param("port", String.valueOf(TEST_PORT));
// Do controller logic
MvcResult mvcResult = mockMvc.perform(requestBuilder).andExpect(MockMvcResultMatchers.status().isOk()).andDo(MockMvcResultHandlers.print()).andReturn();
// Verify the fetchApis method has been called
verify(sentinelApiClient).fetchApis(TEST_APP, TEST_IP, TEST_PORT);
// Verify if two same entities are got
Result<List<ApiDefinitionEntity>> result = JSONObject.parseObject(mvcResult.getResponse().getContentAsString(), new TypeReference<Result<List<ApiDefinitionEntity>>>() {
});
assertTrue(result.isSuccess());
List<ApiDefinitionEntity> data = result.getData();
assertEquals(2, data.size());
assertEquals(entities, data);
// Verify the entities are add into memory repository
List<ApiDefinitionEntity> entitiesInMem = repository.findAllByApp(TEST_APP);
assertEquals(2, entitiesInMem.size());
assertEquals(entities, entitiesInMem);
}
use of com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.ApiDefinitionEntity in project pig by pig-mesh.
the class GatewayApiController method addApi.
@PostMapping("/new.json")
@AuthAction(AuthService.PrivilegeType.WRITE_RULE)
public Result<ApiDefinitionEntity> addApi(HttpServletRequest request, @RequestBody AddApiReqVo reqVo) {
String app = reqVo.getApp();
if (StringUtil.isBlank(app)) {
return Result.ofFail(-1, "app can't be null or empty");
}
ApiDefinitionEntity entity = new ApiDefinitionEntity();
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名称
String apiName = reqVo.getApiName();
if (StringUtil.isBlank(apiName)) {
return Result.ofFail(-1, "apiName can't be null or empty");
}
entity.setApiName(apiName.trim());
// 匹配规则列表
List<ApiPredicateItemVo> predicateItems = reqVo.getPredicateItems();
if (CollectionUtils.isEmpty(predicateItems)) {
return Result.ofFail(-1, "predicateItems can't empty");
}
List<ApiPredicateItemEntity> predicateItemEntities = new ArrayList<>();
for (ApiPredicateItemVo predicateItem : predicateItems) {
ApiPredicateItemEntity predicateItemEntity = new ApiPredicateItemEntity();
// 匹配模式
Integer matchStrategy = predicateItem.getMatchStrategy();
if (!Arrays.asList(URL_MATCH_STRATEGY_EXACT, URL_MATCH_STRATEGY_PREFIX, URL_MATCH_STRATEGY_REGEX).contains(matchStrategy)) {
return Result.ofFail(-1, "invalid matchStrategy: " + matchStrategy);
}
predicateItemEntity.setMatchStrategy(matchStrategy);
// 匹配串
String pattern = predicateItem.getPattern();
if (StringUtil.isBlank(pattern)) {
return Result.ofFail(-1, "pattern can't be null or empty");
}
predicateItemEntity.setPattern(pattern);
predicateItemEntities.add(predicateItemEntity);
}
entity.setPredicateItems(new LinkedHashSet<>(predicateItemEntities));
// 检查API名称不能重复
List<ApiDefinitionEntity> allApis = repository.findAllByMachine(MachineInfo.of(app.trim(), ip.trim(), port));
if (allApis.stream().map(o -> o.getApiName()).anyMatch(o -> o.equals(apiName.trim()))) {
return Result.ofFail(-1, "apiName exists: " + apiName);
}
Date date = new Date();
entity.setGmtCreate(date);
entity.setGmtModified(date);
try {
entity = repository.save(entity);
} catch (Throwable throwable) {
logger.error("add gateway api error:", throwable);
return Result.ofThrowable(-1, throwable);
}
if (!publishApis(app, ip, port)) {
logger.warn("publish gateway apis fail after add");
}
return Result.ofSuccess(entity);
}
Aggregations