Search in sources :

Example 6 with TokenResult

use of com.alibaba.csp.sentinel.cluster.TokenResult in project Sentinel by alibaba.

the class ParamFlowRequestProcessor method processRequest.

@Override
public ClusterResponse<FlowTokenResponseData> processRequest(ClusterRequest<ParamFlowRequestData> request) {
    TokenService tokenService = TokenServiceProvider.getService();
    long flowId = request.getData().getFlowId();
    int count = request.getData().getCount();
    Collection<Object> args = request.getData().getParams();
    TokenResult result = tokenService.requestParamToken(flowId, count, args);
    return toResponse(result, request);
}
Also used : TokenResult(com.alibaba.csp.sentinel.cluster.TokenResult) TokenService(com.alibaba.csp.sentinel.cluster.TokenService)

Example 7 with TokenResult

use of com.alibaba.csp.sentinel.cluster.TokenResult in project Sentinel by alibaba.

the class ConcurrentClusterFlowCheckerTest method testConcurrentAcquireAndRelease.

@Test
public void testConcurrentAcquireAndRelease() throws InterruptedException {
    setCurrentMillis(System.currentTimeMillis());
    final FlowRule rule = ClusterFlowRuleManager.getFlowRuleById(111L);
    final CountDownLatch countDownLatch = new CountDownLatch(1000);
    ExecutorService pool = Executors.newFixedThreadPool(100);
    for (long i = 0; i < 1000; i++) {
        Runnable task = new Runnable() {

            @Override
            public void run() {
                assert rule != null;
                TokenResult result = ConcurrentClusterFlowChecker.acquireConcurrentToken("127.0.0.1", rule, 1);
                Assert.assertTrue("concurrent control fail", CurrentConcurrencyManager.get(111L).get() <= rule.getCount());
                if (result.getStatus() == TokenResultStatus.OK) {
                    ConcurrentClusterFlowChecker.releaseConcurrentToken(result.getTokenId());
                }
                countDownLatch.countDown();
            }
        };
        pool.execute(task);
    }
    countDownLatch.await();
    pool.shutdown();
    assert rule != null;
    Assert.assertTrue("fail to acquire and release token", CurrentConcurrencyManager.get(rule.getClusterConfig().getFlowId()).get() == 0 && TokenCacheNodeManager.getSize() == 0);
}
Also used : TokenResult(com.alibaba.csp.sentinel.cluster.TokenResult) ExecutorService(java.util.concurrent.ExecutorService) FlowRule(com.alibaba.csp.sentinel.slots.block.flow.FlowRule) CountDownLatch(java.util.concurrent.CountDownLatch) AbstractTimeBasedTest(com.alibaba.csp.sentinel.test.AbstractTimeBasedTest) Test(org.junit.Test)

Example 8 with TokenResult

use of com.alibaba.csp.sentinel.cluster.TokenResult in project Sentinel by alibaba.

the class FlowRuleChecker method passClusterCheck.

private static boolean passClusterCheck(FlowRule rule, Context context, DefaultNode node, int acquireCount, boolean prioritized) {
    try {
        TokenService clusterService = pickClusterService();
        if (clusterService == null) {
            return fallbackToLocalOrPass(rule, context, node, acquireCount, prioritized);
        }
        long flowId = rule.getClusterConfig().getFlowId();
        TokenResult result = clusterService.requestToken(flowId, acquireCount, prioritized);
        return applyTokenResult(result, rule, context, node, acquireCount, prioritized);
    // If client is absent, then fallback to local mode.
    } catch (Throwable ex) {
        RecordLog.warn("[FlowRuleChecker] Request cluster token unexpected failed", ex);
    }
    // If fallback is not enabled, then directly pass.
    return fallbackToLocalOrPass(rule, context, node, acquireCount, prioritized);
}
Also used : TokenResult(com.alibaba.csp.sentinel.cluster.TokenResult) TokenService(com.alibaba.csp.sentinel.cluster.TokenService)

Example 9 with TokenResult

use of com.alibaba.csp.sentinel.cluster.TokenResult 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 10 with TokenResult

use of com.alibaba.csp.sentinel.cluster.TokenResult 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

TokenResult (com.alibaba.csp.sentinel.cluster.TokenResult)22 FlowRule (com.alibaba.csp.sentinel.slots.block.flow.FlowRule)11 Test (org.junit.Test)6 TokenService (com.alibaba.csp.sentinel.cluster.TokenService)4 RateLimitDescriptor (io.envoyproxy.envoy.api.v2.ratelimit.RateLimitDescriptor)3 RateLimitDescriptor (io.envoyproxy.envoy.extensions.common.ratelimit.v3.RateLimitDescriptor)3 RateLimitResponse (io.envoyproxy.envoy.service.ratelimit.v2.RateLimitResponse)3 RateLimitResponse (io.envoyproxy.envoy.service.ratelimit.v3.RateLimitResponse)3 ArrayList (java.util.ArrayList)3 TokenResultStatus (com.alibaba.csp.sentinel.cluster.TokenResultStatus)2 TokenCacheNode (com.alibaba.csp.sentinel.cluster.flow.statistic.concurrent.TokenCacheNode)2 ClusterMetric (com.alibaba.csp.sentinel.cluster.flow.statistic.metric.ClusterMetric)2 ClusterRequest (com.alibaba.csp.sentinel.cluster.request.ClusterRequest)2 ParamFlowRequestData (com.alibaba.csp.sentinel.cluster.request.data.ParamFlowRequestData)2 AbstractTimeBasedTest (com.alibaba.csp.sentinel.test.AbstractTimeBasedTest)2 Tuple2 (com.alibaba.csp.sentinel.util.function.Tuple2)2 RateLimitRequest (io.envoyproxy.envoy.service.ratelimit.v2.RateLimitRequest)2 Code (io.envoyproxy.envoy.service.ratelimit.v2.RateLimitResponse.Code)2 RateLimitRequest (io.envoyproxy.envoy.service.ratelimit.v3.RateLimitRequest)2 StreamObserver (io.grpc.stub.StreamObserver)2