Search in sources :

Example 26 with ResourceWrapper

use of com.alibaba.csp.sentinel.slotchain.ResourceWrapper in project Sentinel by alibaba.

the class ParamFlowThrottleRateLimitingCheckerTest method testSingleValueThrottleCheckQps.

@Test
public void testSingleValueThrottleCheckQps() throws Exception {
    final String resourceName = "testSingleValueThrottleCheckQps";
    final ResourceWrapper resourceWrapper = new StringResourceWrapper(resourceName, EntryType.IN);
    int paramIdx = 0;
    TimeUtil.currentTimeMillis();
    long threshold = 5L;
    ParamFlowRule rule = new ParamFlowRule();
    rule.setResource(resourceName);
    rule.setCount(threshold);
    rule.setParamIdx(paramIdx);
    rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER);
    String valueA = "valueA";
    ParameterMetric metric = new ParameterMetric();
    ParameterMetricStorage.getMetricsMap().put(resourceWrapper.getName(), metric);
    metric.getRuleTimeCounterMap().put(rule, new ConcurrentLinkedHashMapWrapper<Object, AtomicLong>(4000));
    long currentTime = TimeUtil.currentTimeMillis();
    long endTime = currentTime + rule.getDurationInSec() * 1000;
    int successCount = 0;
    while (currentTime <= endTime - 10) {
        if (ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA)) {
            successCount++;
        }
        currentTime = TimeUtil.currentTimeMillis();
    }
    assertEquals(successCount, threshold);
    System.out.println("testSingleValueThrottleCheckQps: sleep for 3 seconds");
    TimeUnit.SECONDS.sleep(3);
    currentTime = TimeUtil.currentTimeMillis();
    endTime = currentTime + rule.getDurationInSec() * 1000;
    successCount = 0;
    while (currentTime <= endTime - 10) {
        if (ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA)) {
            successCount++;
        }
        currentTime = TimeUtil.currentTimeMillis();
    }
    assertEquals(successCount, threshold);
}
Also used : StringResourceWrapper(com.alibaba.csp.sentinel.slotchain.StringResourceWrapper) ResourceWrapper(com.alibaba.csp.sentinel.slotchain.ResourceWrapper) StringResourceWrapper(com.alibaba.csp.sentinel.slotchain.StringResourceWrapper) AtomicLong(java.util.concurrent.atomic.AtomicLong) Test(org.junit.Test)

Example 27 with ResourceWrapper

use of com.alibaba.csp.sentinel.slotchain.ResourceWrapper in project Sentinel by alibaba.

the class ParamFlowThrottleRateLimitingCheckerTest method testSingleValueThrottleCheckQpsMultipleThreads.

