Search in sources :

Example 91 with FlowRule

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

the class StandaloneRedisDataSourceTest method testPubMsgAndReceiveSuccess.

@Test
public void testPubMsgAndReceiveSuccess() {
    List<FlowRule> rules = FlowRuleManager.getRules();
    Assert.assertEquals(1, rules.size());
    int maxQueueingTimeMs = new Random().nextInt();
    StatefulRedisPubSubConnection<String, String> connection = client.connectPubSub();
    String flowRules = "[{\"resource\":\"test\", \"limitApp\":\"default\", \"grade\":1, \"count\":\"0.0\", \"strategy\":0, " + "\"refResource\":null, " + "\"controlBehavior\":0, \"warmUpPeriodSec\":10, \"maxQueueingTimeMs\":" + maxQueueingTimeMs + ", \"controller\":null}]";
    RedisPubSubCommands<String, String> subCommands = connection.sync();
    subCommands.multi();
    subCommands.set(ruleKey, flowRules);
    subCommands.publish(channel, flowRules);
    subCommands.exec();
    await().timeout(2, TimeUnit.SECONDS).until(new Callable<List<FlowRule>>() {

        @Override
        public List<FlowRule> call() throws Exception {
            return FlowRuleManager.getRules();
        }
    }, Matchers.hasSize(1));
    rules = FlowRuleManager.getRules();
    Assert.assertEquals(rules.get(0).getMaxQueueingTimeMs(), maxQueueingTimeMs);
    String value = subCommands.get(ruleKey);
    List<FlowRule> flowRulesValuesInRedis = buildFlowConfigParser().convert(value);
    Assert.assertEquals(flowRulesValuesInRedis.size(), 1);
    Assert.assertEquals(flowRulesValuesInRedis.get(0).getMaxQueueingTimeMs(), maxQueueingTimeMs);
}
Also used : Random(java.util.Random) List(java.util.List) FlowRule(com.alibaba.csp.sentinel.slots.block.flow.FlowRule) IOException(java.io.IOException) Test(org.junit.Test)

Example 92 with FlowRule

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

the class ZookeeperDataSourceTest method testZooKeeperDataSourceAuthorization.

@Test
public void testZooKeeperDataSourceAuthorization() throws Exception {
    TestingServer server = new TestingServer(21812);
    server.start();
    final String remoteAddress = server.getConnectString();
    final String groupId = "sentinel-zk-ds-demo";
    final String dataId = "flow-HK";
    final String path = "/" + groupId + "/" + dataId;
    final String scheme = "digest";
    final String auth = "root:123456";
    AuthInfo authInfo = new AuthInfo(scheme, auth.getBytes());
    List<AuthInfo> authInfoList = Collections.singletonList(authInfo);
    CuratorFramework zkClient = CuratorFrameworkFactory.builder().connectString(remoteAddress).retryPolicy(new ExponentialBackoffRetry(3, 100)).authorization(authInfoList).build();
    zkClient.start();
    Stat stat = zkClient.checkExists().forPath(path);
    if (stat == null) {
        ACL acl = new ACL(ZooDefs.Perms.ALL, new Id(scheme, DigestAuthenticationProvider.generateDigest(auth)));
        zkClient.create().creatingParentContainersIfNeeded().withACL(Collections.singletonList(acl)).forPath(path, null);
    }
    ReadableDataSource<String, List<FlowRule>> flowRuleDataSource = new ZookeeperDataSource<List<FlowRule>>(remoteAddress, authInfoList, groupId, dataId, new Converter<String, List<FlowRule>>() {

        @Override
        public List<FlowRule> convert(String source) {
            return JSON.parseObject(source, new TypeReference<List<FlowRule>>() {
            });
        }
    });
    FlowRuleManager.register2Property(flowRuleDataSource.getProperty());
    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) AuthInfo(org.apache.curator.framework.AuthInfo) ExponentialBackoffRetry(org.apache.curator.retry.ExponentialBackoffRetry) ACL(org.apache.zookeeper.data.ACL) CuratorFramework(org.apache.curator.framework.CuratorFramework) Stat(org.apache.zookeeper.data.Stat) List(java.util.List) Id(org.apache.zookeeper.data.Id) FlowRule(com.alibaba.csp.sentinel.slots.block.flow.FlowRule) TypeReference(com.alibaba.fastjson.TypeReference) Test(org.junit.Test)

Example 93 with FlowRule

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

the class ZookeeperDataSourceTest method publishThenTestFor.

