Search in sources :

Example 26 with FlowRule

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

the class EnvoySentinelRuleConverterTest method testConvertToSentinelFlowRules.

@Test
public void testConvertToSentinelFlowRules() {
    String domain = "testConvertToSentinelFlowRules";
    EnvoyRlsRule rlsRule = new EnvoyRlsRule();
    rlsRule.setDomain(domain);
    List<ResourceDescriptor> descriptors = new ArrayList<>();
    ResourceDescriptor d1 = new ResourceDescriptor();
    d1.setCount(10d);
    d1.setResources(Collections.singleton(new KeyValueResource("k1", "v1")));
    descriptors.add(d1);
    ResourceDescriptor d2 = new ResourceDescriptor();
    d2.setCount(20d);
    d2.setResources(new HashSet<>(Arrays.asList(new KeyValueResource("k2", "v2"), new KeyValueResource("k3", "v3"))));
    descriptors.add(d2);
    rlsRule.setDescriptors(descriptors);
    List<FlowRule> rules = EnvoySentinelRuleConverter.toSentinelFlowRules(rlsRule);
    final String expectedK1 = domain + SEPARATOR + "k1" + SEPARATOR + "v1";
    FlowRule r1 = rules.stream().filter(e -> e.getResource().equals(expectedK1)).findAny().orElseThrow(() -> new AssertionError("the converted rule does not exist, expected key: " + expectedK1));
    assertEquals(10d, r1.getCount(), 0.01);
    final String expectedK2 = domain + SEPARATOR + "k2" + SEPARATOR + "v2" + SEPARATOR + "k3" + SEPARATOR + "v3";
    FlowRule r2 = rules.stream().filter(e -> e.getResource().equals(expectedK2)).findAny().orElseThrow(() -> new AssertionError("the converted rule does not exist, expected key: " + expectedK2));
    assertEquals(20d, r2.getCount(), 0.01);
}
Also used : KeyValueResource(com.alibaba.csp.sentinel.cluster.server.envoy.rls.rule.EnvoyRlsRule.KeyValueResource) ArrayList(java.util.ArrayList) FlowRule(com.alibaba.csp.sentinel.slots.block.flow.FlowRule) ResourceDescriptor(com.alibaba.csp.sentinel.cluster.server.envoy.rls.rule.EnvoyRlsRule.ResourceDescriptor) Test(org.junit.Test)

Example 27 with FlowRule

use of com.alibaba.csp.sentinel.slots.block.flow.FlowRule 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 28 with FlowRule

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

the class ConcurrentClusterFlowCheckerTest method testReleaseExpiredToken.

@Test
public void testReleaseExpiredToken() throws InterruptedException {
    ConnectionManager.addConnection("test", "127.0.0.1");
    FlowRule rule = ClusterFlowRuleManager.getFlowRuleById(111L);
    for (int i = 0; i < 10; i++) {
        ConcurrentClusterFlowChecker.acquireConcurrentToken("127.0.0.1", rule, 1);
    }
    Thread.sleep(3000);
    Assert.assertTrue("fail to acquire and release token", CurrentConcurrencyManager.get(rule.getClusterConfig().getFlowId()).get() == 0 && TokenCacheNodeManager.getSize() == 0);
}
Also used : FlowRule(com.alibaba.csp.sentinel.slots.block.flow.FlowRule) AbstractTimeBasedTest(com.alibaba.csp.sentinel.test.AbstractTimeBasedTest) Test(org.junit.Test)

Example 29 with FlowRule

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

the class ZookeeperDataSourceTest method testZooKeeperDataSource.

