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,8 +12,9 @@ import org.springframework.web.socket.server.standard.ServerEndpointExporter;
*/
@Configuration
public class AgentWebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}

View File

@ -15,7 +15,6 @@ import io.jpom.util.SocketSessionUtil;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.File;
import java.io.IOException;
@ -26,175 +25,183 @@ import java.io.IOException;
* @author jiangzeyin
* @date 2019/4/16
*/
@ServerEndpoint(value = "/console/{projectId}/{optUser}")
@ServerEndpoint(value = "/console")
@Component
public class AgentWebSocketConsoleHandle extends BaseAgentWebSocketHandle {
private static ProjectInfoService projectInfoService;
private static ProjectInfoService projectInfoService;
@OnOpen
public void onOpen(Session session) {
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 (projectInfoService == null) {
projectInfoService = SpringUtil.getBean(ProjectInfoService.class);
}
ProjectInfoModel projectInfoModel = this.checkProject(projectId, copyId, session);
if (projectInfoModel == null) {
return;
}
//
SocketSessionUtil.send(session, "连接成功:" + projectInfoModel.getName());
}
} catch (Exception e) {
DefaultSystemLog.getLog().error("socket 错误", e);
try {
SocketSessionUtil.send(session, JsonMessage.getString(500, "系统错误!"));
session.close();
} catch (IOException e1) {
DefaultSystemLog.getLog().error(e1.getMessage(), e1);
}
}
}
@OnOpen
public void onOpen(@PathParam("projectId") String projectId, @PathParam("optUser") String urlOptUser, @PathParam("copyId") String copyId, Session session) {
try {
// 判断项目
if (!JpomApplication.SYSTEM_ID.equals(projectId)) {
if (projectInfoService == null) {
projectInfoService = SpringUtil.getBean(ProjectInfoService.class);
}
ProjectInfoModel projectInfoModel = this.checkProject(projectId, copyId, session);
}
this.addUser(session, urlOptUser);
} catch (Exception e) {
DefaultSystemLog.getLog().error("socket 错误", e);
try {
SocketSessionUtil.send(session, JsonMessage.getString(500, "系统错误!"));
session.close();
} catch (IOException e1) {
DefaultSystemLog.getLog().error(e1.getMessage(), e1);
}
}
}
/**
* 静默消息不做过多处理
*
* @param consoleCommandOp 操作
* @param session 回话
* @return true
*/
private boolean silentMsg(ConsoleCommandOp consoleCommandOp, Session session) {
if (consoleCommandOp == ConsoleCommandOp.heart) {
return true;
}
/**
* 静默消息不做过多处理
*
* @param consoleCommandOp 操作
* @param session 回话
* @return true
*/
private boolean silentMsg(ConsoleCommandOp consoleCommandOp, Session session) {
if (consoleCommandOp == ConsoleCommandOp.heart) {
return true;
}
// if (consoleCommandOp == ConsoleCommandOp.top) {
// TopManager.addMonitor(session);
// return true;
// }
return false;
}
return false;
}
private ProjectInfoModel checkProject(String projectId, String copyId, Session session) throws IOException {
ProjectInfoModel projectInfoModel = projectInfoService.getItem(projectId);
if (projectInfoModel == null) {
SocketSessionUtil.send(session, "没有对应项目");
session.close();
return null;
}
// 判断副本集
if (StrUtil.isNotEmpty(copyId)) {
ProjectInfoModel.JavaCopyItem copyItem = projectInfoModel.findCopyItem(copyId);
if (copyItem == null) {
SocketSessionUtil.send(session, "获取项目信息错误,没有对应副本:" + copyId);
session.close();
return null;
}
}
return projectInfoModel;
}
private ProjectInfoModel checkProject(String projectId, String copyId, Session session) throws IOException {
ProjectInfoModel projectInfoModel = projectInfoService.getItem(projectId);
if (projectInfoModel == null) {
SocketSessionUtil.send(session, "没有对应项目");
session.close();
return null;
}
// 判断副本集
if (StrUtil.isNotEmpty(copyId)) {
ProjectInfoModel.JavaCopyItem copyItem = projectInfoModel.findCopyItem(copyId);
if (copyItem == null) {
SocketSessionUtil.send(session, "获取项目信息错误,没有对应副本:" + copyId);
session.close();
return null;
}
}
return projectInfoModel;
}
@OnMessage
public void onMessage(String message, Session session) throws Exception {
JSONObject json = JSONObject.parseObject(message);
String op = json.getString("op");
ConsoleCommandOp consoleCommandOp = ConsoleCommandOp.valueOf(op);
if (silentMsg(consoleCommandOp, session)) {
return;
}
String projectId = json.getString("projectId");
String copyId = json.getString("copyId");
ProjectInfoModel projectInfoModel = this.checkProject(projectId, copyId, session);
if (projectInfoModel == null) {
return;
}
runMsg(consoleCommandOp, session, projectInfoModel, copyId, json);
}
@OnMessage
public void onMessage(String message, Session session) throws Exception {
JSONObject json = JSONObject.parseObject(message);
String op = json.getString("op");
ConsoleCommandOp consoleCommandOp = ConsoleCommandOp.valueOf(op);
if (silentMsg(consoleCommandOp, session)) {
return;
}
String projectId = json.getString("projectId");
String copyId = json.getString("copyId");
ProjectInfoModel projectInfoModel = this.checkProject(projectId, copyId, session);
if (projectInfoModel == null) {
return;
}
runMsg(consoleCommandOp, session, projectInfoModel, copyId, json);
}
private void runMsg(ConsoleCommandOp consoleCommandOp, Session session, ProjectInfoModel projectInfoModel, String copyId, JSONObject reqJson) throws Exception {
ConsoleService consoleService = SpringUtil.getBean(ConsoleService.class);
//
ProjectInfoModel.JavaCopyItem copyItem = projectInfoModel.findCopyItem(copyId);
JSONObject resultData = null;
String strResult;
boolean logUser = false;
try {
// 执行相应命令
switch (consoleCommandOp) {
case start:
case restart:
logUser = true;
strResult = consoleService.execCommand(consoleCommandOp, projectInfoModel, copyItem);
if (strResult.contains(AbstractProjectCommander.RUNNING_TAG)) {
resultData = JsonMessage.toJson(200, "操作成功:" + strResult);
} else {
resultData = JsonMessage.toJson(400, strResult);
}
break;
case stop:
logUser = true;
// 停止项目
strResult = consoleService.execCommand(consoleCommandOp, projectInfoModel, copyItem);
if (strResult.contains(AbstractProjectCommander.STOP_TAG)) {
resultData = JsonMessage.toJson(200, "操作成功");
} else {
resultData = JsonMessage.toJson(500, strResult);
}
break;
case status:
// 获取项目状态
strResult = consoleService.execCommand(consoleCommandOp, projectInfoModel, copyItem);
if (strResult.contains(AbstractProjectCommander.RUNNING_TAG)) {
resultData = JsonMessage.toJson(200, "运行中", strResult);
} else {
resultData = JsonMessage.toJson(404, "未运行", strResult);
}
break;
case showlog: {
// 进入管理页面后需要实时加载日志
// 日志文件路径
File file = copyItem == null ? new File(projectInfoModel.getLog()) : projectInfoModel.getLog(copyItem);
try {
AgentFileTailWatcher.addWatcher(file, session);
} catch (IOException io) {
DefaultSystemLog.getLog().error("监听日志变化", io);
SocketSessionUtil.send(session, io.getMessage());
}
break;
}
default:
resultData = JsonMessage.toJson(404, "不支持的方式:" + consoleCommandOp.name());
break;
}
} catch (Exception e) {
DefaultSystemLog.getLog().error("执行命令失败", e);
SocketSessionUtil.send(session, "执行命令失败,详情如下:");
SocketSessionUtil.send(session, ExceptionUtil.stacktraceToString(e));
return;
} finally {
if (logUser) {
// 记录操作人
ProjectInfoModel newProjectInfoModel = projectInfoService.getItem(projectInfoModel.getId());
String name = getOptUserName(session);
newProjectInfoModel.setModifyUser(name);
projectInfoService.updateItem(newProjectInfoModel);
}
}
// 返回数据
if (resultData != null) {
reqJson.putAll(resultData);
DefaultSystemLog.getLog().info(reqJson.toString());
SocketSessionUtil.send(session, reqJson.toString());
}
}
private void runMsg(ConsoleCommandOp consoleCommandOp, Session session, ProjectInfoModel projectInfoModel, String copyId, JSONObject reqJson) throws Exception {
ConsoleService consoleService = SpringUtil.getBean(ConsoleService.class);
//
ProjectInfoModel.JavaCopyItem copyItem = projectInfoModel.findCopyItem(copyId);
JSONObject resultData = null;
String strResult;
boolean logUser = false;
try {
// 执行相应命令
switch (consoleCommandOp) {
case start:
case restart:
logUser = true;
strResult = consoleService.execCommand(consoleCommandOp, projectInfoModel, copyItem);
if (strResult.contains(AbstractProjectCommander.RUNNING_TAG)) {
resultData = JsonMessage.toJson(200, "操作成功:" + strResult);
} else {
resultData = JsonMessage.toJson(400, strResult);
}
break;
case stop:
logUser = true;
// 停止项目
strResult = consoleService.execCommand(consoleCommandOp, projectInfoModel, copyItem);
if (strResult.contains(AbstractProjectCommander.STOP_TAG)) {
resultData = JsonMessage.toJson(200, "操作成功");
} else {
resultData = JsonMessage.toJson(500, strResult);
}
break;
case status:
// 获取项目状态
strResult = consoleService.execCommand(consoleCommandOp, projectInfoModel, copyItem);
if (strResult.contains(AbstractProjectCommander.RUNNING_TAG)) {
resultData = JsonMessage.toJson(200, "运行中", strResult);
} else {
resultData = JsonMessage.toJson(404, "未运行", strResult);
}
break;
case showlog: {
// 进入管理页面后需要实时加载日志
// 日志文件路径
File file = copyItem == null ? new File(projectInfoModel.getLog()) : projectInfoModel.getLog(copyItem);
try {
AgentFileTailWatcher.addWatcher(file, session);
} catch (IOException io) {
DefaultSystemLog.getLog().error("监听日志变化", io);
SocketSessionUtil.send(session, io.getMessage());
}
break;
}
default:
resultData = JsonMessage.toJson(404, "不支持的方式:" + consoleCommandOp.name());
break;
}
} catch (Exception e) {
DefaultSystemLog.getLog().error("执行命令失败", e);
SocketSessionUtil.send(session, "执行命令失败,详情如下:");
SocketSessionUtil.send(session, ExceptionUtil.stacktraceToString(e));
return;
} finally {
if (logUser) {
// 记录操作人
ProjectInfoModel newProjectInfoModel = projectInfoService.getItem(projectInfoModel.getId());
String name = getOptUserName(session);
newProjectInfoModel.setModifyUser(name);
projectInfoService.updateItem(newProjectInfoModel);
}
}
// 返回数据
if (resultData != null) {
reqJson.putAll(resultData);
DefaultSystemLog.getLog().info(reqJson.toString());
SocketSessionUtil.send(session, reqJson.toString());
}
}
@Override
@OnClose
public void onClose(Session session) {
super.onClose(session);
}
@Override
@OnClose
public void onClose(Session session) {
super.onClose(session);
}
@OnError
@Override
public void onError(Session session, Throwable thr) {
super.onError(session, thr);
}
@OnError
@Override
public void onError(Session session, Throwable thr) {
super.onError(session, thr);
}
}

