机器管理规范化

This commit is contained in:
唐潇凯 2025-06-09 18:05:30 +08:00
parent 97ffb19c03
commit be07dc0e0a
24 changed files with 1673 additions and 1505 deletions

View File

@ -8,6 +8,16 @@ import cd.casic.framework.commons.exception.ErrorCode;
public interface MachineErrorCodeConstants { public interface MachineErrorCodeConstants {
// ========== 机器模块 1-003-000-000 ========== // ========== 机器模块 1-003-000-000 ==========
ErrorCode MACHINE_INFO_NULL = new ErrorCode(1_003_000_000, "机器信息为空"); ErrorCode MACHINE_INFO_NULL = new ErrorCode(1_003_000_000, "机器信息为空");
ErrorCode MACHINE_INFO_HOST_IP_NULL = new ErrorCode(1_003_000_000, "机器主机IP为空");
ErrorCode MACHINE_INFO_USER_NAME_NULL = new ErrorCode(1_003_000_000, "机器用户名为空");
ErrorCode MACHINE_INFO_TYPE_NULL = new ErrorCode(1_003_000_022, "机器类型为空");
ErrorCode MACHINE_INFO_TYPE_NOT_EXISTS = new ErrorCode(1_003_000_011, "机器类型不存在");
ErrorCode MACHINE_INFO_TAG_NULL = new ErrorCode(1_003_000_044, "机器唯一标识为空");
ErrorCode MACHINE_INFO_TAG_EXISTS = new ErrorCode(1_003_000_044, "机器唯一标识已存在");
ErrorCode MACHINE_INFO_AUTHENTICATION_TYPE_NULL = new ErrorCode(1_003_000_044, "机器认证类型为空");
ErrorCode MACHINE_INFO_AUTHENTICATION_TYPE_NOT_EXISTS = new ErrorCode(1_003_000_044, "机器认证类型不存在");
ErrorCode MACHINE_ENABLE = new ErrorCode(1_003_000_044, "机器启用中");
ErrorCode MACHINE_UN_ENABLE = new ErrorCode(1_003_000_044, "机器不可用");
ErrorCode UPLOADING_FILE_FAIL = new ErrorCode(1_003_000_001, "上传文件失败"); ErrorCode UPLOADING_FILE_FAIL = new ErrorCode(1_003_000_001, "上传文件失败");
ErrorCode DOWNLOAD_FILE_FAIL = new ErrorCode(1_003_000_002, "下载失败"); ErrorCode DOWNLOAD_FILE_FAIL = new ErrorCode(1_003_000_002, "下载失败");
ErrorCode FILENAME_NULL = new ErrorCode(1_003_000_003, "文件名为空"); ErrorCode FILENAME_NULL = new ErrorCode(1_003_000_003, "文件名为空");
@ -15,6 +25,8 @@ public interface MachineErrorCodeConstants {
ErrorCode DELETE_FILE_FAIL = new ErrorCode(1_003_000_005, "删除文件失败"); ErrorCode DELETE_FILE_FAIL = new ErrorCode(1_003_000_005, "删除文件失败");
ErrorCode PARAMETER_ERROR = new ErrorCode(1_003_000_008, "参数错误"); ErrorCode PARAMETER_ERROR = new ErrorCode(1_003_000_008, "参数错误");
// ========== 机器环境变量模块 1-003-000-009 ========== // ========== 机器环境变量模块 1-003-000-009 ==========
ErrorCode MACHINE_ENV_NULL = new ErrorCode(1_003_000_009, "机器环境变量为空"); ErrorCode MACHINE_ENV_NULL = new ErrorCode(1_003_000_009, "机器环境变量为空");
ErrorCode MACHINE_ENV_NOT_EXISTS = new ErrorCode(1_003_000_009, "机器不存在"); ErrorCode MACHINE_ENV_NOT_EXISTS = new ErrorCode(1_003_000_009, "机器不存在");
@ -26,6 +38,15 @@ public interface MachineErrorCodeConstants {
ErrorCode MACHINE_PROXY_TYPE_NOT_EXISTS = new ErrorCode(1_003_000_007, "机器代理类型不存在"); ErrorCode MACHINE_PROXY_TYPE_NOT_EXISTS = new ErrorCode(1_003_000_007, "机器代理类型不存在");
ErrorCode MACHINE_PROXY_IS_ONLINE = new ErrorCode(1_003_000_007, "机器代理在线,不能删除"); ErrorCode MACHINE_PROXY_IS_ONLINE = new ErrorCode(1_003_000_007, "机器代理在线,不能删除");
// ========== 密钥模块 1-003-000-010 ==========
ErrorCode SECRET_KEY_NULL = new ErrorCode(1_003_000_010, "密钥为空");
ErrorCode SECRET_KEY_NOT_EXISTS = new ErrorCode(1_003_000_010, "密钥不存在");
ErrorCode SECRET_KEY_NAME_ILLEGAL = new ErrorCode(1_003_000_010, "密钥名称不合法");
ErrorCode SECRET_KEY_PATH_ILLEGAL = new ErrorCode(1_003_000_010, "密钥路径不合法");
ErrorCode SECRET_KEY_PATH_NULL = new ErrorCode(1_003_000_010, "密钥路径为空");
ErrorCode SECRET_KEY_UPLOAD_FAIL = new ErrorCode(1_003_000_010, "密钥上传失败");
ErrorCode OSS_PARAM_NULL = new ErrorCode(1_003_000_011, "oss参数无法读取"); ErrorCode OSS_PARAM_NULL = new ErrorCode(1_003_000_011, "oss参数无法读取");
ErrorCode SECRETKEY_NULL = new ErrorCode(1_003_000_012, "密钥为空"); ErrorCode SECRETKEY_NULL = new ErrorCode(1_003_000_012, "密钥为空");
} }

View File

@ -1,126 +1,143 @@
//package cd.casic.module.machine.controller; package cd.casic.module.machine.controller;
// import cd.casic.framework.commons.pojo.CommonResult;
//import cd.casic.framework.commons.pojo.CommonResult; import cd.casic.framework.commons.pojo.PageResult;
//import cd.casic.framework.commons.pojo.PageResult; import cd.casic.framework.commons.util.object.BeanUtils;
//import cd.casic.module.machine.dal.dataobject.MachineInfo; import cd.casic.module.machine.dal.dataobject.MachineInfoDO;
//import cd.casic.module.machine.enums.ConnectionStatus; import cd.casic.module.machine.enums.ConnectionStatus;
//import cd.casic.module.machine.service.MachineInfoService; import cd.casic.module.machine.service.MachineInfoService;
//import cd.casic.module.machine.controller.vo.MachineInfoDto; import cd.casic.module.machine.controller.vo.MachineInfoVO;
//import io.swagger.v3.oas.annotations.Operation; import cn.hutool.core.collection.CollUtil;
//import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.Operation;
//import jakarta.annotation.Resource; import io.swagger.v3.oas.annotations.tags.Tag;
//import org.springframework.web.bind.annotation.*; import jakarta.annotation.Resource;
// import jakarta.validation.Valid;
//import java.util.Map; import org.springframework.validation.annotation.Validated;
// import org.springframework.web.bind.annotation.*;
//import static cd.casic.framework.commons.pojo.CommonResult.success; import java.util.List;
// import java.util.Map;
//@RestController import static cd.casic.framework.commons.pojo.CommonResult.success;
//@Tag(name = "机器信息管理")
//@RequestMapping("/api/machineInfo") @RestController
//public class MachineInfoController { @Tag(name = "机器信息管理")
// @Resource @RequestMapping("/ci/machineInfo")
// private MachineInfoService machineInfoService; @Validated
// public class MachineInfoController {
// @PostMapping("/add") @Resource
// @Operation(summary = "新增机器信息") private MachineInfoService machineInfoService;
// public CommonResult<Boolean> add(@RequestBody MachineInfoDto machineInfoDto) {
// return success(machineInfoService.addMachineInfo(machineInfoDto)); @PostMapping("/create")
// } @Operation(summary = "新增机器信息")
// // @PreAuthorize("@ss.hasPermission('ci:machineInfo:create')")
// public CommonResult<Long> createMachine(@Valid @RequestBody MachineInfoVO machineInfoVO) {
// @PostMapping("/list") Long id = machineInfoService.createMachine(machineInfoVO);
// @Operation(summary = "获取机器信息列表") return success(id);
// public CommonResult<PageResult<MachineInfoDto>> list(@RequestBody MachineInfoDto machineInfoDto) { }
// return success(machineInfoService.listMachineInfo(machineInfoDto));
// }
// @PutMapping("/update")
// @PutMapping("/update") @Operation(summary = "编辑机器信息")
// @Operation(summary = "编辑机器信息") // @PreAuthorize("@ss.hasPermission('ci:machineInfo:update')")
// public CommonResult<Boolean> update(@RequestBody MachineInfoDto machineInfoDto) { public CommonResult<Boolean> updateMachineInfo(@Valid @RequestBody MachineInfoVO machineInfoVO) {
// return success(machineInfoService.updateMachineInfo(machineInfoDto)); machineInfoService.updateMachineInfo(machineInfoVO);
// } return success(true);
// }
// @PutMapping("/updateStatus")
// @Operation(summary = "机器启用/停用") @PutMapping("/updateStatus")
// public CommonResult<Boolean> updateStatus(@RequestBody MachineInfoDto machineInfoDto) { @Operation(summary = "机器启用/停用")
// return success(machineInfoService.updateStatus(machineInfoDto)); // @PreAuthorize("@ss.hasPermission('ci:machineInfo:status')")
// } public CommonResult<Integer> updateStatus(@RequestParam("id") Long id, @RequestParam("status") Integer status) {
// Integer newStatus = machineInfoService.updateStatus(id, status);
// @PutMapping("/bindingSecretKey") return success(newStatus);
// @Operation(summary = "绑定密钥") }
// public CommonResult<Boolean> bindingSecretKey(@RequestBody MachineInfoDto machineInfoDto) {
// return success(machineInfoService.bindingSecretKey(machineInfoDto)); @PostMapping("/list")
// } @Operation(summary = "获取机器信息列表")
// public CommonResult<PageResult<MachineInfoVO>> list(@Valid @RequestBody MachineInfoVO machineInfoVO) {
// @DeleteMapping("/delete") PageResult<MachineInfoDO> pageResult = machineInfoService.listMachineInfo(machineInfoVO);
// @Operation(summary = "机器信息删除") if (CollUtil.isEmpty(pageResult.getList())) {
// public CommonResult<Boolean> delete(@RequestParam Long machineInfoId) { return success(new PageResult<>(pageResult.getTotal()));
// machineInfoService.deleteMachineInfo(machineInfoId); }
// return success(true); return success(BeanUtils.toBean(pageResult, MachineInfoVO.class));
// } }
//
// @DeleteMapping("/deleteList") @PutMapping("/bindingSecretKey")
// @Operation(summary = "批量删除机器信息") @Operation(summary = "绑定密钥")
// public CommonResult<Boolean> deleteList(@RequestParam String machineInfoIds) { // @PreAuthorize("@ss.hasPermission('ci:machineInfo:binding')")
// machineInfoService.deleteList(machineInfoIds); public CommonResult<Boolean> bindingSecretKey(@RequestParam("ids") List<Long> ids, @RequestParam("secretKeyId") Long secretKeyId) {
// return success(true); machineInfoService.bindingSecretKey(ids,secretKeyId);
// } return success(true);
// }
// @PostMapping("/test")
// @Operation(summary = "测试机器连接") @DeleteMapping("/delete")
// public CommonResult<Boolean> testConnection(@RequestParam Long id) { @Operation(summary = "机器信息删除")
// return success(machineInfoService.testConnection(id)); // @PreAuthorize("@ss.hasPermission('ci:machineInfo:delete')")
// } public CommonResult<Boolean> deleteMachineInfo(@RequestParam("id") Long id) {
// machineInfoService.deleteMachineInfo(id);
// @GetMapping("/status/{machineName}") return success(true);
// @Operation(summary = "获取机器连接状态") }
// public CommonResult<ConnectionStatus> getConnectionStatus(@PathVariable String machineName) {
// return success(machineInfoService.getConnectionStatus(machineName)); @DeleteMapping("/deleteList")
// } @Operation(summary = "批量删除机器信息")
// // @PreAuthorize("@ss.hasPermission('ci:machineInfo:delete')")
// @GetMapping("/status/all") public CommonResult<Boolean> deleteMachineInfoList(@RequestParam("machineInfoIds") String ids) {
// @Operation(summary = "获取所有机器连接状态") machineInfoService.deleteMachineInfoList(ids);
// public CommonResult<Map<String, ConnectionStatus>> getAllConnectionStatus() { return success(true);
// return success(machineInfoService.getAllConnectionStatus()); }
// }
// @PostMapping("/test")
// @PostMapping("/connect") @Operation(summary = "测试机器连接")
// @Operation(summary = "建立机器连接") public CommonResult<Boolean> testConnection(@RequestParam Long id) {
// public CommonResult<String> connect(@RequestBody MachineInfo machineInfo) { return success(machineInfoService.testConnection(id));
// return success(machineInfoService.connect(machineInfo)); }
// }
// @GetMapping("/status/{machineName}")
// @PostMapping("/disconnect/{sessionId}") @Operation(summary = "获取机器连接状态")
// @Operation(summary = "断开机器连接") public CommonResult<ConnectionStatus> getConnectionStatus(@PathVariable String machineName) {
// public CommonResult<Boolean> disconnect(@PathVariable String sessionId) { return success(machineInfoService.getConnectionStatus(machineName));
// return success(machineInfoService.disconnect(sessionId)); }
// }
// @GetMapping("/status/all")
// @PostMapping("/execute/{sessionId}") @Operation(summary = "获取所有机器连接状态")
// @Operation(summary = "执行远程命令") public CommonResult<Map<String, ConnectionStatus>> getAllConnectionStatus() {
// public CommonResult<String> executeCommand( return success(machineInfoService.getAllConnectionStatus());
// @PathVariable String sessionId, }
// @RequestBody String command) {
// @PostMapping("/connect")
// return success(machineInfoService.executeCommand(sessionId, command)); @Operation(summary = "建立机器连接")
// } public CommonResult<String> connect(@Valid @RequestBody MachineInfoDO machineInfoDO) {
// return success(machineInfoService.connect(machineInfoDO));
// @PostMapping("/upload/{sessionId}") }
// @Operation(summary = "上传文件到远程机器")
// public CommonResult<Boolean> uploadFile( @PostMapping("/disconnect/{sessionId}")
// @PathVariable String sessionId, @Operation(summary = "断开机器连接")
// @RequestParam String localFilePath, public CommonResult<Boolean> disconnect(@PathVariable String sessionId) {
// @RequestParam String remoteFilePath) { return success(machineInfoService.disconnect(sessionId));
// return success(machineInfoService.uploadFile(sessionId, localFilePath, remoteFilePath)); }
// }
// @PostMapping("/execute/{sessionId}")
// @PostMapping("/download/{sessionId}") @Operation(summary = "执行远程命令")
// @Operation(summary = "从远程机器下载文件") public CommonResult<String> executeCommand(
// public CommonResult<Boolean> downloadFile( @PathVariable String sessionId,
// @PathVariable String sessionId, @RequestBody String command) {
// @RequestParam String remoteFilePath,
// @RequestParam String localFilePath) { return success(machineInfoService.executeCommand(sessionId, command));
// return success(machineInfoService.downloadFile(sessionId, remoteFilePath, localFilePath)); }
// }
//} @PostMapping("/upload/{sessionId}")
@Operation(summary = "上传文件到远程机器")
public CommonResult<Boolean> uploadFile(
@PathVariable String sessionId,
@RequestParam String localFilePath,
@RequestParam String remoteFilePath) {
return success(machineInfoService.uploadFile(sessionId, localFilePath, remoteFilePath));
}
@PostMapping("/download/{sessionId}")
@Operation(summary = "从远程机器下载文件")
public CommonResult<Boolean> downloadFile(
@PathVariable String sessionId,
@RequestParam String remoteFilePath,
@RequestParam String localFilePath) {
return success(machineInfoService.downloadFile(sessionId, remoteFilePath, localFilePath));
}
}

View File

@ -1,56 +1,78 @@
//package cd.casic.module.machine.controller; package cd.casic.module.machine.controller;
// import cd.casic.framework.commons.pojo.CommonResult;
//import cd.casic.framework.commons.pojo.CommonResult; import cd.casic.framework.commons.pojo.PageResult;
//import cd.casic.framework.commons.pojo.PageResult; import cd.casic.framework.commons.util.object.BeanUtils;
//import cd.casic.module.machine.dal.dataobject.SecretKey; import cd.casic.module.machine.dal.dataobject.SecretKeyDO;
//import cd.casic.module.machine.service.SecretKeyService; import cd.casic.module.machine.service.SecretKeyService;
//import cd.casic.module.machine.controller.vo.SecretKeyDto; import cd.casic.module.machine.controller.vo.SecretKeyVO;
//import io.swagger.v3.oas.annotations.Operation; import cn.hutool.core.collection.CollUtil;
//import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.Operation;
//import jakarta.annotation.Resource; import io.swagger.v3.oas.annotations.tags.Tag;
//import org.springframework.web.bind.annotation.*; import jakarta.annotation.Resource;
// import jakarta.validation.Valid;
//import java.util.List; import org.springframework.security.access.prepost.PreAuthorize;
// import org.springframework.validation.annotation.Validated;
//import static cd.casic.framework.commons.pojo.CommonResult.success; import org.springframework.web.bind.annotation.*;
// import java.util.List;
//@RestController import static cd.casic.framework.commons.pojo.CommonResult.success;
//@RequestMapping("/api/secretKey")
//@Tag(name = "密钥管理") @RestController
//public class SecretKeyController { @RequestMapping("/ci/secretKey")
// @Resource @Tag(name = "密钥管理")
// private SecretKeyService secretKeyService; @Validated
// public class SecretKeyController {
// @PostMapping(value = "/add") @Resource
// @Operation(summary = "新增密钥") private SecretKeyService secretKeyService;
// public CommonResult<Boolean> add(@RequestBody SecretKeyDto secretKeyDto) throws Exception {
// return success(secretKeyService.addSecretKey(secretKeyDto)); @PostMapping(value = "/create")
// } @Operation(summary = "新增密钥")
// // @PreAuthorize("@ss.hasPermission('ci:secretKey:create')")
// @PutMapping("/bindingMachine") public CommonResult<Long> createSecretKey(@Valid @RequestBody SecretKeyVO secretKeyVO) throws Exception {
// @Operation(summary = "绑定机器") Long secretKeyId = secretKeyService.createSecretKey(secretKeyVO);
// public CommonResult<Boolean> bindingMachine(@RequestParam("secretKeyId") Long secretKeyId, @RequestParam("machineIds") List<Long> machineIds) { return success(secretKeyId);
// secretKeyService.bindingMachine(secretKeyId, machineIds); }
// return success(true);
// } @PutMapping("/update")
// @Operation(summary = "编辑密钥信息")
// @PutMapping("/update") // @PreAuthorize("@ss.hasPermission('ci:secretKey:update')")
// @Operation(summary = "编辑密钥信息") public CommonResult<Boolean> updateSecretKey(@Valid @RequestBody SecretKeyVO secretKeyVO) {
// public CommonResult<Boolean> update(@RequestBody SecretKeyDto secretKeyDto) { secretKeyService.updateSecretKey(secretKeyVO);
// return success(secretKeyService.updateSecretKey(secretKeyDto)); return success(true);
// } }
//
// @DeleteMapping("/deleteList") @PutMapping("/bindingMachine")
// @Operation(summary = "批量删除密钥") @Operation(summary = "绑定机器") //todo解绑机器
// public CommonResult<Boolean> deleteList(@RequestParam("secretKeyId") List<Long> secretKeyIds) { // @PreAuthorize("@ss.hasPermission('ci:secretKey:binding')")
// return success(secretKeyService.deleteList(secretKeyIds)); public CommonResult<Boolean> bindingMachine(@RequestParam("id") Long id, @RequestParam("machineInfoIds") List<Long> machineInfoId) {
// } secretKeyService.bindingMachine(id, machineInfoId);
// return success(true);
// @PostMapping("/list") }
// @Operation(summary = "获取密钥信息列表")
// public CommonResult<PageResult<SecretKey>> list(@RequestBody SecretKeyDto secretKeyDto) { @GetMapping("/getSecretKey")
// return success(secretKeyService.listSecretKey(secretKeyDto)); @Operation(summary = "获取机器的环境变量")
// } public CommonResult<SecretKeyVO> getSecretKey(@RequestParam("id") Long id) {
// SecretKeyVO secretKeyVO = secretKeyService.getSecretKey(id);
// return success(secretKeyVO);
//} }
@DeleteMapping("/deleteList")
@Operation(summary = "批量删除密钥")
// @PreAuthorize("@ss.hasPermission('ci:secretKey:delete')")
public CommonResult<Boolean> deleteSecretKeyList(@RequestParam("ids") List<Long> ids) {
secretKeyService.deleteSecretKeyList(ids);
return success(true);
}
@PostMapping("/list")
@Operation(summary = "获取密钥信息列表")
public CommonResult<PageResult<SecretKeyVO>> getSecretKeypage(@Valid @RequestBody SecretKeyVO secretKeyVO) {
PageResult<SecretKeyDO> pageResult = secretKeyService.getSecretKeypage(secretKeyVO);
if (CollUtil.isEmpty(pageResult.getList())) {
return success(new PageResult<>(pageResult.getTotal()));
}
return success(BeanUtils.toBean(pageResult,SecretKeyVO.class));
}
}

