Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

router plugins support springboot3 #1670

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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>provided</scope>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,21 +18,20 @@

import io.sermant.core.plugin.agent.entity.ExecuteContext;
import io.sermant.core.utils.LogUtils;
import io.sermant.core.utils.ReflectUtils;
import io.sermant.flowcontrol.common.config.ConfigConst;
import io.sermant.flowcontrol.common.entity.FlowControlResult;
import io.sermant.flowcontrol.common.entity.HttpRequestEntity;
import io.sermant.flowcontrol.common.entity.RequestEntity.RequestType;
import io.sermant.flowcontrol.service.InterceptorSupporter;

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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* The API interface of DispatcherServlet is enhanced to define sentinel resources.
*
Expand All @@ -50,18 +49,18 @@ public class DispatcherServletInterceptor extends InterceptorSupporter {
* @param request request
* @return HttpRequestEntity
*/
private Optional<HttpRequestEntity> convertToHttpEntity(HttpServletRequest request) {
private Optional<HttpRequestEntity> convertToHttpEntity(Object request) {
if (request == null) {
return Optional.empty();
}
String uri = request.getRequestURI();
String uri = getRequestUri(request);
return Optional.of(new HttpRequestEntity.Builder()
.setRequestType(RequestType.SERVER)
.setPathInfo(request.getPathInfo())
.setPathInfo(getPathInfo(request))
.setServletPath(uri)
.setHeaders(getHeaders(request))
.setMethod(request.getMethod())
.setServiceName(request.getHeader(ConfigConst.FLOW_REMOTE_SERVICE_NAME_HEADER_KEY))
.setMethod(getMethod(request))
.setServiceName(getHeader(request, ConfigConst.FLOW_REMOTE_SERVICE_NAME_HEADER_KEY))
.build());
}

Expand All @@ -71,12 +70,12 @@ private Optional<HttpRequestEntity> convertToHttpEntity(HttpServletRequest reque
* @param request request information
* @return headers
*/
private Map<String, String> getHeaders(HttpServletRequest request) {
final Enumeration<String> headerNames = request.getHeaderNames();
private Map<String, String> getHeaders(Object request) {
final Enumeration<String> headerNames = getHeaderNames(request);
Comment on lines +73 to +74
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use class name to distinguish low version and high version

final Map<String, String> headers = new HashMap<>();
while (headerNames.hasMoreElements()) {
final String headerName = headerNames.nextElement();
headers.put(headerName, request.getHeader(headerName));
headers.put(headerName, getHeader(request, headerName));
}
return Collections.unmodifiableMap(headers);
}
Expand All @@ -85,19 +84,19 @@ private Map<String, String> getHeaders(HttpServletRequest request) {
protected final ExecuteContext doBefore(ExecuteContext context) throws Exception {
LogUtils.printHttpRequestBeforePoint(context);
final Object[] allArguments = context.getArguments();
final HttpServletRequest argument = (HttpServletRequest) allArguments[0];
final Object request = allArguments[0];
final FlowControlResult result = new FlowControlResult();
final Optional<HttpRequestEntity> httpRequestEntity = convertToHttpEntity(argument);
final Optional<HttpRequestEntity> httpRequestEntity = convertToHttpEntity(request);
if (!httpRequestEntity.isPresent()) {
return context;
}
chooseHttpService().onBefore(className, httpRequestEntity.get(), result);
if (result.isSkip()) {
context.skip(null);
final HttpServletResponse response = (HttpServletResponse) allArguments[1];
final Object response = allArguments[1];
if (response != null) {
response.setStatus(result.getResponse().getCode());
response.getWriter().print(result.buildResponseMsg());
setStatus(response, result.getResponse().getCode());
getWriter(response).print(result.buildResponseMsg());
}
}
return context;
Expand All @@ -116,4 +115,39 @@ protected final ExecuteContext doThrow(ExecuteContext context) {
LogUtils.printHttpRequestOnThrowPoint(context);
return context;
}

private String getRequestUri(Object httpServletRequest) {
return getString(httpServletRequest, "getRequestURI");
}

private String getPathInfo(Object httpServletRequest) {
return getString(httpServletRequest, "getPathInfo");
}

private String getMethod(Object httpServletRequest) {
return getString(httpServletRequest, "getMethod");
}

private Enumeration<String> getHeaderNames(Object httpServletRequest) {
return (Enumeration<String>) ReflectUtils.invokeMethodWithNoneParameter(httpServletRequest, "getHeaderNames")
.orElse(null);
}

private String getHeader(Object httpServletRequest, String key) {
return (String) ReflectUtils.invokeMethod(httpServletRequest, "getHeader", new Class[]{String.class},
new Object[]{key}).orElse(null);
}

private PrintWriter getWriter(Object httpServletRequest) {
return (PrintWriter) ReflectUtils.invokeMethodWithNoneParameter(httpServletRequest, "getWriter")
.orElse(null);
}

private void setStatus(Object httpServletResponse, int code) {
ReflectUtils.invokeMethod(httpServletResponse, "setStatus", new Class[]{int.class}, new Object[]{code});
}

private String getString(Object object, String method) {
return (String) ReflectUtils.invokeMethodWithNoneParameter(object, method).orElse(null);
}
}
6 changes: 0 additions & 6 deletions sermant-plugins/sermant-monitor/monitor-plugin/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,6 @@
<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 @@ -20,11 +20,10 @@
import io.sermant.core.plugin.agent.entity.ExecuteContext;
import io.sermant.core.plugin.agent.interceptor.AbstractInterceptor;
import io.sermant.core.utils.LogUtils;
import io.sermant.core.utils.ReflectUtils;
import io.sermant.monitor.common.MetricCalEntity;
import io.sermant.monitor.util.MonitorCacheUtil;

import javax.servlet.http.HttpServletRequest;

/**
* HTTP Interceptor
*
Expand All @@ -50,7 +49,7 @@ public ExecuteContext after(ExecuteContext context) {
LogUtils.printHttpRequestAfterPoint(context);
return context;
}
String uri = ((HttpServletRequest) context.getArguments()[0]).getRequestURI();
String uri = getRequestUri(context.getArguments()[0]);
MetricCalEntity metricCalEntity = MonitorCacheUtil.getMetricCalEntity(uri);
metricCalEntity.getReqNum().incrementAndGet();
long startTime = (Long) context.getExtMemberFieldValue(START_TIME);
Expand All @@ -70,11 +69,15 @@ public ExecuteContext onThrow(ExecuteContext context) {
LogUtils.printHttpRequestOnThrowPoint(context);
return context;
}
String uri = ((HttpServletRequest) context.getArguments()[0]).getRequestURI();
String uri = getRequestUri(context.getArguments()[0]);
MetricCalEntity metricCalEntity = MonitorCacheUtil.getMetricCalEntity(uri);
metricCalEntity.getReqNum().incrementAndGet();
metricCalEntity.getFailedReqNum().incrementAndGet();
LogUtils.printHttpRequestOnThrowPoint(context);
return context;
}

private String getRequestUri(Object httpServletRequest) {
return (String) ReflectUtils.invokeMethodWithNoneParameter(httpServletRequest, "getRequestURI").orElse(null);
}
}
12 changes: 0 additions & 12 deletions sermant-plugins/sermant-router/spring-router-plugin/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -61,12 +61,6 @@
<version>${jakarta.el.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webflux</artifactId>
Expand All @@ -79,12 +73,6 @@
<version>${spring.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webflux</artifactId>
<version>${spring.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.projectreactor.netty</groupId>
<artifactId>reactor-netty</artifactId>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (C) 2022-2022 Huawei Technologies Co., Ltd. All rights reserved.
* Copyright (C) 2022-2024 Huawei Technologies Co., Ltd. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -19,23 +19,23 @@
import io.sermant.core.plugin.agent.matcher.ClassMatcher;

/**
* Add an injection interceptor by intercepting and inject a spring web interceptor
* get http request data
*
* @author provenceee
* @since 2022-07-12
*/
public class HandlerExecutionChainDeclarer extends AbstractDeclarer {
private static final String ENHANCE_CLASS = "org.springframework.web.servlet.HandlerExecutionChain";
public class DispatcherServletDeclarer extends AbstractDeclarer {
private static final String ENHANCE_CLASS = "org.springframework.web.servlet.DispatcherServlet";

private static final String INTERCEPT_CLASS
= "io.sermant.router.spring.interceptor.HandlerExecutionChainInterceptor";
= "io.sermant.router.spring.interceptor.DispatcherServletInterceptor";

private static final String METHOD_NAME = "applyPreHandle";
private static final String METHOD_NAME = "doService";

/**
* Constructor
*/
public HandlerExecutionChainDeclarer() {
public DispatcherServletDeclarer() {
super(ENHANCE_CLASS, INTERCEPT_CLASS, METHOD_NAME);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ public ExecuteContext before(ExecuteContext context) {
Object serviceName = ReflectUtils.getFieldValue(obj, "serviceName").orElse(null);
if (serviceName instanceof String) {
AppCache.INSTANCE.setAppName((String) serviceName);
configService.init(RouterConstant.SPRING_CACHE_NAME, AppCache.INSTANCE.getAppName());
} else {
LOGGER.warning("Service name is null or not instanceof string.");
}
Expand All @@ -69,7 +70,6 @@ public ExecuteContext before(ExecuteContext context) {

@Override
public ExecuteContext after(ExecuteContext context) {
configService.init(RouterConstant.SPRING_CACHE_NAME, AppCache.INSTANCE.getAppName());
return context;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@

package io.sermant.router.spring.interceptor;

import io.sermant.core.plugin.agent.entity.ExecuteContext;
import io.sermant.core.plugin.agent.interceptor.AbstractInterceptor;
import io.sermant.core.plugin.service.PluginServiceManager;
import io.sermant.router.common.handler.Handler;
import io.sermant.router.common.utils.CollectionUtils;
Expand All @@ -25,9 +27,7 @@
import io.sermant.router.spring.handler.LaneRequestTagHandler;
import io.sermant.router.spring.handler.RouteRequestTagHandler;
import io.sermant.router.spring.service.SpringConfigService;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import io.sermant.router.spring.utils.SpringRouterUtils;

import java.util.ArrayList;
import java.util.Collections;
Expand All @@ -38,24 +38,21 @@
import java.util.Map;
import java.util.Set;

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

/**
* Spring Interceptor
* get http request data
*
* @author provenceee
* @since 2022-07-12
*/
public class RouteHandlerInterceptor implements HandlerInterceptor {
public class DispatcherServletInterceptor extends AbstractInterceptor {
private final List<AbstractRequestTagHandler> handlers;

private final SpringConfigService configService;

/**
* Constructor
*/
public RouteHandlerInterceptor() {
public DispatcherServletInterceptor() {
configService = PluginServiceManager.getPluginService(SpringConfigService.class);
handlers = new ArrayList<>();
handlers.add(new LaneRequestTagHandler());
Expand All @@ -64,38 +61,43 @@ public RouteHandlerInterceptor() {
}

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) {
public ExecuteContext before(ExecuteContext context) {
Set<String> matchKeys = configService.getMatchKeys();
Set<String> injectTags = configService.getInjectTags();
if (CollectionUtils.isEmpty(matchKeys) && CollectionUtils.isEmpty(injectTags)) {
// The staining mark is empty, which means that there are no staining rules, and it is returned directly
return true;
return context;
}
Object request = context.getArguments()[0];
Map<String, List<String>> headers = getHeaders(request);
Map<String, String[]> parameterMap = request.getParameterMap();
String path = request.getRequestURI();
String method = request.getMethod();
Map<String, String[]> parameterMap = SpringRouterUtils.getParameterMap(request);
String path = SpringRouterUtils.getRequestUri(request);
String method = SpringRouterUtils.getMethod(request);
handlers.forEach(handler -> ThreadLocalUtils.addRequestTag(
handler.getRequestTag(path, method, headers, parameterMap, new Keys(matchKeys, injectTags))));
return true;
return context;
}

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object obj,
ModelAndView modelAndView) {
public ExecuteContext after(ExecuteContext context) {
ThreadLocalUtils.removeRequestData();
ThreadLocalUtils.removeRequestTag();
return context;
}

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object obj, Exception ex) {
public ExecuteContext onThrow(ExecuteContext context) {
ThreadLocalUtils.removeRequestData();
ThreadLocalUtils.removeRequestTag();
return context;
}

private Map<String, List<String>> getHeaders(HttpServletRequest request) {
private Map<String, List<String>> getHeaders(Object request) {
Map<String, List<String>> headers = new HashMap<>();
Enumeration<?> enumeration = request.getHeaderNames();
Enumeration<?> enumeration = SpringRouterUtils.getHeaderNames(request);
while (enumeration.hasMoreElements()) {
String key = (String) enumeration.nextElement();
headers.put(key, enumeration2List(request.getHeaders(key)));
headers.put(key, enumeration2List(SpringRouterUtils.getHeaders(request, key)));
}
return headers;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,14 +53,14 @@ public ExecuteContext before(ExecuteContext context) {
if (argument instanceof InstanceInfo) {
InstanceInfo instanceInfo = (InstanceInfo) argument;
AppCache.INSTANCE.setAppName(instanceInfo.getAppName());
configService.init(RouterConstant.SPRING_CACHE_NAME, AppCache.INSTANCE.getAppName());
SpringRouterUtils.putMetaData(instanceInfo.getMetadata(), routerConfig);
}
return context;
}

@Override
public ExecuteContext after(ExecuteContext context) {
configService.init(RouterConstant.SPRING_CACHE_NAME, AppCache.INSTANCE.getAppName());
return context;
}
}
Loading
Loading