Search in sources :

Example 1 with JsonMessage

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

the class JpomManifest method checkJpomJar.

/**
 * 检查是否为jpom包
 *
 * @param path        路径
 * @param type        类型
 * @param checkRepeat 是否检查版本重复
 * @return 结果消息
 * @see Type#getApplicationClass()
 */
public static JsonMessage<Tuple> checkJpomJar(String path, Type type, boolean checkRepeat) {
    File jarFile = new File(path);
    Tuple jarVersion = getJarVersion(jarFile);
    if (jarVersion == null) {
        return new JsonMessage<>(405, "jar 包文件不合法");
    }
    try (JarFile jarFile1 = new JarFile(jarFile)) {
        // Manifest manifest = jarFile1.getManifest();
        // Attributes attributes = manifest.getMainAttributes();
        String mainClass = jarVersion.get(2);
        if (mainClass == null) {
            return new JsonMessage<>(405, "清单文件中没有找到对应的MainClass属性");
        }
        try (JarClassLoader jarClassLoader = JarClassLoader.load(jarFile)) {
            jarClassLoader.loadClass(mainClass);
        } catch (ClassNotFoundException notFound) {
            return new JsonMessage<>(405, "中没有找到对应的MainClass:" + mainClass);
        }
        String applicationClass = type.getApplicationClass();
        ZipEntry entry = jarFile1.getEntry(StrUtil.format("BOOT-INF/classes/{}.class", StrUtil.replace(applicationClass, ".", StrUtil.SLASH)));
        if (entry == null) {
            return new JsonMessage<>(405, "此包不是Jpom【" + type.name() + "】包");
        }
        String version = jarVersion.get(0);
        String timeStamp = jarVersion.get(1);
        String minVersion = jarVersion.get(4);
        if (StrUtil.hasEmpty(version, timeStamp, minVersion)) {
            return new JsonMessage<>(405, "此包没有版本号、打包时间、最小兼容版本");
        }
        if (checkRepeat) {
            // 
            JpomManifest jpomManifest = JpomManifest.getInstance();
            if (StrUtil.equals(version, jpomManifest.getVersion()) && StrUtil.equals(timeStamp, jpomManifest.getTimeStamp())) {
                return new JsonMessage<>(405, "新包和正在运行的包一致");
            }
            if (StrUtil.compareVersion(jpomManifest.getVersion(), minVersion) < 0) {
                return new JsonMessage<>(405, StrUtil.format("当前程序版本 {} 新版程序最低兼容 {} 不能直接升级", jpomManifest.getVersion(), minVersion));
            }
        }
    } catch (Exception e) {
        DefaultSystemLog.getLog().error("解析jar", e);
        return new JsonMessage<>(500, " 解析错误:" + e.getMessage());
    }
    return new JsonMessage<>(200, "", jarVersion);
}
Also used : JsonMessage(cn.jiangzeyin.common.JsonMessage) ZipEntry(java.util.zip.ZipEntry) JarFile(java.util.jar.JarFile) JarFile(java.util.jar.JarFile) ZipFile(java.util.zip.ZipFile) File(java.io.File) Tuple(cn.hutool.core.lang.Tuple) JpomRuntimeException(io.jpom.system.JpomRuntimeException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) JarClassLoader(cn.hutool.core.lang.JarClassLoader)

Example 2 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 3 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 4 with JsonMessage

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

the class ScriptProcessBuilder method run.

@Override
public void run() {
    // 初始化ProcessBuilder对象
    try {
        this.handle("start execute:" + DateUtil.now());
        process = processBuilder.start();
        {
            inputStream = process.getInputStream();
            IoUtil.readLines(inputStream, ExtConfigBean.getInstance().getConsoleLogCharset(), (LineHandler) ScriptProcessBuilder.this::handle);
        }
        int waitFor = process.waitFor();
        JsonMessage<String> jsonMessage = new JsonMessage<>(200, "执行完毕:" + waitFor);
        JSONObject jsonObject = jsonMessage.toJson();
        jsonObject.put("op", ConsoleCommandOp.stop.name());
        this.end(jsonObject.toString());
        this.handle("execute done:" + waitFor + " time:" + DateUtil.now());
    } catch (Exception e) {
        DefaultSystemLog.getLog().error("执行异常", e);
        this.end("执行异常:" + e.getMessage());
    } finally {
        this.close();
    }
}
Also used : JSONObject(com.alibaba.fastjson.JSONObject) JsonMessage(cn.jiangzeyin.common.JsonMessage) IOException(java.io.IOException)

Example 5 with JsonMessage

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

the class BuildTriggerApiController method triggerBatch.