View File

@ -11,7 +11,6 @@ import io.jpom.util.SocketSessionUtil;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
@ -21,86 +20,89 @@ import java.io.IOException;
* @author jiangzeyin
* @date 2019/4/24
*/
@ServerEndpoint(value = "/script_run/{id}/{optUser}")
@ServerEndpoint(value = "/script_run")
@Component
public class AgentWebSocketScriptHandle extends BaseAgentWebSocketHandle {
private ScriptServer scriptServer;
private ScriptServer scriptServer;
@OnOpen
public void onOpen(@PathParam("id") String id, Session session, @PathParam("optUser") String urlOptUser) {
if (scriptServer == null) {
scriptServer = SpringUtil.getBean(ScriptServer.class);
}
try {
if (StrUtil.isEmpty(id)) {
SocketSessionUtil.send(session, "脚本模板未知");
return;
}
ScriptModel scriptModel = scriptServer.getItem(id);
if (scriptModel == null) {
SocketSessionUtil.send(session, "没有找到对应的脚本模板");
return;
}
SocketSessionUtil.send(session, "连接成功:" + scriptModel.getName());
this.addUser(session, urlOptUser);
} catch (Exception e) {
DefaultSystemLog.getLog().error("socket 错误", e);
try {
SocketSessionUtil.send(session, JsonMessage.getString(500, "系统错误!"));
session.close();
} catch (IOException e1) {
DefaultSystemLog.getLog().error(e1.getMessage(), e1);
}
}
}
@OnOpen
public void onOpen(Session session) {
if (scriptServer == null) {
scriptServer = SpringUtil.getBean(ScriptServer.class);
}
try {
if (super.checkAuthorize(session)) {
return;
}
String id = this.getParameters(session, "id");
if (StrUtil.isEmpty(id)) {
SocketSessionUtil.send(session, "脚本模板未知");
return;
}
ScriptModel scriptModel = scriptServer.getItem(id);
if (scriptModel == null) {
SocketSessionUtil.send(session, "没有找到对应的脚本模板");
return;
}
SocketSessionUtil.send(session, "连接成功:" + scriptModel.getName());
} catch (Exception e) {
DefaultSystemLog.getLog().error("socket 错误", e);
try {
SocketSessionUtil.send(session, JsonMessage.getString(500, "系统错误!"));
session.close();
} catch (IOException e1) {
DefaultSystemLog.getLog().error(e1.getMessage(), e1);
}
}
}
@OnMessage
public void onMessage(String message, Session session) throws Exception {
JSONObject json = JSONObject.parseObject(message);
String scriptId = json.getString("scriptId");
ScriptModel scriptModel = scriptServer.getItem(scriptId);
if (scriptModel == null) {
SocketSessionUtil.send(session, "没有对应脚本模板:" + scriptId);
session.close();
return;
}
String op = json.getString("op");
ConsoleCommandOp consoleCommandOp = ConsoleCommandOp.valueOf(op);
switch (consoleCommandOp) {
case start:
String args = json.getString("args");
ScriptProcessBuilder.addWatcher(scriptModel, args, session);
break;
case stop:
ScriptProcessBuilder.stopRun(scriptModel);
break;
case heart:
default:
return;
}
// 记录操作人
scriptModel = scriptServer.getItem(scriptId);
String name = getOptUserName(session);
scriptModel.setLastRunUser(name);
scriptServer.updateItem(scriptModel);
json.put("code", 200);
json.put("msg", "执行成功");
DefaultSystemLog.getLog().info(json.toString());
SocketSessionUtil.send(session, json.toString());
}
@OnMessage
public void onMessage(String message, Session session) throws Exception {
JSONObject json = JSONObject.parseObject(message);
String scriptId = json.getString("scriptId");
ScriptModel scriptModel = scriptServer.getItem(scriptId);
if (scriptModel == null) {
SocketSessionUtil.send(session, "没有对应脚本模板:" + scriptId);
session.close();
return;
}
String op = json.getString("op");
ConsoleCommandOp consoleCommandOp = ConsoleCommandOp.valueOf(op);
switch (consoleCommandOp) {
case start:
String args = json.getString("args");
ScriptProcessBuilder.addWatcher(scriptModel, args, session);
break;
case stop:
ScriptProcessBuilder.stopRun(scriptModel);
break;
case heart:
default:
return;
}
// 记录操作人
scriptModel = scriptServer.getItem(scriptId);
String name = getOptUserName(session);
scriptModel.setLastRunUser(name);
scriptServer.updateItem(scriptModel);
json.put("code", 200);
json.put("msg", "执行成功");
DefaultSystemLog.getLog().info(json.toString());
SocketSessionUtil.send(session, json.toString());
}
@Override
@OnClose
public void onClose(Session session) {
super.onClose(session);
ScriptProcessBuilder.stopWatcher(session);
}
@Override
@OnClose
public void onClose(Session session) {
super.onClose(session);
ScriptProcessBuilder.stopWatcher(session);
}
@OnError
@Override
public void onError(Session session, Throwable thr) {
super.onError(session, thr);
}
@OnError
@Override
public void onError(Session session, Throwable thr) {
super.onError(session, thr);
}
}

