websocket 调整

This commit is contained in:
bwcx_jzy 2021-08-03 22:43:25 +08:00
parent 58e8edb0fc
commit ad0603346d
18 changed files with 971 additions and 777 deletions

View File

@ -12,6 +12,7 @@ import org.springframework.web.socket.server.standard.ServerEndpointExporter;
*/ */
@Configuration @Configuration
public class AgentWebSocketConfig { public class AgentWebSocketConfig {
@Bean @Bean
public ServerEndpointExporter serverEndpointExporter() { public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter(); return new ServerEndpointExporter();

View File

@ -15,7 +15,6 @@ import io.jpom.util.SocketSessionUtil;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.websocket.*; import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint; import javax.websocket.server.ServerEndpoint;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
@ -26,24 +25,32 @@ import java.io.IOException;
* @author jiangzeyin * @author jiangzeyin
* @date 2019/4/16 * @date 2019/4/16
*/ */
@ServerEndpoint(value = "/console/{projectId}/{optUser}") @ServerEndpoint(value = "/console")
@Component @Component
public class AgentWebSocketConsoleHandle extends BaseAgentWebSocketHandle { public class AgentWebSocketConsoleHandle extends BaseAgentWebSocketHandle {
private static ProjectInfoService projectInfoService; private static ProjectInfoService projectInfoService;
@OnOpen @OnOpen
public void onOpen(@PathParam("projectId") String projectId, @PathParam("optUser") String urlOptUser, @PathParam("copyId") String copyId, Session session) { public void onOpen(Session session) {
try { try {
if (super.checkAuthorize(session)) {
return;
}
String projectId = super.getParameters(session, "projectId");
String copyId = super.getParameters(session, "copyId");
// 判断项目 // 判断项目
if (!JpomApplication.SYSTEM_ID.equals(projectId)) { if (!JpomApplication.SYSTEM_ID.equals(projectId)) {
if (projectInfoService == null) { if (projectInfoService == null) {
projectInfoService = SpringUtil.getBean(ProjectInfoService.class); projectInfoService = SpringUtil.getBean(ProjectInfoService.class);
} }
ProjectInfoModel projectInfoModel = this.checkProject(projectId, copyId, session); ProjectInfoModel projectInfoModel = this.checkProject(projectId, copyId, session);
if (projectInfoModel == null) {
return;
}
//
SocketSessionUtil.send(session, "连接成功:" + projectInfoModel.getName());
} }
this.addUser(session, urlOptUser);
} catch (Exception e) { } catch (Exception e) {
DefaultSystemLog.getLog().error("socket 错误", e); DefaultSystemLog.getLog().error("socket 错误", e);
try { try {

View File

@ -11,7 +11,6 @@ import io.jpom.util.SocketSessionUtil;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.websocket.*; import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint; import javax.websocket.server.ServerEndpoint;
import java.io.IOException; import java.io.IOException;
@ -21,18 +20,22 @@ import java.io.IOException;
* @author jiangzeyin * @author jiangzeyin
* @date 2019/4/24 * @date 2019/4/24
*/ */
@ServerEndpoint(value = "/script_run/{id}/{optUser}") @ServerEndpoint(value = "/script_run")
@Component @Component
public class AgentWebSocketScriptHandle extends BaseAgentWebSocketHandle { public class AgentWebSocketScriptHandle extends BaseAgentWebSocketHandle {
private ScriptServer scriptServer; private ScriptServer scriptServer;
@OnOpen @OnOpen
public void onOpen(@PathParam("id") String id, Session session, @PathParam("optUser") String urlOptUser) { public void onOpen(Session session) {
if (scriptServer == null) { if (scriptServer == null) {
scriptServer = SpringUtil.getBean(ScriptServer.class); scriptServer = SpringUtil.getBean(ScriptServer.class);
} }
try { try {
if (super.checkAuthorize(session)) {
return;
}
String id = this.getParameters(session, "id");
if (StrUtil.isEmpty(id)) { if (StrUtil.isEmpty(id)) {
SocketSessionUtil.send(session, "脚本模板未知"); SocketSessionUtil.send(session, "脚本模板未知");
return; return;
@ -43,7 +46,6 @@ public class AgentWebSocketScriptHandle extends BaseAgentWebSocketHandle {
return; return;
} }
SocketSessionUtil.send(session, "连接成功:" + scriptModel.getName()); SocketSessionUtil.send(session, "连接成功:" + scriptModel.getName());
this.addUser(session, urlOptUser);
} catch (Exception e) { } catch (Exception e) {
DefaultSystemLog.getLog().error("socket 错误", e); DefaultSystemLog.getLog().error("socket 错误", e);
try { try {

View File

@ -14,7 +14,6 @@ import io.jpom.util.SocketSessionUtil;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.websocket.*; import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint; import javax.websocket.server.ServerEndpoint;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
@ -27,7 +26,7 @@ import java.util.concurrent.ConcurrentHashMap;
* @author jiangzeyin * @author jiangzeyin
* @date 2019/4/16 * @date 2019/4/16
*/ */
@ServerEndpoint(value = "/tomcat_log/{tomcatId}/{optUser}") @ServerEndpoint(value = "/tomcat_log")
@Component @Component
public class AgentWebSocketTomcatHandle extends BaseAgentWebSocketHandle { public class AgentWebSocketTomcatHandle extends BaseAgentWebSocketHandle {
@ -36,8 +35,12 @@ public class AgentWebSocketTomcatHandle extends BaseAgentWebSocketHandle {
private static final Map<String, File> CACHE_FILE = new ConcurrentHashMap<>(); private static final Map<String, File> CACHE_FILE = new ConcurrentHashMap<>();
@OnOpen @OnOpen
public void onOpen(@PathParam("tomcatId") String tomcatId, @PathParam("optUser") String urlOptUser, Session session) { public void onOpen(Session session) {
try { try {
if (super.checkAuthorize(session)) {
return;
}
String tomcatId = super.getParameters(session, "tomcatId");
if (tomcatEditService == null) { if (tomcatEditService == null) {
tomcatEditService = SpringUtil.getBean(TomcatEditService.class); tomcatEditService = SpringUtil.getBean(TomcatEditService.class);
} }
@ -47,7 +50,7 @@ public class AgentWebSocketTomcatHandle extends BaseAgentWebSocketHandle {
session.close(); session.close();
return; return;
} }
this.addUser(session, urlOptUser); SocketSessionUtil.send(session, "连接成功:" + (tomcatInfoModel == null ? "" : tomcatInfoModel.getName()));
} catch (Exception e) { } catch (Exception e) {
DefaultSystemLog.getLog().error("socket 错误", e); DefaultSystemLog.getLog().error("socket 错误", e);
try { try {

View File

@ -0,0 +1,111 @@
package io.jpom.socket;
import cn.jiangzeyin.common.DefaultSystemLog;
import com.alibaba.fastjson.JSONObject;
import io.jpom.JpomApplication;
import io.jpom.common.JpomManifest;
import io.jpom.model.AgentFileModel;
import io.jpom.model.WebSocketMessageModel;
import io.jpom.model.data.UploadFileModel;
import io.jpom.system.AgentConfigBean;
import io.jpom.util.SocketSessionUtil;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Map;
/**
* 在线升级
*
* @author bwcx_jzy
* @date 2021/8/3
*/
@ServerEndpoint(value = "/node_update")
@Component
public class AgentWebSocketUpdateHandle extends BaseAgentWebSocketHandle {
private static final Map<String, UploadFileModel> UPLOAD_FILE_INFO = new HashMap<>();
@OnOpen
public void onOpen(Session session) {
if (super.checkAuthorize(session)) {
return;
}
session.setMaxBinaryMessageBufferSize(1024 * 1024);
//
}
@OnMessage
public void onMessage(String message, Session session) throws Exception {
WebSocketMessageModel model = WebSocketMessageModel.getInstance(message);
switch (model.getCommand()) {
case "getVersion":
model.setData(JSONObject.toJSONString(JpomManifest.getInstance()));
break;
case "upload":
AgentFileModel agentFileModel = ((JSONObject) model.getParams()).toJavaObject(AgentFileModel.class);
UploadFileModel uploadFileModel = new UploadFileModel();
uploadFileModel.setId(model.getNodeId());
uploadFileModel.setName(agentFileModel.getName());
uploadFileModel.setSize(agentFileModel.getSize());
uploadFileModel.setVersion(agentFileModel.getVersion());
uploadFileModel.setSavePath(AgentConfigBean.getInstance().getTempPath().getAbsolutePath());
uploadFileModel.remove();
UPLOAD_FILE_INFO.put(session.getId(), uploadFileModel);
break;
case "restart":
model.setData(restart(session));
break;
default:
break;
}
SocketSessionUtil.send(session, message.toString());
//session.sendMessage(new TextMessage(model.toString()));
}
@OnMessage
public void onMessage(byte[] message, Session session) throws Exception {
UploadFileModel uploadFileModel = UPLOAD_FILE_INFO.get(session.getId());
uploadFileModel.save(message);
// 更新进度
WebSocketMessageModel model = new WebSocketMessageModel("updateNode", uploadFileModel.getId());
model.setData(uploadFileModel);
SocketSessionUtil.send(session, model.toString());
// session.sendMessage(new TextMessage(model.toString()));
}
/**
* 重启
*
* @param session 回话
* @return 结果
*/
public String restart(Session session) {
String result = "重启中";
try {
UploadFileModel uploadFile = UPLOAD_FILE_INFO.get(session.getId());
JpomManifest.releaseJar(uploadFile.getFilePath(), uploadFile.getVersion(), true);
JpomApplication.restart();
} catch (RuntimeException e) {
result = e.getMessage();
DefaultSystemLog.getLog().error("重启失败", e);
}
return result;
}
@Override
@OnClose
public void onClose(Session session) {
super.onClose(session);
UPLOAD_FILE_INFO.remove(session.getId());
}
@OnError
@Override
public void onError(Session session, Throwable thr) {
super.onError(session, thr);
}
}

View File

@ -1,15 +1,23 @@
package io.jpom.socket; package io.jpom.socket;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.exceptions.ExceptionUtil; import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil; import cn.hutool.core.util.URLUtil;
import cn.jiangzeyin.common.DefaultSystemLog; import cn.jiangzeyin.common.DefaultSystemLog;
import io.jpom.system.AgentAuthorize;
import io.jpom.system.ConfigBean;
import io.jpom.util.SocketSessionUtil; import io.jpom.util.SocketSessionUtil;
import javax.websocket.CloseReason;
import javax.websocket.Session; import javax.websocket.Session;
import java.io.IOException; import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import static javax.websocket.CloseReason.CloseCodes.CANNOT_ACCEPT;
/** /**
* 插件端socket 基类 * 插件端socket 基类
* *
@ -20,7 +28,40 @@ public abstract class BaseAgentWebSocketHandle {
private static final ConcurrentHashMap<String, String> USER = new ConcurrentHashMap<>(); private static final ConcurrentHashMap<String, String> USER = new ConcurrentHashMap<>();
public void addUser(Session session, String name) { protected String getParameters(Session session, String name) {
Map<String, List<String>> pathParameters = session.getRequestParameterMap();
List<String> strings = pathParameters.get(name);
return CollUtil.join(strings, StrUtil.COMMA);
}
/**
* 判断授权信息是否正确
*
* @param session session
* @return true 需要结束回话
*/
public boolean checkAuthorize(Session session) {
String authorize = this.getParameters(session, ConfigBean.JPOM_AGENT_AUTHORIZE);
boolean ok = AgentAuthorize.getInstance().checkAuthorize(authorize);
if (!ok) {
try {
session.close(new CloseReason(CANNOT_ACCEPT, "授权信息错误"));
} catch (Exception e) {
DefaultSystemLog.getLog().error("socket 错误", e);
}
return false;
}
this.addUser(session, this.getParameters(session, "optUser"));
return true;
}
/**
* 添加用户监听的
*
* @param session session
* @param name 用户名
*/
private void addUser(Session session, String name) {
String optUser = URLUtil.decode(name); String optUser = URLUtil.decode(name);
USER.put(session.getId(), optUser); USER.put(session.getId(), optUser);
} }

View File

@ -1,23 +1,23 @@
package io.jpom.socket.spring; //package io.jpom.socket.spring;
//
import io.jpom.socket.spring.handler.NodeUpdateHandler; //import io.jpom.socket.spring.handler.NodeUpdateHandler;
import io.jpom.socket.spring.interceptor.NodeUpdateInterceptor; //import io.jpom.socket.spring.interceptor.NodeUpdateInterceptor;
import org.springframework.context.annotation.Configuration; //import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket; //import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer; //import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; //import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
//
/** ///**
* @author lf // * @author lf
*/ // */
@Configuration //@Configuration
@EnableWebSocket //@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer { //public class WebSocketConfig implements WebSocketConfigurer {
private final NodeUpdateInterceptor nodeUpdateInterceptor = new NodeUpdateInterceptor(); // private final NodeUpdateInterceptor nodeUpdateInterceptor = new NodeUpdateInterceptor();
//
@Override // @Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { // public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
// 节点升级 // // 节点升级
registry.addHandler(new NodeUpdateHandler(), "/node_update").addInterceptors(nodeUpdateInterceptor); // registry.addHandler(new NodeUpdateHandler(), "/node_update").addInterceptors(nodeUpdateInterceptor);
} // }
} //}

View File

@ -1,89 +1,66 @@
package io.jpom.socket.spring.handler; //package io.jpom.socket.spring.handler;
//
import cn.jiangzeyin.common.DefaultSystemLog; //import cn.jiangzeyin.common.DefaultSystemLog;
import com.alibaba.fastjson.JSONObject; //import com.alibaba.fastjson.JSONObject;
import io.jpom.JpomApplication; //import io.jpom.JpomApplication;
import io.jpom.common.JpomManifest; //import io.jpom.common.JpomManifest;
import io.jpom.model.AgentFileModel; //import io.jpom.model.AgentFileModel;
import io.jpom.model.WebSocketMessageModel; //import io.jpom.model.WebSocketMessageModel;
import io.jpom.model.data.UploadFileModel; //import io.jpom.model.data.UploadFileModel;
import io.jpom.system.AgentConfigBean; //import io.jpom.system.AgentConfigBean;
import org.springframework.web.socket.BinaryMessage; //import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.TextMessage; //import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession; //import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler; //import org.springframework.web.socket.handler.AbstractWebSocketHandler;
//
import java.util.HashMap; //import java.util.HashMap;
import java.util.Map; //import java.util.Map;
//
/** ///**
* 节点升级websocket处理器 // * 节点升级websocket处理器
* // *
* @author lf // * @author lf
*/ // */
public class NodeUpdateHandler extends AbstractWebSocketHandler { //public class NodeUpdateHandler extends AbstractWebSocketHandler {
private static final Map<String, UploadFileModel> UPLOAD_FILE_INFO = new HashMap<>(); // private static final Map<String, UploadFileModel> UPLOAD_FILE_INFO = new HashMap<>();
//
@Override // @Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception { // public void afterConnectionEstablished(WebSocketSession session) throws Exception {
// 设置二进制消息的最大长度为1M // // 设置二进制消息的最大长度为1M
session.setBinaryMessageSizeLimit(1024 * 1024); // session.setBinaryMessageSizeLimit(1024 * 1024);
} // }
//
@Override // @Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { // protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
WebSocketMessageModel model = WebSocketMessageModel.getInstance(message); //
switch (model.getCommand()) { // }
case "getVersion": //
model.setData(JSONObject.toJSONString(JpomManifest.getInstance())); // @Override
break; // protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) throws Exception {
case "upload": // UploadFileModel uploadFileModel = UPLOAD_FILE_INFO.get(session.getId());
AgentFileModel agentFileModel = ((JSONObject) model.getParams()).toJavaObject(AgentFileModel.class); // uploadFileModel.save(message.getPayload().array());
UploadFileModel uploadFileModel = new UploadFileModel(); // // 更新进度
uploadFileModel.setId(model.getNodeId()); // WebSocketMessageModel model = new WebSocketMessageModel("updateNode", uploadFileModel.getId());
uploadFileModel.setName(agentFileModel.getName()); // model.setData(uploadFileModel);
uploadFileModel.setSize(agentFileModel.getSize()); // session.sendMessage(new TextMessage(model.toString()));
uploadFileModel.setVersion(agentFileModel.getVersion()); // }
uploadFileModel.setSavePath(AgentConfigBean.getInstance().getTempPath().getAbsolutePath()); //
uploadFileModel.remove(); // /**
UPLOAD_FILE_INFO.put(session.getId(), uploadFileModel); // * 重启
break; // *
case "restart": // * @param session
model.setData(restart(session)); // * @return
break; // */
default: // public String restart(WebSocketSession session) {
break; // String result = "重启中";
} // try {
// UploadFileModel uploadFile = UPLOAD_FILE_INFO.get(session.getId());
session.sendMessage(new TextMessage(model.toString())); // JpomManifest.releaseJar(uploadFile.getFilePath(), uploadFile.getVersion(), true);
} // JpomApplication.restart();
// } catch (RuntimeException e) {
@Override // result = e.getMessage();
protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) throws Exception { // DefaultSystemLog.getLog().error("重启失败", e);
UploadFileModel uploadFileModel = UPLOAD_FILE_INFO.get(session.getId()); // }
uploadFileModel.save(message.getPayload().array()); // return result;
// 更新进度 // }
WebSocketMessageModel model = new WebSocketMessageModel("updateNode", uploadFileModel.getId()); //}
model.setData(uploadFileModel);
session.sendMessage(new TextMessage(model.toString()));
}
/**
* 重启
*
* @param session
* @return
*/
public String restart(WebSocketSession session) {
String result = "重启中";
try {
UploadFileModel uploadFile = UPLOAD_FILE_INFO.get(session.getId());
JpomManifest.releaseJar(uploadFile.getFilePath(), uploadFile.getVersion(), true);
JpomApplication.restart();
} catch (RuntimeException e) {
result = e.getMessage();
DefaultSystemLog.getLog().error("重启失败", e);
}
return result;
}
}

View File

@ -1,39 +1,39 @@
package io.jpom.socket.spring.interceptor; //package io.jpom.socket.spring.interceptor;
//
import cn.jiangzeyin.common.DefaultSystemLog; //import cn.jiangzeyin.common.DefaultSystemLog;
import io.jpom.system.AgentAuthorize; //import io.jpom.system.AgentAuthorize;
import org.springframework.http.server.ServerHttpRequest; //import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse; //import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest; //import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler; //import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor; //import org.springframework.web.socket.server.HandshakeInterceptor;
//
import javax.servlet.http.HttpServletRequest; //import javax.servlet.http.HttpServletRequest;
import java.util.Map; //import java.util.Map;
//
/** ///**
* @author lf // * @author lf
*/ // */
public class NodeUpdateInterceptor implements HandshakeInterceptor { //public class NodeUpdateInterceptor implements HandshakeInterceptor {
@Override // @Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception { // public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {
if (request instanceof ServletServerHttpRequest) { // if (request instanceof ServletServerHttpRequest) {
ServletServerHttpRequest serverHttpRequest = (ServletServerHttpRequest) request; // ServletServerHttpRequest serverHttpRequest = (ServletServerHttpRequest) request;
HttpServletRequest httpServletRequest = serverHttpRequest.getServletRequest(); // HttpServletRequest httpServletRequest = serverHttpRequest.getServletRequest();
// 判断用户 // // 判断用户
String name = httpServletRequest.getParameter("name"); // String name = httpServletRequest.getParameter("name");
String password = httpServletRequest.getParameter("password"); // String password = httpServletRequest.getParameter("password");
//
AgentAuthorize authorize = AgentAuthorize.getInstance(); // AgentAuthorize authorize = AgentAuthorize.getInstance();
return authorize.getAgentName().equals(name) && authorize.getAgentPwd().equals(password); // return authorize.getAgentName().equals(name) && authorize.getAgentPwd().equals(password);
} // }
return false; // return false;
} // }
//
@Override // @Override
public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception exception) { // public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception exception) {
if (exception != null) { // if (exception != null) {
DefaultSystemLog.getLog().error("afterHandshake", exception); // DefaultSystemLog.getLog().error("afterHandshake", exception);
} // }
} // }
} //}

View File

@ -1,7 +1,6 @@
package io.jpom.model; package io.jpom.model;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import org.springframework.web.socket.TextMessage;
/** /**
* websocket发送和接收消息Model * websocket发送和接收消息Model
@ -21,8 +20,8 @@ public class WebSocketMessageModel {
this.data = ""; this.data = "";
} }
public static WebSocketMessageModel getInstance(TextMessage message) { public static WebSocketMessageModel getInstance(String message) {
JSONObject commandObj = JSONObject.parseObject(message.getPayload()); JSONObject commandObj = JSONObject.parseObject(message);
String command = commandObj.getString("command"); String command = commandObj.getString("command");
String nodeId = commandObj.getString("nodeId"); String nodeId = commandObj.getString("nodeId");
WebSocketMessageModel model = new WebSocketMessageModel(command, nodeId); WebSocketMessageModel model = new WebSocketMessageModel(command, nodeId);

View File

@ -1,8 +1,11 @@
package io.jpom.common.forward; package io.jpom.common.forward;
import cn.hutool.core.net.URLEncoder; import cn.hutool.core.net.URLEncoder;
import cn.hutool.core.net.url.UrlQuery;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.CharsetUtil; import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.extra.servlet.ServletUtil; import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.*; import cn.hutool.http.*;
import cn.jiangzeyin.common.DefaultSystemLog; import cn.jiangzeyin.common.DefaultSystemLog;
@ -286,7 +289,7 @@ public class NodeForward {
httpRequest.header(ConfigBean.JPOM_SERVER_USER_NAME, URLEncoder.DEFAULT.encode(UserModel.getOptUserName(userModel), CharsetUtil.CHARSET_UTF_8)); httpRequest.header(ConfigBean.JPOM_SERVER_USER_NAME, URLEncoder.DEFAULT.encode(UserModel.getOptUserName(userModel), CharsetUtil.CHARSET_UTF_8));
// httpRequest.header(ConfigBean.JPOM_SERVER_SYSTEM_USER_ROLE, userModel.getUserRole(nodeModel).name()); // httpRequest.header(ConfigBean.JPOM_SERVER_SYSTEM_USER_ROLE, userModel.getUserRole(nodeModel).name());
} }
httpRequest.header(ConfigBean.JPOM_AGENT_AUTHORIZE, nodeModel.getAuthorize(true)); httpRequest.header(ConfigBean.JPOM_AGENT_AUTHORIZE, nodeModel.toAuthorize());
// //
int timeOut = nodeModel.getTimeOut(); int timeOut = nodeModel.getTimeOut();
if (nodeUrl.getTimeOut() != -1 && timeOut > 0) { if (nodeUrl.getTimeOut() != -1 && timeOut > 0) {
@ -303,14 +306,24 @@ public class NodeForward {
* @param nodeUrl url * @param nodeUrl url
* @return url * @return url
*/ */
public static String getSocketUrl(NodeModel nodeModel, NodeUrl nodeUrl) { public static String getSocketUrl(NodeModel nodeModel, NodeUrl nodeUrl, UserModel userInfo, Object... parameters) {
String ws; String ws;
if ("https".equalsIgnoreCase(nodeModel.getProtocol())) { if ("https".equalsIgnoreCase(nodeModel.getProtocol())) {
ws = "wss"; ws = "wss";
} else { } else {
ws = "ws"; ws = "ws";
} }
return StrUtil.format("{}://{}{}", ws, nodeModel.getUrl(), nodeUrl.getUrl()); UrlQuery urlQuery = new UrlQuery();
urlQuery.add(ConfigBean.JPOM_AGENT_AUTHORIZE, nodeModel.toAuthorize());
String optUser = UserModel.getOptUserName(userInfo);
optUser = URLUtil.encode(optUser);
urlQuery.add("optUser", optUser);
if (ArrayUtil.isNotEmpty(parameters)) {
for (int i = 0; i < parameters.length; i += 2) {
urlQuery.add(parameters[i].toString(), parameters[i + 1]);
}
}
return StrUtil.format("{}://{}?{}", ws, nodeModel.getUrl(), nodeUrl.getUrl(), urlQuery.toString());
} }
/** /**

View File

@ -3,13 +3,10 @@ package io.jpom.model.data;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil; import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.jpom.common.forward.NodeUrl; import io.jpom.common.forward.NodeUrl;
import io.jpom.model.BaseModel; import io.jpom.model.BaseModel;
import io.jpom.model.Cycle; import io.jpom.model.Cycle;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects; import java.util.Objects;
/** /**
@ -164,7 +161,12 @@ public class NodeModel extends BaseModel {
this.loginPwd = loginPwd; this.loginPwd = loginPwd;
} }
public String getAuthorize(boolean get) { /**
* 获取 授权的信息
*
* @return sha1
*/
public String toAuthorize() {
if (authorize == null) { if (authorize == null) {
authorize = SecureUtil.sha1(loginName + "@" + loginPwd); authorize = SecureUtil.sha1(loginName + "@" + loginPwd);
} }

View File

@ -1,7 +1,6 @@
package io.jpom.socket; package io.jpom.socket;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.jiangzeyin.common.spring.SpringUtil; import cn.jiangzeyin.common.spring.SpringUtil;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import io.jpom.common.forward.NodeForward; import io.jpom.common.forward.NodeForward;
@ -27,24 +26,29 @@ public abstract class BaseProxyHandler extends BaseHandler {
protected OperateLogController operateLogController; protected OperateLogController operateLogController;
private final NodeUrl nodeUrl; private final NodeUrl nodeUrl;
private final String dataParName;
public BaseProxyHandler(NodeUrl nodeUrl, String dataParName) { public BaseProxyHandler(NodeUrl nodeUrl) {
this.nodeUrl = nodeUrl; this.nodeUrl = nodeUrl;
this.dataParName = dataParName;
} }
/**
* 连接参数
*
* @param attributes 属性
* @return key, value, key, value.....
*/
protected abstract Object[] getParameters(Map<String, Object> attributes);
@Override @Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception { public void afterConnectionEstablished(WebSocketSession session) throws Exception {
Map<String, Object> attributes = session.getAttributes(); Map<String, Object> attributes = session.getAttributes();
NodeModel nodeModel = (NodeModel) attributes.get("nodeInfo"); NodeModel nodeModel = (NodeModel) attributes.get("nodeInfo");
UserModel userInfo = (UserModel) attributes.get("userInfo"); UserModel userInfo = (UserModel) attributes.get("userInfo");
String dataValue = (String) attributes.get(dataParName);
String userName = UserModel.getOptUserName(userInfo);
userName = URLUtil.encode(userName);
if (nodeModel != null) { if (nodeModel != null) {
String url = NodeForward.getSocketUrl(nodeModel, nodeUrl); Object[] parameters = this.getParameters(attributes);
url = StrUtil.format(url, dataValue, userName); String url = NodeForward.getSocketUrl(nodeModel, nodeUrl, userInfo, parameters);
// 连接节点 // 连接节点
ProxySession proxySession = new ProxySession(url, session); ProxySession proxySession = new ProxySession(url, session);
session.getAttributes().put("proxySession", proxySession); session.getAttributes().put("proxySession", proxySession);
@ -62,7 +66,7 @@ public abstract class BaseProxyHandler extends BaseHandler {
ProxySession proxySession = (ProxySession) attributes.get("proxySession"); ProxySession proxySession = (ProxySession) attributes.get("proxySession");
JSONObject json = JSONObject.parseObject(msg); JSONObject json = JSONObject.parseObject(msg);
String op = json.getString("op"); String op = json.getString("op");
ConsoleCommandOp consoleCommandOp = ConsoleCommandOp.valueOf(op); ConsoleCommandOp consoleCommandOp = StrUtil.isNotEmpty(op) ? ConsoleCommandOp.valueOf(op) : null;
if (proxySession != null) { if (proxySession != null) {
this.handleTextMessage(attributes, proxySession, json, consoleCommandOp); this.handleTextMessage(attributes, proxySession, json, consoleCommandOp);
} else { } else {
@ -70,11 +74,18 @@ public abstract class BaseProxyHandler extends BaseHandler {
} }
} }
/**
* 消息处理方法
*
* @param attributes 属性
* @param session 当前回话
* @param json 数据
* @param consoleCommandOp 操作类型
*/
protected void handleTextMessage(Map<String, Object> attributes, protected void handleTextMessage(Map<String, Object> attributes,
WebSocketSession session, WebSocketSession session,
JSONObject json, JSONObject json,
ConsoleCommandOp consoleCommandOp) throws IOException { ConsoleCommandOp consoleCommandOp) throws IOException {
} }
/** /**
@ -85,10 +96,11 @@ public abstract class BaseProxyHandler extends BaseHandler {
* @param json 数据 * @param json 数据
* @param consoleCommandOp 操作类型 * @param consoleCommandOp 操作类型
*/ */
protected abstract void handleTextMessage(Map<String, Object> attributes, protected void handleTextMessage(Map<String, Object> attributes,
ProxySession proxySession, ProxySession proxySession,
JSONObject json, JSONObject json,
ConsoleCommandOp consoleCommandOp); ConsoleCommandOp consoleCommandOp) {
}
protected OperateLogController.CacheInfo cacheInfo(Map<String, Object> attributes, JSONObject json, UserOperateLogV1.OptType optType, String dataId) { protected OperateLogController.CacheInfo cacheInfo(Map<String, Object> attributes, JSONObject json, UserOperateLogV1.OptType optType, String dataId) {
String ip = (String) attributes.get("ip"); String ip = (String) attributes.get("ip");

View File

@ -72,6 +72,7 @@ public class ServerWebSocketInterceptor implements HandshakeInterceptor {
if (roleService.errorDynamicPermission(userModel, ClassFeature.PROJECT, projectId)) { if (roleService.errorDynamicPermission(userModel, ClassFeature.PROJECT, projectId)) {
return false; return false;
} }
attributes.put("copyId", httpServletRequest.getParameter("copyId"));
attributes.put("projectId", projectId); attributes.put("projectId", projectId);
break; break;
case script: case script:

View File

@ -22,7 +22,12 @@ import java.util.Map;
public class ConsoleHandler extends BaseProxyHandler { public class ConsoleHandler extends BaseProxyHandler {
public ConsoleHandler() { public ConsoleHandler() {
super(NodeUrl.TopSocket, "projectId"); super(NodeUrl.TopSocket);
}
@Override
protected Object[] getParameters(Map<String, Object> attributes) {
return new Object[]{"projectId", attributes.get("projectId"), "copyId", attributes.get("copyId")};
} }
@Override @Override

View File

@ -3,7 +3,6 @@ package io.jpom.socket.handler;
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil; import cn.hutool.core.io.FileUtil;
import cn.hutool.core.thread.ThreadUtil; import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import cn.jiangzeyin.common.DefaultSystemLog; import cn.jiangzeyin.common.DefaultSystemLog;
import cn.jiangzeyin.common.spring.SpringUtil; import cn.jiangzeyin.common.spring.SpringUtil;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
@ -14,17 +13,21 @@ import io.jpom.model.AgentFileModel;
import io.jpom.model.WebSocketMessageModel; import io.jpom.model.WebSocketMessageModel;
import io.jpom.model.data.NodeModel; import io.jpom.model.data.NodeModel;
import io.jpom.model.data.NodeVersionModel; import io.jpom.model.data.NodeVersionModel;
import io.jpom.model.data.UserModel;
import io.jpom.service.node.AgentFileService; import io.jpom.service.node.AgentFileService;
import io.jpom.service.node.NodeService; import io.jpom.service.node.NodeService;
import io.jpom.socket.BaseHandler; import io.jpom.socket.BaseProxyHandler;
import io.jpom.socket.ConsoleCommandOp;
import io.jpom.socket.client.NodeClient; import io.jpom.socket.client.NodeClient;
import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.WebSocketSession;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentMap;
import java.util.jar.Attributes; import java.util.jar.Attributes;
@ -36,25 +39,35 @@ import java.util.jar.Manifest;
* *
* @author lf * @author lf
*/ */
public class NodeUpdateHandler extends BaseHandler { public class NodeUpdateHandler extends BaseProxyHandler {
private final ConcurrentMap<String, NodeClient> clientMap = new ConcurrentHashMap<>(); private final ConcurrentMap<String, NodeClient> clientMap = new ConcurrentHashMap<>();
private AgentFileService agentFileService; private AgentFileService agentFileService;
private NodeService nodeService; private NodeService nodeService;
public NodeUpdateHandler() {
super(null);
}
private void init() { private void init() {
agentFileService = SpringUtil.getBean(AgentFileService.class); agentFileService = SpringUtil.getBean(AgentFileService.class);
nodeService = SpringUtil.getBean(NodeService.class); nodeService = SpringUtil.getBean(NodeService.class);
} }
@Override
protected Object[] getParameters(Map<String, Object> attributes) {
return new Object[]{};
}
private void pullNodeList(WebSocketSession session) { private void pullNodeList(WebSocketSession session) {
List<NodeModel> nodeModelList = nodeService.list(); List<NodeModel> nodeModelList = nodeService.list();
for (NodeModel model : nodeModelList) { for (NodeModel model : nodeModelList) {
if (clientMap.containsKey(model.getId())) { if (clientMap.containsKey(model.getId())) {
continue; continue;
} }
String url = StrUtil.format("{}?name={}&password={}", NodeForward.getSocketUrl(model, NodeUrl.NodeUpdate), model.getLoginName(), model.getLoginPwd()); Map<String, Object> attributes = session.getAttributes();
String url = NodeForward.getSocketUrl(model, NodeUrl.NodeUpdate, (UserModel) attributes.get("userInfo"));
// 连接节点 // 连接节点
try { try {
NodeClient client = new NodeClient(url, model, session); NodeClient client = new NodeClient(url, model, session);
@ -74,11 +87,13 @@ public class NodeUpdateHandler extends BaseHandler {
} }
} }
clientMap.clear(); clientMap.clear();
//
super.destroy(session);
} }
@Override @Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { protected void handleTextMessage(Map<String, Object> attributes, WebSocketSession session, JSONObject json, ConsoleCommandOp consoleCommandOp) throws IOException {
WebSocketMessageModel model = WebSocketMessageModel.getInstance(message); WebSocketMessageModel model = WebSocketMessageModel.getInstance(json.toString());
this.init(); this.init();
boolean pull = false; boolean pull = false;
switch (model.getCommand()) { switch (model.getCommand()) {
@ -104,11 +119,6 @@ public class NodeUpdateHandler extends BaseHandler {
} }
} }
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) {
DefaultSystemLog.getLog().error("发生异常", exception);
}
/** /**
* 更新节点 * 更新节点
* *

View File

@ -21,7 +21,12 @@ import java.util.Map;
public class ScriptHandler extends BaseProxyHandler { public class ScriptHandler extends BaseProxyHandler {
public ScriptHandler() { public ScriptHandler() {
super(NodeUrl.Script_Run, "scriptId"); super(NodeUrl.Script_Run);
}
@Override
protected Object[] getParameters(Map<String, Object> attributes) {
return new Object[]{"id", attributes.get("scriptId")};
} }
@Override @Override

View File

@ -27,7 +27,12 @@ import java.util.Map;
public class TomcatHandler extends BaseProxyHandler { public class TomcatHandler extends BaseProxyHandler {
public TomcatHandler() { public TomcatHandler() {
super(NodeUrl.Tomcat_Socket, "tomcatId"); super(NodeUrl.Tomcat_Socket);
}
@Override
protected Object[] getParameters(Map<String, Object> attributes) {
return new Object[]{"tomcatId", attributes.get("tomcatId")};
} }
@Override @Override