com.alibaba.csp.sentinel.util.StringUtil Java Examples

The following examples show how to use com.alibaba.csp.sentinel.util.StringUtil. 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: HttpEventTask.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
/**
 * Parse raw HTTP request line to a {@link CommandRequest}.
 *
 * @param line HTTP request line
 * @return parsed command request
 */
protected static CommandRequest processQueryString(String line) {
    CommandRequest request = new CommandRequest();
    if (StringUtil.isBlank(line)) {
        return request;
    }
    int start = line.indexOf('/');
    int ask = line.indexOf('?') == -1 ? line.lastIndexOf(' ') : line.indexOf('?');
    int space = line.lastIndexOf(' ');
    String target = line.substring(start != -1 ? start + 1 : 0, ask != -1 ? ask : line.length());
    request.addMetadata(HttpCommandUtils.REQUEST_TARGET, target);
    if (ask == -1 || ask == space) {
        return request;
    }
    String parameterStr = line.substring(ask != -1 ? ask + 1 : 0, space != -1 ? space : line.length());
    parseParams(parameterStr, request);
    return request;
}
 
Example #2
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 #3
Source File: HttpHeartbeatSender.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Override
public boolean sendHeartbeat() throws Exception {
    if (StringUtil.isEmpty(consoleHost)) {
        return false;
    }
    URIBuilder uriBuilder = new URIBuilder();
    uriBuilder.setScheme("http").setHost(consoleHost).setPort(consolePort)
        .setPath("/registry/machine")
        .setParameter("app", AppNameUtil.getAppName())
        .setParameter("app_type", String.valueOf(SentinelConfig.getAppType()))
        .setParameter("v", Constants.SENTINEL_VERSION)
        .setParameter("version", String.valueOf(System.currentTimeMillis()))
        .setParameter("hostname", HostNameUtil.getHostName())
        .setParameter("ip", TransportConfig.getHeartbeatClientIp())
        .setParameter("port", TransportConfig.getPort())
        .setParameter("pid", String.valueOf(PidUtil.getPid()));

    HttpGet request = new HttpGet(uriBuilder.build());
    request.setConfig(requestConfig);
    // Send heartbeat request.
    CloseableHttpResponse response = client.execute(request);
    response.close();
    return true;
}
 
Example #4
Source File: SentinelApiClient.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
public CompletableFuture<Void> modifyClusterMode(String ip, int port, int mode) {
    if (StringUtil.isBlank(ip) || port <= 0) {
        return AsyncUtils.newFailedFuture(new IllegalArgumentException("Invalid parameter"));
    }
    try {
        Map<String, String> params = new HashMap<>(1);
        params.put("mode", String.valueOf(mode));
        return executeCommand(ip, port, MODIFY_CLUSTER_MODE_PATH, params, false)
            .thenCompose(e -> {
                if (CommandConstants.MSG_SUCCESS.equals(e)) {
                    return CompletableFuture.completedFuture(null);
                } else {
                    logger.warn("Error when modifying cluster mode: " + e);
                    return AsyncUtils.newFailedFuture(new RuntimeException(e));
                }
            });
    } catch (Exception ex) {
        logger.warn("Error when modifying cluster mode", ex);
        return AsyncUtils.newFailedFuture(ex);
    }
}
 
Example #5
Source File: HttpServerHandler.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    FullHttpRequest httpRequest = (FullHttpRequest)msg;
    try {
        CommandRequest request = parseRequest(httpRequest);
        if (StringUtil.isBlank(HttpCommandUtils.getTarget(request))) {
            writeErrorResponse(BAD_REQUEST.code(), "Invalid command", ctx);
            return;
        }
        handleRequest(request, ctx, HttpUtil.isKeepAlive(httpRequest));

    } catch (Exception ex) {
        writeErrorResponse(INTERNAL_SERVER_ERROR.code(), SERVER_ERROR_MESSAGE, ctx);
        CommandCenterLog.warn("Internal error", ex);
    }
}
 
