Search in sources :

Example 1 with Files1

use of com.orion.utils.io.Files1 in project orion-kit by lijiahangmax.

the class GzDecompressor method doDecompress.

@Override
public void doDecompress() throws Exception {
    OutputStream out = null;
    try {
        if (decompressInputStream != null) {
            this.inputStream = new GzipCompressorInputStream(decompressInputStream);
        } else {
            this.inputStream = new GzipCompressorInputStream(Files1.openInputStreamFast(decompressFile));
        }
        String entityName = Optional.ofNullable(inputStream.getMetaData()).map(GzipParameters::getFilename).orElse(null);
        if (decompressTargetFileName == null) {
            // 配置 > entity > file > objectId
            this.decompressTargetFileName = Objects1.def(entityName, Optional.ofNullable(decompressFile).map(File::getName).map(s -> s.substring(0, s.length() - suffix.length() - 1)).orElseGet(ObjectIds::next));
        }
        if (decompressTargetOutputStream != null) {
            out = decompressTargetOutputStream;
        } else {
            this.decompressTargetFile = new File(decompressTargetPath, decompressTargetFileName);
            out = Files1.openOutputStream(decompressTargetFile);
        }
        Streams.transfer(inputStream, out);
    } finally {
        Streams.close(inputStream);
        if (decompressTargetOutputStream == null) {
            Streams.close(out);
        }
    }
}
Also used : GzipCompressorInputStream(org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream) OutputStream(java.io.OutputStream) BaseFileDecompressor(com.orion.utils.io.compress.BaseFileDecompressor) GzipParameters(org.apache.commons.compress.compressors.gzip.GzipParameters) Valid(com.orion.utils.Valid) ObjectIds(com.orion.id.ObjectIds) File(java.io.File) Files1(com.orion.utils.io.Files1) Const(com.orion.constant.Const) Streams(com.orion.utils.io.Streams) Objects1(com.orion.utils.Objects1) Optional(java.util.Optional) GzipCompressorInputStream(org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream) InputStream(java.io.InputStream) ObjectIds(com.orion.id.ObjectIds) OutputStream(java.io.OutputStream) File(java.io.File)

Example 2 with Files1

use of com.orion.utils.io.Files1 in project orion-ops by lijiahangmax.

the class FileDownloadServiceImpl method getDownloadToken.

@Override
public String getDownloadToken(Long id, FileDownloadType type) {
    String path = null;
    String name = null;
    Long machineId = Const.HOST_MACHINE_ID;
    // 获取日志绝对路径
    switch(type) {
        case SECRET_KEY:
            // 秘钥
            path = this.getDownloadSecretKeyFilePath(id);
            name = Optional.ofNullable(path).map(Files1::getFileName).orElse(null);
            break;
        case TERMINAL_LOG:
            // terminal 日志
            path = this.getDownloadTerminalLogFilePath(id);
            name = Optional.ofNullable(path).map(Files1::getFileName).orElse(null);
            break;
        case EXEC_LOG:
            // 执行日志
            path = commandExecService.getExecLogFilePath(id);
            name = Optional.ofNullable(path).map(Files1::getFileName).orElse(null);
            break;
        case SFTP_DOWNLOAD:
            // sftp 下载文件
            FileTransferLogDO transferLog = sftpService.getDownloadFilePath(id);
            if (transferLog != null) {
                path = transferLog.getLocalFile();
                name = Files1.getFileName(transferLog.getRemoteFile());
            }
            break;
        case TAIL_LIST_FILE:
            // tail 列表文件
            FileTailListDO tailFile = fileTailListDAO.selectById(id);
            if (tailFile != null) {
                path = tailFile.getFilePath();
                name = Files1.getFileName(path);
                machineId = tailFile.getMachineId();
            }
            break;
        case APP_BUILD_LOG:
            // 应用构建日志
            path = applicationBuildService.getBuildLogPath(id);
            name = Optional.ofNullable(path).map(Files1::getFileName).orElse(null);
            break;
        case APP_BUILD_ACTION_LOG:
        case APP_RELEASE_ACTION_LOG:
            // 应用构建操作日志
            path = applicationActionLogService.getActionLogPath(id);
            name = Optional.ofNullable(path).map(Files1::getFileName).orElse(null);
            break;
        case APP_BUILD_BUNDLE:
            // 应用构建 产物文件
            path = applicationBuildService.getBuildBundlePath(id);
            // 如果是文件夹则获取压缩文件
            if (path != null && Files1.isDirectory(path)) {
                path += "." + Const.SUFFIX_ZIP;
            }
            name = Optional.ofNullable(path).map(Files1::getFileName).orElse(null);
            break;
        case APP_RELEASE_MACHINE_LOG:
            // 应用发布机器日志
            path = applicationReleaseMachineService.getReleaseMachineLogPath(id);
            name = Optional.ofNullable(path).map(Files1::getFileName).orElse(null);
            break;
        case SCHEDULER_TASK_MACHINE_LOG:
            // 调度任务机器日志
            path = schedulerTaskMachineRecordService.getTaskMachineLogPath(id);
            name = Optional.ofNullable(path).map(Files1::getFileName).orElse(null);
            break;
        default:
            break;
    }
    // 检查文件是否存在
    if (path == null || (type.isLocal() && !Files1.isFile(path))) {
        throw Exceptions.httpWrapper(HttpWrapper.of(ResultCode.FILE_MISSING));
    }
    // 设置缓存
    FileDownloadDTO download = new FileDownloadDTO();
    download.setFilePath(path);
    download.setFileName(Strings.def(name, Const.UNKNOWN));
    download.setUserId(Currents.getUserId());
    download.setType(type.getType());
    download.setMachineId(machineId);
    String token = UUIds.random19();
    String key = Strings.format(KeyConst.FILE_DOWNLOAD_TOKEN, token);
    redisTemplate.opsForValue().set(key, JSON.toJSONString(download), KeyConst.FILE_DOWNLOAD_EXPIRE, TimeUnit.SECONDS);
    return token;
}
Also used : FileTailListDO(com.orion.ops.entity.domain.FileTailListDO) FileTransferLogDO(com.orion.ops.entity.domain.FileTransferLogDO) Files1(com.orion.utils.io.Files1) FileDownloadDTO(com.orion.ops.entity.dto.FileDownloadDTO)