View File

@ -1,46 +0,0 @@
package cd.casic.module.machine.controller.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import java.util.Date;
@EqualsAndHashCode(callSuper = true)
@Data
@AllArgsConstructor
@NoArgsConstructor
public class MachineInfoDto extends PageDto {
private Long id;
private Date createDate;
private Date updateDate;
private String name;
private String tag;
private String hostIp;
private String description;
private String username;
private String status;
private Integer sshPort;
private String password;
private Long secretKeyId;
private Long machineProxyId;
private String authenticationType;
private String machineInfoType;
private int isProxy;
}

View File

@ -0,0 +1,64 @@
package cd.casic.module.machine.controller.vo;
import cd.casic.framework.commons.pojo.PageParam;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.*;
import lombok.experimental.Accessors;
import java.util.Date;
@EqualsAndHashCode(callSuper = true)
@Schema(description = "管理后台 - 机器信息 Response VO")
@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class MachineInfoVO extends PageParam {
@Schema(description = "机器ID", requiredMode = Schema.RequiredMode.REQUIRED, example = "1")
private Long id;
@Schema(description = "创建时间", requiredMode = Schema.RequiredMode.REQUIRED, example = "2023-06-15T10:30:00")
private Date createTime;
@Schema(description = "更新时间", example = "2023-06-15T10:30:00")
private Date updateTime;
@Schema(description = "机器名称", requiredMode = Schema.RequiredMode.REQUIRED, example = "server-01")
private String name;
@Schema(description = "机器标签,唯一标识", example = "production,web-server")
private String tag;
@Schema(description = "主机IP", requiredMode = Schema.RequiredMode.REQUIRED, example = "192.168.1.100")
private String hostIp;
@Schema(description = "机器描述", example = "生产环境Web服务器")
private String description;
@Schema(description = "登录用户名", requiredMode = Schema.RequiredMode.REQUIRED, example = "admin")
private String username;
@Schema(description = "机器状态", example = "online,offline,maintenance")
private Integer status;
@Schema(description = "SSH端口", example = "22")
private Integer sshPort;
@Schema(description = "登录密码", example = "******")
private String password;
@Schema(description = "密钥ID", example = "5")
private Long secretKeyId;
@Schema(description = "代理ID", example = "101")
private Long machineProxyId;
@Schema(description = "认证类型", example = "password,key")
private Integer authenticationType;
@Schema(description = "机器信息类型", example = "Linux,Windows")
private Integer machineInfoType;
}