View File

@ -14,7 +14,6 @@ import io.jpom.util.SocketSessionUtil;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.File;
import java.io.IOException;
@ -27,112 +26,116 @@ import java.util.concurrent.ConcurrentHashMap;
* @author jiangzeyin
* @date 2019/4/16
*/
@ServerEndpoint(value = "/tomcat_log/{tomcatId}/{optUser}")
@ServerEndpoint(value = "/tomcat_log")
@Component
public class AgentWebSocketTomcatHandle extends BaseAgentWebSocketHandle {
private TomcatEditService tomcatEditService;
private TomcatEditService tomcatEditService;
private static final Map<String, File> CACHE_FILE = new ConcurrentHashMap<>();
private static final Map<String, File> CACHE_FILE = new ConcurrentHashMap<>();
@OnOpen
public void onOpen(@PathParam("tomcatId") String tomcatId, @PathParam("optUser") String urlOptUser, Session session) {
try {
if (tomcatEditService == null) {
tomcatEditService = SpringUtil.getBean(TomcatEditService.class);
}
TomcatInfoModel tomcatInfoModel = tomcatEditService.getItem(tomcatId);
if (tomcatInfoModel == null && !JpomApplication.SYSTEM_ID.equalsIgnoreCase(tomcatId)) {
SocketSessionUtil.send(session, "获取tomcat信息错误");
session.close();
return;
}
this.addUser(session, urlOptUser);
} catch (Exception e) {
DefaultSystemLog.getLog().error("socket 错误", e);
try {
SocketSessionUtil.send(session, JsonMessage.getString(500, "系统错误!"));
session.close();
} catch (IOException e1) {
DefaultSystemLog.getLog().error(e1.getMessage(), e1);
}
}
}
@OnOpen
public void onOpen(Session session) {
try {
if (super.checkAuthorize(session)) {
return;
}
String tomcatId = super.getParameters(session, "tomcatId");
if (tomcatEditService == null) {
tomcatEditService = SpringUtil.getBean(TomcatEditService.class);
}
TomcatInfoModel tomcatInfoModel = tomcatEditService.getItem(tomcatId);
if (tomcatInfoModel == null && !JpomApplication.SYSTEM_ID.equalsIgnoreCase(tomcatId)) {
SocketSessionUtil.send(session, "获取tomcat信息错误");
session.close();
return;
}
SocketSessionUtil.send(session, "连接成功:" + (tomcatInfoModel == null ? "" : tomcatInfoModel.getName()));
} catch (Exception e) {
DefaultSystemLog.getLog().error("socket 错误", e);
try {
SocketSessionUtil.send(session, JsonMessage.getString(500, "系统错误!"));
session.close();
} catch (IOException e1) {
DefaultSystemLog.getLog().error(e1.getMessage(), e1);
}
}
}
@OnMessage
public void onMessage(String message, Session session) throws Exception {
JSONObject json = JSONObject.parseObject(message);
String op = json.getString("op");
ConsoleCommandOp consoleCommandOp = ConsoleCommandOp.valueOf(op);
if (consoleCommandOp == ConsoleCommandOp.heart) {
return;
}
String tomcatId = json.getString("tomcatId");
if (JpomApplication.SYSTEM_ID.equalsIgnoreCase(tomcatId)) {
runMsg(session, json);
} else {
TomcatInfoModel tomcatInfoModel = tomcatEditService.getItem(tomcatId);
if (tomcatInfoModel == null) {
SocketSessionUtil.send(session, "没有对应tomcat");
session.close();
return;
}
runMsg(session, tomcatInfoModel, json);
}
}
@OnMessage
public void onMessage(String message, Session session) throws Exception {
JSONObject json = JSONObject.parseObject(message);
String op = json.getString("op");
ConsoleCommandOp consoleCommandOp = ConsoleCommandOp.valueOf(op);
if (consoleCommandOp == ConsoleCommandOp.heart) {
return;
}
String tomcatId = json.getString("tomcatId");
if (JpomApplication.SYSTEM_ID.equalsIgnoreCase(tomcatId)) {
runMsg(session, json);
} else {
TomcatInfoModel tomcatInfoModel = tomcatEditService.getItem(tomcatId);
if (tomcatInfoModel == null) {
SocketSessionUtil.send(session, "没有对应tomcat");
session.close();
return;
}
runMsg(session, tomcatInfoModel, json);
}
}
private void runMsg(Session session, JSONObject reqJson) throws Exception {
try {
String fileName = reqJson.getString("fileName");
WebAopLog webAopLog = SpringUtil.getBean(WebAopLog.class);
// 进入管理页面后需要实时加载日志
File file = FileUtil.file(webAopLog.getPropertyValue(), fileName);
File file1 = CACHE_FILE.get(session.getId());
if (file1 != null && !file1.equals(file)) {
// 离线上一个日志
AgentFileTailWatcher.offlineFile(file, session);
}
try {
AgentFileTailWatcher.addWatcher(file, session);
CACHE_FILE.put(session.getId(), file);
} catch (IOException io) {
DefaultSystemLog.getLog().error("监听日志变化", io);
SocketSessionUtil.send(session, io.getMessage());
}
} catch (Exception e) {
DefaultSystemLog.getLog().error("执行命令失败", e);
SocketSessionUtil.send(session, "执行命令失败,详情如下:");
SocketSessionUtil.send(session, ExceptionUtil.stacktraceToString(e));
}
}
private void runMsg(Session session, JSONObject reqJson) throws Exception {
try {
String fileName = reqJson.getString("fileName");
WebAopLog webAopLog = SpringUtil.getBean(WebAopLog.class);
// 进入管理页面后需要实时加载日志
File file = FileUtil.file(webAopLog.getPropertyValue(), fileName);
File file1 = CACHE_FILE.get(session.getId());
if (file1 != null && !file1.equals(file)) {
// 离线上一个日志
AgentFileTailWatcher.offlineFile(file, session);
}
try {
AgentFileTailWatcher.addWatcher(file, session);
CACHE_FILE.put(session.getId(), file);
} catch (IOException io) {
DefaultSystemLog.getLog().error("监听日志变化", io);
SocketSessionUtil.send(session, io.getMessage());
}
} catch (Exception e) {
DefaultSystemLog.getLog().error("执行命令失败", e);
SocketSessionUtil.send(session, "执行命令失败,详情如下:");
SocketSessionUtil.send(session, ExceptionUtil.stacktraceToString(e));
}
}
private void runMsg(Session session, TomcatInfoModel tomcatInfoModel, JSONObject reqJson) throws Exception {
try {
String fileName = reqJson.getString("fileName");
// 进入管理页面后需要实时加载日志
File file = FileUtil.file(tomcatInfoModel.getPath(), "logs", fileName);
try {
AgentFileTailWatcher.addWatcher(file, session);
} catch (IOException io) {
DefaultSystemLog.getLog().error("监听日志变化", io);
SocketSessionUtil.send(session, io.getMessage());
}
} catch (Exception e) {
DefaultSystemLog.getLog().error("执行命令失败", e);
SocketSessionUtil.send(session, "执行命令失败,详情如下:");
SocketSessionUtil.send(session, ExceptionUtil.stacktraceToString(e));
}
}
private void runMsg(Session session, TomcatInfoModel tomcatInfoModel, JSONObject reqJson) throws Exception {
try {
String fileName = reqJson.getString("fileName");
// 进入管理页面后需要实时加载日志
File file = FileUtil.file(tomcatInfoModel.getPath(), "logs", fileName);
try {
AgentFileTailWatcher.addWatcher(file, session);
} catch (IOException io) {
DefaultSystemLog.getLog().error("监听日志变化", io);
SocketSessionUtil.send(session, io.getMessage());
}
} catch (Exception e) {
DefaultSystemLog.getLog().error("执行命令失败", e);
SocketSessionUtil.send(session, "执行命令失败,详情如下:");
SocketSessionUtil.send(session, ExceptionUtil.stacktraceToString(e));
}
}
@Override
@OnClose
public void onClose(Session session) {
super.onClose(session);
}
@Override
@OnClose
public void onClose(Session session) {
super.onClose(session);
}
@OnError
@Override
public void onError(Session session, Throwable thr) {
super.onError(session, thr);
}
@OnError
@Override
public void onError(Session session, Throwable thr) {
super.onError(session, thr);
}
}

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;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.jiangzeyin.common.DefaultSystemLog;
import io.jpom.system.AgentAuthorize;
import io.jpom.system.ConfigBean;
import io.jpom.util.SocketSessionUtil;
import javax.websocket.CloseReason;
import javax.websocket.Session;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import static javax.websocket.CloseReason.CloseCodes.CANNOT_ACCEPT;
/**
* 插件端socket 基类
*
@ -18,36 +26,69 @@ import java.util.concurrent.ConcurrentHashMap;
*/
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) {
String optUser = URLUtil.decode(name);
USER.put(session.getId(), optUser);
}
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);
}
public void onError(Session session, Throwable thr) {
// java.io.IOException: Broken pipe
try {
SocketSessionUtil.send(session, "服务端发生异常" + ExceptionUtil.stacktraceToString(thr));
} catch (IOException ignored) {
}
DefaultSystemLog.getLog().error(session.getId() + "socket 异常", thr);
}
/**
* 判断授权信息是否正确
*
* @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;
}
protected String getOptUserName(Session session) {
String name = USER.get(session.getId());
return StrUtil.emptyToDefault(name, StrUtil.DASHED);
}
/**
* 添加用户监听的
*
* @param session session
* @param name 用户名
*/
private void addUser(Session session, String name) {
String optUser = URLUtil.decode(name);
USER.put(session.getId(), optUser);
}
public void onClose(Session session) {
// 清理日志监听
try {
AgentFileTailWatcher.offline(session);
} catch (Exception e) {
DefaultSystemLog.getLog().error("关闭异常", e);
}
// top
// TopManager.removeMonitor(session);
USER.remove(session.getId());
}
public void onError(Session session, Throwable thr) {
// java.io.IOException: Broken pipe
try {
SocketSessionUtil.send(session, "服务端发生异常" + ExceptionUtil.stacktraceToString(thr));
} catch (IOException ignored) {
}
DefaultSystemLog.getLog().error(session.getId() + "socket 异常", thr);
}
protected String getOptUserName(Session session) {
String name = USER.get(session.getId());
return StrUtil.emptyToDefault(name, StrUtil.DASHED);
}
public void onClose(Session session) {
// 清理日志监听
try {
AgentFileTailWatcher.offline(session);
} catch (Exception e) {
DefaultSystemLog.getLog().error("关闭异常", e);
}
// top
// TopManager.removeMonitor(session);
USER.remove(session.getId());
}
}

