Java Code Examples for com.alibaba.csp.sentinel.context.ContextUtil#exit()

The following examples show how to use com.alibaba.csp.sentinel.context.ContextUtil#exit() . 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: SentinelReactorSubscriber.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
private void entryWhenSubscribed() {
    ContextConfig sentinelContextConfig = entryConfig.getContextConfig();
    if (sentinelContextConfig != null) {
        // If current we're already in a context, the context config won't work.
        ContextUtil.enter(sentinelContextConfig.getContextName(), sentinelContextConfig.getOrigin());
    }
    try {
        AsyncEntry entry = SphU.asyncEntry(entryConfig.getResourceName(), entryConfig.getResourceType(),
            entryConfig.getEntryType(), entryConfig.getAcquireCount(), entryConfig.getArgs());
        this.currentEntry = entry;
        actual.onSubscribe(this);
    } catch (BlockException ex) {
        // Mark as completed (exited) explicitly.
        entryExited.set(true);
        // Signal cancel and propagate the {@code BlockException}.
        cancel();
        actual.onSubscribe(this);
        actual.onError(ex);
    } finally {
        if (sentinelContextConfig != null) {
            ContextUtil.exit();
        }
    }
}
 
Example 2
Source File: AuthoritySlotTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Test(expected = AuthorityException.class)
public void testCheckAuthorityNoExceptionItemsBlackFail() throws Exception {
    String origin = "appA";
    String resourceName = "testCheckAuthorityNoExceptionItemsBlackFail";
    ResourceWrapper resourceWrapper = new StringResourceWrapper(resourceName, EntryType.IN);
    ContextUtil.enter("entrance", origin);
    try {
        AuthorityRule ruleA = new AuthorityRule()
            .setResource(resourceName)
            .setLimitApp(origin + ",appC")
            .as(AuthorityRule.class)
            .setStrategy(RuleConstant.AUTHORITY_BLACK);

        AuthorityRuleManager.loadRules(Collections.singletonList(ruleA));
        authoritySlot.checkBlackWhiteAuthority(resourceWrapper, ContextUtil.getContext());
    } finally {
        ContextUtil.exit();
    }
}
 
Example 3
Source File: BaseTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
/**
 * Clean up resources.
 */
protected static void cleanUpAll() {
    Context context = ContextUtil.getContext();
    if (context != null) {
        context.setCurEntry(null);
        ContextUtil.exit();
    }

    Constants.ROOT.removeChildList();

    ClusterBuilderSlot.getClusterNodeMap().clear();

    // Clear chainMap in CtSph
    try {
        Method resetChainMapMethod = CtSph.class.getDeclaredMethod("resetChainMap");
        resetChainMapMethod.setAccessible(true);
        resetChainMapMethod.invoke(null);
    } catch (Exception e) {
        // Empty
    }
}
 
Example 4
Source File: ClusterNodeBuilderTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@Test
public void clusterNodeBuilder_normal() throws Exception {
    ContextUtil.enter("entry1", "caller1");

    Entry nodeA = SphU.entry("nodeA");

    Node curNode = nodeA.getCurNode();
    assertSame(curNode.getClass(), DefaultNode.class);
    DefaultNode dN = (DefaultNode)curNode;
    assertTrue(dN.getClusterNode().getOriginCountMap().containsKey("caller1"));
    assertSame(nodeA.getOriginNode(), dN.getClusterNode().getOrCreateOriginNode("caller1"));

    if (nodeA != null) {
        nodeA.exit();
    }
    ContextUtil.exit();

    ContextUtil.enter("entry4", "caller2");

    nodeA = SphU.entry("nodeA");

    curNode = nodeA.getCurNode();
    assertSame(curNode.getClass(), DefaultNode.class);
    DefaultNode dN1 = (DefaultNode)curNode;
    assertTrue(dN1.getClusterNode().getOriginCountMap().containsKey("caller2"));
    assertNotSame(dN1, dN);

    if (nodeA != null) {
        nodeA.exit();
    }
    ContextUtil.exit();
}
 
