Search in sources :

Example 56 with FlowRule

use of com.alibaba.csp.sentinel.slots.block.flow.FlowRule in project spring-cloud-alibaba by alibaba.

the class DataSourcePropertiesTests method testPostRegister.

@Test
public void testPostRegister() throws Exception {
    FileDataSourceProperties fileDataSourceProperties = new FileDataSourceProperties();
    fileDataSourceProperties.setFile("classpath: flowrule.json");
    fileDataSourceProperties.setRuleType(RuleType.FLOW);
    FileRefreshableDataSource fileRefreshableDataSource = new FileRefreshableDataSource(ResourceUtils.getFile(StringUtils.trimAllWhitespace(fileDataSourceProperties.getFile())).getAbsolutePath(), new Converter<String, List<FlowRule>>() {

        ObjectMapper objectMapper = new ObjectMapper();

        @Override
        public List<FlowRule> convert(String source) {
            try {
                return objectMapper.readValue(source, new TypeReference<List<FlowRule>>() {
                });
            } catch (IOException e) {
            // ignore
            }
            return null;
        }
    });
    fileDataSourceProperties.postRegister(fileRefreshableDataSource);
    assertThat(FlowRuleManager.getRules()).isEqualTo(fileRefreshableDataSource.loadConfig());
}
Also used : FileDataSourceProperties(com.alibaba.cloud.sentinel.datasource.config.FileDataSourceProperties) List(java.util.List) TypeReference(com.fasterxml.jackson.core.type.TypeReference) FlowRule(com.alibaba.csp.sentinel.slots.block.flow.FlowRule) IOException(java.io.IOException) FileRefreshableDataSource(com.alibaba.csp.sentinel.datasource.FileRefreshableDataSource) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Test(org.junit.Test)

Example 57 with FlowRule

use of com.alibaba.csp.sentinel.slots.block.flow.FlowRule in project spring-cloud-alibaba by alibaba.

the class SentinelDubboConsumerApp method main.