/**
 * 构建触发器
 * <p>
 * 参数 <code>[
 * {
 * "id":"1",
 * "token":"a",
 * "delay":"0"
 * }
 * ]</code>
 * <p>
 * 响应 <code>[
 * {
 * "id":"1",
 * "token":"a",
 * "delay":"0",
 * "msg":"开始构建",
 * "data":1
 * }
 * ]</code>
 *
 * @return json
 */
@PostMapping(value = ServerOpenApi.BUILD_TRIGGER_BUILD_BATCH, produces = MediaType.APPLICATION_JSON_VALUE)
public String triggerBatch() {
    try {
        String body = ServletUtil.getBody(getRequest());
        JSONArray jsonArray = JSONArray.parseArray(body);
        List<Object> collect = jsonArray.stream().peek(o -> {
            JSONObject jsonObject = (JSONObject) o;
            String id = jsonObject.getString("id");
            String token = jsonObject.getString("token");
            Integer delay = jsonObject.getInteger("delay");
            String buildRemark = jsonObject.getString("buildRemark");
            BuildInfoModel item = buildInfoService.getByKey(id);
            if (item == null) {
                jsonObject.put("msg", "没有对应数据");
                return;
            }
            UserModel userModel = BuildTriggerApiController.this.getByUrlToken(token);
            if (userModel == null) {
                jsonObject.put("msg", "对应的用户不存在,触发器已失效");
                return;
            }
            // 
            if (!StrUtil.equals(token, item.getTriggerToken())) {
                jsonObject.put("msg", "触发token错误,或者已经失效");
                return;
            }
            // 更新字段
            String updateItemErrorMsg = this.updateItem(jsonObject);
            if (updateItemErrorMsg != null) {
                jsonObject.put("msg", updateItemErrorMsg);
                return;
            }
            BaseServerController.resetInfo(userModel);
            // 
            JsonMessage<Integer> start = buildExecuteService.start(id, userModel, delay, 1, buildRemark);
            jsonObject.put("msg", start.getMsg());
            jsonObject.put("buildId", start.getData());
        }).collect(Collectors.toList());
        return JsonMessage.getString(200, "触发成功", collect);
    } catch (Exception e) {
        DefaultSystemLog.getLog().error("构建触发批量触发异常", e);
        return JsonMessage.getString(500, "触发异常", e.getMessage());
    }
}
Also used : ObjectUtil(cn.hutool.core.util.ObjectUtil) ServerOpenApi(io.jpom.common.ServerOpenApi) DefaultSystemLog(cn.jiangzeyin.common.DefaultSystemLog) ServletUtil(cn.hutool.extra.servlet.ServletUtil) JsonMessage(cn.jiangzeyin.common.JsonMessage) JSONArray(com.alibaba.fastjson.JSONArray) BuildInfoTriggerController(io.jpom.controller.build.BuildInfoTriggerController) BaseEnum(io.jpom.model.BaseEnum) RegexPool(cn.hutool.core.lang.RegexPool) MediaType(org.springframework.http.MediaType) Collectors(java.util.stream.Collectors) BaseJpomController(io.jpom.common.BaseJpomController) StringUtils(org.h2.util.StringUtils) StrUtil(cn.hutool.core.util.StrUtil) List(java.util.List) ValidatorItem(cn.jiangzeyin.common.validator.ValidatorItem) BuildInfoService(io.jpom.service.dblog.BuildInfoService) org.springframework.web.bind.annotation(org.springframework.web.bind.annotation) Convert(cn.hutool.core.convert.Convert) JSONObject(com.alibaba.fastjson.JSONObject) Entity(cn.hutool.db.Entity) BuildInfoModel(io.jpom.model.data.BuildInfoModel) NotLogin(io.jpom.common.interceptor.NotLogin) BuildExecuteService(io.jpom.build.BuildExecuteService) UserModel(io.jpom.model.data.UserModel) BuildStatus(io.jpom.model.enums.BuildStatus) UserService(io.jpom.service.user.UserService) BaseServerController(io.jpom.common.BaseServerController) Validator(cn.hutool.core.lang.Validator) Assert(org.springframework.util.Assert) UserModel(io.jpom.model.data.UserModel) JSONObject(com.alibaba.fastjson.JSONObject) JsonMessage(cn.jiangzeyin.common.JsonMessage) JSONArray(com.alibaba.fastjson.JSONArray) JSONObject(com.alibaba.fastjson.JSONObject) BuildInfoModel(io.jpom.model.data.BuildInfoModel)

Aggregations

JsonMessage (cn.jiangzeyin.common.JsonMessage)14 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 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 ClassFeature (io.jpom.permission.ClassFeature)2 Feature (io.jpom.permission.Feature)2 MethodFeature (io.jpom.permission.MethodFeature)2 UserService (io.jpom.service.user.UserService)2 IOException (java.io.IOException)2