Search in sources :

Example 11 with ResourceWrapper

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

the class ParamFlowDefaultCheckerTest method testParamFlowDefaultCheckSingleValueCheckQpsMultipleThreads.

@Test
public void testParamFlowDefaultCheckSingleValueCheckQpsMultipleThreads() throws Exception {
    // In this test case we use the actual time.
    useActualTime();
    final String resourceName = "testParamFlowDefaultCheckSingleValueCheckQpsMultipleThreads";
    final ResourceWrapper resourceWrapper = new StringResourceWrapper(resourceName, EntryType.IN);
    int paramIdx = 0;
    long threshold = 5L;
    final ParamFlowRule rule = new ParamFlowRule();
    rule.setResource(resourceName);
    rule.setCount(threshold);
    rule.setParamIdx(paramIdx);
    final String valueA = "valueA";
    ParameterMetric metric = new ParameterMetric();
    ParameterMetricStorage.getMetricsMap().put(resourceWrapper.getName(), metric);
    metric.getRuleTimeCounterMap().put(rule, new ConcurrentLinkedHashMapWrapper<Object, AtomicLong>(4000));
    metric.getRuleTokenCounterMap().put(rule, new ConcurrentLinkedHashMapWrapper<Object, AtomicLong>(4000));
    int threadCount = 40;
    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(), threshold);
    successCount.set(0);
    System.out.println("testParamFlowDefaultCheckSingleValueCheckQpsMultipleThreads: 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();
                    }
                    try {
                        TimeUnit.MILLISECONDS.sleep(ThreadLocalRandom.current().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) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AbstractTimeBasedTest(com.alibaba.csp.sentinel.test.AbstractTimeBasedTest) Test(org.junit.Test)

Example 12 with ResourceWrapper

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

the class ParamFlowSlotTest method testEntryWhenParamFlowExists.

@Test
public void testEntryWhenParamFlowExists() throws Throwable {
    String resourceName = "testEntryWhenParamFlowExists";
    ResourceWrapper resourceWrapper = new StringResourceWrapper(resourceName, EntryType.IN);
    long argToGo = 1L;
    double count = 1;
    ParamFlowRule rule = new ParamFlowRule(resourceName).setCount(count).setBurstCount(0).setParamIdx(0);
    ParamFlowRuleManager.loadRules(Collections.singletonList(rule));
    ParameterMetric metric = mock(ParameterMetric.class);
    CacheMap<Object, AtomicLong> map = new ConcurrentLinkedHashMapWrapper<>(4000);
    CacheMap<Object, AtomicLong> map2 = new ConcurrentLinkedHashMapWrapper<>(4000);
    when(metric.getRuleTimeCounter(rule)).thenReturn(map);
    when(metric.getRuleTokenCounter(rule)).thenReturn(map2);
    map.put(argToGo, new AtomicLong(TimeUtil.currentTimeMillis()));
    // Insert the mock metric to control pass or block.
    ParameterMetricStorage.getMetricsMap().put(resourceWrapper.getName(), metric);
    // The first entry will pass.
    paramFlowSlot.entry(null, resourceWrapper, null, 1, false, argToGo);
    // The second entry will be blocked.
    try {
        paramFlowSlot.entry(null, resourceWrapper, null, 1, false, argToGo);
    } catch (ParamFlowException ex) {
        assertEquals(String.valueOf(argToGo), ex.getMessage());
        assertEquals(resourceName, ex.getResourceName());
        return;
    }
    fail("The second entry should be blocked");
}
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) ConcurrentLinkedHashMapWrapper(com.alibaba.csp.sentinel.slots.statistic.cache.ConcurrentLinkedHashMapWrapper) Test(org.junit.Test)

Example 13 with ResourceWrapper

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

the class ParameterMetricStorageTest method testInitParamMetrics.

