Search in sources :

Example 6 with JsonMessage

use of cn.jiangzeyin.common.JsonMessage in project Jpom by dromara.

the class WhitelistDirectoryController method save.

// 
// private JsonMessage<String> save(String project, List<String> certificate, List<String> nginx, List<String> allowEditSuffixList) {
// 
// return save(list, certificate, nginx);
// }
private JsonMessage<String> save(List<String> projects, List<String> certificate, List<String> nginx, List<String> allowEditSuffixList, List<String> allowRemoteDownloadHostList) {
    List<String> projectArray;
    {
        projectArray = AgentWhitelist.covertToArray(projects, "项目路径白名单不能位于Jpom目录下");
        String error = findStartsWith(projectArray, 0);
        if (error != null) {
            return new JsonMessage<>(401, "白名单目录中不能存在包含关系:" + error);
        }
    }
    List<String> certificateArray = null;
    if (certificate != null && !certificate.isEmpty()) {
        certificateArray = AgentWhitelist.covertToArray(certificate, "证书路径白名单不能位于Jpom目录下");
        String error = findStartsWith(certificateArray, 0);
        if (error != null) {
            return new JsonMessage<>(401, "证书目录中不能存在包含关系:" + error);
        }
    }
    List<String> nginxArray = null;
    if (nginx != null && !nginx.isEmpty()) {
        nginxArray = AgentWhitelist.covertToArray(nginx, "nginx路径白名单不能位于Jpom目录下");
        String error = findStartsWith(nginxArray, 0);
        if (error != null) {
            return new JsonMessage<>(401, "nginx目录中不能存在包含关系:" + error);
        }
    }
    // 
    if (CollUtil.isNotEmpty(allowEditSuffixList)) {
        for (String s : allowEditSuffixList) {
            List<String> split = StrUtil.split(s, StrUtil.AT);
            if (split.size() > 1) {
                String last = CollUtil.getLast(split);
                try {
                    CharsetUtil.charset(last);
                } catch (Exception e) {
                    throw new IllegalArgumentException("配置的字符编码格式不合法:" + s);
                }
            }
        }
    }
    if (CollUtil.isNotEmpty(allowRemoteDownloadHostList)) {
        for (String s : allowRemoteDownloadHostList) {
            Assert.state(ReUtil.isMatch(RegexPool.URL_HTTP, s), "配置的远程地址不规范,请重新填写:" + s);
        }
    }
    AgentWhitelist agentWhitelist = whitelistDirectoryService.getWhitelist();
    agentWhitelist.setProject(projectArray);
    agentWhitelist.setCertificate(certificateArray);
    agentWhitelist.setNginx(nginxArray);
    agentWhitelist.setAllowEditSuffix(allowEditSuffixList);
    agentWhitelist.setAllowRemoteDownloadHost(allowRemoteDownloadHostList == null ? null : CollUtil.newHashSet(allowRemoteDownloadHostList));
    whitelistDirectoryService.saveWhitelistDirectory(agentWhitelist);
    return new JsonMessage<>(200, "保存成功");
}
Also used : JsonMessage(cn.jiangzeyin.common.JsonMessage) AgentWhitelist(io.jpom.model.data.AgentWhitelist)

Example 7 with JsonMessage

use of cn.jiangzeyin.common.JsonMessage in project Jpom by dromara.

the class MonitorItem method reqNodeStatus.

/**
 * 检查节点节点对信息
 *
 * @param nodeModel 节点
 * @param projects  项目
 * @return true 所有项目都正常
 */
