com.alibaba.csp.sentinel.Tracer Java Examples

The following examples show how to use com.alibaba.csp.sentinel.Tracer. 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: SentinelZuulOutboundFilter.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
public HttpResponseMessage apply(HttpResponseMessage response) {
    SessionContext context = response.getContext();

    if (context.get(SentinelZuul2Constants.ZUUL_CTX_SENTINEL_ENTRIES_KEY) == null) {
        return response;
    }
    boolean previousBlocked = context.getFilterErrors().stream()
        .anyMatch(e -> BlockException.isBlockException(e.getException()));
    Deque<EntryHolder> holders = (Deque<EntryHolder>) context.get(SentinelZuul2Constants.ZUUL_CTX_SENTINEL_ENTRIES_KEY);
    while (!holders.isEmpty()) {
        EntryHolder holder = holders.pop();
        if (!previousBlocked) {
            Tracer.traceEntry(context.getError(), holder.getEntry());
            holder.getEntry().exit(1, holder.getParams());
        }
    }
    return response;
}
 
Example #2
Source File: CommonTotalFilter.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response,
                     FilterChain chain) throws IOException, ServletException {
    HttpServletRequest sRequest = (HttpServletRequest)request;

    Entry entry = null;
    try {
        ContextUtil.enter(WebServletConfig.WEB_SERVLET_CONTEXT_NAME);
        entry = SphU.entry(TOTAL_URL_REQUEST, ResourceTypeConstants.COMMON_WEB);
        chain.doFilter(request, response);
    } catch (BlockException e) {
        HttpServletResponse sResponse = (HttpServletResponse)response;
        WebCallbackManager.getUrlBlockHandler().blocked(sRequest, sResponse, e);
    } catch (IOException | ServletException | RuntimeException e2) {
        Tracer.trace(e2);
        throw e2;
    } finally {
        if (entry != null) {
            entry.exit();
        }
        ContextUtil.exit();
    }
}
 
Example #3
Source File: SentinelEntryUtils.java    From Sentinel-Dashboard-Nacos 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<AsyncEntry> asyncEntries = (Deque<AsyncEntry>) ctx.get(ZuulConstant.ZUUL_CTX_SENTINEL_ENTRIES_KEY);
        AsyncEntry entry;
        while (!asyncEntries.isEmpty()) {
            entry = asyncEntries.pop();
            Tracer.traceEntry(t, entry);
            entry.exit();
        }
        ctx.remove(ZuulConstant.ZUUL_CTX_SENTINEL_ENTRIES_KEY);
    }
    ContextUtil.exit();
}
 
Example #4
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 #5
Source File: SentinelReactorSubscriber.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@Override
protected void hookOnError(Throwable t) {
    if (currentEntry != null && currentEntry.getAsyncContext() != null) {
        // Normal requests with non-BlockException will go through here.
        Tracer.traceContext(t, 1, currentEntry.getAsyncContext());
    }
    tryCompleteEntry();
    actual.onError(t);
}
 
Example #6
Source File: CommonTotalFilter.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response,
                     FilterChain chain) throws IOException, ServletException {
    HttpServletRequest sRequest = (HttpServletRequest)request;
    String target = FilterUtil.filterTarget(sRequest);
    target = WebCallbackManager.getUrlCleaner().clean(target);

    Entry entry = null;
    try {
        ContextUtil.enter(target);
        entry = SphU.entry(TOTAL_URL_REQUEST);
        chain.doFilter(request, response);
    } catch (BlockException e) {
        HttpServletResponse sResponse = (HttpServletResponse)response;
        WebCallbackManager.getUrlBlockHandler().blocked(sRequest, sResponse, e);
    } catch (IOException e2) {
        Tracer.trace(e2);
        throw e2;
    } catch (ServletException e3) {
        Tracer.trace(e3);
        throw e3;
    } catch (RuntimeException e4) {
        Tracer.trace(e4);
        throw e4;
    } finally {
        if (entry != null) {
            entry.exit();
        }
        ContextUtil.exit();
    }
}
 