Example #6
Source File: ModifyClusterFlowRulesCommandHandler.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Override
public CommandResponse<String> handle(CommandRequest request) {
    String namespace = request.getParam("namespace");
    if (StringUtil.isEmpty(namespace)) {
        return CommandResponse.ofFailure(new IllegalArgumentException("empty namespace"));
    }
    String data = request.getParam("data");
    if (StringUtil.isBlank(data)) {
        return CommandResponse.ofFailure(new IllegalArgumentException("empty data"));
    }
    try {
        data = URLDecoder.decode(data, "UTF-8");
        RecordLog.info("[ModifyClusterFlowRulesCommandHandler] Receiving cluster flow rules for namespace <{}>: {}", namespace, data);

        List<FlowRule> flowRules = JSONArray.parseArray(data, FlowRule.class);
        ClusterFlowRuleManager.loadRules(namespace, flowRules);

        return CommandResponse.ofSuccess(SUCCESS);
    } catch (Exception e) {
        RecordLog.warn("[ModifyClusterFlowRulesCommandHandler] Decode cluster flow rules error", e);
        return CommandResponse.ofFailure(e, "decode cluster flow rules error");
    }
}
 
Example #7
Source File: SentinelApiClient.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
public CompletableFuture<Void> modifyClusterMode(String ip, int port, int mode) {
    if (StringUtil.isBlank(ip) || port <= 0) {
        return AsyncUtils.newFailedFuture(new IllegalArgumentException("Invalid parameter"));
    }
    try {
        Map<String, String> params = new HashMap<>(1);
        params.put("mode", String.valueOf(mode));
        return executeCommand(ip, port, MODIFY_CLUSTER_MODE_PATH, params, false)
            .thenCompose(e -> {
                if (CommandConstants.MSG_SUCCESS.equals(e)) {
                    return CompletableFuture.completedFuture(null);
                } else {
                    logger.warn("Error when modifying cluster mode: " + e);
                    return AsyncUtils.newFailedFuture(new RuntimeException(e));
                }
            });
    } catch (Exception ex) {
        logger.warn("Error when modifying cluster mode", ex);
        return AsyncUtils.newFailedFuture(ex);
    }
}
 
Example #8
Source File: ModifyParamFlowRulesCommandHandler.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 rule data error", e);
        return CommandResponse.ofFailure(e, "decode rule data error");
    }

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

    String result = SUCCESS_MSG;
    List<ParamFlowRule> flowRules = JSONArray.parseArray(data, ParamFlowRule.class);
    ParamFlowRuleManager.loadRules(flowRules);
    if (!writeToDataSource(paramFlowWds, flowRules)) {
        result = WRITE_DS_FAILURE_MSG;
    }
    return CommandResponse.ofSuccess(result);
}
 
Example #9
Source File: LogConfigLoader.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
private static void load() {
    String file = System.getProperty(LOG_CONFIG);
    if (StringUtil.isBlank(file)) {
        file = DEFAULT_LOG_CONFIG_FILE;
    }

    Properties p = ConfigUtil.loadProperties(file);
    if (p != null && !p.isEmpty()) {
        properties.putAll(p);
    }

    CopyOnWriteArraySet<Map.Entry<Object, Object>> copy = new CopyOnWriteArraySet<>(System.getProperties().entrySet());
    for (Map.Entry<Object, Object> entry : copy) {
        String configKey = entry.getKey().toString();
        String newConfigValue = entry.getValue().toString();
        properties.put(configKey, newConfigValue);
    }
}
 
Example #10
Source File: SentinelApiClient.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example #11
Source File: RedisDataSource.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
private RedisClient getRedisStandaloneClient(RedisConnectionConfig connectionConfig) {
    char[] password = connectionConfig.getPassword();
    String clientName = connectionConfig.getClientName();
    RedisURI.Builder redisUriBuilder = RedisURI.builder();
    redisUriBuilder.withHost(connectionConfig.getHost())
        .withPort(connectionConfig.getPort())
        .withDatabase(connectionConfig.getDatabase())
        .withTimeout(Duration.ofMillis(connectionConfig.getTimeout()));
    if (password != null) {
        redisUriBuilder.withPassword(connectionConfig.getPassword());
    }
    if (StringUtil.isNotEmpty(connectionConfig.getClientName())) {
        redisUriBuilder.withClientName(clientName);
    }
    return RedisClient.create(redisUriBuilder.build());
}
 