Example 5
Source File: SentinelSofaRpcProviderFilter.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Override
public SofaResponse invoke(FilterInvoker invoker, SofaRequest request) throws SofaRpcException {
    // Now only support sync invoke.
    if (request.getInvokeType() != null && !RpcConstants.INVOKER_TYPE_SYNC.equals(request.getInvokeType())) {
        return invoker.invoke(request);
    }

    String callerApp = getApplicationName(request);
    String interfaceResourceName = getInterfaceResourceName(request);
    String methodResourceName = getMethodResourceName(request);

    Entry interfaceEntry = null;
    Entry methodEntry = null;
    try {
        ContextUtil.enter(methodResourceName, callerApp);

        interfaceEntry = SphU.entry(interfaceResourceName, ResourceTypeConstants.COMMON_RPC, EntryType.IN);
        methodEntry = SphU.entry(methodResourceName, ResourceTypeConstants.COMMON_RPC,
            EntryType.IN, getMethodArguments(request));

        SofaResponse response = invoker.invoke(request);

        traceResponseException(response, interfaceEntry, methodEntry);
        return response;
    } catch (BlockException e) {
        return SofaRpcFallbackRegistry.getProviderFallback().handle(invoker, request, e);
    } catch (Throwable t) {
        throw traceOtherException(t, interfaceEntry, methodEntry);
    } finally {
        if (methodEntry != null) {
            methodEntry.exit(1, getMethodArguments(request));
        }
        if (interfaceEntry != null) {
            interfaceEntry.exit();
        }
        ContextUtil.exit();
    }
}
 
Example 6
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 7
Source File: NodeSelectorTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
public void testMultipleLayer() throws Exception {
    // TODO: fix this
    ContextUtil.enter("entry1", "appA");

    Entry nodeA = SphU.entry("nodeA");
    assertSame(ContextUtil.getContext().getCurEntry(), nodeA);

    DefaultNode dnA = (DefaultNode)nodeA.getCurNode();
    assertNotNull(dnA);
    assertSame("nodeA", dnA.getId().getName());

    Entry nodeB = SphU.entry("nodeB");
    assertSame(ContextUtil.getContext().getCurEntry(), nodeB);
    DefaultNode dnB = (DefaultNode)nodeB.getCurNode();
    assertNotNull(dnB);
    assertTrue(dnA.getChildList().contains(dnB));

    Entry nodeC = SphU.entry("nodeC");
    assertSame(ContextUtil.getContext().getCurEntry(), nodeC);
    DefaultNode dnC = (DefaultNode)nodeC.getCurNode();
    assertNotNull(dnC);
    assertTrue(dnB.getChildList().contains(dnC));

    if (nodeC != null) {
        nodeC.exit();
    }
    assertSame(ContextUtil.getContext().getCurEntry(), nodeB);

    if (nodeB != null) {
        nodeB.exit();
    }
    assertSame(ContextUtil.getContext().getCurEntry(), nodeA);

    if (nodeA != null) {
        nodeA.exit();
    }
    assertNull(ContextUtil.getContext().getCurEntry());
    ContextUtil.exit();

}
 
Example 8
Source File: AuthorityRuleCheckerTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@Test
public void testPassCheck() {
    String origin = "appA";
    ContextUtil.enter("entrance", origin);
    try {
        String resourceName = "testPassCheck";
        AuthorityRule ruleA = new AuthorityRule()
            .setResource(resourceName)
            .setLimitApp(origin + ",appB")
            .as(AuthorityRule.class)
            .setStrategy(RuleConstant.AUTHORITY_WHITE);
        AuthorityRule ruleB = new AuthorityRule()
            .setResource(resourceName)
            .setLimitApp("appB")
            .as(AuthorityRule.class)
            .setStrategy(RuleConstant.AUTHORITY_WHITE);
        AuthorityRule ruleC = new AuthorityRule()
            .setResource(resourceName)
            .setLimitApp(origin)
            .as(AuthorityRule.class)
            .setStrategy(RuleConstant.AUTHORITY_BLACK);
        AuthorityRule ruleD = new AuthorityRule()
            .setResource(resourceName)
            .setLimitApp("appC")
            .as(AuthorityRule.class)
            .setStrategy(RuleConstant.AUTHORITY_BLACK);

        assertTrue(AuthorityRuleChecker.passCheck(ruleA, ContextUtil.getContext()));
        assertFalse(AuthorityRuleChecker.passCheck(ruleB, ContextUtil.getContext()));
        assertFalse(AuthorityRuleChecker.passCheck(ruleC, ContextUtil.getContext()));
        assertTrue(AuthorityRuleChecker.passCheck(ruleD, ContextUtil.getContext()));
    } finally {
        ContextUtil.exit();
    }
}
 