Example #7
Source File: AbstractSofaRpcFilter.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
protected void traceResponseException(SofaResponse response, Entry interfaceEntry, Entry methodEntry) {
    if (response.isError()) {
        SofaRpcException rpcException = new SofaRpcException(RpcErrorType.SERVER_FILTER, response.getErrorMsg());
        Tracer.traceEntry(rpcException, interfaceEntry);
        Tracer.traceEntry(rpcException, methodEntry);
    } else {
        Object appResponse = response.getAppResponse();
        if (appResponse instanceof Throwable) {
            Tracer.traceEntry((Throwable) appResponse, interfaceEntry);
            Tracer.traceEntry((Throwable) appResponse, methodEntry);
        }
    }
}
 
Example #8
Source File: AbstractSentinelInterceptor.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
protected void traceExceptionAndExit(Entry entry, Exception ex) {
    if (entry != null) {
        if (ex != null) {
            Tracer.traceEntry(ex, entry);
        }
        entry.exit();
    }
}
 
Example #9
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 #10
Source File: ReactorSphU.java    From Sentinel 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 #11
Source File: SentinelReactorSubscriber.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Override
protected void hookOnError(Throwable t) {
    if (currentEntry != null && currentEntry.getAsyncContext() != null) {
        // Normal requests with non-BlockException will go through here.
        Tracer.traceContext(t, 1, currentEntry.getAsyncContext());
    }
    tryCompleteEntry();
    actual.onError(t);
}
 
Example #12
Source File: AbstractSentinelProccesser.java    From jboot with Apache License 2.0 4 votes vote down vote up
protected void traceException(Throwable ex) {
    Tracer.trace(ex);
}
 
Example #13
Source File: ExceptionCountDegradeDemo.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    tick();
    initDegradeRule();

    for (int i = 0; i < threadCount; i++) {
        Thread entryThread = new Thread(new Runnable() {

            @Override
            public void run() {
                int count = 0;
                while (true) {
                    count++;
                    Entry entry = null;
                    try {
                        Thread.sleep(20);
                        entry = SphU.entry(KEY);
                        // token acquired, means pass
                        pass.addAndGet(1);
                        if (count % 2 == 0) {
                            // biz code raise an exception.
                            throw new RuntimeException("throw runtime ");
                        }
                    } catch (BlockException e) {
                        block.addAndGet(1);
                    } catch (Throwable t) {
                        bizException.incrementAndGet();
                        Tracer.trace(t);
                    } finally {
                        total.addAndGet(1);
                        if (entry != null) {
                            entry.exit();
                        }
                    }
                }
            }

        });
        entryThread.setName("working-thread");
        entryThread.start();
    }

}
 
Example #14
Source File: SentinelProtectInterceptor.java    From spring-cloud-alibaba with Apache License 2.0 4 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
		ClientHttpRequestExecution execution) throws IOException {
	URI uri = request.getURI();
	String hostResource = request.getMethod().toString() + ":" + uri.getScheme()
			+ "://" + uri.getHost()
			+ (uri.getPort() == -1 ? "" : ":" + uri.getPort());
	String hostWithPathResource = hostResource + uri.getPath();
	boolean entryWithPath = true;
	if (hostResource.equals(hostWithPathResource)) {
		entryWithPath = false;
	}
	Method urlCleanerMethod = BlockClassRegistry.lookupUrlCleaner(
			sentinelRestTemplate.urlCleanerClass(),
			sentinelRestTemplate.urlCleaner());
	if (urlCleanerMethod != null) {
		hostWithPathResource = (String) methodInvoke(urlCleanerMethod,
				hostWithPathResource);
	}

	Entry hostEntry = null;
	Entry hostWithPathEntry = null;
	ClientHttpResponse response = null;
	try {
		hostEntry = SphU.entry(hostResource, EntryType.OUT);
		if (entryWithPath) {
			hostWithPathEntry = SphU.entry(hostWithPathResource, EntryType.OUT);
		}
		response = execution.execute(request, body);
		if (this.restTemplate.getErrorHandler().hasError(response)) {
			Tracer.trace(
					new IllegalStateException("RestTemplate ErrorHandler has error"));
		}
	}
	catch (Throwable e) {
		if (!BlockException.isBlockException(e)) {
			Tracer.trace(e);
		}
		else {
			return handleBlockException(request, body, execution, (BlockException) e);
		}
	}
	finally {
		if (hostWithPathEntry != null) {
			hostWithPathEntry.exit();
		}
		if (hostEntry != null) {
			hostEntry.exit();
		}
	}
	return response;
}
 
