com.alibaba.csp.sentinel.slots.block.BlockException Java Examples

The following examples show how to use com.alibaba.csp.sentinel.slots.block.BlockException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DemoController.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@RequestMapping("/link")
@ResponseBody
public String link() throws BlockException {

    Entry entry = SphU.entry("head1", EntryType.IN);

    Entry entry1 = SphU.entry("head2", EntryType.IN);
    Entry entry2 = SphU.entry("head3", EntryType.IN);
    Entry entry3 = SphU.entry("head4", EntryType.IN);

    entry3.exit();
    entry2.exit();
    entry1.exit();
    entry.exit();
    return "successfully create a call link";
}
 
Example #2
Source File: MonoSentinelOperatorIntegrationTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Test
public void testEmitSingleValueWhenFlowControlTriggered() {
    String resourceName = createResourceName("testEmitSingleValueWhenFlowControlTriggered");
    FlowRuleManager.loadRules(Collections.singletonList(
        new FlowRule(resourceName).setCount(0)
    ));
    StepVerifier.create(Mono.just(1)
        .map(e -> e * 2)
        .transform(new SentinelReactorTransformer<>(resourceName)))
        .expectError(BlockException.class)
        .verify();

    ClusterNode cn = ClusterBuilderSlot.getClusterNode(resourceName);
    assertNotNull(cn);
    assertEquals(0, cn.passQps(), 0.01);
    assertEquals(1, cn.blockRequest());

    FlowRuleManager.loadRules(new ArrayList<>());
}
 
Example #3
Source File: CtSphTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
private void testCustomContextEntryWithFullContextSize(String resourceName, boolean async) {
    fillFullContext();
    ResourceWrapper resourceWrapper = new StringResourceWrapper(resourceName, EntryType.IN);
    String contextName = "custom-context-" + System.currentTimeMillis();
    ContextUtil.enter(contextName, "9527");

    // Prepare a slot that "should not pass". If entered the slot, exception will be thrown.
    addShouldNotPassSlotFor(resourceWrapper);

    Entry entry = null;
    try {
        if (async) {
            entry = ctSph.asyncEntry(resourceName, resourceWrapper.getEntryType(), 1);
        } else {
            entry = ctSph.entry(resourceWrapper, 1);
        }
    } catch (BlockException ex) {
        fail("Unexpected blocked: " + ex.getClass().getCanonicalName());
    } finally {
        if (entry != null) {
            entry.exit();
        }
        ContextUtil.exit();
    }
}
 
Example #4
Source File: AbstractSentinelInterceptor.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
    throws Exception {
    try {
        String resourceName = getResourceName(request);

        if (StringUtil.isNotEmpty(resourceName)) {
            // Parse the request origin using registered origin parser.
            String origin = parseOrigin(request);
            String contextName = getContextName(request);
            ContextUtil.enter(contextName, origin);
            Entry entry = SphU.entry(resourceName, ResourceTypeConstants.COMMON_WEB, EntryType.IN);

            setEntryInRequest(request, baseWebMvcConfig.getRequestAttributeName(), entry);
        }
        return true;
    } catch (BlockException e) {
        try {
            handleBlockException(request, response, e);
        } finally {
            ContextUtil.exit();
        }
        return false;
    }
}
 
Example #5
Source File: AsyncEntryDemo.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
private void directlyAsync() {
    try {
        final AsyncEntry entry = SphU.asyncEntry("test-async-not-nested");

        this.invoke("abc", result -> {
            // If no nested entry later, we don't have to wrap in `ContextUtil.runOnContext()`.
            try {
                // Here to handle the async result (without other entry).
            } finally {
                // Exit the async entry.
                entry.exit();
            }
        });
    } catch (BlockException e) {
        // Request blocked, handle the exception.
        e.printStackTrace();
    }
}
 