Example 9
Source File: CtEntry.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
protected void exitForContext(Context context, int count, Object... args) throws ErrorEntryFreeException {
    if (context != null) {
        // Null context should exit without clean-up.
        if (context instanceof NullContext) {
            return;
        }
        if (context.getCurEntry() != this) {
            String curEntryNameInContext = context.getCurEntry() == null ? null : context.getCurEntry().getResourceWrapper().getName();
            // Clean previous call stack.
            CtEntry e = (CtEntry)context.getCurEntry();
            while (e != null) {
                e.exit(count, args);
                e = (CtEntry)e.parent;
            }
            String errorMessage = String.format("The order of entry exit can't be paired with the order of entry"
                + ", current entry in context: <%s>, but expected: <%s>", curEntryNameInContext, resourceWrapper.getName());
            throw new ErrorEntryFreeException(errorMessage);
        } else {
            if (chain != null) {
                chain.exit(context, resourceWrapper, count, args);
            }
            // Restore the call stack.
            context.setCurEntry(parent);
            if (parent != null) {
                ((CtEntry)parent).child = null;
            }
            if (parent == null) {
                // Default context (auto entered) will be exited automatically.
                if (ContextUtil.isDefaultContext(context)) {
                    ContextUtil.exit();
                }
            }
            // Clean the reference of context in current entry to avoid duplicate exit.
            clearEntryContext();
        }
    }
}
 
Example 10
Source File: SentinelZuulInboundFilter.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
private Observable<HttpRequestMessage> apply(HttpRequestMessage request) {
    SessionContext context = request.getContext();
    Deque<EntryHolder> holders = new ArrayDeque<>();
    String routeId = routeExtractor.apply(request);
    String fallBackRoute = routeId;
    try {
        if (StringUtil.isNotBlank(routeId)) {
            ContextUtil.enter(GATEWAY_CONTEXT_ROUTE_PREFIX + routeId);
            doSentinelEntry(routeId, RESOURCE_MODE_ROUTE_ID, request, holders);
        }
        Set<String> matchingApis = pickMatchingApiDefinitions(request);
        if (!matchingApis.isEmpty() && ContextUtil.getContext() == null) {
            ContextUtil.enter(SentinelZuul2Constants.ZUUL_DEFAULT_CONTEXT);
        }
        for (String apiName : matchingApis) {
            fallBackRoute = apiName;
            doSentinelEntry(apiName, RESOURCE_MODE_CUSTOM_API_NAME, request, holders);
        }
        return Observable.just(request);
    } catch (BlockException t) {
        context.put(SentinelZuul2Constants.ZUUL_CTX_SENTINEL_BLOCKED_FLAG, Boolean.TRUE);
        context.put(SentinelZuul2Constants.ZUUL_CTX_SENTINEL_FALLBACK_ROUTE, fallBackRoute);
        if (fastError) {
            context.setShouldSendErrorResponse(true);
            context.setErrorEndpoint(blockedEndpointName);
        } else {
            context.setEndpoint(blockedEndpointName);
        }
        return Observable.error(t);
    } finally {
        if (!holders.isEmpty()) {
            context.put(SentinelZuul2Constants.ZUUL_CTX_SENTINEL_ENTRIES_KEY, holders);
        }
        // clear context to avoid another request use incorrect context
        ContextUtil.exit();
    }
}
 