Example #15
Source File: AbstractSentinelAspectSupport.java    From Sentinel with Apache License 2.0 4 votes vote down vote up
protected void traceException(Throwable ex) {
    Tracer.trace(ex);
}
 
Example #16
Source File: AbstractSentinelInterceptorSupport.java    From Sentinel with Apache License 2.0 4 votes vote down vote up
protected void traceException(Throwable ex) {
    Tracer.trace(ex);
}
 
Example #17
Source File: CommonFilter.java    From Sentinel with Apache License 2.0 4 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest sRequest = (HttpServletRequest) request;
    Entry urlEntry = null;

    try {
        String target = FilterUtil.filterTarget(sRequest);
        // Clean and unify the URL.
        // For REST APIs, you have to clean the URL (e.g. `/foo/1` and `/foo/2` -> `/foo/:id`), or
        // the amount of context and resources will exceed the threshold.
        UrlCleaner urlCleaner = WebCallbackManager.getUrlCleaner();
        if (urlCleaner != null) {
            target = urlCleaner.clean(target);
        }

        // If you intend to exclude some URLs, you can convert the URLs to the empty string ""
        // in the UrlCleaner implementation.
        if (!StringUtil.isEmpty(target)) {
            // Parse the request origin using registered origin parser.
            String origin = parseOrigin(sRequest);
            String contextName = webContextUnify ? WebServletConfig.WEB_SERVLET_CONTEXT_NAME : target;
            ContextUtil.enter(contextName, origin);

            if (httpMethodSpecify) {
                // Add HTTP method prefix if necessary.
                String pathWithHttpMethod = sRequest.getMethod().toUpperCase() + COLON + target;
                urlEntry = SphU.entry(pathWithHttpMethod, ResourceTypeConstants.COMMON_WEB, EntryType.IN);
            } else {
                urlEntry = SphU.entry(target, ResourceTypeConstants.COMMON_WEB, EntryType.IN);
            }
        }
        chain.doFilter(request, response);
    } catch (BlockException e) {
        HttpServletResponse sResponse = (HttpServletResponse) response;
        // Return the block page, or redirect to another URL.
        WebCallbackManager.getUrlBlockHandler().blocked(sRequest, sResponse, e);
    } catch (IOException | ServletException | RuntimeException e2) {
        Tracer.traceEntry(e2, urlEntry);
        throw e2;
    } finally {
        if (urlEntry != null) {
            urlEntry.exit();
        }
        ContextUtil.exit();
    }
}
 
Example #18
Source File: ExceptionRatioDegradeDemo.java    From Sentinel with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    tick();
    initDegradeRule();

    for (int i = 0; i < threadCount; i++) {
        Thread entryThread = new Thread(new Runnable() {

            @Override
            public void run() {
                int count = 0;
                while (true) {
                    count++;
                    Entry entry = null;
                    try {
                        Thread.sleep(20);
                        entry = SphU.entry(KEY);
                        // token acquired, means pass
                        pass.addAndGet(1);
                        if (count % 2 == 0) {
                            // biz code raise an exception.
                            throw new RuntimeException("throw runtime ");
                        }
                    } catch (BlockException e) {
                        block.addAndGet(1);
                    } catch (Throwable t) {
                        bizException.incrementAndGet();
                        Tracer.trace(t);
                    } finally {
                        total.addAndGet(1);
                        if (entry != null) {
                            entry.exit();
                        }
                    }
                }
            }

        });
        entryThread.setName("working-thread");
        entryThread.start();
    }

}
 