Example #6
Source File: SentinelProtectInterceptor.java    From spring-cloud-alibaba with Apache License 2.0 6 votes vote down vote up
private ClientHttpResponse handleBlockException(HttpRequest request, byte[] body,
		ClientHttpRequestExecution execution, BlockException ex) {
	Object[] args = new Object[] { request, body, execution, ex };
	// handle degrade
	if (isDegradeFailure(ex)) {
		Method fallbackMethod = extractFallbackMethod(sentinelRestTemplate.fallback(),
				sentinelRestTemplate.fallbackClass());
		if (fallbackMethod != null) {
			return (ClientHttpResponse) methodInvoke(fallbackMethod, args);
		}
		else {
			return new SentinelClientHttpResponse();
		}
	}
	// handle flow
	Method blockHandler = extractBlockHandlerMethod(
			sentinelRestTemplate.blockHandler(),
			sentinelRestTemplate.blockHandlerClass());
	if (blockHandler != null) {
		return (ClientHttpResponse) methodInvoke(blockHandler, args);
	}
	else {
		return new SentinelClientHttpResponse();
	}
}
 
Example #7
Source File: FluxSentinelOperatorTestIntegrationTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Test
public void testEmitMultipleValuesWhenFlowControlTriggered() {
    String resourceName = createResourceName("testEmitMultipleValuesWhenFlowControlTriggered");
    FlowRuleManager.loadRules(Collections.singletonList(
        new FlowRule(resourceName).setCount(0)
    ));
    StepVerifier.create(Flux.just(1, 3, 5)
        .map(e -> e * 2)
        .transform(new SentinelReactorTransformer<>(resourceName)))
        .expectError(BlockException.class)
        .verify();

    ClusterNode cn = ClusterBuilderSlot.getClusterNode(resourceName);
    assertNotNull(cn);
    assertEquals(0, cn.passQps(), 0.01);
    assertEquals(1, cn.blockRequest());

    FlowRuleManager.loadRules(new ArrayList<>());
}
 
Example #8
Source File: AbstractSentinelAspectSupport.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
protected Object handleBlockException(ProceedingJoinPoint pjp, SentinelResource annotation, BlockException ex)
    throws Throwable {

    // Execute block handler if configured.
    Method blockHandlerMethod = extractBlockHandlerMethod(pjp, annotation.blockHandler(),
        annotation.blockHandlerClass());
    if (blockHandlerMethod != null) {
        Object[] originArgs = pjp.getArgs();
        // Construct args.
        Object[] args = Arrays.copyOf(originArgs, originArgs.length + 1);
        args[args.length - 1] = ex;
        try {
            if (isStatic(blockHandlerMethod)) {
                return blockHandlerMethod.invoke(null, args);
            }
            return blockHandlerMethod.invoke(pjp.getTarget(), args);
        } catch (InvocationTargetException e) {
            // throw the actual exception
            throw e.getTargetException();
        }
    }

    // If no block handler is present, then go to fallback.
    return handleFallback(pjp, annotation, ex);
}
 
Example #9
Source File: AsyncEntryDemo.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
private void anotherAsync() {
    try {
        final AsyncEntry entry = SphU.asyncEntry("test-another-async");

        CompletableFuture.runAsync(() -> {
            ContextUtil.runOnContext(entry.getAsyncContext(), () -> {
                try {
                    TimeUnit.SECONDS.sleep(2);
                    // Normal entry nested in asynchronous entry.
                    anotherSyncInAsync();

                    System.out.println("Async result: 666");
                } catch (InterruptedException e) {
                    // Ignore.
                } finally {
                    entry.exit();
                }
            });
        });
    } catch (BlockException ex) {
        ex.printStackTrace();
    }
}
 
Example #10
Source File: GatewayFlowSlot.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
private void checkGatewayParamFlow(ResourceWrapper resourceWrapper, int count, Object... args)
    throws BlockException {
    if (args == null) {
        return;
    }

    List<ParamFlowRule> rules = GatewayRuleManager.getConvertedParamRules(resourceWrapper.getName());
    if (rules == null || rules.isEmpty()) {
        return;
    }

    for (ParamFlowRule rule : rules) {
        // Initialize the parameter metrics.
        ParameterMetricStorage.initParamMetricsFor(resourceWrapper, rule);

        if (!ParamFlowChecker.passCheck(resourceWrapper, rule, count, args)) {
            String triggeredParam = "";
            if (args.length > rule.getParamIdx()) {
                Object value = args[rule.getParamIdx()];
                triggeredParam = String.valueOf(value);
            }
            throw new ParamFlowException(resourceWrapper.getName(), triggeredParam, rule);
        }
    }
}
 
