Skip to content

Commit

Permalink
feat: sentinel can feel exception though application has configured E…
Browse files Browse the repository at this point in the history
…xceptionHandler (#3409)
  • Loading branch information
24kpure authored Aug 20, 2024
1 parent 02c97fe commit b78b09d
Show file tree
Hide file tree
Showing 10 changed files with 178 additions and 36 deletions.
6 changes: 6 additions & 0 deletions sentinel-adapter/sentinel-spring-webmvc-adapter/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,12 @@ public class InterceptorConfig implements WebMvcConfigurer {
// Add to the interceptor list.
registry.addInterceptor(new SentinelWebInterceptor(config)).addPathPatterns("/**");
}

@Bean
public SentinelExceptionAware sentinelExceptionAware(){
//Make exception visible to Sentinel if you have configured ExceptionHandler
return new SentinelExceptionAware();
}
}
```

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,6 @@
*/
package com.alibaba.csp.sentinel.adapter.spring.webmvc;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.EntryType;
import com.alibaba.csp.sentinel.ResourceTypeConstants;
Expand All @@ -29,14 +26,19 @@
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.util.AssertUtil;
import com.alibaba.csp.sentinel.util.StringUtil;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
* Since request may be reprocessed in flow if any forwarding or including or other action
* happened (see {@link javax.servlet.ServletRequest#getDispatcherType()}) we will only
* deal with the initial request. So we use <b>reference count</b> to track in
* happened (see {@link javax.servlet.ServletRequest#getDispatcherType()}) we will only
* deal with the initial request. So we use <b>reference count</b> to track in
* dispathing "onion" though which we could figure out whether we are in initial type "REQUEST".
* That means the sub-requests which we rarely meet in practice will NOT be recorded in Sentinel.
* <p>
Expand Down Expand Up @@ -71,15 +73,15 @@ public AbstractSentinelInterceptor(BaseWebMvcConfig config) {
* @param step
* @return reference count after increasing (initial value as zero to be increased)
*/
private Integer increaseReferece(HttpServletRequest request, String rcKey, int step) {
private Integer increaseReference(HttpServletRequest request, String rcKey, int step) {
Object obj = request.getAttribute(rcKey);

if (obj == null) {
// initial
obj = Integer.valueOf(0);
obj = 0;
}
Integer newRc = (Integer)obj + step;

Integer newRc = (Integer) obj + step;
request.setAttribute(rcKey, newRc);
return newRc;
}
Expand All @@ -93,8 +95,8 @@ public boolean preHandle(HttpServletRequest request, HttpServletResponse respons
if (StringUtil.isEmpty(resourceName)) {
return true;
}
if (increaseReferece(request, this.baseWebMvcConfig.getRequestRefName(), 1) != 1) {

if (increaseReference(request, this.baseWebMvcConfig.getRequestRefName(), 1) != 1) {
return true;
}

Expand Down Expand Up @@ -136,7 +138,7 @@ protected String getContextName(HttpServletRequest request) {
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception ex) throws Exception {
if (increaseReferece(request, this.baseWebMvcConfig.getRequestRefName(), -1) != 0) {
if (increaseReference(request, this.baseWebMvcConfig.getRequestRefName(), -1) != 0) {
return;
}

Expand Down Expand Up @@ -168,12 +170,21 @@ protected void removeEntryInRequest(HttpServletRequest request) {
}

protected void traceExceptionAndExit(Entry entry, Exception ex) {
if (entry != null) {
if (ex != null) {
Tracer.traceEntry(ex, entry);
}
entry.exit();
if (entry == null) {
return;
}
HttpServletRequest request = getHttpServletRequest();
if (request != null
&& ex == null
&& increaseReference(request, this.baseWebMvcConfig.getRequestRefName() + ":" + BaseWebMvcConfig.REQUEST_REF_EXCEPTION_NAME, 1) == 1) {
//Each interceptor can only catch exception once
ex = (Exception) request.getAttribute(BaseWebMvcConfig.REQUEST_REF_EXCEPTION_NAME);
}

if (ex != null) {
Tracer.traceEntry(ex, entry);
}
entry.exit();
}

protected void handleBlockException(HttpServletRequest request, HttpServletResponse response, BlockException e)
Expand All @@ -197,4 +208,9 @@ protected String parseOrigin(HttpServletRequest request) {
return origin;
}

private HttpServletRequest getHttpServletRequest() {
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

return Objects.isNull(servletRequestAttributes) ? null : servletRequestAttributes.getRequest();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
* Copyright 1999-2019 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.csp.sentinel.adapter.spring.webmvc;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.config.BaseWebMvcConfig;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* Make exception visible to Sentinel.SentinelExceptionAware should be front of ExceptionHandlerExceptionResolver
* whose order is 0 {@link org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport#handlerExceptionResolver}
*
* @author lemonJ
*/
@Order(-1)
public class SentinelExceptionAware implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
addExceptionToRequest(request, ex);
return null;
}

private void addExceptionToRequest(HttpServletRequest httpServletRequest, Exception exception) {
if(BlockException.isBlockException(exception)){
return;
}
httpServletRequest.setAttribute(BaseWebMvcConfig.REQUEST_REF_EXCEPTION_NAME, exception);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@
*/
public abstract class BaseWebMvcConfig {

public final static String REQUEST_REF_EXCEPTION_NAME = "$$sentinel_spring_web_entry_attr-exception";

protected String requestAttributeName;
protected String requestRefName;
protected BlockExceptionHandler blockExceptionHandler;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@

import com.alibaba.csp.sentinel.node.ClusterNode;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.csp.sentinel.slots.clusterbuilder.ClusterBuilderSlot;
Expand Down Expand Up @@ -128,6 +130,32 @@ public void testRuntimeException() throws Exception {
assertEquals(1, cn.blockRequest(), 1);
}


@Test
public void testExceptionPerception() throws Exception {
String url = "/bizException";
configureExceptionDegradeRulesFor(url, 2.6, null);
int repeat = 3;
for (int i = 0; i < repeat; i++) {
this.mvc.perform(get(url))
.andExpect(status().isOk())
.andExpect(content().string(new ResultWrapper(-1, "Biz error").toJsonString()));

ClusterNode cn = ClusterBuilderSlot.getClusterNode(url);
assertNotNull(cn);
assertEquals(i + 1, cn.passQps(), 0.01);
}

// This will be blocked and response json.
this.mvc.perform(get(url))
.andExpect(status().isOk())
.andExpect(content().string(ResultWrapper.blocked().toJsonString()));
ClusterNode cn = ClusterBuilderSlot.getClusterNode(url);
assertNotNull(cn);
assertEquals(repeat, cn.passQps(), 0.01);
assertEquals(1, cn.blockRequest(), 1);
}

private void configureRulesFor(String resource, int count, String limitApp) {
FlowRule rule = new FlowRule()
.setCount(count)
Expand All @@ -150,6 +178,20 @@ private void configureExceptionRulesFor(String resource, int count, String limit
FlowRuleManager.loadRules(Collections.singletonList(rule));
}

private void configureExceptionDegradeRulesFor(String resource, double count, String limitApp) {
DegradeRule rule = new DegradeRule()
.setCount(count)
.setStatIntervalMs(1000)
.setMinRequestAmount(1)
.setTimeWindow(5)
.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT);
rule.setResource(resource);
if (StringUtil.isNotBlank(limitApp)) {
rule.setLimitApp(limitApp);
}
DegradeRuleManager.loadRules(Collections.singletonList(rule));
}

@After
public void cleanUp() {
FlowRuleManager.loadRules(null);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,16 @@
*/
package com.alibaba.csp.sentinel.adapter.spring.webmvc.config;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.SentinelExceptionAware;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.SentinelWebInterceptor;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.SentinelWebTotalInterceptor;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.RequestOriginParser;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* Config sentinel interceptor
Expand All @@ -35,6 +34,11 @@
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

@Bean
public SentinelExceptionAware sentinelExceptionAware() {
return new SentinelExceptionAware();
}

@Override
public void addInterceptors(InterceptorRegistry registry) {
//Add sentinel interceptor
Expand All @@ -48,19 +52,16 @@ private void addSpringMvcInterceptor(InterceptorRegistry registry) {
//Config
SentinelWebMvcConfig config = new SentinelWebMvcConfig();

config.setBlockExceptionHandler(new BlockExceptionHandler() {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
String resourceName = e.getRule().getResource();
//Depending on your situation, you can choose to process or throw
if ("/hello".equals(resourceName)) {
//Do something ......
//Write string or json string;
response.getWriter().write("/Blocked by sentinel");
} else {
//Handle in global exception handling
throw e;
}
config.setBlockExceptionHandler((request, response, e) -> {
String resourceName = e.getRule().getResource();
//Depending on your situation, you can choose to process or throw
if ("/hello".equals(resourceName)) {
//Do something ......
//Write string or json string;
response.getWriter().write("/Blocked by sentinel");
} else {
//Handle in global exception handling
throw e;
}
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
package com.alibaba.csp.sentinel.adapter.spring.webmvc.config;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.ResultWrapper;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.exception.BizException;
import com.alibaba.csp.sentinel.slots.block.AbstractRule;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.slf4j.Logger;
Expand Down Expand Up @@ -51,4 +52,11 @@ public ResultWrapper exceptionHandler(Exception e) {
logger.error("System error", e.getMessage());
return new ResultWrapper(-1, "System error");
}

@ExceptionHandler(BizException.class)
@ResponseBody
public ResultWrapper bizExceptionHandler(BizException e) {
logger.error("Biz error", e.getMessage());
return new ResultWrapper(-1, "Biz error");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
package com.alibaba.csp.sentinel.adapter.spring.webmvc.controller;


import com.alibaba.csp.sentinel.adapter.spring.webmvc.exception.BizException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
Expand Down Expand Up @@ -47,6 +48,11 @@ public String runtimeException() {
return "runtimeException";
}

@GetMapping("/bizException")
public String bizException() {
throw new BizException();
}

@GetMapping("/exclude/{id}")
public String apiExclude(@PathVariable("id") Long id) {
return "Exclude " + id;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.alibaba.csp.sentinel.adapter.spring.webmvc.exception;

/**
* @author lemonj
*/
public class BizException extends RuntimeException{
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,13 @@
*/
package com.alibaba.csp.sentinel.demo.spring.webmvc.config;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.SentinelExceptionAware;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.SentinelWebInterceptor;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.SentinelWebTotalInterceptor;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.DefaultBlockExceptionHandler;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.config.SentinelWebMvcConfig;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.config.SentinelWebMvcTotalConfig;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
Expand All @@ -39,6 +40,12 @@ public void addInterceptors(InterceptorRegistry registry) {
addSpringMvcInterceptor(registry);
}

@Bean
public SentinelExceptionAware sentinelExceptionAware() {
//Make exception visible to Sentinel if you have configured ExceptionHandler
return new SentinelExceptionAware();
}

private void addSpringMvcInterceptor(InterceptorRegistry registry) {
SentinelWebMvcConfig config = new SentinelWebMvcConfig();

Expand Down

0 comments on commit b78b09d

Please sign in to comment.