Example #19
Source File: ExceptionCountDegradeDemo.java    From Sentinel with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    tick();
    initDegradeRule();

    for (int i = 0; i < threadCount; i++) {
        Thread entryThread = new Thread(new Runnable() {

            @Override
            public void run() {
                int count = 0;
                while (true) {
                    count++;
                    Entry entry = null;
                    try {
                        Thread.sleep(20);
                        entry = SphU.entry(KEY);
                        // token acquired, means pass
                        pass.addAndGet(1);
                        if (count % 2 == 0) {
                            // biz code raise an exception.
                            throw new RuntimeException("throw runtime ");
                        }
                    } catch (BlockException e) {
                        block.addAndGet(1);
                    } catch (Throwable t) {
                        bizException.incrementAndGet();
                        Tracer.trace(t);
                    } finally {
                        total.addAndGet(1);
                        if (entry != null) {
                            entry.exit();
                        }
                    }
                }
            }

        });
        entryThread.setName("working-thread");
        entryThread.start();
    }

}
 
Example #20
Source File: AbstractSentinelAspectSupport.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 4 votes vote down vote up
protected void traceException(Throwable ex) {
    Tracer.trace(ex);
}
 
Example #21
Source File: SentinelGrpcServerInterceptor.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 4 votes vote down vote up
private void recordException(Throwable t) {
    Tracer.trace(t);
}
 
Example #22
Source File: SentinelGrpcClientInterceptor.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 4 votes vote down vote up
private void recordException(Throwable t) {
    Tracer.trace(t);
}
 
Example #23
Source File: CommonFilter.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 4 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest sRequest = (HttpServletRequest) request;
    Entry entry = null;

    Entry methodEntry = null;

    try {
        String target = FilterUtil.filterTarget(sRequest);
        // Clean and unify the URL.
        // For REST APIs, you have to clean the URL (e.g. `/foo/1` and `/foo/2` -> `/foo/:id`), or
        // the amount of context and resources will exceed the threshold.
        UrlCleaner urlCleaner = WebCallbackManager.getUrlCleaner();
        if (urlCleaner != null) {
            target = urlCleaner.clean(target);
        }

        // Parse the request origin using registered origin parser.
        String origin = parseOrigin(sRequest);

        ContextUtil.enter(target, origin);
        entry = SphU.entry(target, EntryType.IN);


        // Add method specification if necessary
        if (httpMethodSpecify) {
            methodEntry = SphU.entry(sRequest.getMethod().toUpperCase() + COLON + target,
                    EntryType.IN);
        }

        chain.doFilter(request, response);
    } catch (BlockException e) {
        HttpServletResponse sResponse = (HttpServletResponse) response;
        // Return the block page, or redirect to another URL.
        WebCallbackManager.getUrlBlockHandler().blocked(sRequest, sResponse, e);
    } catch (IOException e2) {
        Tracer.trace(e2);
        throw e2;
    } catch (ServletException e3) {
        Tracer.trace(e3);
        throw e3;
    } catch (RuntimeException e4) {
        Tracer.trace(e4);
        throw e4;
    } finally {
        if (methodEntry != null) {
            methodEntry.exit();
        }
        if (entry != null) {
            entry.exit();
        }
        ContextUtil.exit();
    }
}
 
Example #24
Source File: ExceptionRatioDegradeDemo.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    tick();
    initDegradeRule();

    for (int i = 0; i < threadCount; i++) {
        Thread entryThread = new Thread(new Runnable() {

            @Override
            public void run() {
                int count = 0;
                while (true) {
                    count++;
                    Entry entry = null;
                    try {
                        Thread.sleep(20);
                        entry = SphU.entry(KEY);
                        // token acquired, means pass
                        pass.addAndGet(1);
                        if (count % 2 == 0) {
                            // biz code raise an exception.
                            throw new RuntimeException("throw runtime ");
                        }
                    } catch (BlockException e) {
                        block.addAndGet(1);
                    } catch (Throwable t) {
                        bizException.incrementAndGet();
                        Tracer.trace(t);
                    } finally {
                        total.addAndGet(1);
                        if (entry != null) {
                            entry.exit();
                        }
                    }
                }
            }

        });
        entryThread.setName("working-thread");
        entryThread.start();
    }

}