private boolean reqNodeStatus(NodeModel nodeModel, List<String> projects) {
    if (projects == null || projects.isEmpty()) {
        return true;
    }
    List<Boolean> collect = projects.stream().map(id -> {
        // 
        String title;
        String context;
        try {
            // 查询项目运行状态
            JsonMessage<JSONObject> jsonMessage = NodeForward.requestBySys(nodeModel, NodeUrl.Manage_GetProjectStatus, "id", id, "getCopy", true);
            if (jsonMessage.getCode() == HttpStatus.HTTP_OK) {
                JSONObject jsonObject = jsonMessage.getData();
                int pid = jsonObject.getIntValue("pId");
                boolean runStatus = this.checkNotify(monitorModel, nodeModel, id, null, pid > 0);
                // 检查副本
                List<Boolean> booleanList = null;
                JSONArray copys = jsonObject.getJSONArray("copys");
                if (CollUtil.isNotEmpty(copys)) {
                    booleanList = copys.stream().map(o -> {
                        JSONObject jsonObject1 = (JSONObject) o;
                        String copyId = jsonObject1.getString("copyId");
                        boolean status = jsonObject1.getBooleanValue("status");
                        return MonitorItem.this.checkNotify(monitorModel, nodeModel, id, copyId, status);
                    }).filter(aBoolean -> !aBoolean).collect(Collectors.toList());
                }
                return runStatus && CollUtil.isEmpty(booleanList);
            } else {
                title = StrUtil.format("【{}】节点的状态码异常:{}", nodeModel.getName(), jsonMessage.getCode());
                context = jsonMessage.toString();
            }
        } catch (Exception e) {
            DefaultSystemLog.getLog().error("监控 {} 节点异常 {}", nodeModel.getName(), e.getMessage());
            // 
            title = StrUtil.format("【{}】节点的运行状态异常", nodeModel.getName());
            context = ExceptionUtil.stacktraceToString(e);
        }
        // 获取上次状态
        boolean pre = this.getPreStatus(monitorModel.getId(), nodeModel.getId(), id);
        if (pre) {
            // 上次正常
            MonitorNotifyLog monitorNotifyLog = new MonitorNotifyLog();
            monitorNotifyLog.setStatus(false);
            monitorNotifyLog.setTitle(title);
            monitorNotifyLog.setContent(context);
            monitorNotifyLog.setCreateTime(System.currentTimeMillis());
            monitorNotifyLog.setNodeId(nodeModel.getId());
            monitorNotifyLog.setProjectId(id);
            monitorNotifyLog.setMonitorId(monitorModel.getId());
            // 
            this.notifyMsg(nodeModel, monitorNotifyLog);
        }
        return false;
    }).filter(aBoolean -> !aBoolean).collect(Collectors.toList());
    return CollUtil.isEmpty(collect);
}
Also used : IPlugin(io.jpom.plugin.IPlugin) ExceptionUtil(cn.hutool.core.exceptions.ExceptionUtil) DefaultSystemLog(cn.jiangzeyin.common.DefaultSystemLog) IdUtil(cn.hutool.core.util.IdUtil) MonitorModel(io.jpom.model.data.MonitorModel) HashMap(java.util.HashMap) ProjectInfoCacheService(io.jpom.service.node.ProjectInfoCacheService) Order(cn.hutool.db.sql.Order) JsonMessage(cn.jiangzeyin.common.JsonMessage) JSONArray(com.alibaba.fastjson.JSONArray) ProjectInfoCacheModel(io.jpom.model.node.ProjectInfoCacheModel) NodeService(io.jpom.service.node.NodeService) Map(java.util.Map) PluginFactory(io.jpom.plugin.PluginFactory) NodeForward(io.jpom.common.forward.NodeForward) NodeModel(io.jpom.model.data.NodeModel) MonitorService(io.jpom.service.monitor.MonitorService) Direction(cn.hutool.db.sql.Direction) DbMonitorNotifyLogService(io.jpom.service.dblog.DbMonitorNotifyLogService) SpringUtil(cn.jiangzeyin.common.spring.SpringUtil) Collectors(java.util.stream.Collectors) NodeUrl(io.jpom.common.forward.NodeUrl) CollUtil(cn.hutool.core.collection.CollUtil) StrUtil(cn.hutool.core.util.StrUtil) List(java.util.List) Task(cn.hutool.cron.task.Task) JSONObject(com.alibaba.fastjson.JSONObject) MonitorNotifyLog(io.jpom.model.log.MonitorNotifyLog) ThreadUtil(cn.hutool.core.thread.ThreadUtil) UserModel(io.jpom.model.data.UserModel) UserService(io.jpom.service.user.UserService) HttpStatus(cn.hutool.http.HttpStatus) JSONObject(com.alibaba.fastjson.JSONObject) JSONArray(com.alibaba.fastjson.JSONArray) MonitorNotifyLog(io.jpom.model.log.MonitorNotifyLog)

Example 8 with JsonMessage