public static void main(String[] args) {
    FlowRule flowRule = new FlowRule();
    flowRule.setResource("com.alibaba.cloud.examples.FooService:hello(java.lang.String)");
    flowRule.setCount(10);
    flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
    flowRule.setLimitApp("default");
    FlowRuleManager.loadRules(Collections.singletonList(flowRule));
    SpringApplicationBuilder consumerBuilder = new SpringApplicationBuilder();
    ApplicationContext applicationContext = consumerBuilder.web(WebApplicationType.NONE).sources(SentinelDubboConsumerApp.class).run(args);
    FooServiceConsumer service = applicationContext.getBean(FooServiceConsumer.class);
    for (int i = 0; i < 15; i++) {
        try {
            String message = service.hello("Jim");
            System.out.println((i + 1) + " -> Success: " + message);
        } catch (SentinelRpcException ex) {
            System.out.println("Blocked");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
Also used : ApplicationContext(org.springframework.context.ApplicationContext) SentinelRpcException(com.alibaba.csp.sentinel.slots.block.SentinelRpcException) SpringApplicationBuilder(org.springframework.boot.builder.SpringApplicationBuilder) FlowRule(com.alibaba.csp.sentinel.slots.block.flow.FlowRule) SentinelRpcException(com.alibaba.csp.sentinel.slots.block.SentinelRpcException)

Example 58 with FlowRule

use of com.alibaba.csp.sentinel.slots.block.flow.FlowRule in project Sentinel by alibaba.

the class EnvoySentinelRuleConverter method toSentinelFlowRule.

public static FlowRule toSentinelFlowRule(String domain, EnvoyRlsRule.ResourceDescriptor descriptor) {
    // One descriptor could have only one rule.
    String identifier = generateKey(domain, descriptor);
    long flowId = generateFlowId(identifier);
    return new FlowRule(identifier).setCount(descriptor.getCount()).setClusterMode(true).setClusterConfig(new ClusterFlowConfig().setFlowId(flowId).setThresholdType(ClusterRuleConstant.FLOW_THRESHOLD_GLOBAL).setSampleCount(1).setFallbackToLocalWhenFail(false));
}
Also used : FlowRule(com.alibaba.csp.sentinel.slots.block.flow.FlowRule) ClusterFlowConfig(com.alibaba.csp.sentinel.slots.block.flow.ClusterFlowConfig)

Example 59 with FlowRule

use of com.alibaba.csp.sentinel.slots.block.flow.FlowRule in project Sentinel by alibaba.

the class SentinelEnvoyRlsServiceImpl method checkToken.

protected Tuple2<FlowRule, TokenResult> checkToken(String domain, RateLimitDescriptor descriptor, int acquireCount) {
    long ruleId = EnvoySentinelRuleConverter.generateFlowId(generateKey(domain, descriptor));
    FlowRule rule = ClusterFlowRuleManager.getFlowRuleById(ruleId);
    if (rule == null) {
        // Pass if the target rule is absent.
        return Tuple2.of(null, new TokenResult(TokenResultStatus.NO_RULE_EXISTS));
    }
    // If the rule is present, it should be valid.
    return Tuple2.of(rule, SimpleClusterFlowChecker.acquireClusterToken(rule, acquireCount));
}
Also used : TokenResult(com.alibaba.csp.sentinel.cluster.TokenResult) FlowRule(com.alibaba.csp.sentinel.slots.block.flow.FlowRule)

Example 60 with FlowRule

use of com.alibaba.csp.sentinel.slots.block.flow.FlowRule in project Sentinel by alibaba.

the class SentinelEnvoyRlsServiceImpl method shouldRateLimit.

@Override
public void shouldRateLimit(RateLimitRequest request, StreamObserver<RateLimitResponse> responseObserver) {
    int acquireCount = request.getHitsAddend();
    if (acquireCount < 0) {
        responseObserver.onError(new IllegalArgumentException("acquireCount should be positive, but actual: " + acquireCount));
        return;
    }
    if (acquireCount == 0) {
        // Not present, use the default "1" by default.
        acquireCount = 1;
    }
    String domain = request.getDomain();
    boolean blocked = false;
    List<DescriptorStatus> statusList = new ArrayList<>(request.getDescriptorsCount());
    for (RateLimitDescriptor descriptor : request.getDescriptorsList()) {
        Tuple2<FlowRule, TokenResult> t = checkToken(domain, descriptor, acquireCount);
        TokenResult r = t.r2;
        printAccessLogIfNecessary(domain, descriptor, r);
        if (r.getStatus() == TokenResultStatus.NO_RULE_EXISTS) {
            // If the rule of the descriptor is absent, the request will pass directly.
            r.setStatus(TokenResultStatus.OK);
        }
        if (!blocked && r.getStatus() != TokenResultStatus.OK) {
            blocked = true;
        }
        Code statusCode = r.getStatus() == TokenResultStatus.OK ? Code.OK : Code.OVER_LIMIT;
        DescriptorStatus.Builder descriptorStatusBuilder = DescriptorStatus.newBuilder().setCode(statusCode);
        if (t.r1 != null) {
            descriptorStatusBuilder.setCurrentLimit(RateLimit.newBuilder().setUnit(RateLimit.Unit.SECOND).setRequestsPerUnit((int) t.r1.getCount()).build()).setLimitRemaining(r.getRemaining());
        }
        statusList.add(descriptorStatusBuilder.build());
    }
    Code overallStatus = blocked ? Code.OVER_LIMIT : Code.OK;
    RateLimitResponse response = RateLimitResponse.newBuilder().setOverallCode(overallStatus).addAllStatuses(statusList).build();
    responseObserver.onNext(response);
    responseObserver.onCompleted();
}
Also used : DescriptorStatus(io.envoyproxy.envoy.service.ratelimit.v3.RateLimitResponse.DescriptorStatus) TokenResult(com.alibaba.csp.sentinel.cluster.TokenResult) ArrayList(java.util.ArrayList) RateLimitResponse(io.envoyproxy.envoy.service.ratelimit.v3.RateLimitResponse) Code(io.envoyproxy.envoy.service.ratelimit.v3.RateLimitResponse.Code) RateLimitDescriptor(io.envoyproxy.envoy.extensions.common.ratelimit.v3.RateLimitDescriptor) FlowRule(com.alibaba.csp.sentinel.slots.block.flow.FlowRule)

Aggregations

FlowRule (com.alibaba.csp.sentinel.slots.block.flow.FlowRule)113 ArrayList (java.util.ArrayList)31 Test (org.junit.Test)31 ClusterNode (com.alibaba.csp.sentinel.node.ClusterNode)22 List (java.util.List)17 TokenResult (com.alibaba.csp.sentinel.cluster.TokenResult)11 DegradeRule (com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule)9 BlockException (com.alibaba.csp.sentinel.slots.block.BlockException)6 Test (org.junit.jupiter.api.Test)6 ClusterFlowConfig (com.alibaba.csp.sentinel.slots.block.flow.ClusterFlowConfig)5 TypeReference (com.alibaba.fastjson.TypeReference)5 QuarkusUnitTest (io.quarkus.test.QuarkusUnitTest)5 Before (org.junit.Before)5 ParamFlowRule (com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule)4 ClusterMetric (com.alibaba.csp.sentinel.cluster.flow.statistic.metric.ClusterMetric)3 FlowRuleManager (com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager)3 AbstractTimeBasedTest (com.alibaba.csp.sentinel.test.AbstractTimeBasedTest)3 RateLimitDescriptor (io.envoyproxy.envoy.extensions.common.ratelimit.v3.RateLimitDescriptor)3 RateLimitResponse (io.envoyproxy.envoy.service.ratelimit.v3.RateLimitResponse)3 IOException (java.io.IOException)3