Skip to content

Commit

Permalink
*router piugin support springboot3
Browse files Browse the repository at this point in the history
Signed-off-by: provenceee <[email protected]>
  • Loading branch information
provenceee committed Nov 15, 2024
1 parent 0a55234 commit c4ba949
Show file tree
Hide file tree
Showing 6 changed files with 220 additions and 24 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet-api.version}</version>
<scope>test</scope>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,19 @@
import com.huaweicloud.sermant.core.utils.LogUtils;
import com.huaweicloud.sermant.core.utils.ReflectUtils;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Function;

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

/**
* DispatcherServlet 的 API接口增强 埋点定义sentinel资源
Expand All @@ -42,6 +49,28 @@
public class DispatcherServletInterceptor extends InterceptorSupporter {
private final String className = DispatcherServletInterceptor.class.getName();

private Function<Object, String> getRequestUri;

private Function<Object, String> getPathInfo;

private Function<Object, String> getMethod;

private Function<Object, Enumeration<String>> getHeaderNames;

private BiFunction<Object, String, String> getHeader;

private Function<Object, PrintWriter> getWriter;

private BiConsumer<Object, Integer> setStatus;

/**
* 构造方法
*/
public DispatcherServletInterceptor() {
super();
initFunction();
}

/**
* http请求数据转换 适应plugin -> service数据传递 注意,该方法不可抽出,由于宿主依赖仅可由该拦截器加载,因此抽出会导致找不到类
*
Expand All @@ -52,14 +81,14 @@ private Optional<HttpRequestEntity> convertToHttpEntity(Object request) {
if (request == null) {
return Optional.empty();
}
String uri = getRequestUri(request);
String uri = getRequestUri.apply(request);
return Optional.of(new HttpRequestEntity.Builder()
.setRequestType(RequestType.SERVER)
.setPathInfo(getPathInfo(request))
.setPathInfo(getPathInfo.apply(request))
.setServletPath(uri)
.setHeaders(getHeaders(request))
.setMethod(getMethod(request))
.setServiceName(getHeader(request, ConfigConst.FLOW_REMOTE_SERVICE_NAME_HEADER_KEY))
.setMethod(getMethod.apply(request))
.setServiceName(getHeader.apply(request, ConfigConst.FLOW_REMOTE_SERVICE_NAME_HEADER_KEY))
.build());
}

Expand All @@ -70,11 +99,11 @@ private Optional<HttpRequestEntity> convertToHttpEntity(Object request) {
* @return headers
*/
private Map<String, String> getHeaders(Object request) {
final Enumeration<String> headerNames = getHeaderNames(request);
final Enumeration<String> headerNames = getHeaderNames.apply(request);
final Map<String, String> headers = new HashMap<>();
while (headerNames.hasMoreElements()) {
final String headerName = headerNames.nextElement();
headers.put(headerName, getHeader(request, headerName));
headers.put(headerName, getHeader.apply(request, headerName));
}
return Collections.unmodifiableMap(headers);
}
Expand All @@ -94,8 +123,8 @@ protected final ExecuteContext doBefore(ExecuteContext context) throws Exception
context.skip(null);
final Object response = allArguments[1];
if (response != null) {
setStatus(response, result.getResponse().getCode());
getWriter(response).print(result.buildResponseMsg());
setStatus.accept(response, result.getResponse().getCode());
getWriter.apply(response).print(result.buildResponseMsg());
}
}
return context;
Expand Down Expand Up @@ -149,4 +178,40 @@ private void setStatus(Object httpServletResponse, int code) {
private String getString(Object object, String method) {
return (String) ReflectUtils.invokeMethodWithNoneParameter(object, method).orElse(null);
}

private void initFunction() {
boolean canLoadLowVersion = canLoadLowVersion();
if (canLoadLowVersion) {
getRequestUri = obj -> ((HttpServletRequest) obj).getRequestURI();
getPathInfo = obj -> ((HttpServletRequest) obj).getPathInfo();
getMethod = obj -> ((HttpServletRequest) obj).getMethod();
getHeaderNames = obj -> ((HttpServletRequest) obj).getHeaderNames();
getHeader = (obj, key) -> ((HttpServletRequest) obj).getHeader(key);
getWriter = obj -> {
try {
return ((HttpServletResponse) obj).getWriter();
} catch (IOException e) {
throw new RuntimeException(e);
}
};
setStatus = (obj, code) -> ((HttpServletResponse) obj).setStatus(code);
} else {
getRequestUri = this::getRequestUri;
getPathInfo = this::getPathInfo;
getMethod = this::getMethod;
getHeaderNames = this::getHeaderNames;
getHeader = this::getHeader;
getWriter = this::getWriter;
setStatus = this::setStatus;
}
}

private boolean canLoadLowVersion() {
try {
Class.forName(HttpServletRequest.class.getCanonicalName());
} catch (NoClassDefFoundError | ClassNotFoundException error) {
return false;
}
return true;
}
}
6 changes: 6 additions & 0 deletions sermant-plugins/sermant-monitor/monitor-plugin/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,12 @@
<version>${apache.dubbo.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet-api.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@
import com.huaweicloud.sermant.core.utils.LogUtils;
import com.huaweicloud.sermant.core.utils.ReflectUtils;

import java.util.function.Function;

import javax.servlet.http.HttpServletRequest;

/**
* HTTP拦截定义
*
Expand All @@ -34,6 +38,15 @@
public class DispatcherServletInterceptor extends AbstractInterceptor {
private static final String START_TIME = "startTime";

private Function<Object, String> getRequestUri;

/**
* 构造方法
*/
public DispatcherServletInterceptor() {
initFunction();
}

@Override
public ExecuteContext before(ExecuteContext context) {
LogUtils.printHttpRequestBeforePoint(context);
Expand All @@ -50,7 +63,7 @@ public ExecuteContext after(ExecuteContext context) {
LogUtils.printHttpRequestAfterPoint(context);
return context;
}
String uri = getRequestUri(context.getArguments()[0]);
String uri = getRequestUri.apply(context.getArguments()[0]);
MetricCalEntity metricCalEntity = MonitorCacheUtil.getMetricCalEntity(uri);
metricCalEntity.getReqNum().incrementAndGet();
long startTime = (Long) context.getExtMemberFieldValue(START_TIME);
Expand All @@ -70,7 +83,7 @@ public ExecuteContext onThrow(ExecuteContext context) {
LogUtils.printHttpRequestOnThrowPoint(context);
return context;
}
String uri = getRequestUri(context.getArguments()[0]);
String uri = getRequestUri.apply(context.getArguments()[0]);
MetricCalEntity metricCalEntity = MonitorCacheUtil.getMetricCalEntity(uri);
metricCalEntity.getReqNum().incrementAndGet();
metricCalEntity.getFailedReqNum().incrementAndGet();
Expand All @@ -81,4 +94,22 @@ public ExecuteContext onThrow(ExecuteContext context) {
private String getRequestUri(Object httpServletRequest) {
return (String) ReflectUtils.invokeMethodWithNoneParameter(httpServletRequest, "getRequestURI").orElse(null);
}

private void initFunction() {
boolean canLoadLowVersion = canLoadLowVersion();
if (canLoadLowVersion) {
getRequestUri = obj -> ((HttpServletRequest) obj).getRequestURI();
} else {
getRequestUri = this::getRequestUri;
}
}

private boolean canLoadLowVersion() {
try {
Class.forName(HttpServletRequest.class.getCanonicalName());
} catch (NoClassDefFoundError | ClassNotFoundException error) {
return false;
}
return true;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.function.Function;

import javax.servlet.http.HttpServletRequest;

/**
* 获取http请求数据
Expand All @@ -54,6 +58,16 @@ public class DispatcherServletInterceptor extends AbstractInterceptor {

private final SpringConfigService configService;

private Function<Object, String> getQueryString;

private Function<Object, String> getRequestUri;

private Function<Object, String> getMethod;

private Function<Object, Enumeration<?>> getHeaderNames;

private BiFunction<Object, String, Enumeration<?>> getHeaders;

/**
* 构造方法
*/
Expand All @@ -63,6 +77,7 @@ public DispatcherServletInterceptor() {
handlers.add(new LaneHandler());
handlers.add(new RouteHandler());
handlers.sort(Comparator.comparingInt(Handler::getOrder));
initFunction();
}

@Override
Expand All @@ -75,11 +90,11 @@ public ExecuteContext before(ExecuteContext context) {
}
Object request = context.getArguments()[0];
Map<String, List<String>> headers = getHeaders(request);
String queryString = SpringRouterUtils.getQueryString(request);
String queryString = getQueryString.apply(request);
String decode = Optional.ofNullable(queryString).map(this::decode).orElse(StringUtils.EMPTY);
Map<String, List<String>> queryParams = SpringRouterUtils.getParametersByQuery(decode);
String path = SpringRouterUtils.getRequestUri(request);
String method = SpringRouterUtils.getMethod(request);
String path = getRequestUri.apply(request);
String method = getMethod.apply(request);
handlers.forEach(handler -> ThreadLocalUtils.addRequestTag(
handler.getRequestTag(path, method, headers, queryParams, new Keys(matchKeys, injectTags))));
return context;
Expand Down Expand Up @@ -109,10 +124,10 @@ private String decode(String str) {

private Map<String, List<String>> getHeaders(Object request) {
Map<String, List<String>> headers = new HashMap<>();
Enumeration<?> enumeration = SpringRouterUtils.getHeaderNames(request);
Enumeration<?> enumeration = getHeaderNames.apply(request);
while (enumeration.hasMoreElements()) {
String key = (String) enumeration.nextElement();
headers.put(key, enumeration2List(SpringRouterUtils.getHeaders(request, key)));
headers.put(key, enumeration2List(getHeaders.apply(request, key)));
}
return headers;
}
Expand All @@ -127,4 +142,30 @@ private List<String> enumeration2List(Enumeration<?> enumeration) {
}
return collection;
}

private void initFunction() {
boolean canLoadLowVersion = canLoadLowVersion();
if (canLoadLowVersion) {
getQueryString = obj -> ((HttpServletRequest) obj).getQueryString();
getRequestUri = obj -> ((HttpServletRequest) obj).getRequestURI();
getMethod = obj -> ((HttpServletRequest) obj).getMethod();
getHeaderNames = obj -> ((HttpServletRequest) obj).getHeaderNames();
getHeaders = (obj, key) -> ((HttpServletRequest) obj).getHeaders(key);
} else {
getQueryString = SpringRouterUtils::getQueryString;
getRequestUri = SpringRouterUtils::getRequestUri;
getMethod = SpringRouterUtils::getMethod;
getHeaderNames = SpringRouterUtils::getHeaderNames;
getHeaders = SpringRouterUtils::getHeaders;
}
}

private boolean canLoadLowVersion() {
try {
Class.forName(HttpServletRequest.class.getCanonicalName());
} catch (NoClassDefFoundError | ClassNotFoundException error) {
return false;
}
return true;
}
}
Loading

0 comments on commit c4ba949

Please sign in to comment.