use of cn.jiangzeyin.common.JsonMessage in project Jpom by dromara.

the class ReleaseManage method diffSyncProject.

/**
 * 差异上传发布
 *
 * @param nodeModel 节点
 * @param projectId 项目ID
 * @param afterOpt  发布后的操作
 */
private void diffSyncProject(NodeModel nodeModel, String projectId, AfterOpt afterOpt, boolean clearOld) {
    File resultFile = this.resultFile;
    String resultFileParent = resultFile.isFile() ? FileUtil.getAbsolutePath(resultFile.getParent()) : FileUtil.getAbsolutePath(this.resultFile);
    // 
    List<File> files = FileUtil.loopFiles(resultFile);
    List<JSONObject> collect = files.stream().map(file -> {
        // 
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", StringUtil.delStartPath(file, resultFileParent, true));
        jsonObject.put("sha1", SecureUtil.sha1(file));
        return jsonObject;
    }).collect(Collectors.toList());
    // 
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("id", projectId);
    jsonObject.put("data", collect);
    JsonMessage<JSONObject> requestBody = NodeForward.requestBody(nodeModel, NodeUrl.MANAGE_FILE_DIFF_FILE, this.userModel, jsonObject);
    if (requestBody.getCode() != HttpStatus.HTTP_OK) {
        throw new JpomRuntimeException("对比项目文件失败:" + requestBody);
    }
    JSONObject data = requestBody.getData();
    JSONArray diff = data.getJSONArray("diff");
    JSONArray del = data.getJSONArray("del");
    int delSize = CollUtil.size(del);
    int diffSize = CollUtil.size(diff);
    if (clearOld) {
        logRecorder.info(StrUtil.format("对比文件结果,产物文件 {} 个、需要上传 {} 个、需要删除 {} 个", CollUtil.size(collect), CollUtil.size(diff), delSize));
    } else {
        logRecorder.info(StrUtil.format("对比文件结果,产物文件 {} 个、需要上传 {} 个", CollUtil.size(collect), CollUtil.size(diff)));
    }
    // 清空发布才先执行删除
    if (delSize > 0 && clearOld) {
        jsonObject.put("data", del);
        requestBody = NodeForward.requestBody(nodeModel, NodeUrl.MANAGE_FILE_BATCH_DELETE, this.userModel, jsonObject);
        if (requestBody.getCode() != HttpStatus.HTTP_OK) {
            throw new JpomRuntimeException("删除项目文件失败:" + requestBody);
        }
    }
    for (int i = 0; i < diffSize; i++) {
        boolean last = (i == diffSize - 1);
        JSONObject diffData = (JSONObject) diff.get(i);
        String name = diffData.getString("name");
        File file = FileUtil.file(resultFileParent, name);
        // 
        String startPath = StringUtil.delStartPath(file, resultFileParent, false);
        // 
        JsonMessage<String> jsonMessage = OutGivingRun.fileUpload(file, startPath, projectId, false, last ? afterOpt : AfterOpt.No, nodeModel, this.userModel, false);
        if (jsonMessage.getCode() != HttpStatus.HTTP_OK) {
            throw new JpomRuntimeException("同步项目文件失败:" + jsonMessage);
        }
        if (last) {
            // 最后一个
            logRecorder.info("发布项目包成功:" + jsonMessage);
        }
    }
}
Also used : DateUtil(cn.hutool.core.date.DateUtil) SecureUtil(cn.hutool.crypto.SecureUtil) DockerInfoService(io.jpom.service.docker.DockerInfoService) Map(java.util.Map) WorkspaceEnvVarService(io.jpom.service.system.WorkspaceEnvVarService) BetweenFormatter(cn.hutool.core.date.BetweenFormatter) Sftp(cn.hutool.extra.ssh.Sftp) NodeForward(io.jpom.common.forward.NodeForward) LineHandler(cn.hutool.core.io.LineHandler) SshService(io.jpom.service.node.ssh.SshService) NodeModel(io.jpom.model.data.NodeModel) AfterOpt(io.jpom.model.AfterOpt) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) Objects(java.util.Objects) StrUtil(cn.hutool.core.util.StrUtil) List(java.util.List) Builder(lombok.Builder) Session(com.jcraft.jsch.Session) ArrayUtil(cn.hutool.core.util.ArrayUtil) SshModel(io.jpom.model.data.SshModel) SystemClock(cn.hutool.core.date.SystemClock) CharPool(cn.hutool.core.text.CharPool) JSONObject(com.alibaba.fastjson.JSONObject) HttpStatus(cn.hutool.http.HttpStatus) IPlugin(io.jpom.plugin.IPlugin) CommandUtil(io.jpom.util.CommandUtil) ResourceUtil(cn.hutool.core.io.resource.ResourceUtil) LogRecorder(io.jpom.util.LogRecorder) BuildReleaseMethod(io.jpom.model.enums.BuildReleaseMethod) FileUtils(io.jpom.util.FileUtils) JschUtil(cn.hutool.extra.ssh.JschUtil) JpomRuntimeException(io.jpom.system.JpomRuntimeException) JsonMessage(cn.jiangzeyin.common.JsonMessage) JSONArray(com.alibaba.fastjson.JSONArray) BaseEnum(io.jpom.model.BaseEnum) NodeService(io.jpom.service.node.NodeService) OutGivingRun(io.jpom.outgiving.OutGivingRun) PluginFactory(io.jpom.plugin.PluginFactory) IoUtil(cn.hutool.core.io.IoUtil) DockerInfoModel(io.jpom.model.docker.DockerInfoModel) SpringUtil(cn.jiangzeyin.common.spring.SpringUtil) DockerSwarmInfoService(io.jpom.service.docker.DockerSwarmInfoService) File(java.io.File) NodeUrl(io.jpom.common.forward.NodeUrl) Consumer(java.util.function.Consumer) CollUtil(cn.hutool.core.collection.CollUtil) StringUtil(io.jpom.util.StringUtil) ConfigBean(io.jpom.system.ConfigBean) FileUtil(cn.hutool.core.io.FileUtil) UserModel(io.jpom.model.data.UserModel) BuildStatus(io.jpom.model.enums.BuildStatus) InputStream(java.io.InputStream) JSONObject(com.alibaba.fastjson.JSONObject) JpomRuntimeException(io.jpom.system.JpomRuntimeException) JSONArray(com.alibaba.fastjson.JSONArray) File(java.io.File)