Example #12
Source File: ClusterConfigService.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
public CompletableFuture<ClusterGroupEntity> getClusterUniversalStateForAppMachine(String app, String machineId) {
    if (StringUtil.isBlank(app)) {
        return AsyncUtils.newFailedFuture(new IllegalArgumentException("app cannot be empty"));
    }
    AppInfo appInfo = appManagement.getDetailApp(app);
    if (appInfo == null || appInfo.getMachines() == null) {
        return AsyncUtils.newFailedFuture(new IllegalArgumentException("app does not have machines"));
    }

    boolean machineOk = appInfo.getMachines().stream()
        .filter(e -> e.isHealthy())
        .map(e -> e.getIp() + '@' + e.getPort())
        .anyMatch(e -> e.equals(machineId));
    if (!machineOk) {
        return AsyncUtils.newFailedFuture(new IllegalStateException("machine does not exist or disconnected"));
    }

    return getClusterUniversalState(app)
        .thenApply(ClusterEntityUtils::wrapToClusterGroup)
        .thenCompose(e -> e.stream()
            .filter(e1 -> e1.getMachineId().equals(machineId))
            .findAny()
            .map(CompletableFuture::completedFuture)
            .orElse(AsyncUtils.newFailedFuture(new IllegalStateException("not a server: " + machineId)))
        );
}
 
Example #13
Source File: HttpEventTask.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
/**
 * Parse raw HTTP request line to a {@link CommandRequest}.
 *
 * @param line HTTP request line
 * @return parsed command request
 */
private CommandRequest parseRequest(String line) {
    CommandRequest request = new CommandRequest();
    if (StringUtil.isBlank(line)) {
        return request;
    }
    int start = line.indexOf('/');
    int ask = line.indexOf('?') == -1 ? line.lastIndexOf(' ') : line.indexOf('?');
    int space = line.lastIndexOf(' ');
    String target = line.substring(start != -1 ? start + 1 : 0, ask != -1 ? ask : line.length());
    request.addMetadata(HttpCommandUtils.REQUEST_TARGET, target);
    if (ask == -1 || ask == space) {
        return request;
    }
    String parameterStr = line.substring(ask != -1 ? ask + 1 : 0, space != -1 ? space : line.length());
    parseParams(parameterStr, request);
    return request;
}
 
Example #14
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 #15
Source File: WebServletConfig.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
/**
 * <p>Get the HTTP status when using the default block page.</p>
 * <p>You can set the status code with the {@code -Dcsp.sentinel.web.servlet.block.status}
 * property. When the property is empty or invalid, Sentinel will use 429 (Too Many Requests)
 * as the default status code.</p>
 *
 * @return the HTTP status of the default block page
 * @since 1.7.0
 */
public static int getBlockPageHttpStatus() {
    String value = SentinelConfig.getConfig(BLOCK_PAGE_HTTP_STATUS_CONF_KEY);
    if (StringUtil.isEmpty(value)) {
        return HTTP_STATUS_TOO_MANY_REQUESTS;
    }
    try {
        int s = Integer.parseInt(value);
        if (s <= 0) {
            throw new IllegalArgumentException("Invalid status code: " + s);
        }
        return s;
    } catch (Exception e) {
        RecordLog.warn("[WebServletConfig] Invalid block HTTP status (" + value + "), using default 429");
        setBlockPageHttpStatus(HTTP_STATUS_TOO_MANY_REQUESTS);
    }
    return HTTP_STATUS_TOO_MANY_REQUESTS;
}
 
Example #16
Source File: ClusterAssignController.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@PostMapping("/unbind_server/{app}")
public Result<ClusterAppAssignResultVO> apiUnbindClusterServersOfApp(@PathVariable String app,
                                                                     @RequestBody Set<String> machineIds) {
    if (StringUtil.isEmpty(app)) {
        return Result.ofFail(-1, "app cannot be null or empty");
    }
    if (machineIds == null || machineIds.isEmpty()) {
        return Result.ofFail(-1, "bad request body");
    }
    try {
        return Result.ofSuccess(clusterAssignService.unbindClusterServers(app, machineIds));
    } catch (Throwable throwable) {
        logger.error("Error when unbinding cluster server {} for app <{}>", machineIds, app, throwable);
        return Result.ofFail(-1, throwable.getMessage());
    }
}
 