View File

@ -1,35 +0,0 @@
package cd.casic.module.machine.controller.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import java.util.Date;
import java.util.List;
@EqualsAndHashCode(callSuper = true)
@Data
@AllArgsConstructor
@NoArgsConstructor
public class SecretKeyDto extends PageDto {
private Long id;
private String name;
private String description;
//存储路径,本地上传文件路径
private String path;
private String fileName;
//密钥密码
private String password;
private Date createDate;
private Date updateDate;
private List<Long> machineInfoIds;
}

View File

@ -0,0 +1,43 @@
package cd.casic.module.machine.controller.vo;
import cd.casic.framework.commons.pojo.PageParam;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.*;
import lombok.experimental.Accessors;
import java.time.LocalDateTime;
import java.util.List;
@EqualsAndHashCode(callSuper = true)
@Schema(description = "管理后台 - 密钥信息 Response VO")
@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true) // 添加链式调用支持
public class SecretKeyVO extends PageParam {
@Schema(description = "密钥ID", requiredMode = Schema.RequiredMode.REQUIRED, example = "1")
private Long id;
@Schema(description = "密钥名称", requiredMode = Schema.RequiredMode.REQUIRED, example = "生产环境密钥")
private String name;
@Schema(description = "密钥描述", example = "用于加密敏感数据的密钥")
private String description;
@Schema(description = "存储路径(本地上传文件路径)", example = "/data/secret_keys/")
private String path;
@Schema(description = "文件名", example = "key.pem")
private String fileName;
@Schema(description = "密钥密码", example = "******")
private String password;
@Schema(description = "创建时间", requiredMode = Schema.RequiredMode.REQUIRED, example = "2023-06-15T10:30:00")
private LocalDateTime createTime;
@Schema(description = "更新时间", example = "2023-06-15T10:30:00")
private LocalDateTime updateTime;
@Schema(description = "关联的机器ID列表", requiredMode = Schema.RequiredMode.REQUIRED, example = "[1024, 2048]")
private List<Long> machineInfoIds;
}

View File