@Test
public void testInitParamMetrics() {
    ParamFlowRule rule = new ParamFlowRule();
    rule.setParamIdx(1);
    int index = 1;
    String resourceName = "res-" + System.currentTimeMillis();
    ResourceWrapper resourceWrapper = new StringResourceWrapper(resourceName, EntryType.IN);
    assertNull(ParameterMetricStorage.getParamMetric(resourceWrapper));
    ParameterMetricStorage.initParamMetricsFor(resourceWrapper, rule);
    ParameterMetric metric = ParameterMetricStorage.getParamMetric(resourceWrapper);
    assertNotNull(metric);
    assertNotNull(metric.getRuleTimeCounterMap().get(rule));
    assertNotNull(metric.getThreadCountMap().get(index));
    // Duplicate init.
    ParameterMetricStorage.initParamMetricsFor(resourceWrapper, rule);
    assertSame(metric, ParameterMetricStorage.getParamMetric(resourceWrapper));
    ParamFlowRule rule2 = new ParamFlowRule();
    rule2.setParamIdx(1);
    assertSame(metric, ParameterMetricStorage.getParamMetric(resourceWrapper));
}
Also used : StringResourceWrapper(com.alibaba.csp.sentinel.slotchain.StringResourceWrapper) ResourceWrapper(com.alibaba.csp.sentinel.slotchain.ResourceWrapper) StringResourceWrapper(com.alibaba.csp.sentinel.slotchain.StringResourceWrapper) Test(org.junit.Test)

Example 14 with ResourceWrapper

use of com.alibaba.csp.sentinel.slotchain.ResourceWrapper in project skywalking-java by apache.

the class SentinelAsyncEntryConstructorInterceptor method onConstruct.

@Override
public void onConstruct(EnhancedInstance objInst, Object[] allArguments) {
    ResourceWrapper resourceWrapper = (ResourceWrapper) allArguments[0];
    AbstractSpan activeSpan = ContextManager.createLocalSpan("Sentinel/" + resourceWrapper.getName());
    activeSpan.setComponent(ComponentsDefine.SENTINEL);
    AbstractSpan span = activeSpan.prepareForAsync();
    objInst.setSkyWalkingDynamicField(span);
    ContextManager.getRuntimeContext().put(SENTINEL_SPAN, span);
    ContextManager.stopSpan(activeSpan);
}
Also used : ResourceWrapper(com.alibaba.csp.sentinel.slotchain.ResourceWrapper) AbstractSpan(org.apache.skywalking.apm.agent.core.context.trace.AbstractSpan)

Example 15 with ResourceWrapper

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

the class CtSph method lookProcessChain.

/**
 * Get {@link ProcessorSlotChain} of the resource. new {@link ProcessorSlotChain} will
 * be created if the resource doesn't relate one.
 *
 * <p>Same resource({@link ResourceWrapper#equals(Object)}) will share the same
 * {@link ProcessorSlotChain} globally, no matter in which {@link Context}.<p/>
 *
 * <p>
 * Note that total {@link ProcessorSlot} count must not exceed {@link Constants#MAX_SLOT_CHAIN_SIZE},
 * otherwise null will return.
 * </p>
 *
 * @param resourceWrapper target resource
 * @return {@link ProcessorSlotChain} of the resource
 */
ProcessorSlot<Object> lookProcessChain(ResourceWrapper resourceWrapper) {
    ProcessorSlotChain chain = chainMap.get(resourceWrapper);
    if (chain == null) {
        synchronized (LOCK) {
            chain = chainMap.get(resourceWrapper);
            if (chain == null) {
                // Entry size limit.
                if (chainMap.size() >= Constants.MAX_SLOT_CHAIN_SIZE) {
                    return null;
                }
                chain = SlotChainProvider.newSlotChain();
                Map<ResourceWrapper, ProcessorSlotChain> newMap = new HashMap<ResourceWrapper, ProcessorSlotChain>(chainMap.size() + 1);
                newMap.putAll(chainMap);
                newMap.put(resourceWrapper, chain);
                chainMap = newMap;
            }
        }
    }
    return chain;
}
Also used : StringResourceWrapper(com.alibaba.csp.sentinel.slotchain.StringResourceWrapper) ResourceWrapper(com.alibaba.csp.sentinel.slotchain.ResourceWrapper) MethodResourceWrapper(com.alibaba.csp.sentinel.slotchain.MethodResourceWrapper) ProcessorSlotChain(com.alibaba.csp.sentinel.slotchain.ProcessorSlotChain) HashMap(java.util.HashMap)

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