Example #17
Source File: ClusterConfigController.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@GetMapping("/client_state/{app}")
public Result<List<AppClusterClientStateWrapVO>> apiGetClusterClientStateOfApp(@PathVariable String app) {
    if (StringUtil.isEmpty(app)) {
        return Result.ofFail(-1, "app cannot be null or empty");
    }
    try {
        return clusterConfigService.getClusterUniversalState(app)
            .thenApply(ClusterEntityUtils::wrapToAppClusterClientState)
            .thenApply(Result::ofSuccess)
            .get();
    } catch (ExecutionException ex) {
        logger.error("Error when fetching cluster token client state of app: " + app, ex.getCause());
        return errorResponse(ex);
    } catch (Throwable throwable) {
        logger.error("Error when fetching cluster token client state of app: " + app, throwable);
        return Result.ofFail(-1, throwable.getMessage());
    }
}
 
Example #18
Source File: ClusterConfigController.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@GetMapping("/server_state/{app}")
public Result<List<AppClusterServerStateWrapVO>> apiGetClusterServerStateOfApp(@PathVariable String app) {
    if (StringUtil.isEmpty(app)) {
        return Result.ofFail(-1, "app cannot be null or empty");
    }
    try {
        return clusterConfigService.getClusterUniversalState(app)
            .thenApply(ClusterEntityUtils::wrapToAppClusterServerState)
            .thenApply(Result::ofSuccess)
            .get();
    } catch (ExecutionException ex) {
        logger.error("Error when fetching cluster server state of app: " + app, ex.getCause());
        return errorResponse(ex);
    } catch (Throwable throwable) {
        logger.error("Error when fetching cluster server state of app: " + app, throwable);
        return Result.ofFail(-1, throwable.getMessage());
    }
}
 
Example #19
Source File: InMemoryMetricsRepository.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Override
public void save(MetricEntity entity) {
    if (entity == null || StringUtil.isBlank(entity.getApp())) {
        return;
    }
    readWriteLock.writeLock().lock();
    try {
        allMetrics.computeIfAbsent(entity.getApp(), e -> new HashMap<>(16))
                .computeIfAbsent(entity.getResource(), e -> new LinkedHashMap<Long, MetricEntity>() {
                    @Override
                    protected boolean removeEldestEntry(Entry<Long, MetricEntity> eldest) {
                        // Metric older than {@link #MAX_METRIC_LIVE_TIME_MS} will be removed.
                        return eldest.getKey() < TimeUtil.currentTimeMillis() - MAX_METRIC_LIVE_TIME_MS;
                    }
                }).put(entity.getTimestamp().getTime(), entity);
    } finally {
        readWriteLock.writeLock().unlock();
    }

}
 
Example #20
Source File: ClusterFlowRuleManager.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
/**
 * Get all cluster flow rules within a specific namespace.
 *
 * @param namespace valid namespace
 * @return cluster flow rules within the provided namespace
 */
public static List<FlowRule> getFlowRules(String namespace) {
    if (StringUtil.isEmpty(namespace)) {
        return new ArrayList<>();
    }
    List<FlowRule> rules = new ArrayList<>();
    Set<Long> flowIdSet = NAMESPACE_FLOW_ID_MAP.get(namespace);
    if (flowIdSet == null || flowIdSet.isEmpty()) {
        return rules;
    }
    for (Long flowId : flowIdSet) {
        FlowRule rule = FLOW_RULES.get(flowId);
        if (rule != null) {
            rules.add(rule);
        }
    }
    return rules;
}
 