@ -1,24 +1,35 @@
package cd.casic.module.machine.dal.dataobject; package cd.casic.module.machine.dal.dataobject;
import cd.casic.framework.mybatis.core.dataobject.BaseDO;
import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.annotation.TableName;
import cd.casic.module.machine.enums.AuthenticationType;
import cd.casic.module.machine.enums.MachineInfoStatus;
import cd.casic.module.machine.enums.MachineInfoType;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
@EqualsAndHashCode(callSuper = true) @EqualsAndHashCode(callSuper = true)
@Data @Data
@AllArgsConstructor @AllArgsConstructor
@NoArgsConstructor @NoArgsConstructor
@TableName(value = "machine_info") @TableName(value = "machine_info")
public class MachineInfo extends BaseEntity { public class MachineInfoDO extends BaseDO {
/**
* 机器id
*/
@TableId
private Long id;
@TableField(value = "name") @TableField(value = "name")
private String name; private String name;
/**
* 机器唯一标识
*/
@TableField(value = "tag") @TableField(value = "tag")
private String tag; private String tag;
@ -28,18 +39,11 @@ public class MachineInfo extends BaseEntity {
@TableField(value = "description") @TableField(value = "description")
private String description; private String description;
@TableField(exist = false) @TableField(value = "machine_info_type")
private MachineInfoType machineInfoType; private Integer machineInfoType;
@TableField(value = "machine_info_type_code") @TableField(value = "status")
private int machineInfoTypeCode; private Integer status;
@TableField(exist = false)
private MachineInfoStatus status;
@TableField(value = "status_code")
private int statusCode;
//用户名 //用户名
@TableField(value = "username") @TableField(value = "username")
@ -58,12 +62,7 @@ public class MachineInfo extends BaseEntity {
@TableField(value = "machine_proxy_id") @TableField(value = "machine_proxy_id")
private Long machineProxyId; private Long machineProxyId;
@TableField(value = "authentication_type_code") @TableField(value = "authentication_type")
private int authenticationTypeCode; private Integer authenticationType;
@TableField(exist = false)
private AuthenticationType authenticationType;
@TableField(value = "is_proxy")
private int isProxy;
} }

View File

@ -1,6 +1,8 @@
package cd.casic.module.machine.dal.dataobject; package cd.casic.module.machine.dal.dataobject;
import cd.casic.framework.mybatis.core.dataobject.BaseDO;
import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
@ -12,7 +14,14 @@ import lombok.NoArgsConstructor;
@AllArgsConstructor @AllArgsConstructor
@NoArgsConstructor @NoArgsConstructor
@TableName(value = "machine_secret_key") @TableName(value = "machine_secret_key")
public class SecretKey extends BaseEntity{ public class SecretKeyDO extends BaseDO {
/**
* 密钥id
*/
@TableId
private Long id;
@TableField(value = "name") @TableField(value = "name")
private String name; private String name;

View File

@ -1,11 +1,50 @@
package cd.casic.module.machine.dal.mysql; package cd.casic.module.machine.dal.mysql;
import cd.casic.framework.commons.pojo.PageResult;
import cd.casic.framework.mybatis.core.mapper.BaseMapperX; import cd.casic.framework.mybatis.core.mapper.BaseMapperX;
import cd.casic.framework.mybatis.core.query.LambdaQueryWrapperX;
import cd.casic.module.machine.controller.vo.MachineEnvVO;
import cd.casic.module.machine.controller.vo.MachineInfoVO;
import cd.casic.module.machine.dal.dataobject.MachineEnvDO; import cd.casic.module.machine.dal.dataobject.MachineEnvDO;
import cd.casic.module.machine.dal.dataobject.MachineInfo; import cd.casic.module.machine.dal.dataobject.MachineInfoDO;
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper @Mapper
public interface MachineInfoMapper extends BaseMapperX<MachineInfo> { public interface MachineInfoMapper extends BaseMapperX<MachineInfoDO> {
default Boolean existsByTag(String tag){
return selectOne(new QueryWrapper<MachineInfoDO>().eq("tag", tag))!=null;
}
default void updateStatus(Long machineInfoId, Integer status){
UpdateWrapper<MachineInfoDO> set = new UpdateWrapper<>();
set.eq("id", machineInfoId).set("status", status);
this.update(null,set);
}
default void bindingSecretKey(List<Long> machineInfoIds, Long secretKeyId){
LambdaUpdateWrapper<MachineInfoDO> wrapper = new LambdaUpdateWrapper<MachineInfoDO>()
.set(MachineInfoDO::getSecretKeyId, secretKeyId)
.in(MachineInfoDO::getId, machineInfoIds);
this.update(null, wrapper);
}
default void unBindingSecretKey(List<Long> secretKeyId){
LambdaUpdateWrapper<MachineInfoDO> wrapper = new LambdaUpdateWrapper<MachineInfoDO>()
.set(MachineInfoDO::getSecretKeyId, null)
.in(MachineInfoDO::getSecretKeyId, secretKeyId);
this.update(null, wrapper);
}
default PageResult<MachineInfoDO> selectPage(MachineInfoVO machineInfoVO){
return selectPage(machineInfoVO,new LambdaQueryWrapperX<MachineInfoDO>()
.likeIfPresent(MachineInfoDO::getName, machineInfoVO.getName())
.likeIfPresent(MachineInfoDO::getTag, machineInfoVO.getTag())
.likeIfPresent(MachineInfoDO::getDescription, machineInfoVO.getDescription())
.likeIfPresent(MachineInfoDO::getUsername, machineInfoVO.getUsername())
.eqIfPresent(MachineInfoDO::getHostIp, machineInfoVO.getHostIp()));
}
} }

View File

@ -0,0 +1,29 @@
package cd.casic.module.machine.dal.mysql;
import cd.casic.framework.commons.pojo.PageResult;
import cd.casic.framework.mybatis.core.mapper.BaseMapperX;
import cd.casic.framework.mybatis.core.query.LambdaQueryWrapperX;
import cd.casic.module.machine.controller.vo.SecretKeyVO;
import cd.casic.module.machine.dal.dataobject.MachineInfoDO;
import cd.casic.module.machine.dal.dataobject.SecretKeyDO;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface SecretKeyMapper extends BaseMapperX<SecretKeyDO> {
//查询列表
default PageResult<SecretKeyDO> selectPage(SecretKeyVO secretKeyVO){
return selectPage(secretKeyVO,new LambdaQueryWrapperX<SecretKeyDO>()
.likeIfPresent(SecretKeyDO::getName,secretKeyVO.getName())
.likeIfPresent(SecretKeyDO::getDescription,secretKeyVO.getDescription()));
}
default void bindingMachine(Long machineInfoId, List<Long> secretKeyId){
UpdateWrapper<SecretKeyDO> set = new UpdateWrapper<>();
set.eq("id", secretKeyId).set("machineInfoId", machineInfoId);
this.update(null,set);
}
}

View File

@ -1,9 +0,0 @@
package cd.casic.module.machine.dal.mysql;
import cd.casic.module.machine.dal.dataobject.SecretKey;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface SecretServiceMapper extends BaseMapper<SecretKey> {
}

View File

@ -1,16 +1,25 @@
package cd.casic.module.machine.enums; package cd.casic.module.machine.enums;
import cd.casic.framework.commons.core.IntArrayValuable;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Getter; import lombok.Getter;
import java.util.Arrays;
@Getter @Getter
@AllArgsConstructor @AllArgsConstructor
public enum AuthenticationType implements CodeEnum { public enum AuthenticationType implements IntArrayValuable {
PASSWORD(1,"密码认证"), PASSWORD(1,"密码认证"),
SECRET_KEY(2,"密钥认证"); SECRET_KEY(2,"密钥认证");
public static final int[] ARRAYS = Arrays.stream(values()).mapToInt(AuthenticationType::getCode).toArray();
private final int code; private final int code;
private final String message; private final String message;
@Override
public int[] array() {
return ARRAYS;
}
} }

View File

@ -1,16 +1,22 @@
package cd.casic.module.machine.enums; package cd.casic.module.machine.enums;
import cd.casic.framework.commons.core.IntArrayValuable;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Getter; import lombok.Getter;
@Getter @Getter
@AllArgsConstructor @AllArgsConstructor
public enum MachineInfoStatus implements CodeEnum { public enum MachineInfoStatus implements IntArrayValuable {
ENABLE(1,"启用"), ENABLE(1,"启用"),
UN_ENABLE(0,"停用"); UN_ENABLE(0,"停用");
private final int code; private final int code;
private final String message; private final String message;
@Override
public int[] array() {
return new int[0];
}
} }

View File

@ -1,16 +1,24 @@
package cd.casic.module.machine.enums; package cd.casic.module.machine.enums;
import cd.casic.framework.commons.core.IntArrayValuable;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Getter; import lombok.Getter;
import java.util.Arrays;
@Getter @Getter
@AllArgsConstructor @AllArgsConstructor
public enum MachineInfoType implements CodeEnum { public enum MachineInfoType implements IntArrayValuable {
Linux(1,"Linux"), Linux(1,"Linux"),
WINDOWS(2,"Windows"); WINDOWS(2,"Windows");
public static final int[] ARRAYS = Arrays.stream(values()).mapToInt(MachineInfoType::getCode).toArray();
private final int code; private final int code;
private final String message; private final String message;
@Override
public int[] array() {
return ARRAYS;
}
} }

View File

@ -6,6 +6,7 @@ import lombok.AllArgsConstructor;
import lombok.Getter; import lombok.Getter;
import java.util.Arrays; import java.util.Arrays;
import java.util.List;
@Getter @Getter
@AllArgsConstructor @AllArgsConstructor

View File

@ -1,19 +0,0 @@
package cd.casic.module.machine.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor
public enum PermissionExceptionEnum implements CodeEnum {
URL_NOT_EXIST(1, "资源路径不存在,请检查请求地址"),
NO_PERMISSION(2, "没有权限访问资源,请联系管理员"),
NO_PERMISSION_OPERATE(3, "没有权限操作该数据,请联系管理员");
private final int code;
private final String message;
}

View File

@ -1,25 +1,26 @@
package cd.casic.module.machine.service; package cd.casic.module.machine.service;
import cd.casic.framework.commons.pojo.PageResult; import cd.casic.framework.commons.pojo.PageResult;
import cd.casic.module.machine.controller.vo.MachineInfoDto; import cd.casic.module.machine.controller.vo.MachineInfoVO;
import cd.casic.module.machine.dal.dataobject.MachineInfo; import cd.casic.module.machine.dal.dataobject.MachineInfoDO;
import cd.casic.module.machine.enums.ConnectionStatus; import cd.casic.module.machine.enums.ConnectionStatus;
import com.baomidou.mybatisplus.extension.service.IService; import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
import java.util.Map; import java.util.Map;
public interface MachineInfoService { public interface MachineInfoService {
boolean addMachineInfo(MachineInfoDto MachineInfoDto); Long createMachine(MachineInfoVO MachineInfoVO);
PageResult<MachineInfoDto> listMachineInfo(MachineInfoDto MachineInfoDto); PageResult<MachineInfoDO> listMachineInfo(MachineInfoVO MachineInfoVO);
boolean updateMachineInfo(MachineInfoDto machineInfoDto); void updateMachineInfo(MachineInfoVO machineInfoVO);
boolean updateStatus(MachineInfoDto machineInfoDto); Integer updateStatus(Long machineInfoId, Integer status);
boolean bindingSecretKey(MachineInfoDto machineInfoDto); void bindingSecretKey(List<Long> machineInfoIds, Long secretKeyId);
void deleteList(String machineInfoIds); void deleteMachineInfoList(String machineInfoIds);
void deleteMachineInfo(Long machineInfoId); void deleteMachineInfo(Long machineInfoId);
@ -50,10 +51,10 @@ public interface MachineInfoService {
/** /**
* 建立机器连接 * 建立机器连接
* *
* @param machineInfo 机器信息 * @param machineInfoDO 机器信息
* @return 连接会话ID * @return 连接会话ID
*/ */
String connect(MachineInfo machineInfo); String connect(MachineInfoDO machineInfoDO);
/** /**
* 断开机器连接 * 断开机器连接
@ -91,4 +92,6 @@ public interface MachineInfoService {
* @return 操作结果 * @return 操作结果
*/ */
boolean downloadFile(String sessionId, String remoteFilePath, String localFilePath); boolean downloadFile(String sessionId, String remoteFilePath, String localFilePath);
void unBindingSecretKey(List<Long> SecretKeyIds);
} }

View File

@ -1,24 +1,25 @@
package cd.casic.module.machine.service; package cd.casic.module.machine.service;
import cd.casic.framework.commons.pojo.PageResult; import cd.casic.framework.commons.pojo.PageResult;
import cd.casic.module.machine.dal.dataobject.SecretKey; import cd.casic.module.machine.dal.dataobject.SecretKeyDO;
import cd.casic.module.machine.controller.vo.SecretKeyDto; import cd.casic.module.machine.controller.vo.SecretKeyVO;
import com.baomidou.mybatisplus.extension.service.IService; import jakarta.validation.Valid;
import java.util.List; import java.util.List;
public interface SecretKeyService extends IService<SecretKey> { public interface SecretKeyService{
boolean addSecretKey(SecretKeyDto secretKeyDto) throws Exception; Long createSecretKey(@Valid SecretKeyVO secretKeyVO) throws Exception;
void bindingMachine(Long secretKeyId, List<Long> machineInfoIds); void bindingMachine(Long id, List<Long> machineInfoId);
boolean updateSecretKey(SecretKeyDto secretKeyDto); void updateSecretKey(@Valid SecretKeyVO secretKeyVO);
PageResult<SecretKey> listSecretKey(SecretKeyDto secretKeyDto); PageResult<SecretKeyDO> getSecretKeypage(@Valid SecretKeyVO secretKeyVO);
boolean deleteList(List<Long> secretKeyIds); void deleteSecretKeyList(List<Long> ids);
SecretKeyVO getSecretKey(Long id);
} }

View File

@ -1,5 +1,4 @@
package cd.casic.module.machine.service.impl; package cd.casic.module.machine.service.impl;
import cd.casic.module.machine.convert.MachineEnvConvert;
import cd.casic.module.machine.controller.vo.MachineEnvVO; import cd.casic.module.machine.controller.vo.MachineEnvVO;
import cd.casic.module.machine.dal.dataobject.MachineEnvDO; import cd.casic.module.machine.dal.dataobject.MachineEnvDO;
import cd.casic.module.machine.dal.mysql.MachineEnvMapper; import cd.casic.module.machine.dal.mysql.MachineEnvMapper;
@ -45,11 +44,8 @@ public class MachineEnvServiceImpl implements MachineEnvService {
@Override @Override
public MachineEnvVO getEnv(Long machineId) { public MachineEnvVO getEnv(Long machineId) {
if (machineId == null) { MachineEnvDO machineEnvDO = validateMachineEnvExists(machineId);
return null; return BeanUtils.toBean(machineEnvDO, MachineEnvVO.class);
}
MachineEnvDO machineEnvDO = machineEnvMapper.selectById(machineId);
return machineEnvDO != null ? MachineEnvConvert.INSTANCE.convertToVO(machineEnvDO) : null;
} }

View File

@ -6,10 +6,7 @@ import cd.casic.module.machine.enums.MachineProxyStatus;
import cd.casic.module.machine.enums.MachineProxyType; import cd.casic.module.machine.enums.MachineProxyType;
import cd.casic.module.machine.dal.mysql.MachineProxyMapper; import cd.casic.module.machine.dal.mysql.MachineProxyMapper;
import cd.casic.module.machine.service.MachineProxyService; import cd.casic.module.machine.service.MachineProxyService;
import cd.casic.module.machine.utils.EnumUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.annotations.VisibleForTesting; import com.google.common.annotations.VisibleForTesting;
import jakarta.annotation.Resource; import jakarta.annotation.Resource;
import cd.casic.framework.commons.util.object.BeanUtils; import cd.casic.framework.commons.util.object.BeanUtils;
@ -19,16 +16,14 @@ import org.springframework.util.CollectionUtils;
import java.util.*; import java.util.*;
import java.util.function.Function; import java.util.function.Function;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import static cd.casic.framework.commons.exception.util.ServiceExceptionUtil.exception; import static cd.casic.framework.commons.exception.util.ServiceExceptionUtil.exception;
import static cd.casic.module.machine.contants.MachineErrorCodeConstants.*; import static cd.casic.module.machine.contants.MachineErrorCodeConstants.*;
import static com.baomidou.mybatisplus.extension.toolkit.Db.save; import static com.baomidou.mybatisplus.extension.toolkit.Db.save;
import static org.apache.catalina.security.SecurityUtil.remove;
/** /**
* 机器代理服务实现类 * 机器代理服务实现类
*/ */
@Service @Service("machineProxyService")
public class MachineProxyServiceImpl implements MachineProxyService { public class MachineProxyServiceImpl implements MachineProxyService {
@Resource @Resource
private MachineProxyMapper machineProxyMapper; private MachineProxyMapper machineProxyMapper;

View File

@ -1,354 +1,370 @@
//package cd.casic.module.machine.service.impl; package cd.casic.module.machine.service.impl;
//import cd.casic.module.machine.enums.MachineInfoType; import cd.casic.framework.commons.pojo.PageResult;
//import cd.casic.module.machine.handler.ConnectionSession; import cd.casic.module.machine.controller.vo.SecretKeyVO;
//import cd.casic.module.machine.dal.mysql.MachineInfoMapper; import cd.casic.module.machine.enums.AuthenticationType;
//import cd.casic.module.machine.controller.vo.MachineInfoDto; import cd.casic.module.machine.enums.MachineInfoType;
//import cd.casic.module.machine.dal.dataobject.MachineInfo; import cd.casic.module.machine.handler.ConnectionSession;
//import cd.casic.module.machine.enums.AuthenticationType; import cd.casic.module.machine.dal.mysql.MachineInfoMapper;
//import cd.casic.module.machine.enums.ConnectionStatus; import cd.casic.module.machine.controller.vo.MachineInfoVO;
//import cd.casic.module.machine.enums.MachineInfoStatus; import cd.casic.module.machine.dal.dataobject.MachineInfoDO;
//import cd.casic.module.machine.service.MachineInfoService; import cd.casic.module.machine.enums.ConnectionStatus;
//import cd.casic.module.machine.utils.EnumUtils; import cd.casic.module.machine.enums.MachineInfoStatus;
//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import cd.casic.module.machine.service.MachineInfoService;
//import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import cd.casic.module.machine.service.SecretKeyService;
//import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.google.common.annotations.VisibleForTesting;
//import jakarta.annotation.Resource; import jakarta.annotation.Resource;
//import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.BeanUtils; import cd.casic.framework.commons.util.object.BeanUtils;
//import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
//import java.util.Arrays; import org.springframework.transaction.annotation.Transactional;
//import java.util.HashMap;
//import java.util.List; import java.util.*;
//import java.util.Map; import java.util.concurrent.ConcurrentHashMap;
//import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger;
//import java.util.concurrent.atomic.AtomicInteger;
//import java.util.stream.Collectors; import static cd.casic.framework.commons.exception.util.ServiceExceptionUtil.exception;
// import static cd.casic.module.machine.contants.MachineErrorCodeConstants.*;
//@Slf4j
//@Service("machineInfoService") /**
//public class MachineinfoServiceImpl implements MachineInfoService { * 机器信息服务实现类
// */
// int ENABLE = 1; @Slf4j
// int UN_ENABLE = 0; @Service("machineInfoService")
// public class MachineinfoServiceImpl implements MachineInfoService {
// @Resource
// private MachineInfoMapper machineInfoMapper; @Resource
// @Resource private SecretKeyService secretKeyService;
// private ConnectionSession connectionSession; @Resource
// /** private MachineInfoMapper machineInfoMapper;
// * 会话ID生成器 @Resource
// */ private ConnectionSession connectionSession;
// private final AtomicInteger sessionIdGenerator = new AtomicInteger(1000); /**
// * 会话ID生成器
// /** */
// * 会话管理会话ID -> 连接会话 private final AtomicInteger sessionIdGenerator = new AtomicInteger(1000);
// */
// private final Map<String, ConnectionSession> sessions = new ConcurrentHashMap<>(); /**
// * 会话管理会话ID -> 连接会话
// /** */
// * 机器名称 -> 会话ID private final Map<String, ConnectionSession> sessions = new ConcurrentHashMap<>();
// */
// private final Map<String, String> machineSessionMapping = new ConcurrentHashMap<>(); /**
// * 机器名称 -> 会话ID
// @Override */
// public boolean addMachineInfo(MachineInfoDto machineInfoDto) { private final Map<String, String> machineSessionMapping = new ConcurrentHashMap<>();
// if (machineInfoDto == null) {
// throw new ServiceException(ServiceException.MACHINE_INFO_NULL, "机器信息为空"); @Override
// } public Long createMachine(MachineInfoVO machineInfoVO) {
// MachineInfo machineInfo = new MachineInfo(); validateMachineEnvAdd(machineInfoVO);
// BeanUtils.copyProperties(machineInfoDto, machineInfo); validateMachineTagUnique(machineInfoVO.getTag());
// machineInfo.setStatusCode(1); MachineInfoDO machineInfoDO = BeanUtils.toBean(machineInfoVO, MachineInfoDO.class);
// machineInfo.setAuthenticationTypeCode( Long secretKeyId = machineInfoDO.getSecretKeyId();
// "密码认证".equals(machineInfoDto.getAuthenticationType()) SecretKeyVO secretKey = secretKeyService.getSecretKey(secretKeyId);
// ? AuthenticationType.PASSWORD.getCode() if (secretKey==null){
// : AuthenticationType.SECRET_KEY.getCode() throw exception(SECRET_KEY_NOT_EXISTS);
// ); }
// machineInfo.setMachineInfoTypeCode( machineInfoMapper.insert(machineInfoDO);
// "Windows".equals(machineInfoDto.getMachineInfoType()) Long id = machineInfoDO.getId();
// ? MachineInfoType.WINDOWS.getCode() return id;
// : MachineInfoType.Linux.getCode() }
// );
// @Override
// return this.save(machineInfo); public void updateMachineInfo(MachineInfoVO machineInfoVO) {
// } validateMachineEnvAdd(machineInfoVO);
// String newTag = machineInfoVO.getTag();
// @Override MachineInfoDO machineInfoDO = validateMachineInfoExists(machineInfoVO.getId());
// public PageResult<MachineInfoDto> listMachineInfo(MachineInfoDto machineInfoDto) { String oldTag = machineInfoDO.getTag();
// QueryWrapper<MachineInfo> queryWrapper = getMachineInfoQueryWrapper(machineInfoDto); if (!newTag.equals(oldTag)){
// Page<MachineInfo> page = machineInfoMapper.selectPage( validateMachineTagUnique(newTag);
// new Page<>(machineInfoDto.getPageIndex(), machineInfoDto.getPageSize()), }
// queryWrapper BeanUtils.copyProperties(machineInfoVO, machineInfoDO);
// ); machineInfoMapper.updateById(machineInfoDO);
// }
// List<MachineInfoDto> machineInfoDtos = page.getRecords().stream()
// .map(machineInfo -> { @Override
// MachineInfoDto dto = new MachineInfoDto(); public Integer updateStatus(Long machineInfoId, Integer status) {
// BeanUtils.copyProperties(machineInfo, dto); machineInfoMapper.updateStatus(machineInfoId, status);
// // 直接调用原有枚举转换方法 return machineInfoMapper.selectById(machineInfoId).getStatus();
// dto.setMachineInfoType(EnumUtils.getEnumByCode(machineInfo.getMachineInfoTypeCode(), MachineInfoType.class).getMessage()); }
// dto.setStatus(EnumUtils.getEnumByCode(machineInfo.getStatusCode(), MachineInfoStatus.class).getMessage());
// dto.setAuthenticationType(EnumUtils.getEnumByCode(machineInfo.getAuthenticationTypeCode(), AuthenticationType.class).getMessage()); @Override
// return dto; public PageResult<MachineInfoDO> listMachineInfo(MachineInfoVO machineInfoVO) {
// }) return machineInfoMapper.selectPage(machineInfoVO);
// .toList(); }
//
// return new PageResult<>( @Override
// page.getCurrent(), public void bindingSecretKey(List<Long> machineInfoId,Long secretKeyId) {
// page.getSize(), machineInfoMapper.bindingSecretKey(machineInfoId,secretKeyId);
// page.getTotal(), }
// page.getPages(),
// machineInfoDtos @Override
// ); @Transactional//其中一个在线那么就回滚
// } public void deleteMachineInfoList(String machineInfoIds) {
// List<Long> machineInfoIdList = Arrays.stream(machineInfoIds.split(","))
// @Override .map(String::trim)
// public boolean updateMachineInfo(MachineInfoDto machineInfoDto) { .filter(s -> !s.isEmpty())
// MachineInfo machineInfo = new MachineInfo(); .map(Long::parseLong)
// BeanUtils.copyProperties(machineInfoDto, machineInfo); .toList();
// machineInfo.setAuthenticationTypeCode( machineInfoIdList.forEach(this::deleteMachineInfo);
// "密码认证".equals(machineInfoDto.getAuthenticationType()) }
// ? AuthenticationType.PASSWORD.getCode()
// : AuthenticationType.SECRET_KEY.getCode() @Override
// ); public void deleteMachineInfo(Long machineInfoId) {
// machineInfo.setMachineInfoTypeCode( MachineInfoDO machineInfoDO = validateMachineInfoExists(machineInfoId);
// "Windows".equals(machineInfoDto.getMachineInfoType()) validateMachineEnable(machineInfoDO);
// ? MachineInfoType.WINDOWS.getCode() machineInfoMapper.deleteById(machineInfoId);
// : MachineInfoType.Linux.getCode() }
// );
// return this.updateById(machineInfo);
// } @Override
// public boolean testConnection(Long id) {
// @Override //先查询机器是否存在在判断机器可用性
// public boolean updateStatus(MachineInfoDto machineInfoDto) { MachineInfoDO machineInfoDO = validateMachineInfoExists(id);
// UpdateWrapper<MachineInfo> updateWrapper = new UpdateWrapper<>(); validateMachineUnEnable(machineInfoDO);
// updateWrapper.eq("id", machineInfoDto.getId()).set("status_code", EnumUtils.getEnumByMessage(machineInfoDto.getStatus(), MachineInfoStatus.class).getCode()); log.info("测试机器连接: {}", machineInfoDO.getHostIp());
// return this.update(updateWrapper); connectionSession.setMachineInfo(machineInfoDO);
// } try{
// connectionSession.connect();
// @Override return true;
// public boolean bindingSecretKey(MachineInfoDto machineInfoDto) { } catch (Exception e) {
// UpdateWrapper<MachineInfo> updateWrapper = new UpdateWrapper<>(); log.error("机器连接测试失败: {}", e.getMessage(), e);
// updateWrapper.eq("id", machineInfoDto.getId()).set("secret_key_id", machineInfoDto.getSecretKeyId()).set("authentication_type_code", 2); return false;
// return this.update(updateWrapper); }
// } }
//
// @Override @Override
// public void deleteList(String machineInfoIds) { public ConnectionStatus getConnectionStatus(String machineName) {
// List<Long> machineInfoIdList = Arrays.stream(machineInfoIds.split(",")) String sessionId = machineSessionMapping.get(machineName);
// .map(String::trim) if (sessionId == null) {
// .filter(s -> !s.isEmpty()) return ConnectionStatus.DISCONNECTED;
// .map(Long::parseLong) }
// .collect(Collectors.toList());
// machineInfoMapper.selectBatchIds(machineInfoIdList).forEach(machineInfo -> { ConnectionSession session = sessions.get(sessionId);
// if (machineInfo.getStatusCode() == 1) { return session != null ? session.getStatus() : ConnectionStatus.DISCONNECTED;
// this.removeById(machineInfo.getId()); }
// }
// }); @Override
// } public Map<String, ConnectionStatus> getAllConnectionStatus() {
// Map<String, ConnectionStatus> result = new HashMap<>();
// @Override
// public void deleteMachineInfo(Long machineInfoId) { machineSessionMapping.forEach((machineName, sessionId) -> {
// MachineInfo machineInfo = this.getById(machineInfoId); ConnectionSession session = sessions.get(sessionId);
// if (machineInfo.getStatusCode() == 1) { result.put(machineName, session != null ? session.getStatus() : ConnectionStatus.DISCONNECTED);
// this.removeById(machineInfoId); });
// }
// } return result;
// }
// private QueryWrapper<MachineInfo> getMachineInfoQueryWrapper(MachineInfoDto machineInfoDto) {
// QueryWrapper<MachineInfo> queryWrapper = new QueryWrapper<>(); @Override
// if (machineInfoDto.getStatus() != null && !machineInfoDto.getStatus().isEmpty()) { public String connect(MachineInfoDO machineInfoDO) {
// queryWrapper.eq("status_code", EnumUtils.getEnumByMessage(machineInfoDto.getStatus(), MachineInfoStatus.class).getCode()); //先查询机器是否存在在判断机器可用性
// } validateMachineUnEnable(machineInfoDO);
// if (machineInfoDto.getName() != null && !machineInfoDto.getName().isEmpty()) { log.info("建立机器连接: {}", machineInfoDO.getHostIp());
// queryWrapper.like("name", machineInfoDto.getName());
// } // 检查是否已连接
// if (machineInfoDto.getTag() != null && !machineInfoDto.getTag().isEmpty()) { String existingSessionId = machineSessionMapping.get(machineInfoDO.getName());
// queryWrapper.like("tag", machineInfoDto.getTag()); if (existingSessionId != null) {
// } ConnectionSession existingSession = sessions.get(existingSessionId);
// if (machineInfoDto.getHostIp() != null && !machineInfoDto.getHostIp().isEmpty()) { if (existingSession != null && existingSession.getStatus() == ConnectionStatus.CONNECTED) {
// queryWrapper.like("host_ip", machineInfoDto.getHostIp()); log.info("机器已连接,返回现有会话: {}", machineInfoDO.getHostIp());
// } return existingSessionId;
// if (machineInfoDto.getDescription() != null && !machineInfoDto.getDescription().isEmpty()) { }
// queryWrapper.like("description", machineInfoDto.getDescription()); }
// }
// return queryWrapper.orderByDesc("create_date"); try {
// } connectionSession.setMachineInfo(machineInfoDO);
//
// connectionSession.connect();
// @Override
// public boolean testConnection(Long id) { // 生成会话ID
// //先查询机器是否存在在判断机器可用性 String sessionId = generateSessionId();
// MachineInfo machineInfo = machineInfoMapper.getById(id);
// if (machineInfo==null){ // 保存会话
// throw new RuntimeException("机器不存在"); sessions.put(sessionId, connectionSession);
// } machineSessionMapping.put(machineInfoDO.getName(), sessionId);
// if (machineInfo.getStatusCode() == 0) {
// throw new RuntimeException("机器不可用"); log.info("机器连接成功: {}, 会话ID: {}", machineInfoDO.getHostIp(), sessionId);
// } return sessionId;
// log.info("测试机器连接: {}", machineInfo.getHostIp()); } catch (Exception e) {
// connectionSession.setMachineInfo(machineInfo); log.error("机器连接失败: {}", e.getMessage(), e);
// try{ throw new RuntimeException("机器连接失败: " + e.getMessage(), e);
// connectionSession.connect(); }
// return true; }
// } catch (Exception e) {
// log.error("机器连接测试失败: {}", e.getMessage(), e); @Override
// return false; public boolean disconnect(String sessionId) {
// } log.info("断开机器连接: {}", sessionId);
// }
// ConnectionSession session = sessions.get(sessionId);
// @Override if (session == null) {
// public ConnectionStatus getConnectionStatus(String machineName) { log.warn("会话不存在: {}", sessionId);
// String sessionId = machineSessionMapping.get(machineName); return false;
// if (sessionId == null) { }
// return ConnectionStatus.DISCONNECTED;
// } try {
// session.disconnect();
// ConnectionSession session = sessions.get(sessionId);
// return session != null ? session.getStatus() : ConnectionStatus.DISCONNECTED; // 清理会话
// } sessions.remove(sessionId);
// machineSessionMapping.entrySet().removeIf(entry -> entry.getValue().equals(sessionId));
// @Override
// public Map<String, ConnectionStatus> getAllConnectionStatus() { log.info("机器连接已断开: {}", sessionId);
// Map<String, ConnectionStatus> result = new HashMap<>(); return true;
// } catch (Exception e) {
// machineSessionMapping.forEach((machineName, sessionId) -> { log.error("断开连接失败: {}", e.getMessage(), e);
// ConnectionSession session = sessions.get(sessionId); return false;
// result.put(machineName, session != null ? session.getStatus() : ConnectionStatus.DISCONNECTED); }
// }); }
//
// return result; @Override
// } public String executeCommand(String sessionId, String command) {
// log.info("执行命令: {}, 会话ID: {}", command, sessionId);
// @Override
// public String connect(MachineInfo machineInfo) { ConnectionSession session = sessions.get(sessionId);
// if (machineInfo.getStatus().getCode() == UN_ENABLE) { if (session == null) {
// throw new RuntimeException("机器不可用"); throw new RuntimeException("会话不存在: " + sessionId);
// } }
// log.info("建立机器连接: {}", machineInfo.getHostIp());
// if (session.getStatus() != ConnectionStatus.CONNECTED) {
// // 检查是否已连接 throw new RuntimeException("会话未连接: " + sessionId);
// String existingSessionId = machineSessionMapping.get(machineInfo.getName()); }
// if (existingSessionId != null) {
// ConnectionSession existingSession = sessions.get(existingSessionId); try {
// if (existingSession != null && existingSession.getStatus() == ConnectionStatus.CONNECTED) { return session.executeCommand(command);
// log.info("机器已连接,返回现有会话: {}", machineInfo.getHostIp()); } catch (Exception e) {
// return existingSessionId; log.error("命令执行失败: {}", e.getMessage(), e);
// } throw new RuntimeException("命令执行失败: " + e.getMessage(), e);
// } }
// }
// try {
// connectionSession.setMachineInfo(machineInfo); @Override
// public boolean uploadFile(String sessionId, String localFilePath, String remoteFilePath) {
// connectionSession.connect(); log.info("上传文件: {} -> {}, 会话ID: {}", localFilePath, remoteFilePath, sessionId);
//
// // 生成会话ID ConnectionSession session = sessions.get(sessionId);
// String sessionId = generateSessionId(); if (session == null) {
// throw new RuntimeException("会话不存在: " + sessionId);
// // 保存会话 }
// sessions.put(sessionId, connectionSession);
// machineSessionMapping.put(machineInfo.getName(), sessionId); if (session.getStatus() != ConnectionStatus.CONNECTED) {
// throw new RuntimeException("会话未连接: " + sessionId);
// log.info("机器连接成功: {}, 会话ID: {}", machineInfo.getHostIp(), sessionId); }
// return sessionId;
// } catch (Exception e) { try {
// log.error("机器连接失败: {}", e.getMessage(), e); return session.uploadFile(localFilePath, remoteFilePath);
// throw new RuntimeException("机器连接失败: " + e.getMessage(), e); } catch (Exception e) {
// } log.error("文件上传失败: {}", e.getMessage(), e);
// } throw new RuntimeException("文件上传失败: " + e.getMessage(), e);
// }
// @Override }
// public boolean disconnect(String sessionId) {
// log.info("断开机器连接: {}", sessionId); @Override
// public boolean downloadFile(String sessionId, String remoteFilePath, String localFilePath) {
// ConnectionSession session = sessions.get(sessionId); log.info("下载文件: {} -> {}, 会话ID: {}", remoteFilePath, localFilePath, sessionId);
// if (session == null) {
// log.warn("会话不存在: {}", sessionId); ConnectionSession session = sessions.get(sessionId);
// return false; if (session == null) {
// } throw new RuntimeException("会话不存在: " + sessionId);
// }
// try {
// session.disconnect(); if (session.getStatus() != ConnectionStatus.CONNECTED) {
// throw new RuntimeException("会话未连接: " + sessionId);
// // 清理会话 }
// sessions.remove(sessionId);
// machineSessionMapping.entrySet().removeIf(entry -> entry.getValue().equals(sessionId)); try {
// return session.downloadFile(remoteFilePath, localFilePath);
// log.info("机器连接已断开: {}", sessionId); } catch (Exception e) {
// return true; log.error("文件下载失败: {}", e.getMessage(), e);
// } catch (Exception e) { throw new RuntimeException("文件下载失败: " + e.getMessage(), e);
// log.error("断开连接失败: {}", e.getMessage(), e); }
// return false; }
// }
// } @Override
// public void unBindingSecretKey(List<Long> SecretKeyIds) {
// @Override machineInfoMapper.unBindingSecretKey(SecretKeyIds);
// public String executeCommand(String sessionId, String command) { }
// log.info("执行命令: {}, 会话ID: {}", command, sessionId);
// @VisibleForTesting
// ConnectionSession session = sessions.get(sessionId); void validateMachineEnvAdd(MachineInfoVO machineInfoVO) {
// if (session == null) { if (machineInfoVO.getHostIp().isEmpty()) {
// throw new RuntimeException("会话不存在: " + sessionId); throw exception(MACHINE_INFO_HOST_IP_NULL);
// } }
// if (machineInfoVO.getUsername().isEmpty()){
// if (session.getStatus() != ConnectionStatus.CONNECTED) { throw exception(MACHINE_INFO_USER_NAME_NULL);
// throw new RuntimeException("会话未连接: " + sessionId); }
// } if(machineInfoVO.getTag().isEmpty()){
// throw exception(MACHINE_INFO_TAG_NULL);
// try { }
// return session.executeCommand(command);
// } catch (Exception e) { if (machineInfoVO.getAuthenticationType()!=null){
// log.error("命令执行失败: {}", e.getMessage(), e); boolean flag=true;
// throw new RuntimeException("命令执行失败: " + e.getMessage(), e); for (int type : AuthenticationType.ARRAYS) {
// } if (type == machineInfoVO.getAuthenticationType()) {
// } flag=false;
// break;
// @Override }
// public boolean uploadFile(String sessionId, String localFilePath, String remoteFilePath) { if (flag){
// log.info("上传文件: {} -> {}, 会话ID: {}", localFilePath, remoteFilePath, sessionId); throw exception(MACHINE_INFO_AUTHENTICATION_TYPE_NOT_EXISTS);
// }
// ConnectionSession session = sessions.get(sessionId); }
// if (session == null) { }else {
// throw new RuntimeException("会话不存在: " + sessionId); throw exception(MACHINE_INFO_AUTHENTICATION_TYPE_NULL);
// } }
//
// if (session.getStatus() != ConnectionStatus.CONNECTED) {
// throw new RuntimeException("会话未连接: " + sessionId); if (machineInfoVO.getMachineInfoType()!= null){
// } boolean flag = true;
// for (int type : MachineInfoType.ARRAYS) {
// try { if (type == machineInfoVO.getMachineInfoType()) {
// return session.uploadFile(localFilePath, remoteFilePath); flag=false;
// } catch (Exception e) { break;
// log.error("文件上传失败: {}", e.getMessage(), e); }
// throw new RuntimeException("文件上传失败: " + e.getMessage(), e); }
// } if (flag) {
// } throw exception(MACHINE_INFO_TYPE_NOT_EXISTS);
// }
// @Override }else {
// public boolean downloadFile(String sessionId, String remoteFilePath, String localFilePath) { throw exception(MACHINE_INFO_TYPE_NULL);
// log.info("下载文件: {} -> {}, 会话ID: {}", remoteFilePath, localFilePath, sessionId); }
//
// ConnectionSession session = sessions.get(sessionId); }
// if (session == null) {
// throw new RuntimeException("会话不存在: " + sessionId); @VisibleForTesting
// } void validateMachineTagUnique(String tag){
// if (machineInfoMapper.existsByTag(tag)) {
// if (session.getStatus() != ConnectionStatus.CONNECTED) { throw exception(MACHINE_INFO_TAG_EXISTS);
// throw new RuntimeException("会话未连接: " + sessionId); }
// } }
// @VisibleForTesting
// try { MachineInfoDO validateMachineInfoExists(Long id) {
// return session.downloadFile(remoteFilePath, localFilePath); if (id == null) {
// } catch (Exception e) { return null;
// log.error("文件下载失败: {}", e.getMessage(), e); }
// throw new RuntimeException("文件下载失败: " + e.getMessage(), e); MachineInfoDO machineInfoDO = machineInfoMapper.selectById(id);
// } if (machineInfoDO == null) {
// } throw exception(MACHINE_INFO_NULL);
// }
// return machineInfoDO;
// /** }
// * 生成会话ID @VisibleForTesting
// */ void validateMachineEnable(MachineInfoDO machineInfoDO) {
// private String generateSessionId() {
// return "session-" + sessionIdGenerator.incrementAndGet(); if (machineInfoDO.getStatus()==MachineInfoStatus.ENABLE.getCode()){
// } throw exception(MACHINE_ENABLE);
//} }
}
@VisibleForTesting
void validateMachineUnEnable(MachineInfoDO machineInfoDO) {
if (machineInfoDO.getStatus()==MachineInfoStatus.UN_ENABLE.getCode()){
throw exception(MACHINE_UN_ENABLE);
}
}
/**
* 生成会话ID
*/
private String generateSessionId() {
return "session-" + sessionIdGenerator.incrementAndGet();
}
}

View File

@ -1,159 +1,157 @@
//package cd.casic.module.machine.service.impl; package cd.casic.module.machine.service.impl;
// import cd.casic.framework.commons.pojo.PageResult;
//import cd.casic.module.machine.controller.vo.SecretKeyDto; import cd.casic.framework.commons.util.object.BeanUtils;
//import cd.casic.module.machine.dal.dataobject.MachineInfo; import cd.casic.module.machine.controller.vo.SecretKeyVO;
//import cd.casic.module.machine.dal.dataobject.SecretKey; import cd.casic.module.machine.dal.dataobject.SecretKeyDO;
//import cd.casic.module.machine.dal.mysql.SecretServiceMapper; import cd.casic.module.machine.dal.mysql.SecretKeyMapper;
//import cd.casic.module.machine.service.MachineInfoService; import cd.casic.module.machine.service.MachineInfoService;
//import cn.hutool.core.io.resource.ResourceUtil; import cn.hutool.core.io.resource.ResourceUtil;
//import cn.hutool.core.util.IdUtil; import cn.hutool.core.util.IdUtil;
//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import cd.casic.module.machine.utils.AliYunOssClient;
//import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import cd.casic.module.machine.service.SecretKeyService;
//import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.google.common.annotations.VisibleForTesting;
// import jakarta.annotation.Resource;
//import cd.casic.module.machine.utils.AliYunOssClient; import org.springframework.stereotype.Service;
//import cd.casic.module.machine.exception.ServiceException; import org.springframework.transaction.annotation.Transactional;
////import cd.casic.module.machine.service.MachineInfoService;
//import cd.casic.module.machine.service.SecretKeyService; import java.util.List;
//import jakarta.annotation.Resource; import static cd.casic.framework.commons.exception.util.ServiceExceptionUtil.exception;
//import org.springframework.beans.BeanUtils; import static cd.casic.module.machine.contants.MachineErrorCodeConstants.*;
//import org.springframework.stereotype.Service;
// /**
//import java.util.List; * 密钥服务实现类
// */
//@Service @Service("secretKeyService")
//public class SecretKeyServiceImpl extends ServiceImpl<SecretServiceMapper, SecretKey> implements SecretKeyService { public class SecretKeyServiceImpl implements SecretKeyService {
//
// @Resource @Resource
// private MachineInfoService machineInfoService; private MachineInfoService machineInfoService;
//
// @Resource @Resource
// private AliYunOssClient aliYunOssClient; private AliYunOssClient aliYunOssClient;
//
// @Resource @Resource
// private SecretServiceMapper secretServiceMapper; private SecretKeyMapper secretKeyMapper;
//
//
//
// @Override
// @Override public SecretKeyVO getSecretKey(Long id){
// public boolean addSecretKey(SecretKeyDto secretKeyDto){ SecretKeyDO secretKeyDO = validateSecretKeyExists(id);
// if (secretKeyDto.getPath()==null) return BeanUtils.toBean(secretKeyDO, SecretKeyVO.class);
// { }
// throw new ServiceException(ServiceException.MACHINE_PROXY_NULL,"密钥不能为空");
// } @Override
// public Long createSecretKey(SecretKeyVO secretKeyVO){
// String ossPath = upLoadSecretKey(secretKeyDto.getPath()); validateSecretKeyAdd(secretKeyVO);
// if (ossPath == null){ String ossPath = upLoadSecretKey(secretKeyVO.getPath());
// throw new ServiceException(ServiceException.MACHINE_PROXY_NULL,"密钥上传失败"); //检查得到的oss路径是否为空
// } validateSecretKeyPath(ossPath);
// secretKeyDto.setPath(ossPath); secretKeyVO.setPath(ossPath);
// SecretKey secretKey = new SecretKey(); SecretKeyDO secretKeyDO = BeanUtils.toBean(secretKeyVO, SecretKeyDO.class);
// BeanUtils.copyProperties(secretKeyDto,secretKey); //todo检查密钥合法
// //todo检查密钥合法
// return this.save(secretKey); secretKeyMapper.insert(secretKeyDO);
// return secretKeyDO.getId();
//
// }
// @Override }
// public boolean updateSecretKey(SecretKeyDto secretKeyDto) { @Override
// public void updateSecretKey(SecretKeyVO secretKeyVO) {
// Long id = secretKeyDto.getId(); SecretKeyDO secretKeyDO = validateSecretKeyExists(secretKeyVO.getId());
// SecretKey secretKey = this.getById(id); //如果路径改变==改变密钥
// if (secretKey == null){ if (!secretKeyDO.getPath().equals(secretKeyVO.getPath())) {
// throw new ServiceException(ServiceException.MACHINE_PROXY_NULL,"密钥不存在"); //todo检查密钥合法
// } String ossPath = upLoadSecretKey(secretKeyVO.getPath());
// if (!secretKey.getPath().equals(secretKeyDto.getPath())) { BeanUtils.copyProperties(secretKeyVO, secretKeyDO);
// //todo检查密钥合法 secretKeyDO.setPath(ossPath);
// String ossPath = upLoadSecretKey(secretKeyDto.getPath()); }
// BeanUtils.copyProperties(secretKeyDto,secretKey); else {
// secretKey.setPath(ossPath); BeanUtils.copyProperties(secretKeyVO,secretKeyDO);
// } }
// else { secretKeyMapper.updateById(secretKeyDO);
// BeanUtils.copyProperties(secretKeyDto,secretKey); }
// }
// @Override
// return this.updateById(secretKey); public void bindingMachine(Long id,List<Long> machineInfoIds) {
// validateSecretKeyExists(id);
// machineInfoService.bindingSecretKey(machineInfoIds, id);
// } }
//
// @Override @Override
// public void bindingMachine(Long secretKeyId, List<Long> machineIds) { @Transactional
// SecretKey secretKey = this.getById(secretKeyId); public void deleteSecretKeyList(List<Long> ids) {
// if (secretKey==null){ ids.forEach(
// throw new ServiceException(ServiceException.SECRETKEY_NULL,"密钥不存在"); secretKeyId -> {
// } SecretKeyDO secretKeyDO = validateSecretKeyExists(secretKeyId);
// List<MachineInfo> machineList = machineInfoService.listByIds(machineIds); if (secretKeyDO.getPath() != null && !secretKeyDO.getPath().isEmpty()){
// machineList.forEach(machine -> machine.setSecretKeyId(secretKeyId)); try {
// machineInfoService.updateBatchById(machineList); //文件名
// } //删除子目录文件需要在前面加上根目录文件路径
// String fileName = secretKeyDO.getPath().substring(secretKeyDO.getPath().lastIndexOf("/") + 1);
// aliYunOssClient.delete(fileName);
// } catch (Exception e) {
// throw exception(DELETE_FILE_FAIL);
// }
// @Override }
// public PageResult<SecretKey> listSecretKey(SecretKeyDto secretKeyDto) { }
// QueryWrapper<SecretKey> queryWrapper = new QueryWrapper<>(); );
// if (secretKeyDto.getName() != null && !secretKeyDto.getName().isEmpty()){
// queryWrapper.like("name", secretKeyDto.getName()); //绑定的机器全部设置为空
// } machineInfoService.unBindingSecretKey(ids);
// if (secretKeyDto.getDescription() != null && !secretKeyDto.getDescription().isEmpty()){
// queryWrapper.like("description", secretKeyDto.getDescription()); secretKeyMapper.deleteBatchIds(ids);
// } }
// Page<SecretKey> page = secretServiceMapper.selectPage(new Page<>(secretKeyDto.getPageIndex(), secretKeyDto.getPageSize()), queryWrapper);
// return new PageResult<>( @Override
// page.getCurrent(), public PageResult<SecretKeyDO> getSecretKeypage(SecretKeyVO secretKeyVO) {
// page.getSize(), return secretKeyMapper.selectPage(secretKeyVO);
// page.getTotal(), }
// page.getPages(),
// page.getRecords() public String upLoadSecretKey(String localPath) {
// ); //使用S3FileClient上传文件
// } aliYunOssClient.init();
// //传输到指定文件需要在path前面加上文件路径
// String path = IdUtil.fastSimpleUUID() + ".txt";
// //上传文件是从本地上传这里传的是本地文件地址
// @Override byte[] content = ResourceUtil.readBytes(localPath);
// public boolean deleteList(List<Long> secretKeyIds) { String ossPath;
// List<SecretKey> secretKeys = this.listByIds(secretKeyIds); try {
// ossPath = aliYunOssClient.upload(content, path, "txt");
// for (SecretKey secretKey : secretKeys) { }catch (Exception e) {
// if (secretKey.getPath() != null && !secretKey.getPath().isEmpty()){ throw exception(UPLOADING_FILE_FAIL);
// try { }
// //文件名 return ossPath;
// //删除子目录文件需要在前面加上根目录文件路径 }
// String fileName = secretKey.getPath().substring(secretKey.getPath().lastIndexOf("/") + 1);
// aliYunOssClient.delete(fileName); @VisibleForTesting
// } catch (Exception e) { void validateSecretKeyAdd(SecretKeyVO secretKeyVO) {
// throw new RuntimeException(e); if (secretKeyVO==null) {
// } throw exception(SECRET_KEY_NULL);
// } }
// } if (secretKeyVO.getPath().isEmpty()) {
// throw exception(SECRET_KEY_PATH_NULL);
// }
// //todo是否删除已经绑定的机器 }
// return secretServiceMapper.deleteBatchIds(secretKeyIds) > 0 ;
// } @VisibleForTesting
// void validateSecretKeyPath(String path) {
// if (path.isEmpty()) {
// public String upLoadSecretKey(String localPath) { throw exception(SECRET_KEY_PATH_NULL);
// }
// //使用S3FileClient上传文件 }
// aliYunOssClient.init();
//
// //传输到指定文件需要在path前面加上文件路径 @VisibleForTesting
// String path = IdUtil.fastSimpleUUID() + ".txt"; SecretKeyDO validateSecretKeyExists(Long id) {
// if (id == null) {
// return null;
// //上传文件是从本地上传这里传的是本地文件地址 }
// byte[] content = ResourceUtil.readBytes(localPath); SecretKeyDO secretKeyDO = secretKeyMapper.selectById(id);
// String ossPath; if (secretKeyDO == null) {
// try { throw exception(SECRET_KEY_NOT_EXISTS);
// ossPath = aliYunOssClient.upload(content, path, "txt"); }
// }catch (Exception e) { return secretKeyDO;
// throw new RuntimeException(e+"上传文件失败"); }
// }
// return ossPath; }
// }
//}