View File

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

View File

@ -1,89 +1,66 @@
package io.jpom.socket.spring.handler;
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 org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;
import java.util.HashMap;
import java.util.Map;
/**
* 节点升级websocket处理器
*
* @author lf
*/
public class NodeUpdateHandler extends AbstractWebSocketHandler {
private static final Map<String, UploadFileModel> UPLOAD_FILE_INFO = new HashMap<>();
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
// 设置二进制消息的最大长度为1M
session.setBinaryMessageSizeLimit(1024 * 1024);
}
@Override
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()));
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;
}
session.sendMessage(new TextMessage(model.toString()));
}
@Override
protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) throws Exception {
UploadFileModel uploadFileModel = UPLOAD_FILE_INFO.get(session.getId());
uploadFileModel.save(message.getPayload().array());
// 更新进度
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;
}
}
//package io.jpom.socket.spring.handler;
//
//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 org.springframework.web.socket.BinaryMessage;
//import org.springframework.web.socket.TextMessage;
//import org.springframework.web.socket.WebSocketSession;
//import org.springframework.web.socket.handler.AbstractWebSocketHandler;
//
//import java.util.HashMap;
//import java.util.Map;
//
///**
// * 节点升级websocket处理器
// *
// * @author lf
// */
//public class NodeUpdateHandler extends AbstractWebSocketHandler {
// private static final Map<String, UploadFileModel> UPLOAD_FILE_INFO = new HashMap<>();
//
// @Override
// public void afterConnectionEstablished(WebSocketSession session) throws Exception {
// // 设置二进制消息的最大长度为1M
// session.setBinaryMessageSizeLimit(1024 * 1024);
// }
//
// @Override
// protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
//
// }
//
// @Override
// protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) throws Exception {
// UploadFileModel uploadFileModel = UPLOAD_FILE_INFO.get(session.getId());
// uploadFileModel.save(message.getPayload().array());
// // 更新进度
// 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;
import cn.jiangzeyin.common.DefaultSystemLog;
import io.jpom.system.AgentAuthorize;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
/**
* @author lf
*/
public class NodeUpdateInterceptor implements HandshakeInterceptor {
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {
if (request instanceof ServletServerHttpRequest) {
ServletServerHttpRequest serverHttpRequest = (ServletServerHttpRequest) request;
HttpServletRequest httpServletRequest = serverHttpRequest.getServletRequest();
// 判断用户
String name = httpServletRequest.getParameter("name");
String password = httpServletRequest.getParameter("password");
AgentAuthorize authorize = AgentAuthorize.getInstance();
return authorize.getAgentName().equals(name) && authorize.getAgentPwd().equals(password);
}
return false;
}
@Override
public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception exception) {
if (exception != null) {
DefaultSystemLog.getLog().error("afterHandshake", exception);
}
}
}
//package io.jpom.socket.spring.interceptor;
//
//import cn.jiangzeyin.common.DefaultSystemLog;
//import io.jpom.system.AgentAuthorize;
//import org.springframework.http.server.ServerHttpRequest;
//import org.springframework.http.server.ServerHttpResponse;
//import org.springframework.http.server.ServletServerHttpRequest;
//import org.springframework.web.socket.WebSocketHandler;
//import org.springframework.web.socket.server.HandshakeInterceptor;
//
//import javax.servlet.http.HttpServletRequest;
//import java.util.Map;
//
///**
// * @author lf
// */
//public class NodeUpdateInterceptor implements HandshakeInterceptor {
// @Override
// public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {
// if (request instanceof ServletServerHttpRequest) {
// ServletServerHttpRequest serverHttpRequest = (ServletServerHttpRequest) request;
// HttpServletRequest httpServletRequest = serverHttpRequest.getServletRequest();
// // 判断用户
// String name = httpServletRequest.getParameter("name");
// String password = httpServletRequest.getParameter("password");
//
// AgentAuthorize authorize = AgentAuthorize.getInstance();
// return authorize.getAgentName().equals(name) && authorize.getAgentPwd().equals(password);
// }
// return false;
// }
//
// @Override
// public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception exception) {
// if (exception != null) {
// DefaultSystemLog.getLog().error("afterHandshake", exception);
// }
// }
//}