@Test
public void testSingleValueThrottleCheckQpsMultipleThreads() throws Exception {
    final String resourceName = "testSingleValueThrottleCheckQpsMultipleThreads";
    final ResourceWrapper resourceWrapper = new StringResourceWrapper(resourceName, EntryType.IN);
    int paramIdx = 0;
    long threshold = 5L;
    final ParamFlowRule rule = new ParamFlowRule(resourceName).setCount(threshold).setParamIdx(paramIdx).setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER);
    final String valueA = "valueA";
    ParameterMetric metric = new ParameterMetric();
    ParameterMetricStorage.getMetricsMap().put(resourceWrapper.getName(), metric);
    metric.getRuleTimeCounterMap().put(rule, new ConcurrentLinkedHashMapWrapper<Object, AtomicLong>(4000));
    int threadCount = 40;
    System.out.println(metric.getRuleTimeCounter(rule));
    final CountDownLatch waitLatch = new CountDownLatch(threadCount);
    final AtomicInteger successCount = new AtomicInteger();
    for (int i = 0; i < threadCount; i++) {
        Thread t = new Thread(new Runnable() {

            @Override
            public void run() {
                if (ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA)) {
                    successCount.incrementAndGet();
                }
                waitLatch.countDown();
            }
        });
        t.setName("sentinel-simulate-traffic-task-" + i);
        t.start();
    }
    waitLatch.await();
    assertEquals(successCount.get(), 1);
    System.out.println(threadCount);
    successCount.set(0);
    System.out.println("testSingleValueThrottleCheckQpsMultipleThreads: sleep for 3 seconds");
    TimeUnit.SECONDS.sleep(3);
    successCount.set(0);
    final CountDownLatch waitLatch1 = new CountDownLatch(threadCount);
    final long currentTime = TimeUtil.currentTimeMillis();
    final long endTime = currentTime + rule.getDurationInSec() * 1000 - 1;
    for (int i = 0; i < threadCount; i++) {
        Thread t = new Thread(new Runnable() {

            @Override
            public void run() {
                long currentTime1 = currentTime;
                while (currentTime1 <= endTime) {
                    if (ParamFlowChecker.passSingleValueCheck(resourceWrapper, rule, 1, valueA)) {
                        successCount.incrementAndGet();
                    }
                    Random random = new Random();
                    try {
                        TimeUnit.MILLISECONDS.sleep(random.nextInt(20));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    currentTime1 = TimeUtil.currentTimeMillis();
                }
                waitLatch1.countDown();
            }
        });
        t.setName("sentinel-simulate-traffic-task-" + i);
        t.start();
    }
    waitLatch1.await();
    assertEquals(successCount.get(), threshold);
}
Also used : StringResourceWrapper(com.alibaba.csp.sentinel.slotchain.StringResourceWrapper) ResourceWrapper(com.alibaba.csp.sentinel.slotchain.ResourceWrapper) StringResourceWrapper(com.alibaba.csp.sentinel.slotchain.StringResourceWrapper) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicLong(java.util.concurrent.atomic.AtomicLong) Random(java.util.Random) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Test(org.junit.Test)

Example 28 with ResourceWrapper

use of com.alibaba.csp.sentinel.slotchain.ResourceWrapper in project Sentinel by alibaba.

the class MetricTimerListener method run.

@Override
public void run() {
    Map<Long, List<MetricNode>> maps = new TreeMap<>();
    for (Entry<ResourceWrapper, ClusterNode> e : ClusterBuilderSlot.getClusterNodeMap().entrySet()) {
        ClusterNode node = e.getValue();
        Map<Long, MetricNode> metrics = node.metrics();
        aggregate(maps, metrics, node);
    }
    aggregate(maps, Constants.ENTRY_NODE.metrics(), Constants.ENTRY_NODE);
    if (!maps.isEmpty()) {
        for (Entry<Long, List<MetricNode>> entry : maps.entrySet()) {
            try {
                metricWriter.write(entry.getKey(), entry.getValue());
            } catch (Exception e) {
                RecordLog.warn("[MetricTimerListener] Write metric error", e);
            }
        }
    }
}
Also used : ResourceWrapper(com.alibaba.csp.sentinel.slotchain.ResourceWrapper) ClusterNode(com.alibaba.csp.sentinel.node.ClusterNode) List(java.util.List) ArrayList(java.util.ArrayList) TreeMap(java.util.TreeMap)

Example 29 with ResourceWrapper

use of com.alibaba.csp.sentinel.slotchain.ResourceWrapper in project Sentinel by alibaba.

the class CtSphTest method testDefaultContextEntryWithFullContextSize.

private void testDefaultContextEntryWithFullContextSize(String resourceName, boolean async) {
    fillFullContext();
    ResourceWrapper resourceWrapper = new StringResourceWrapper(resourceName, EntryType.IN);
    // Prepare a slot that "should pass".
    ShouldPassSlot slot = addShouldPassSlotFor(resourceWrapper);
    assertFalse(slot.entered || slot.exited);
    Entry entry = null;
    try {
        if (!async) {
            entry = ctSph.entry(resourceWrapper, 1);
        } else {
            entry = ctSph.asyncEntry(resourceName, resourceWrapper.getEntryType(), 1);
            Context asyncContext = ((AsyncEntry) entry).getAsyncContext();
            assertTrue(ContextUtil.isDefaultContext(asyncContext));
            assertTrue(asyncContext.isAsync());
        }
        assertTrue(ContextUtil.isDefaultContext(ContextUtil.getContext()));
        assertTrue(slot.entered);
    } catch (BlockException ex) {
        fail("Unexpected blocked: " + ex.getClass().getCanonicalName());
    } finally {
        if (entry != null) {
            entry.exit();
            assertTrue(slot.exited);
        }
    }
}
Also used : StringResourceWrapper(com.alibaba.csp.sentinel.slotchain.StringResourceWrapper) ResourceWrapper(com.alibaba.csp.sentinel.slotchain.ResourceWrapper) StringResourceWrapper(com.alibaba.csp.sentinel.slotchain.StringResourceWrapper) Context(com.alibaba.csp.sentinel.context.Context) BlockException(com.alibaba.csp.sentinel.slots.block.BlockException)