Example #11
Source File: SystemRuleManagerTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Test
public void testCheckMaxCpuUsageNotBBR() throws Exception {
    SystemRule rule1 = new SystemRule();
    rule1.setHighestCpuUsage(0d);
    SystemRuleManager.loadRules(Collections.singletonList(rule1));

    // Wait until SystemStatusListener triggered the first CPU usage collecting.
    Thread.sleep(1500);

    boolean blocked = false;
    try {
        SystemRuleManager.checkSystem(new StringResourceWrapper("testCheckMaxCpuUsageNotBBR", EntryType.IN));
    } catch (BlockException ex) {
        blocked = true;
    }
    assertTrue("The entry should be blocked under SystemRule maxCpuUsage=0", blocked);
}
 
Example #12
Source File: FlowPartialIntegrationTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Test
public void testFlowRule_other() {

    FlowRule flowRule = new FlowRule();
    flowRule.setResource("testOther");
    flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
    flowRule.setCount(0);
    flowRule.setLimitApp("other");
    FlowRuleManager.loadRules(Arrays.asList(flowRule));

    Entry e = null;
    try {
        e = SphU.entry("testOther");
    } catch (BlockException e1) {
        e1.printStackTrace();fail("Should had failed");
    }

    if (e != null) {
        e.exit();
    } else {
        fail("Should had failed");
    }
}
 
Example #13
Source File: FlowPartialIntegrationTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Test
public void testFlowRule_other() {

    FlowRule flowRule = new FlowRule();
    flowRule.setResource("testOther");
    flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
    flowRule.setCount(0);
    flowRule.setLimitApp("other");
    FlowRuleManager.loadRules(Arrays.asList(flowRule));

    Entry e = null;
    try {
        e = SphU.entry("testOther");
    } catch (BlockException e1) {
        e1.printStackTrace();fail("Should had failed");
    }

    if (e != null) {
        e.exit();
    } else {
        fail("Should had failed");
    }
}
 
Example #14
Source File: DefaultSofaRpcFallbackTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Test
public void testHandle() {
    SofaRpcFallback sofaRpcFallback = new DefaultSofaRpcFallback();
    BlockException blockException = mock(BlockException.class);

    boolean throwSentinelRpcException = false;
    boolean causeIsBlockException = false;
    try {
        sofaRpcFallback.handle(null, null, blockException);
    } catch (Exception e) {
        throwSentinelRpcException = e instanceof SentinelRpcException;
        causeIsBlockException = e.getCause() instanceof BlockException;
    }
    assertTrue(throwSentinelRpcException);
    assertTrue(causeIsBlockException);
}
 
Example #15
Source File: AbstractSentinelProccesser.java    From jboot with Apache License 2.0 6 votes vote down vote up
protected Object handleBlockException(Invocation inv, SentinelResource annotation, BlockException ex)
        throws Throwable {

    // Execute block handler if configured.
    Method blockHandlerMethod = extractBlockHandlerMethod(inv, annotation.blockHandler(),
            annotation.blockHandlerClass());
    if (blockHandlerMethod != null) {
        Object[] originArgs = inv.getArgs();
        // Construct args.
        Object[] args = Arrays.copyOf(originArgs, originArgs.length + 1);
        args[args.length - 1] = ex;
        try {
            if (isStatic(blockHandlerMethod)) {
                return blockHandlerMethod.invoke(null, args);
            }
            return blockHandlerMethod.invoke(inv.getTarget(), args);
        } catch (InvocationTargetException e) {
            // throw the actual exception
            throw e.getTargetException();
        }
    }

    // If no block handler is present, then go to fallback.
    return handleFallback(inv, annotation, ex);
}
 