Example 9 with JsonMessage

use of cn.jiangzeyin.common.JsonMessage in project Jpom by dromara.

the class DbBuildHistoryLogService method deleteLogAndFile.

/**
 * 清理文件并删除记录
 *
 * @param buildHistoryLog 构建记录
 * @return json
 */
public JsonMessage<String> deleteLogAndFile(BuildHistoryLog buildHistoryLog) {
    if (buildHistoryLog == null) {
        return new JsonMessage<>(405, "没有对应构建记录");
    }
    BuildInfoModel item = buildService.getByKey(buildHistoryLog.getBuildDataId());
    if (item != null) {
        File logFile = BuildUtil.getLogFile(item.getId(), buildHistoryLog.getBuildNumberId());
        if (logFile != null) {
            File dataFile = logFile.getParentFile();
            if (dataFile.exists()) {
                boolean s = FileUtil.del(dataFile);
                if (!s) {
                    return new JsonMessage<>(500, "清理文件失败");
                }
            }
        }
    }
    int count = this.delByKey(buildHistoryLog.getId());
    return new JsonMessage<>(200, "删除成功", count + "");
}
Also used : JsonMessage(cn.jiangzeyin.common.JsonMessage) File(java.io.File) BuildInfoModel(io.jpom.model.data.BuildInfoModel)

Example 10 with JsonMessage

use of cn.jiangzeyin.common.JsonMessage in project Jpom by dromara.

the class AutoRegSeverNode method reg.

/**
 * 向服务端注册插件端
 */