Example 30 with ResourceWrapper

use of com.alibaba.csp.sentinel.slotchain.ResourceWrapper in project Sentinel by alibaba.

the class CtSphTest method testAsyncEntryNormalPass.

@Test
public void testAsyncEntryNormalPass() {
    String resourceName = "testAsyncEntryNormalPass";
    ResourceWrapper resourceWrapper = new StringResourceWrapper(resourceName, EntryType.IN);
    AsyncEntry entry = null;
    // Prepare a slot that "should pass".
    ShouldPassSlot slot = addShouldPassSlotFor(resourceWrapper);
    assertFalse(slot.entered || slot.exited);
    ContextUtil.enter("abc");
    Entry previousEntry = ContextUtil.getContext().getCurEntry();
    try {
        entry = ctSph.asyncEntry(resourceName, EntryType.IN, 1);
        assertTrue(slot.entered);
        assertFalse(slot.exited);
        Context asyncContext = entry.getAsyncContext();
        assertNotNull(asyncContext);
        assertSame(entry, asyncContext.getCurEntry());
        assertNotSame("The async entry should not be added to current context", entry, ContextUtil.getContext().getCurEntry());
        assertSame(previousEntry, ContextUtil.getContext().getCurEntry());
    } catch (BlockException ex) {
        fail("Unexpected blocked: " + ex.getClass().getCanonicalName());
    } finally {
        if (entry != null) {
            Context asyncContext = entry.getAsyncContext();
            entry.exit();
            assertTrue(slot.exited);
            assertNull(entry.getAsyncContext());
            assertSame(previousEntry, asyncContext.getCurEntry());
        }
        ContextUtil.exit();
    }
}
Also used : StringResourceWrapper(com.alibaba.csp.sentinel.slotchain.StringResourceWrapper) ResourceWrapper(com.alibaba.csp.sentinel.slotchain.ResourceWrapper) StringResourceWrapper(com.alibaba.csp.sentinel.slotchain.StringResourceWrapper) Context(com.alibaba.csp.sentinel.context.Context) BlockException(com.alibaba.csp.sentinel.slots.block.BlockException) Test(org.junit.Test)

Aggregations

ResourceWrapper (com.alibaba.csp.sentinel.slotchain.ResourceWrapper)42 StringResourceWrapper (com.alibaba.csp.sentinel.slotchain.StringResourceWrapper)31 Test (org.junit.Test)26 AtomicLong (java.util.concurrent.atomic.AtomicLong)12 ClusterNode (com.alibaba.csp.sentinel.node.ClusterNode)10 Context (com.alibaba.csp.sentinel.context.Context)7 Node (com.alibaba.csp.sentinel.node.Node)7 DefaultNode (com.alibaba.csp.sentinel.node.DefaultNode)6 StatisticNode (com.alibaba.csp.sentinel.node.StatisticNode)6 Entry (com.alibaba.csp.sentinel.Entry)5 BlockException (com.alibaba.csp.sentinel.slots.block.BlockException)5 AbstractTimeBasedTest (com.alibaba.csp.sentinel.test.AbstractTimeBasedTest)5 HashMap (java.util.HashMap)5 DemoService (com.alibaba.csp.sentinel.adapter.dubbo.provider.DemoService)2 CountDownLatch (java.util.concurrent.CountDownLatch)2 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2 AbstractSpan (org.apache.skywalking.apm.agent.core.context.trace.AbstractSpan)2 AsyncEntry (com.alibaba.csp.sentinel.AsyncEntry)1 MetricNode (com.alibaba.csp.sentinel.node.metric.MetricNode)1 MethodResourceWrapper (com.alibaba.csp.sentinel.slotchain.MethodResourceWrapper)1