Example 3 with Files1

use of com.orion.utils.io.Files1 in project orion-ops by lijiahangmax.

the class ApplicationBuildServiceImpl method submitBuildTask.

@Override
public Long submitBuildTask(ApplicationBuildRequest request) {
    Long appId = request.getAppId();
    Long profileId = request.getProfileId();
    // 查询应用
    ApplicationInfoDO app = applicationInfoDAO.selectById(appId);
    Valid.notNull(app, MessageConst.APP_ABSENT);
    // 查询环境
    ApplicationProfileDO profile = applicationProfileDAO.selectById(profileId);
    Valid.notNull(profile, MessageConst.PROFILE_ABSENT);
    // 查询应用执行块
    List<ApplicationActionDO> actions = applicationActionService.getAppProfileActions(appId, profileId, StageType.BUILD.getType());
    Valid.notEmpty(actions, MessageConst.APP_PROFILE_NOT_CONFIGURED);
    UserDTO user = Currents.getUser();
    // 获取构建序列
    Integer buildSeq = applicationEnvService.getBuildSeqAndIncrement(appId, profileId);
    // 设置构建参数
    ApplicationBuildDO buildTask = new ApplicationBuildDO();
    buildTask.setAppId(appId);
    buildTask.setAppName(app.getAppName());
    buildTask.setAppTag(app.getAppTag());
    buildTask.setProfileId(profileId);
    buildTask.setProfileName(profile.getProfileName());
    buildTask.setProfileTag(profile.getProfileTag());
    buildTask.setBuildSeq(buildSeq);
    buildTask.setBranchName(request.getBranchName());
    buildTask.setCommitId(request.getCommitId());
    buildTask.setVcsId(app.getVcsId());
    buildTask.setBuildStatus(BuildStatus.WAIT.getStatus());
    buildTask.setDescription(request.getDescription());
    buildTask.setCreateUserId(user.getId());
    buildTask.setCreateUserName(user.getUsername());
    applicationBuildDAO.insert(buildTask);
    Long buildId = buildTask.getId();
    // 设置目录信息
    buildTask.setLogPath(PathBuilders.getBuildLogPath(buildId));
    String bundlePath = applicationEnvService.getAppEnvValue(appId, profileId, ApplicationEnvAttr.BUNDLE_PATH.getKey());
    buildTask.setBundlePath(PathBuilders.getBuildBundlePath(buildId) + "/" + Files1.getFileName(bundlePath));
    // 更新构建信息
    applicationBuildDAO.updateById(buildTask);
    // 检查是否包含环境变量命令
    final boolean hasEnvCommand = actions.stream().filter(s -> ActionType.BUILD_COMMAND.getType().equals(s.getActionType())).map(ApplicationActionDO::getActionCommand).filter(Strings::isNotBlank).anyMatch(s -> s.contains(EnvConst.SYMBOL));
    Map<String, String> env = Maps.newMap();
    if (hasEnvCommand) {
        // 查询应用环境变量
        env.putAll(applicationEnvService.getAppProfileFullEnv(appId, profileId));
        // 查询机器环境变量
        env.putAll(machineEnvService.getFullMachineEnv(Const.HOST_MACHINE_ID));
        // 查询系统环境变量
        env.putAll(systemEnvService.getFullSystemEnv());
        // 添加构建环境变量
        env.putAll(this.getBuildEnv(buildId, buildSeq, app.getVcsId(), request));
    }
    // 设置action
    for (ApplicationActionDO action : actions) {
        ApplicationActionLogDO actionLog = new ApplicationActionLogDO();
        actionLog.setRelId(buildId);
        actionLog.setStageType(StageType.BUILD.getType());
        actionLog.setMachineId(Const.HOST_MACHINE_ID);
        actionLog.setActionId(action.getAppId());
        actionLog.setActionName(action.getActionName());
        actionLog.setActionType(action.getActionType());
        if (ActionType.BUILD_COMMAND.equals(ActionType.of(action.getActionType()))) {
            actionLog.setActionCommand(Strings.format(action.getActionCommand(), EnvConst.SYMBOL, env));
        }
        actionLog.setRunStatus(ActionStatus.WAIT.getStatus());
        applicationActionLogDAO.insert(actionLog);
        // 设置日志路径
        actionLog.setLogPath(PathBuilders.getBuildActionLogPath(buildId, actionLog.getId()));
        // 更新
        applicationActionLogDAO.updateById(actionLog);
    }
    // 提交构建任务
    log.info("提交应用构建任务 buildId: {}", buildId);
    BuildMachineProcessor buildProcessor = new BuildMachineProcessor(buildId);
    Threads.start(buildProcessor, SchedulerPools.APP_BUILD_SCHEDULER);
    // 设置日志参数
    EventParamsHolder.addParams(buildTask);
    return buildId;
}
Also used : EventKeys(com.orion.ops.consts.event.EventKeys) com.orion.ops.dao(com.orion.ops.dao) com.orion.ops.entity.vo(com.orion.ops.entity.vo) MessageConst(com.orion.ops.consts.MessageConst) EnvConst(com.orion.ops.consts.env.EnvConst) EventParamsHolder(com.orion.ops.consts.event.EventParamsHolder) LambdaQueryWrapper(com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper) BuildMachineProcessor(com.orion.ops.handler.app.machine.BuildMachineProcessor) ApplicationBuildRequest(com.orion.ops.entity.request.ApplicationBuildRequest) PathBuilders(com.orion.ops.utils.PathBuilders) Service(org.springframework.stereotype.Service) Map(java.util.Map) MutableLinkedHashMap(com.orion.lang.collect.MutableLinkedHashMap) Maps(com.orion.utils.collect.Maps) Const(com.orion.ops.consts.Const) com.orion.ops.consts.app(com.orion.ops.consts.app) DataGrid(com.orion.lang.wrapper.DataGrid) com.orion.ops.entity.domain(com.orion.ops.entity.domain) com.orion.ops.service.api(com.orion.ops.service.api) Resource(javax.annotation.Resource) Threads(com.orion.utils.Threads) IMachineProcessor(com.orion.ops.handler.app.machine.IMachineProcessor) Valid(com.orion.ops.utils.Valid) UserDTO(com.orion.ops.entity.dto.UserDTO) Files1(com.orion.utils.io.Files1) Objects(java.util.Objects) DataQuery(com.orion.ops.utils.DataQuery) Converts(com.orion.utils.convert.Converts) BuildSessionHolder(com.orion.ops.handler.app.build.BuildSessionHolder) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) SystemEnvAttr(com.orion.ops.consts.system.SystemEnvAttr) SchedulerPools(com.orion.ops.consts.SchedulerPools) Optional(java.util.Optional) Currents(com.orion.ops.utils.Currents) Strings(com.orion.utils.Strings) Transactional(org.springframework.transaction.annotation.Transactional) BuildMachineProcessor(com.orion.ops.handler.app.machine.BuildMachineProcessor) UserDTO(com.orion.ops.entity.dto.UserDTO)