Example 11
Source File: AbstractSentinelInterceptor.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                            Object handler, Exception ex) throws Exception {
    Entry entry = getEntryInRequest(request, baseWebMvcConfig.getRequestAttributeName());
    if (entry != null) {
        traceExceptionAndExit(entry, ex);
        removeEntryInRequest(request);
    }
    ContextUtil.exit();
}
 
Example 12
Source File: AuthorityDemo.java    From Sentinel-Dashboard-Nacos 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 13
Source File: SentinelJaxRsProviderFilter.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext containerRequestContext, ContainerResponseContext containerResponseContext) throws IOException {
    Entry entry = (Entry) containerRequestContext.getProperty(SENTINEL_JAX_RS_PROVIDER_ENTRY_PROPERTY);
    if (entry != null) {
        entry.exit();
    }
    containerRequestContext.removeProperty(SENTINEL_JAX_RS_PROVIDER_ENTRY_PROPERTY);
    ContextUtil.exit();
}
 
Example 14
Source File: CtEntry.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
protected void exitForContext(Context context, int count, Object... args) throws ErrorEntryFreeException {
    if (context != null) {
        // Null context should exit without clean-up.
        if (context instanceof NullContext) {
            return;
        }
        if (context.getCurEntry() != this) {
            String curEntryNameInContext = context.getCurEntry() == null ? null : context.getCurEntry().getResourceWrapper().getName();
            // Clean previous call stack.
            CtEntry e = (CtEntry)context.getCurEntry();
            while (e != null) {
                e.exit(count, args);
                e = (CtEntry)e.parent;
            }
            String errorMessage = String.format("The order of entry exit can't be paired with the order of entry"
                + ", current entry in context: <%s>, but expected: <%s>", curEntryNameInContext, resourceWrapper.getName());
            throw new ErrorEntryFreeException(errorMessage);
        } else {
            if (chain != null) {
                chain.exit(context, resourceWrapper, count, args);
            }
            // Restore the call stack.
            context.setCurEntry(parent);
            if (parent != null) {
                ((CtEntry)parent).child = null;
            }
            if (parent == null) {
                // Default context (auto entered) will be exited automatically.
                if (ContextUtil.isDefaultContext(context)) {
                    ContextUtil.exit();
                }
            }
            // Clean the reference of context in current entry to avoid duplicate exit.
            clearEntryContext();
        }
    }
}
 
Example 15
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 16
Source File: CtEntryTest.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Test
public void testExitNotMatchCurEntry() {
    String contextName = "context-rpc";
    ContextUtil.enter(contextName);
    Context context = ContextUtil.getContext();
    CtEntry entry1 = null;
    CtEntry entry2 = null;
    try {
        entry1 = new CtEntry(new StringResourceWrapper("res1", EntryType.IN),
            null, ContextUtil.getContext());
        assertSame(entry1, context.getCurEntry());
        entry2 = new CtEntry(new StringResourceWrapper("res2", EntryType.IN),
            null, ContextUtil.getContext());
        assertSame(entry2, context.getCurEntry());

        // Forget to exit for entry 2...
        // Directly exit for entry 1, then boom...
        entry1.exit();
    } catch (ErrorEntryFreeException ex) {
        assertNotNull(entry1);
        assertNotNull(entry2);
        assertNull(entry1.context);
        assertNull(entry2.context);
        assertNull(context.getCurEntry());
        return;
    } finally {
        ContextUtil.exit();
    }
    fail("Mismatch entry-exit should throw an ErrorEntryFreeException");
}
 