Example #16
Source File: AsyncEntryDemo.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    initFlowRule();

    AsyncEntryDemo service = new AsyncEntryDemo();

    // Expected invocation chain:
    //
    // EntranceNode: machine-root
    // -EntranceNode: async-context
    // --test-top
    // ---test-sync
    // ---test-async
    // ----test-another-async
    // -----test-another-sync-in-async
    // ----test-sync-in-async
    ContextUtil.enter("async-context", "originA");
    Entry entry = null;
    try {
        entry = SphU.entry("test-top");
        System.out.println("Do something...");
        service.doAsyncThenSync();
    } catch (BlockException ex) {
        // Request blocked, handle the exception.
        ex.printStackTrace();
    } finally {
        if (entry != null) {
            entry.exit();
        }
        ContextUtil.exit();
    }

    TimeUnit.SECONDS.sleep(20);
}
 
Example #17
Source File: ExceptionUtil.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
public static void handleException(BlockException ex) {
    // Handler method that handles BlockException when blocked.
    // The method parameter list should match original method, with the last additional
    // parameter with type BlockException. The return type should be same as the original method.
    // The block handler method should be located in the same class with original method by default.
    // If you want to use method in other classes, you can set the blockHandlerClass
    // with corresponding Class (Note the method in other classes must be static).
    System.out.println("Oops: " + ex.getClass().getCanonicalName());
}
 
Example #18
Source File: DegradeRuleManager.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
public static void checkDegrade(ResourceWrapper resource, Context context, DefaultNode node, int count)
    throws BlockException {

    Set<DegradeRule> rules = degradeRules.get(resource.getName());
    if (rules == null) {
        return;
    }

    for (DegradeRule rule : rules) {
        if (!rule.passCheck(context, node, count)) {
            throw new DegradeException(rule.getLimitApp(), rule);
        }
    }
}
 
Example #19
Source File: FlowQpsRunner.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    while (!stop) {
        Entry entry = null;

        try {
            entry = SphU.entry(KEY);
            // token acquired, means pass
            pass.addAndGet(1);
        } catch (BlockException e1) {
            block.incrementAndGet();
        } catch (Exception e2) {
            // biz exception
        } finally {
            total.incrementAndGet();
            if (entry != null) {
                entry.exit();
            }
        }

        Random random2 = new Random();
        try {
            TimeUnit.MILLISECONDS.sleep(random2.nextInt(50));
        } catch (InterruptedException e) {
            // ignore
        }
    }
}
 
Example #20
Source File: SentinelGrpcServerInterceptor.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@Override
public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> serverCall, Metadata metadata,
                                                  ServerCallHandler<ReqT, RespT> serverCallHandler) {
    String resourceName = serverCall.getMethodDescriptor().getFullMethodName();
    // Remote address: serverCall.getAttributes().get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR);
    Entry entry = null;
    try {
        ContextUtil.enter(resourceName);
        entry = SphU.entry(resourceName, EntryType.IN);
        // Allow access, forward the call.
        return new ForwardingServerCallListener.SimpleForwardingServerCallListener<ReqT>(
            serverCallHandler.startCall(
                new ForwardingServerCall.SimpleForwardingServerCall<ReqT, RespT>(serverCall) {
                    @Override
                    public void close(Status status, Metadata trailers) {
                        super.close(status, trailers);
                        // Record the exception metrics.
                        if (!status.isOk()) {
                            recordException(status.asRuntimeException());
                        }
                    }
                }, metadata)) {};
    } catch (BlockException e) {
        serverCall.close(FLOW_CONTROL_BLOCK, new Metadata());
        return new ServerCall.Listener<ReqT>() {};
    } finally {
        if (entry != null) {
            entry.exit();
        }
        ContextUtil.exit();
    }
}
 
Example #21
Source File: AsyncEntryDemo.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
private void fetchSync() {
    Entry entry = null;
    try {
        entry = SphU.entry("test-sync");
    } catch (BlockException ex) {
        ex.printStackTrace();
    } finally {
        if (entry != null) {
            entry.exit();
        }
    }
}
 
Example #22
Source File: SphUTest.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Test
public void testMethodEntryAll() throws BlockException, NoSuchMethodException, SecurityException {
    final String arg0 = "foo";
    final String arg1 = "baz";
    Method method = SphUTest.class.getMethod("testMethodEntryNormal");
    Entry e = SphU.entry(method, EntryType.IN, 2, arg0, arg1);

    assertSame(e.resourceWrapper.getEntryType(), EntryType.IN);

    e.exit(2, arg0, arg1);
}
 