private void publishThenTestFor(CuratorFramework zkClient, String path, String resourceName, long count) throws Exception {
    FlowRule rule = new FlowRule().setResource(resourceName).setLimitApp("default").as(FlowRule.class).setCount(count).setGrade(RuleConstant.FLOW_GRADE_QPS);
    String ruleString = JSON.toJSONString(Collections.singletonList(rule));
    zkClient.setData().forPath(path, ruleString.getBytes());
    await().timeout(5, TimeUnit.SECONDS).until(new Callable<Boolean>() {

        @Override
        public Boolean call() throws Exception {
            List<FlowRule> rules = FlowRuleManager.getRules();
            return rules != null && !rules.isEmpty();
        }
    });
    List<FlowRule> rules = FlowRuleManager.getRules();
    boolean exists = false;
    for (FlowRule r : rules) {
        if (resourceName.equals(r.getResource())) {
            exists = true;
            assertEquals(count, new Double(r.getCount()).longValue());
        }
    }
    assertTrue(exists);
}
Also used : List(java.util.List) FlowRule(com.alibaba.csp.sentinel.slots.block.flow.FlowRule)

Example 94 with FlowRule

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

the class ClusterModeRedisDataSourceTest method testConnectToSentinelAndPubMsgSuccess.

@Test
public void testConnectToSentinelAndPubMsgSuccess() {
    int maxQueueingTimeMs = new Random().nextInt();
    String flowRulesJson = "[{\"resource\":\"test\", \"limitApp\":\"default\", \"grade\":1, \"count\":\"0.0\", \"strategy\":0, " + "\"refResource\":null, " + "\"controlBehavior\":0, \"warmUpPeriodSec\":10, \"maxQueueingTimeMs\":" + maxQueueingTimeMs + ", \"controller\":null}]";
    RedisAdvancedClusterCommands<String, String> subCommands = client.connect().sync();
    int slot = SlotHash.getSlot(ruleKey);
    NodeSelection<String, String> nodes = subCommands.nodes((n) -> n.hasSlot(slot));
    RedisCommands<String, String> commands = nodes.commands(0);
    commands.multi();
    commands.set(ruleKey, flowRulesJson);
    commands.publish(channel, flowRulesJson);
    commands.exec();
    await().timeout(2, TimeUnit.SECONDS).until(new Callable<List<FlowRule>>() {

        @Override
        public List<FlowRule> call() throws Exception {
            return FlowRuleManager.getRules();
        }
    }, Matchers.hasSize(1));
    List<FlowRule> rules = FlowRuleManager.getRules();
    Assert.assertEquals(rules.get(0).getMaxQueueingTimeMs(), maxQueueingTimeMs);
    String value = subCommands.get(ruleKey);
    List<FlowRule> flowRulesValuesInRedis = buildFlowConfigParser().convert(value);
    Assert.assertEquals(flowRulesValuesInRedis.size(), 1);
    Assert.assertEquals(flowRulesValuesInRedis.get(0).getMaxQueueingTimeMs(), maxQueueingTimeMs);
}
Also used : Random(java.util.Random) List(java.util.List) FlowRule(com.alibaba.csp.sentinel.slots.block.flow.FlowRule)

Example 95 with FlowRule

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

the class SentinelAnnotationInterceptorIntegrationTest method testDefaultFallbackWithSingleParam.

@Test
public void testDefaultFallbackWithSingleParam() {
    assertThat(fooService.anotherFoo(1)).isEqualTo("Hello for 1");
    String resourceName = "apiAnotherFooWithDefaultFallback";
    ClusterNode cn = ClusterBuilderSlot.getClusterNode(resourceName);
    assertThat(cn).isNotNull();
    assertThat(cn.passQps()).isPositive();
    // Default fallback should take effect.
    assertThat(fooService.anotherFoo(5758)).isEqualTo(FooUtil.FALLBACK_DEFAULT_RESULT);
    assertThat(cn.exceptionQps()).isPositive();
    assertThat(cn.blockQps()).isZero();
    FlowRuleManager.loadRules(Collections.singletonList(new FlowRule(resourceName).setCount(0)));
    // Default fallback should also take effect for BlockException.
    assertThat(fooService.anotherFoo(5758)).isEqualTo(FooUtil.FALLBACK_DEFAULT_RESULT);
    assertThat(cn.blockQps()).isPositive();
}
Also used : ClusterNode(com.alibaba.csp.sentinel.node.ClusterNode) 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