Example 17
Source File: NodeSelectorTest.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
public void testMultipleLayer() throws Exception {
    // TODO: fix this
    ContextUtil.enter("entry1", "appA");

    Entry nodeA = SphU.entry("nodeA");
    assertSame(ContextUtil.getContext().getCurEntry(), nodeA);

    DefaultNode dnA = (DefaultNode)nodeA.getCurNode();
    assertNotNull(dnA);
    assertSame("nodeA", dnA.getId().getName());

    Entry nodeB = SphU.entry("nodeB");
    assertSame(ContextUtil.getContext().getCurEntry(), nodeB);
    DefaultNode dnB = (DefaultNode)nodeB.getCurNode();
    assertNotNull(dnB);
    assertTrue(dnA.getChildList().contains(dnB));

    Entry nodeC = SphU.entry("nodeC");
    assertSame(ContextUtil.getContext().getCurEntry(), nodeC);
    DefaultNode dnC = (DefaultNode)nodeC.getCurNode();
    assertNotNull(dnC);
    assertTrue(dnB.getChildList().contains(dnC));

    if (nodeC != null) {
        nodeC.exit();
    }
    assertSame(ContextUtil.getContext().getCurEntry(), nodeB);

    if (nodeB != null) {
        nodeB.exit();
    }
    assertSame(ContextUtil.getContext().getCurEntry(), nodeA);

    if (nodeA != null) {
        nodeA.exit();
    }
    assertNull(ContextUtil.getContext().getCurEntry());
    ContextUtil.exit();

}
 
Example 18
Source File: AuthorityRuleCheckerTest.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Test
public void testPassCheck() {
    String origin = "appA";
    ContextUtil.enter("entrance", origin);
    try {
        String resourceName = "testPassCheck";
        AuthorityRule ruleA = new AuthorityRule()
            .setResource(resourceName)
            .setLimitApp(origin + ",appB")
            .as(AuthorityRule.class)
            .setStrategy(RuleConstant.AUTHORITY_WHITE);
        AuthorityRule ruleB = new AuthorityRule()
            .setResource(resourceName)
            .setLimitApp("appB")
            .as(AuthorityRule.class)
            .setStrategy(RuleConstant.AUTHORITY_WHITE);
        AuthorityRule ruleC = new AuthorityRule()
            .setResource(resourceName)
            .setLimitApp(origin)
            .as(AuthorityRule.class)
            .setStrategy(RuleConstant.AUTHORITY_BLACK);
        AuthorityRule ruleD = new AuthorityRule()
            .setResource(resourceName)
            .setLimitApp("appC")
            .as(AuthorityRule.class)
            .setStrategy(RuleConstant.AUTHORITY_BLACK);

        assertTrue(AuthorityRuleChecker.passCheck(ruleA, ContextUtil.getContext()));
        assertFalse(AuthorityRuleChecker.passCheck(ruleB, ContextUtil.getContext()));
        assertFalse(AuthorityRuleChecker.passCheck(ruleC, ContextUtil.getContext()));
        assertTrue(AuthorityRuleChecker.passCheck(ruleD, ContextUtil.getContext()));
    } finally {
        ContextUtil.exit();
    }
}
 
Example 19
Source File: SentinelEntryUtils.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
static void tryTraceExceptionThenExitFromCurrentContext(Throwable t) {
    RequestContext ctx = RequestContext.getCurrentContext();
    if (ctx.containsKey(ZuulConstant.ZUUL_CTX_SENTINEL_ENTRIES_KEY)) {
        Deque<EntryHolder> holders = (Deque<EntryHolder>) ctx.get(ZuulConstant.ZUUL_CTX_SENTINEL_ENTRIES_KEY);
        EntryHolder holder;
        while (!holders.isEmpty()) {
            holder = holders.pop();
            Tracer.traceEntry(t, holder.getEntry());
            exit(holder);
        }
        ctx.remove(ZuulConstant.ZUUL_CTX_SENTINEL_ENTRIES_KEY);
    }
    ContextUtil.exit();
}
 
Example 20
Source File: CtSphTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 4 votes vote down vote up
private void fillFullContext() {
    for (int i = 0; i < Constants.MAX_CONTEXT_NAME_SIZE; i++) {
        ContextUtil.enter("test-context-" + i);
        ContextUtil.exit();
    }
}