Example #23
Source File: AuthorityDemo.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
private static void testFor(/*@NonNull*/ String resource, /*@NonNull*/ String origin) {
    ContextUtil.enter(resource, origin);
    Entry entry = null;
    try {
        entry = SphU.entry(resource);
        System.out.println(String.format("Passed for resource %s, origin is %s", resource, origin));
    } catch (BlockException ex) {
        System.err.println(String.format("Blocked for resource %s, origin is %s", resource, origin));
    } finally {
        if (entry != null) {
            entry.exit();
        }
        ContextUtil.exit();
    }
}
 
Example #24
Source File: SentinelBlockExceptionHandler.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
    if (exchange.getResponse().isCommitted()) {
        return Mono.error(ex);
    }
    // This exception handler only handles rejection by Sentinel.
    if (!BlockException.isBlockException(ex)) {
        return Mono.error(ex);
    }
    return handleBlockedRequest(exchange, ex)
        .flatMap(response -> writeResponse(response, exchange));
}
 
Example #25
Source File: SphUTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@Test
public void testMethodEntryAll() throws BlockException, NoSuchMethodException, SecurityException {
    final String arg0 = "foo";
    final String arg1 = "baz";
    Method method = SphUTest.class.getMethod("testMethodEntryNormal");
    Entry e = SphU.entry(method, EntryType.IN, 2, arg0, arg1);

    assertSame(e.resourceWrapper.getType(), EntryType.IN);

    e.exit(2, arg0, arg1);
}
 
Example #26
Source File: DubboFallbackRegistryTest.java    From dubbo-sentinel-support with Apache License 2.0 5 votes vote down vote up
@Test
public void testCustomFallback() {
    BlockException ex = new FlowException("xxx");
    DubboFallbackRegistry.setConsumerFallback(
        (invoker, invocation, e) -> new RpcResult("Error: " + e.getClass().getName()));
    Result result = DubboFallbackRegistry.getConsumerFallback()
        .handle(null, null, ex);
    Assert.assertFalse("The invocation should not fail", result.hasException());
    Assert.assertEquals("Error: " + ex.getClass().getName(), result.getValue());
}
 
Example #27
Source File: DemoController.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@RequestMapping("/slow")
@ResponseBody
public String slow(String name, int time) throws BlockException {
    for (int i = 0; i < 10; i++) {
        Thread timer = new Thread(new RunTask(name, time, true));
        timer.setName("false");
        timer.start();
    }
    return "successfully create a loop thread";
}
 
Example #28
Source File: ReactorSphU.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
public static <R> Mono<R> entryWith(String resourceName, EntryType entryType, Mono<R> actual) {
    final AtomicReference<AsyncEntry> entryWrapper = new AtomicReference<>(null);
    return Mono.defer(() -> {
        try {
            AsyncEntry entry = SphU.asyncEntry(resourceName, entryType);
            entryWrapper.set(entry);
            return actual.subscriberContext(context -> {
                if (entry == null) {
                    return context;
                }
                Context sentinelContext = entry.getAsyncContext();
                if (sentinelContext == null) {
                    return context;
                }
                // TODO: check GC friendly?
                return context.put(SentinelReactorConstants.SENTINEL_CONTEXT_KEY, sentinelContext);
            }).doOnSuccessOrError((o, t) -> {
                if (entry != null && entryWrapper.compareAndSet(entry, null)) {
                    if (t != null) {
                        Tracer.traceContext(t, 1, entry.getAsyncContext());
                    }
                    entry.exit();
                }
            });
        } catch (BlockException ex) {
            return Mono.error(ex);
        }
    });
}
 
Example #29
Source File: SphUTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@Test
public void testStringEntryType() throws BlockException {
    Entry e = SphU.entry("resourceName", EntryType.IN);

    assertSame(e.resourceWrapper.getType(), EntryType.IN);

    e.exit();
}
 
Example #30
Source File: DemoController.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@RequestMapping("/slow")
@ResponseBody
public String slow(String name, int time) throws BlockException {
    for (int i = 0; i < 10; i++) {
        Thread timer = new Thread(new RunTask(name, time, true));
        timer.setName("false");
        timer.start();
    }
    return "successfully create a loop thread";
}