Example 4 with Files1

use of com.orion.utils.io.Files1 in project orion-ops by lijiahangmax.

the class ApplicationVcsServiceImpl method cleanBuildVcs.

@Override
public void cleanBuildVcs(Long id) {
    // 查询数据
    ApplicationVcsDO vcs = applicationVcsDAO.selectById(id);
    Valid.notNull(vcs, MessageConst.UNKNOWN_DATA);
    // 设置日志参数
    EventParamsHolder.addParam(EventKeys.ID, id);
    EventParamsHolder.addParam(EventKeys.NAME, vcs.getVcsName());
    File rootPath = new File(Files1.getPath(SystemEnvAttr.VCS_PATH.getValue(), id + Const.EMPTY));
    if (!Files1.isDirectory(rootPath)) {
        return;
    }
    // 查询文件夹
    File[] files = rootPath.listFiles(e -> !e.getName().equals(Const.EVENT) && e.isDirectory() && Strings.isInteger(e.getName()));
    if (Arrays1.isEmpty(files)) {
        return;
    }
    // 保留两个版本 防止清空正在进行中的构建任务
    int length = files.length;
    if (length <= 2) {
        return;
    }
    Arrays.sort(files, Comparator.comparing(s -> Integer.parseInt(s.getName())));
    for (int i = 0; i < length - 2; i++) {
        Files1.delete(files[i]);
    }
}
Also used : EventKeys(com.orion.ops.consts.event.EventKeys) LogInfo(com.orion.vcs.git.info.LogInfo) Exceptions(com.orion.utils.Exceptions) java.util(java.util) ApplicationVcsCommitVO(com.orion.ops.entity.vo.ApplicationVcsCommitVO) ValueMix(com.orion.ops.utils.ValueMix) ApplicationVcsRequest(com.orion.ops.entity.request.ApplicationVcsRequest) ApplicationInfoDAO(com.orion.ops.dao.ApplicationInfoDAO) MessageConst(com.orion.ops.consts.MessageConst) ApplicationVcsBranchVO(com.orion.ops.entity.vo.ApplicationVcsBranchVO) EventParamsHolder(com.orion.ops.consts.event.EventParamsHolder) LambdaQueryWrapper(com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper) ApplicationVcsDAO(com.orion.ops.dao.ApplicationVcsDAO) VcsStatus(com.orion.ops.consts.app.VcsStatus) ApplicationBuildDAO(com.orion.ops.dao.ApplicationBuildDAO) ApplicationVcsInfoVO(com.orion.ops.entity.vo.ApplicationVcsInfoVO) Streams(com.orion.utils.io.Streams) Service(org.springframework.stereotype.Service) Arrays1(com.orion.utils.Arrays1) VcsAuthType(com.orion.ops.consts.app.VcsAuthType) Utils(com.orion.ops.utils.Utils) Const(com.orion.ops.consts.Const) DataGrid(com.orion.lang.wrapper.DataGrid) ApplicationVcsDO(com.orion.ops.entity.domain.ApplicationVcsDO) ApplicationVcsVO(com.orion.ops.entity.vo.ApplicationVcsVO) Resource(javax.annotation.Resource) BranchInfo(com.orion.vcs.git.info.BranchInfo) Valid(com.orion.ops.utils.Valid) File(java.io.File) Files1(com.orion.utils.io.Files1) DataQuery(com.orion.ops.utils.DataQuery) Converts(com.orion.utils.convert.Converts) Slf4j(lombok.extern.slf4j.Slf4j) VcsTokenType(com.orion.ops.consts.app.VcsTokenType) SystemEnvAttr(com.orion.ops.consts.system.SystemEnvAttr) ApplicationVcsService(com.orion.ops.service.api.ApplicationVcsService) VcsType(com.orion.ops.consts.app.VcsType) Strings(com.orion.utils.Strings) Gits(com.orion.vcs.git.Gits) Transactional(org.springframework.transaction.annotation.Transactional) ApplicationVcsDO(com.orion.ops.entity.domain.ApplicationVcsDO) File(java.io.File)