Example #21
Source File: ClusterAssignController.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@PostMapping("/single_server/{app}")
public Result<ClusterAppAssignResultVO> apiAssignSingleClusterServersOfApp(@PathVariable String app,
                                                                           @RequestBody ClusterAppSingleServerAssignRequest assignRequest) {
    if (StringUtil.isEmpty(app)) {
        return Result.ofFail(-1, "app cannot be null or empty");
    }
    if (assignRequest == null || assignRequest.getClusterMap() == null) {
        return Result.ofFail(-1, "bad request body");
    }
    try {
        return Result.ofSuccess(clusterAssignService.applyAssignToApp(app, Collections.singletonList(assignRequest.getClusterMap()),
            assignRequest.getRemainingList()));
    } catch (Throwable throwable) {
        logger.error("Error when assigning single cluster servers for app: " + app, throwable);
        return Result.ofFail(-1, throwable.getMessage());
    }
}
 
Example #22
Source File: DegradeController.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@ResponseBody
@RequestMapping("/rules.json")
@AuthAction(PrivilegeType.READ_RULE)
public Result<List<DegradeRuleEntity>> queryMachineRules(String app, String ip, Integer port) {

    if (StringUtil.isEmpty(app)) {
        return Result.ofFail(-1, "app can't be null or empty");
    }
    if (StringUtil.isEmpty(ip)) {
        return Result.ofFail(-1, "ip can't be null or empty");
    }
    if (port == null) {
        return Result.ofFail(-1, "port can't be null");
    }
    try {
        List<DegradeRuleEntity> rules = sentinelApiClient.fetchDegradeRuleOfMachine(app, ip, port);
        rules = repository.saveAll(rules);
        return Result.ofSuccess(rules);
    } catch (Throwable throwable) {
        logger.error("queryApps error:", throwable);
        return Result.ofThrowable(-1, throwable);
    }
}
 
Example #23
Source File: EnvoyRlsRuleManager.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
/**
 * Check whether the given Envoy RLS rule is valid.
 *
 * @param rule the rule to check
 * @return true if the rule is valid, otherwise false
 */
public static boolean isValidRule(EnvoyRlsRule rule) {
    if (rule == null || StringUtil.isBlank(rule.getDomain())) {
        return false;
    }
    List<EnvoyRlsRule.ResourceDescriptor> descriptors = rule.getDescriptors();
    if (descriptors == null || descriptors.isEmpty()) {
        return false;
    }
    for (EnvoyRlsRule.ResourceDescriptor descriptor : descriptors) {
        if (descriptor == null || descriptor.getCount() == null || descriptor.getCount() < 0) {
            return false;
        }
        Set<EnvoyRlsRule.KeyValueResource> resources = descriptor.getResources();
        if (resources == null || resources.isEmpty()) {
            return false;
        }
        for (EnvoyRlsRule.KeyValueResource resource : resources) {
            if (resource == null ||
                StringUtil.isBlank(resource.getKey()) || StringUtil.isBlank(resource.getValue())) {
                return false;
            }
        }
    }
    return true;
}
 
Example #24
Source File: FlowRuleChecker.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
static Node selectReferenceNode(FlowRule rule, Context context, DefaultNode node) {
    String refResource = rule.getRefResource();
    int strategy = rule.getStrategy();

    if (StringUtil.isEmpty(refResource)) {
        return null;
    }

    if (strategy == RuleConstant.STRATEGY_RELATE) {
        return ClusterBuilderSlot.getClusterNode(refResource);
    }

    if (strategy == RuleConstant.STRATEGY_CHAIN) {
        if (!refResource.equals(context.getName())) {
            return null;
        }
        return node;
    }
    // No node.
    return null;
}
 
Example #25
Source File: AbstractSentinelAspectSupport.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
private Method extractBlockHandlerMethod(ProceedingJoinPoint pjp, String name, Class<?>[] locationClass) {
    if (StringUtil.isBlank(name)) {
        return null;
    }

    boolean mustStatic = locationClass != null && locationClass.length >= 1;
    Class<?> clazz;
    if (mustStatic) {
        clazz = locationClass[0];
    } else {
        // By default current class.
        clazz = pjp.getTarget().getClass();
    }
    MethodWrapper m = ResourceMetadataRegistry.lookupBlockHandler(clazz, name);
    if (m == null) {
        // First time, resolve the block handler.
        Method method = resolveBlockHandlerInternal(pjp, name, clazz, mustStatic);
        // Cache the method instance.
        ResourceMetadataRegistry.updateBlockHandlerFor(clazz, name, method);
        return method;
    }
    if (!m.isPresent()) {
        return null;
    }
    return m.getMethod();
}
 