@PreLoadMethod
private static void reg() {
    AgentExtConfigBean instance = AgentExtConfigBean.getInstance();
    String agentId = instance.getAgentId();
    String serverUrl = instance.getServerUrl();
    if (StrUtil.isEmpty(agentId) || StrUtil.isEmpty(serverUrl)) {
        // 如果二者缺一不注册
        return;
    }
    String oldInstallId = null;
    File file = FileUtil.file(ConfigBean.getInstance().getDataPath(), AgentConfigBean.SERVER_ID);
    JSONObject serverJson = null;
    if (file.exists()) {
        try {
            serverJson = (JSONObject) JsonFileUtil.readJson(file.getAbsolutePath());
        } catch (FileNotFoundException e) {
            serverJson = new JSONObject();
        }
        oldInstallId = serverJson.getString("installId");
    }
    HttpRequest installRequest = instance.createServerRequest(ServerOpenApi.INSTALL_ID);
    String body1 = installRequest.execute().body();
    JsonMessage jsonMessage = JSON.parseObject(body1, JsonMessage.class);
    if (jsonMessage.getCode() != HttpStatus.HTTP_OK) {
        DefaultSystemLog.getLog().error("获取Server 安装id失败:" + jsonMessage);
        return;
    }
    String installId = jsonMessage.dataToString();
    boolean eqInstall = StrUtil.equals(oldInstallId, installId);
    // 
    URL url = URLUtil.toUrlForHttp(instance.getAgentUrl());
    String protocol = url.getProtocol();
    HttpRequest serverRequest = instance.createServerRequest(ServerOpenApi.UPDATE_NODE_INFO);
    serverRequest.form("id", agentId);
    serverRequest.form("name", "节点:" + agentId);
    serverRequest.form("openStatus", 1);
    serverRequest.form("protocol", protocol);
    serverRequest.form("url", url.getHost() + CharPool.COLON + url.getPort());
    AgentAuthorize agentAuthorize = AgentAuthorize.getInstance();
    serverRequest.form("loginName", agentAuthorize.getAgentName());
    serverRequest.form("loginPwd", agentAuthorize.getAgentPwd());
    serverRequest.form("type", eqInstall ? "update" : "add");
    String body = serverRequest.execute().body();
    DefaultSystemLog.getLog().info("自动注册Server:" + body);
    JsonMessage regJsonMessage = JSON.parseObject(body, JsonMessage.class);
    if (regJsonMessage.getCode() == HttpStatus.HTTP_OK) {
        if (serverJson == null) {
            serverJson = new JSONObject();
        }
        if (!eqInstall) {
            serverJson.put("installId", installId);
            serverJson.put("regTime", DateTime.now().toString());
        } else {
            serverJson.put("updateTime", DateTime.now().toString());
        }
        JsonFileUtil.saveJson(file.getAbsolutePath(), serverJson);
    } else {
        DefaultSystemLog.getLog().error("自动注册插件端失败:{}", body);
    }
}
Also used : HttpRequest(cn.hutool.http.HttpRequest) JSONObject(com.alibaba.fastjson.JSONObject) AgentAuthorize(io.jpom.system.AgentAuthorize) JsonMessage(cn.jiangzeyin.common.JsonMessage) FileNotFoundException(java.io.FileNotFoundException) AgentExtConfigBean(io.jpom.system.AgentExtConfigBean) File(java.io.File) URL(java.net.URL) PreLoadMethod(cn.jiangzeyin.common.PreLoadMethod)

Aggregations

JsonMessage (cn.jiangzeyin.common.JsonMessage)15 JSONObject (com.alibaba.fastjson.JSONObject)8 StrUtil (cn.hutool.core.util.StrUtil)3 JSONArray (com.alibaba.fastjson.JSONArray)3 BuildInfoModel (io.jpom.model.data.BuildInfoModel)3 UserModel (io.jpom.model.data.UserModel)3 DockerInfoModel (io.jpom.model.docker.DockerInfoModel)3 ClassFeature (io.jpom.permission.ClassFeature)3 Feature (io.jpom.permission.Feature)3 MethodFeature (io.jpom.permission.MethodFeature)3 File (java.io.File)3 CollUtil (cn.hutool.core.collection.CollUtil)2 HttpStatus (cn.hutool.http.HttpStatus)2 DefaultSystemLog (cn.jiangzeyin.common.DefaultSystemLog)2 SpringUtil (cn.jiangzeyin.common.spring.SpringUtil)2 NodeForward (io.jpom.common.forward.NodeForward)2 NodeUrl (io.jpom.common.forward.NodeUrl)2 BaseEnum (io.jpom.model.BaseEnum)2 UserService (io.jpom.service.user.UserService)2 IOException (java.io.IOException)2