View File

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

View File

@ -1,8 +1,11 @@
package io.jpom.common.forward;
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.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.*;
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_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();
if (nodeUrl.getTimeOut() != -1 && timeOut > 0) {
@ -303,14 +306,24 @@ public class NodeForward {
* @param nodeUrl 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;
if ("https".equalsIgnoreCase(nodeModel.getProtocol())) {
ws = "wss";
} else {
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.crypto.SecureUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.jpom.common.forward.NodeUrl;
import io.jpom.model.BaseModel;
import io.jpom.model.Cycle;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/**
@ -20,85 +17,85 @@ import java.util.Objects;
*/
public class NodeModel extends BaseModel {
private String url;
private String loginName;
private String loginPwd;
/**
* 节点协议
*/
private String protocol = "http";
private String url;
private String loginName;
private String loginPwd;
/**
* 节点协议
*/
private String protocol = "http";
private String authorize;
/**
* 项目信息 临时信息
*/
private JSONArray projects;
/**
* 开启状态如果关闭状态就暂停使用节点
*/
private boolean openStatus;
/**
* 节点超时时间
*/
private int timeOut;
/**
* 绑定的sshId
*/
private String sshId;
private String authorize;
/**
* 项目信息 临时信息
*/
private JSONArray projects;
/**
* 开启状态如果关闭状态就暂停使用节点
*/
private boolean openStatus;
/**
* 节点超时时间
*/
private int timeOut;
/**
* 绑定的sshId
*/
private String sshId;
/**
* 节点分组
*/
private String group;
/**
* 节点分组
*/
private String group;
/**
* 监控周期
*/
private int cycle = Cycle.none.getCode();
/**
* 监控周期
*/
private int cycle = Cycle.none.getCode();
public int getCycle() {
return cycle;
}
public int getCycle() {
return cycle;
}
public void setCycle(int cycle) {
this.cycle = cycle;
}
public void setCycle(int cycle) {
this.cycle = cycle;
}
public String getGroup() {
return StrUtil.emptyToDefault(group, "默认");
}
public String getGroup() {
return StrUtil.emptyToDefault(group, "默认");
}
public void setGroup(String group) {
this.group = group;
}
public void setGroup(String group) {
this.group = group;
}
public String getSshId() {
return sshId;
}
public String getSshId() {
return sshId;
}
public void setSshId(String sshId) {
this.sshId = sshId;
}
public void setSshId(String sshId) {
this.sshId = sshId;
}
public int getTimeOut() {
return timeOut;
}
public int getTimeOut() {
return timeOut;
}
public void setTimeOut(int timeOut) {
this.timeOut = timeOut;
}
public void setTimeOut(int timeOut) {
this.timeOut = timeOut;
}
public boolean isOpenStatus() {
return openStatus;
}
public boolean isOpenStatus() {
return openStatus;
}
public void setOpenStatus(boolean openStatus) {
this.openStatus = openStatus;
}
public void setOpenStatus(boolean openStatus) {
this.openStatus = openStatus;
}
public JSONArray getProjects() {
return projects;
}
public JSONArray getProjects() {
return projects;
}
//
// /**
// * 返回按照项目分组 排列的数组
@ -128,74 +125,79 @@ public class NodeModel extends BaseModel {
// return newArray;
// }
public void setProjects(JSONArray projects) {
this.projects = projects;
}
public void setProjects(JSONArray projects) {
this.projects = projects;
}
public String getProtocol() {
return protocol;
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol.toLowerCase();
}
public void setProtocol(String protocol) {
this.protocol = protocol.toLowerCase();
}
public String getUrl() {
return url;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public void setUrl(String url) {
this.url = url;
}
public String getLoginName() {
return loginName;
}
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public String getLoginPwd() {
return loginPwd;
}
public String getLoginPwd() {
return loginPwd;
}
public void setLoginPwd(String loginPwd) {
this.loginPwd = loginPwd;
}
public void setLoginPwd(String loginPwd) {
this.loginPwd = loginPwd;
}
public String getAuthorize(boolean get) {
if (authorize == null) {
authorize = SecureUtil.sha1(loginName + "@" + loginPwd);
}
return authorize;
}
/**
* 获取 授权的信息
*
* @return sha1
*/
public String toAuthorize() {
if (authorize == null) {
authorize = SecureUtil.sha1(loginName + "@" + loginPwd);
}
return authorize;
}
public String getRealUrl(NodeUrl nodeUrl) {
return StrUtil.format("{}://{}{}", getProtocol(), getUrl(), nodeUrl.getUrl());
}
public String getRealUrl(NodeUrl nodeUrl) {
return StrUtil.format("{}://{}{}", getProtocol(), getUrl(), nodeUrl.getUrl());
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
NodeModel nodeModel = (NodeModel) o;
return openStatus == nodeModel.openStatus &&
timeOut == nodeModel.timeOut &&
Objects.equals(url, nodeModel.url) &&
Objects.equals(loginName, nodeModel.loginName) &&
Objects.equals(loginPwd, nodeModel.loginPwd) &&
Objects.equals(protocol, nodeModel.protocol) &&
Objects.equals(authorize, nodeModel.authorize) &&
Objects.equals(projects, nodeModel.projects);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
NodeModel nodeModel = (NodeModel) o;
return openStatus == nodeModel.openStatus &&
timeOut == nodeModel.timeOut &&
Objects.equals(url, nodeModel.url) &&
Objects.equals(loginName, nodeModel.loginName) &&
Objects.equals(loginPwd, nodeModel.loginPwd) &&
Objects.equals(protocol, nodeModel.protocol) &&
Objects.equals(authorize, nodeModel.authorize) &&
Objects.equals(projects, nodeModel.projects);
}
@Override
public int hashCode() {
return Objects.hash(url, loginName, loginPwd, protocol, authorize, projects, openStatus, timeOut);
}
@Override
public int hashCode() {
return Objects.hash(url, loginName, loginPwd, protocol, authorize, projects, openStatus, timeOut);
}
}

View File

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

View File

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

View File

@ -21,40 +21,45 @@ import java.util.Map;
*/
public class ConsoleHandler extends BaseProxyHandler {
public ConsoleHandler() {
super(NodeUrl.TopSocket, "projectId");
}
public ConsoleHandler() {
super(NodeUrl.TopSocket);
}
@Override
protected void handleTextMessage(Map<String, Object> attributes, ProxySession proxySession, JSONObject json, ConsoleCommandOp consoleCommandOp) {
UserOperateLogV1.OptType type = null;
switch (consoleCommandOp) {
case stop:
type = UserOperateLogV1.OptType.Stop;
break;
case start:
type = UserOperateLogV1.OptType.Start;
break;
case restart:
type = UserOperateLogV1.OptType.Restart;
break;
default:
break;
}
if (type != null) {
// 记录操作日志
UserModel userInfo = (UserModel) attributes.get("userInfo");
String reqId = IdUtil.fastUUID();
json.put("reqId", reqId);
//
String projectId = (String) attributes.get("projectId");
OperateLogController.CacheInfo cacheInfo = cacheInfo(attributes, json, type, projectId);
try {
operateLogController.log(reqId, userInfo, "还没有响应", cacheInfo);
} catch (Exception e) {
DefaultSystemLog.getLog().error("记录操作日志异常", e);
}
}
proxySession.send(json.toString());
}
@Override
protected Object[] getParameters(Map<String, Object> attributes) {
return new Object[]{"projectId", attributes.get("projectId"), "copyId", attributes.get("copyId")};
}
@Override
protected void handleTextMessage(Map<String, Object> attributes, ProxySession proxySession, JSONObject json, ConsoleCommandOp consoleCommandOp) {
UserOperateLogV1.OptType type = null;
switch (consoleCommandOp) {
case stop:
type = UserOperateLogV1.OptType.Stop;
break;
case start:
type = UserOperateLogV1.OptType.Start;
break;
case restart:
type = UserOperateLogV1.OptType.Restart;
break;
default:
break;
}
if (type != null) {
// 记录操作日志
UserModel userInfo = (UserModel) attributes.get("userInfo");
String reqId = IdUtil.fastUUID();
json.put("reqId", reqId);
//
String projectId = (String) attributes.get("projectId");
OperateLogController.CacheInfo cacheInfo = cacheInfo(attributes, json, type, projectId);
try {
operateLogController.log(reqId, userInfo, "还没有响应", cacheInfo);
} catch (Exception e) {
DefaultSystemLog.getLog().error("记录操作日志异常", e);
}
}
proxySession.send(json.toString());
}
}

View File

@ -3,7 +3,6 @@ package io.jpom.socket.handler;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import cn.jiangzeyin.common.DefaultSystemLog;
import cn.jiangzeyin.common.spring.SpringUtil;
import com.alibaba.fastjson.JSONArray;
@ -14,17 +13,21 @@ import io.jpom.model.AgentFileModel;
import io.jpom.model.WebSocketMessageModel;
import io.jpom.model.data.NodeModel;
import io.jpom.model.data.NodeVersionModel;
import io.jpom.model.data.UserModel;
import io.jpom.service.node.AgentFileService;
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 org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.jar.Attributes;
@ -36,25 +39,35 @@ import java.util.jar.Manifest;
*
* @author lf
*/
public class NodeUpdateHandler extends BaseHandler {
public class NodeUpdateHandler extends BaseProxyHandler {
private final ConcurrentMap<String, NodeClient> clientMap = new ConcurrentHashMap<>();
private AgentFileService agentFileService;
private NodeService nodeService;
public NodeUpdateHandler() {
super(null);
}
private void init() {
agentFileService = SpringUtil.getBean(AgentFileService.class);
nodeService = SpringUtil.getBean(NodeService.class);
}
@Override
protected Object[] getParameters(Map<String, Object> attributes) {
return new Object[]{};
}
private void pullNodeList(WebSocketSession session) {
List<NodeModel> nodeModelList = nodeService.list();
for (NodeModel model : nodeModelList) {
if (clientMap.containsKey(model.getId())) {
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 {
NodeClient client = new NodeClient(url, model, session);
@ -74,11 +87,13 @@ public class NodeUpdateHandler extends BaseHandler {
}
}
clientMap.clear();
//
super.destroy(session);
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
WebSocketMessageModel model = WebSocketMessageModel.getInstance(message);
protected void handleTextMessage(Map<String, Object> attributes, WebSocketSession session, JSONObject json, ConsoleCommandOp consoleCommandOp) throws IOException {
WebSocketMessageModel model = WebSocketMessageModel.getInstance(json.toString());
this.init();
boolean pull = false;
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

@ -20,35 +20,40 @@ import java.util.Map;
*/
public class ScriptHandler extends BaseProxyHandler {
public ScriptHandler() {
super(NodeUrl.Script_Run, "scriptId");
}
public ScriptHandler() {
super(NodeUrl.Script_Run);
}
@Override
protected void handleTextMessage(Map<String, Object> attributes, ProxySession proxySession, JSONObject json, ConsoleCommandOp consoleCommandOp) {
UserOperateLogV1.OptType type = null;
switch (consoleCommandOp) {
case stop:
type = UserOperateLogV1.OptType.Script_Stop;
break;
case start:
type = UserOperateLogV1.OptType.Script_Start;
break;
default:
break;
}
if (type != null) {
// 记录操作日志
UserModel userInfo = (UserModel) attributes.get("userInfo");
//
String scriptId = (String) attributes.get("scriptId");
OperateLogController.CacheInfo cacheInfo = cacheInfo(attributes, json, type, scriptId);
try {
operateLogController.log(userInfo, "脚本模板执行...", cacheInfo);
} catch (Exception e) {
DefaultSystemLog.getLog().error("记录操作日志异常", e);
}
}
proxySession.send(json.toString());
}
@Override
protected Object[] getParameters(Map<String, Object> attributes) {
return new Object[]{"id", attributes.get("scriptId")};
}
@Override
protected void handleTextMessage(Map<String, Object> attributes, ProxySession proxySession, JSONObject json, ConsoleCommandOp consoleCommandOp) {
UserOperateLogV1.OptType type = null;
switch (consoleCommandOp) {
case stop:
type = UserOperateLogV1.OptType.Script_Stop;
break;
case start:
type = UserOperateLogV1.OptType.Script_Start;
break;
default:
break;
}
if (type != null) {
// 记录操作日志
UserModel userInfo = (UserModel) attributes.get("userInfo");
//
String scriptId = (String) attributes.get("scriptId");
OperateLogController.CacheInfo cacheInfo = cacheInfo(attributes, json, type, scriptId);
try {
operateLogController.log(userInfo, "脚本模板执行...", cacheInfo);
} catch (Exception e) {
DefaultSystemLog.getLog().error("记录操作日志异常", e);
}
}
proxySession.send(json.toString());
}
}

View File

@ -26,46 +26,51 @@ import java.util.Map;
*/
public class TomcatHandler extends BaseProxyHandler {
public TomcatHandler() {
super(NodeUrl.Tomcat_Socket, "tomcatId");
}
public TomcatHandler() {
super(NodeUrl.Tomcat_Socket);
}
@Override
protected void handleTextMessage(Map<String, Object> attributes, WebSocketSession session, JSONObject json, ConsoleCommandOp consoleCommandOp) throws IOException {
String tomcatId = (String) attributes.get("tomcatId");
String fileName = json.getString("fileName");
if (!JpomApplication.SYSTEM_ID.equals(tomcatId) && consoleCommandOp == ConsoleCommandOp.heart) {
// 服务端心跳
return;
}
if (consoleCommandOp == ConsoleCommandOp.showlog && JpomApplication.SYSTEM_ID.equals(tomcatId)) {
WebAopLog webAopLog = SpringUtil.getBean(WebAopLog.class);
// 进入管理页面后需要实时加载日志
File file = FileUtil.file(webAopLog.getPropertyValue(), fileName);
//
File nowFile = (File) attributes.get("nowFile");
if (nowFile != null && !nowFile.equals(file)) {
// 离线上一个日志
ServiceFileTailWatcher.offlineFile(file, session);
}
try {
ServiceFileTailWatcher.addWatcher(file, session);
attributes.put("nowFile", file);
} catch (Exception io) {
DefaultSystemLog.getLog().error("监听日志变化", io);
SocketSessionUtil.send(session, io.getMessage());
}
}
}
@Override
protected Object[] getParameters(Map<String, Object> attributes) {
return new Object[]{"tomcatId", attributes.get("tomcatId")};
}
@Override
protected void handleTextMessage(Map<String, Object> attributes, ProxySession proxySession, JSONObject json, ConsoleCommandOp consoleCommandOp) {
proxySession.send(json.toString());
}
@Override
protected void handleTextMessage(Map<String, Object> attributes, WebSocketSession session, JSONObject json, ConsoleCommandOp consoleCommandOp) throws IOException {
String tomcatId = (String) attributes.get("tomcatId");
String fileName = json.getString("fileName");
if (!JpomApplication.SYSTEM_ID.equals(tomcatId) && consoleCommandOp == ConsoleCommandOp.heart) {
// 服务端心跳
return;
}
if (consoleCommandOp == ConsoleCommandOp.showlog && JpomApplication.SYSTEM_ID.equals(tomcatId)) {
WebAopLog webAopLog = SpringUtil.getBean(WebAopLog.class);
// 进入管理页面后需要实时加载日志
File file = FileUtil.file(webAopLog.getPropertyValue(), fileName);
//
File nowFile = (File) attributes.get("nowFile");
if (nowFile != null && !nowFile.equals(file)) {
// 离线上一个日志
ServiceFileTailWatcher.offlineFile(file, session);
}
try {
ServiceFileTailWatcher.addWatcher(file, session);
attributes.put("nowFile", file);
} catch (Exception io) {
DefaultSystemLog.getLog().error("监听日志变化", io);
SocketSessionUtil.send(session, io.getMessage());
}
}
}
@Override
public void destroy(WebSocketSession session) {
super.destroy(session);
ServiceFileTailWatcher.offline(session);
}
@Override
protected void handleTextMessage(Map<String, Object> attributes, ProxySession proxySession, JSONObject json, ConsoleCommandOp consoleCommandOp) {
proxySession.send(json.toString());
}
@Override
public void destroy(WebSocketSession session) {
super.destroy(session);
ServiceFileTailWatcher.offline(session);
}
}