Example #26
Source File: FlowRuleApolloProvider.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Override
public List<FlowRuleEntity> getRules(String appName) throws Exception {
    String appId = "appId";
    String flowDataId = ApolloConfigUtil.getFlowDataId(appName);
    OpenNamespaceDTO openNamespaceDTO = apolloOpenApiClient.getNamespace(appId, "DEV", "default", "application");
    String rules = openNamespaceDTO
        .getItems()
        .stream()
        .filter(p -> p.getKey().equals(flowDataId))
        .map(OpenItemDTO::getValue)
        .findFirst()
        .orElse("");

    if (StringUtil.isEmpty(rules)) {
        return new ArrayList<>();
    }
    return converter.convert(rules);
}
 
Example #27
Source File: DegradeController.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@ResponseBody
@RequestMapping("/rules.json")
public Result<List<DegradeRuleEntity>> queryMachineRules(HttpServletRequest request, String app, String ip, Integer port) {
    AuthUser authUser = authService.getAuthUser(request);
    authUser.authTarget(app, PrivilegeType.READ_RULE);

    if (StringUtil.isEmpty(app)) {
        return Result.ofFail(-1, "app can't be null or empty");
    }
    if (StringUtil.isEmpty(ip)) {
        return Result.ofFail(-1, "ip can't be null or empty");
    }
    if (port == null) {
        return Result.ofFail(-1, "port can't be null");
    }
    try {
        List<DegradeRuleEntity> rules = sentinelApiClient.fetchDegradeRuleOfMachine(app, ip, port);
        rules = repository.saveAll(rules);
        return Result.ofSuccess(rules);
    } catch (Throwable throwable) {
        logger.error("queryApps error:", throwable);
        return Result.ofThrowable(-1, throwable);
    }
}
 
Example #28
Source File: SentinelApiClient.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
public CompletableFuture<List<GatewayFlowRuleEntity>> fetchGatewayFlowRules(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_FLOW_RULE_PATH, false)
                .thenApply(r -> {
                    List<GatewayFlowRule> gatewayFlowRules = JSON.parseArray(r, GatewayFlowRule.class);
                    List<GatewayFlowRuleEntity> entities = gatewayFlowRules.stream().map(rule -> GatewayFlowRuleEntity.fromGatewayFlowRule(app, ip, port, rule)).collect(Collectors.toList());
                    return entities;
                });
    } catch (Exception ex) {
        logger.warn("Error when fetching gateway flow rules", ex);
        return AsyncUtils.newFailedFuture(ex);
    }
}
 
Example #29
Source File: CommonFilterMethodTest.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
private void configureRulesFor(String resource, int count, String limitApp) {
    FlowRule rule = new FlowRule()
            .setCount(count)
            .setGrade(RuleConstant.FLOW_GRADE_QPS);
    rule.setResource(resource);
    if (StringUtil.isNotBlank(limitApp)) {
        rule.setLimitApp(limitApp);
    }
    FlowRuleManager.loadRules(Collections.singletonList(rule));
}
 
Example #30
Source File: SphOTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@Test
public void testMethodEntryAll() throws NoSuchMethodException, SecurityException {
    Method method = SphOTest.class.getMethod("testMethodEntryAll");
    if (SphO.entry(method, EntryType.IN, 2, "hello1", "hello2")) {
        try {
            assertTrue(StringUtil.equalsIgnoreCase(
                ContextUtil.getContext().getCurEntry().getResourceWrapper().getName(),
                "com.alibaba.csp.sentinel.SphOTest:testMethodEntryAll()"));
            assertSame(ContextUtil.getContext().getCurEntry().getResourceWrapper().getType(), EntryType.IN);
        } finally {
            SphO.exit(2, "hello1", "hello2");
        }
    }
}