@Test
public void testZooKeeperDataSource() throws Exception {
    TestingServer server = new TestingServer(21812);
    server.start();
    final String remoteAddress = server.getConnectString();
    final String path = "/sentinel-zk-ds-demo/flow-HK";
    ReadableDataSource<String, List<FlowRule>> flowRuleDataSource = new ZookeeperDataSource<List<FlowRule>>(remoteAddress, path, new Converter<String, List<FlowRule>>() {

        @Override
        public List<FlowRule> convert(String source) {
            return JSON.parseObject(source, new TypeReference<List<FlowRule>>() {
            });
        }
    });
    FlowRuleManager.register2Property(flowRuleDataSource.getProperty());
    CuratorFramework zkClient = CuratorFrameworkFactory.newClient(remoteAddress, new ExponentialBackoffRetry(3, 1000));
    zkClient.start();
    Stat stat = zkClient.checkExists().forPath(path);
    if (stat == null) {
        zkClient.create().creatingParentContainersIfNeeded().withMode(CreateMode.PERSISTENT).forPath(path, null);
    }
    final String resourceName = "HK";
    publishThenTestFor(zkClient, path, resourceName, 10);
    publishThenTestFor(zkClient, path, resourceName, 15);
    zkClient.close();
    server.stop();
}
Also used : TestingServer(org.apache.curator.test.TestingServer) CuratorFramework(org.apache.curator.framework.CuratorFramework) Stat(org.apache.zookeeper.data.Stat) ExponentialBackoffRetry(org.apache.curator.retry.ExponentialBackoffRetry) List(java.util.List) FlowRule(com.alibaba.csp.sentinel.slots.block.flow.FlowRule) TypeReference(com.alibaba.fastjson.TypeReference) Test(org.junit.Test)

Example 30 with FlowRule

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

the class ZookeeperDataSourceTest method testZooKeeperDataSourceSameZkClient.

/**
 * Test whether different dataSources can share the same zkClient when the connection parameters are the same.
 * @throws Exception
 */
@Test
public void testZooKeeperDataSourceSameZkClient() throws Exception {
    TestingServer server = new TestingServer(21813);
    server.start();
    final String remoteAddress = server.getConnectString();
    final String flowPath = "/sentinel-zk-ds-demo/flow-HK";
    final String degradePath = "/sentinel-zk-ds-demo/degrade-HK";
    ZookeeperDataSource<List<FlowRule>> flowRuleZkDataSource = new ZookeeperDataSource<>(remoteAddress, flowPath, new Converter<String, List<FlowRule>>() {

        @Override
        public List<FlowRule> convert(String source) {
            return JSON.parseObject(source, new TypeReference<List<FlowRule>>() {
            });
        }
    });
    ZookeeperDataSource<List<DegradeRule>> degradeRuleZkDataSource = new ZookeeperDataSource<>(remoteAddress, degradePath, new Converter<String, List<DegradeRule>>() {

        @Override
        public List<DegradeRule> convert(String source) {
            return JSON.parseObject(source, new TypeReference<List<DegradeRule>>() {
            });
        }
    });
    Assert.assertTrue(flowRuleZkDataSource.getZkClient() == degradeRuleZkDataSource.getZkClient());
    final String groupId = "sentinel-zk-ds-demo";
    final String flowDataId = "flow-HK";
    final String degradeDataId = "degrade-HK";
    final String scheme = "digest";
    final String auth = "root:123456";
    AuthInfo authInfo = new AuthInfo(scheme, auth.getBytes());
    List<AuthInfo> authInfoList = Collections.singletonList(authInfo);
    ZookeeperDataSource<List<FlowRule>> flowRuleZkAutoDataSource = new ZookeeperDataSource<List<FlowRule>>(remoteAddress, authInfoList, groupId, flowDataId, new Converter<String, List<FlowRule>>() {

        @Override
        public List<FlowRule> convert(String source) {
            return JSON.parseObject(source, new TypeReference<List<FlowRule>>() {
            });
        }
    });
    ZookeeperDataSource<List<DegradeRule>> degradeRuleZkAutoDataSource = new ZookeeperDataSource<List<DegradeRule>>(remoteAddress, authInfoList, groupId, degradeDataId, new Converter<String, List<DegradeRule>>() {

        @Override
        public List<DegradeRule> convert(String source) {
            return JSON.parseObject(source, new TypeReference<List<DegradeRule>>() {
            });
        }
    });
    Assert.assertTrue(flowRuleZkAutoDataSource.getZkClient() == degradeRuleZkAutoDataSource.getZkClient());
    server.stop();
}
Also used : TestingServer(org.apache.curator.test.TestingServer) AuthInfo(org.apache.curator.framework.AuthInfo) DegradeRule(com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule) List(java.util.List) TypeReference(com.alibaba.fastjson.TypeReference) FlowRule(com.alibaba.csp.sentinel.slots.block.flow.FlowRule) Test(org.junit.Test)

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