Example 5 with Files1

use of com.orion.utils.io.Files1 in project orion-ops by lijiahangmax.

the class MachineKeyServiceImpl method listKeys.

@Override
public DataGrid<MachineSecretKeyVO> listKeys(MachineKeyRequest request) {
    final int page = request.getPage();
    final int limit = request.getLimit();
    final boolean checkStatus = request.getMountStatus() != null;
    if (checkStatus) {
        request.setPage(Const.N_1);
        request.setLimit(Const.N_100000);
    }
    LambdaQueryWrapper<MachineSecretKeyDO> wrapper = new LambdaQueryWrapper<MachineSecretKeyDO>().like(Strings.isNotBlank(request.getName()), MachineSecretKeyDO::getKeyName, request.getName()).like(Strings.isNotBlank(request.getDescription()), MachineSecretKeyDO::getDescription, request.getDescription()).orderByDesc(MachineSecretKeyDO::getCreateTime);
    DataGrid<MachineSecretKeyVO> dataGrid = DataQuery.of(machineSecretKeyDAO).page(request).wrapper(wrapper).dataGrid(MachineSecretKeyVO.class);
    if (!dataGrid.isEmpty()) {
        List<String> loadKeys = SessionHolder.getLoadKeys();
        for (MachineSecretKeyVO row : dataGrid.getRows()) {
            String path = row.getPath();
            boolean isFile = Files1.isFile(new File(MachineKeyService.getKeyPath(path)));
            if (isFile) {
                boolean match = loadKeys.stream().anyMatch(key -> key.endsWith(path));
                if (match) {
                    row.setMountStatus(MountKeyStatus.MOUNTED.getStatus());
                } else {
                    row.setMountStatus(MountKeyStatus.DUMPED.getStatus());
                }
            } else {
                row.setMountStatus(MountKeyStatus.NOT_FOUND.getStatus());
            }
        }
    }
    if (!checkStatus) {
        return dataGrid;
    } else {
        // 手动过滤
        List<MachineSecretKeyVO> totalRows = dataGrid.stream().filter(row -> request.getMountStatus().equals(row.getMountStatus())).collect(Collectors.toList());
        List<MachineSecretKeyVO> rows = new LimitList<>(totalRows, limit).page(page);
        // 封装返回
        DataGrid<MachineSecretKeyVO> newDataGrid = DataGrid.of(rows, totalRows.size());
        newDataGrid.setPage(page);
        newDataGrid.setLimit(limit);
        return newDataGrid;
    }
}
Also used : EventKeys(com.orion.ops.consts.event.EventKeys) ValueMix(com.orion.ops.utils.ValueMix) MachineSecretKeyVO(com.orion.ops.entity.vo.MachineSecretKeyVO) Date(java.util.Date) MessageConst(com.orion.ops.consts.MessageConst) EventParamsHolder(com.orion.ops.consts.event.EventParamsHolder) LambdaQueryWrapper(com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper) FileWriters(com.orion.utils.io.FileWriters) ObjectIds(com.orion.id.ObjectIds) MachineSecretKeyDO(com.orion.ops.entity.domain.MachineSecretKeyDO) LimitList(com.orion.lang.collect.LimitList) MachineSecretKeyDAO(com.orion.ops.dao.MachineSecretKeyDAO) PathBuilders(com.orion.ops.utils.PathBuilders) Service(org.springframework.stereotype.Service) MachineKeyRequest(com.orion.ops.entity.request.MachineKeyRequest) Map(java.util.Map) Maps(com.orion.utils.collect.Maps) Const(com.orion.ops.consts.Const) MountKeyStatus(com.orion.ops.consts.machine.MountKeyStatus) DataGrid(com.orion.lang.wrapper.DataGrid) MachineKeyService(com.orion.ops.service.api.MachineKeyService) Resource(javax.annotation.Resource) Valid(com.orion.ops.utils.Valid) Collectors(java.util.stream.Collectors) File(java.io.File) Files1(com.orion.utils.io.Files1) DataQuery(com.orion.ops.utils.DataQuery) Converts(com.orion.utils.convert.Converts) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) Base64s(com.orion.utils.codec.Base64s) SessionHolder(com.orion.remote.channel.SessionHolder) Strings(com.orion.utils.Strings) Transactional(org.springframework.transaction.annotation.Transactional) MachineSecretKeyVO(com.orion.ops.entity.vo.MachineSecretKeyVO) MachineSecretKeyDO(com.orion.ops.entity.domain.MachineSecretKeyDO) File(java.io.File)

Aggregations

Files1 (com.orion.utils.io.Files1)5 LambdaQueryWrapper (com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper)3 DataGrid (com.orion.lang.wrapper.DataGrid)3 Const (com.orion.ops.consts.Const)3 MessageConst (com.orion.ops.consts.MessageConst)3 EventKeys (com.orion.ops.consts.event.EventKeys)3 EventParamsHolder (com.orion.ops.consts.event.EventParamsHolder)3 DataQuery (com.orion.ops.utils.DataQuery)3 Valid (com.orion.ops.utils.Valid)3 Strings (com.orion.utils.Strings)3 Converts (com.orion.utils.convert.Converts)3 File (java.io.File)3 Resource (javax.annotation.Resource)3 Slf4j (lombok.extern.slf4j.Slf4j)3 Service (org.springframework.stereotype.Service)3 Transactional (org.springframework.transaction.annotation.Transactional)3 ObjectIds (com.orion.id.ObjectIds)2 SystemEnvAttr (com.orion.ops.consts.system.SystemEnvAttr)2 PathBuilders (com.orion.ops.utils.PathBuilders)2 ValueMix (com.orion.ops.utils.ValueMix)2