更改目录结构

This commit is contained in:
liuyingfang
2024-03-02 18:31:44 +08:00
parent 8f7acca8e6
commit 0a70a66807
603 changed files with 2256 additions and 6114 deletions

View File

@@ -0,0 +1,67 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.domain;
import io.swagger.annotations.ApiModelProperty;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import lombok.Getter;
import lombok.Setter;
import cn.ysk.cashier.base.BaseEntity;
import javax.persistence.*;
import java.io.Serializable;
/**
* @author zhanghouying
* @date 2019-08-24
*/
@Entity
@Getter
@Setter
@Table(name="mnt_app")
public class App extends BaseEntity implements Serializable {
@Id
@Column(name = "app_id")
@ApiModelProperty(value = "ID", hidden = true)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ApiModelProperty(value = "名称")
private String name;
@ApiModelProperty(value = "端口")
private int port;
@ApiModelProperty(value = "上传路径")
private String uploadPath;
@ApiModelProperty(value = "部署路径")
private String deployPath;
@ApiModelProperty(value = "备份路径")
private String backupPath;
@ApiModelProperty(value = "启动脚本")
private String startScript;
@ApiModelProperty(value = "部署脚本")
private String deployScript;
public void copy(App source){
BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true));
}
}

View File

@@ -0,0 +1,57 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.domain;
import io.swagger.annotations.ApiModelProperty;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import lombok.Getter;
import lombok.Setter;
import cn.ysk.cashier.base.BaseEntity;
import javax.persistence.*;
import java.io.Serializable;
/**
* @author zhanghouying
* @date 2019-08-24
*/
@Entity
@Getter
@Setter
@Table(name="mnt_database")
public class Database extends BaseEntity implements Serializable {
@Id
@Column(name = "db_id")
@ApiModelProperty(value = "ID", hidden = true)
private String id;
@ApiModelProperty(value = "数据库名称")
private String name;
@ApiModelProperty(value = "数据库连接地址")
private String jdbcUrl;
@ApiModelProperty(value = "数据库密码")
private String pwd;
@ApiModelProperty(value = "用户名")
private String userName;
public void copy(Database source){
BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true));
}
}

View File

@@ -0,0 +1,59 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.domain;
import io.swagger.annotations.ApiModelProperty;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import lombok.Getter;
import lombok.Setter;
import cn.ysk.cashier.base.BaseEntity;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Set;
/**
* @author zhanghouying
* @date 2019-08-24
*/
@Entity
@Getter
@Setter
@Table(name="mnt_deploy")
public class Deploy extends BaseEntity implements Serializable {
@Id
@Column(name = "deploy_id")
@ApiModelProperty(value = "ID", hidden = true)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToMany
@ApiModelProperty(name = "服务器", hidden = true)
@JoinTable(name = "mnt_deploy_server",
joinColumns = {@JoinColumn(name = "deploy_id",referencedColumnName = "deploy_id")},
inverseJoinColumns = {@JoinColumn(name = "server_id",referencedColumnName = "server_id")})
private Set<ServerDeploy> deploys;
@ManyToOne
@JoinColumn(name = "app_id")
@ApiModelProperty(value = "应用编号")
private App app;
public void copy(Deploy source){
BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true));
}
}

View File

@@ -0,0 +1,62 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.domain;
import io.swagger.annotations.ApiModelProperty;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.CreationTimestamp;
import javax.persistence.*;
import java.io.Serializable;
import java.sql.Timestamp;
/**
* @author zhanghouying
* @date 2019-08-24
*/
@Entity
@Getter
@Setter
@Table(name="mnt_deploy_history")
public class DeployHistory implements Serializable {
@Id
@Column(name = "history_id")
@ApiModelProperty(value = "ID", hidden = true)
private String id;
@ApiModelProperty(value = "应用名称")
private String appName;
@ApiModelProperty(value = "IP")
private String ip;
@CreationTimestamp
@ApiModelProperty(value = "部署时间")
private Timestamp deployDate;
@ApiModelProperty(value = "部署者")
private String deployUser;
@ApiModelProperty(value = "部署ID")
private Long deployId;
public void copy(DeployHistory source){
BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true));
}
}

View File

@@ -0,0 +1,80 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.domain;
import io.swagger.annotations.ApiModelProperty;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import lombok.Getter;
import lombok.Setter;
import cn.ysk.cashier.base.BaseEntity;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Objects;
/**
* @author zhanghouying
* @date 2019-08-24
*/
@Entity
@Getter
@Setter
@Table(name="mnt_server")
public class ServerDeploy extends BaseEntity implements Serializable {
@Id
@Column(name = "server_id")
@ApiModelProperty(value = "ID", hidden = true)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ApiModelProperty(value = "服务器名称")
private String name;
@ApiModelProperty(value = "IP")
private String ip;
@ApiModelProperty(value = "端口")
private Integer port;
@ApiModelProperty(value = "账号")
private String account;
@ApiModelProperty(value = "密码")
private String password;
public void copy(ServerDeploy source){
BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true));
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ServerDeploy that = (ServerDeploy) o;
return Objects.equals(id, that.id) &&
Objects.equals(name, that.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
}

View File

@@ -0,0 +1,27 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.repository;
import cn.ysk.cashier.mnt.domain.App;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
/**
* @author zhanghouying
* @date 2019-08-24
*/
public interface AppRepository extends JpaRepository<App, Long>, JpaSpecificationExecutor<App> {
}

View File

@@ -0,0 +1,27 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.repository;
import cn.ysk.cashier.mnt.domain.Database;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
/**
* @author zhanghouying
* @date 2019-08-24
*/
public interface DatabaseRepository extends JpaRepository<Database, String>, JpaSpecificationExecutor<Database> {
}

View File

@@ -0,0 +1,27 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.repository;
import cn.ysk.cashier.mnt.domain.DeployHistory;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
/**
* @author zhanghouying
* @date 2019-08-24
*/
public interface DeployHistoryRepository extends JpaRepository<DeployHistory, String>, JpaSpecificationExecutor<DeployHistory> {
}

View File

@@ -0,0 +1,27 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.repository;
import cn.ysk.cashier.mnt.domain.Deploy;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
/**
* @author zhanghouying
* @date 2019-08-24
*/
public interface DeployRepository extends JpaRepository<Deploy, Long>, JpaSpecificationExecutor<Deploy> {
}

View File

@@ -0,0 +1,34 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.repository;
import cn.ysk.cashier.mnt.domain.ServerDeploy;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
/**
* @author zhanghouying
* @date 2019-08-24
*/
public interface ServerDeployRepository extends JpaRepository<ServerDeploy, Long>, JpaSpecificationExecutor<ServerDeploy> {
/**
* 根据IP查询
* @param ip /
* @return /
*/
ServerDeploy findByIp(String ip);
}

View File

@@ -0,0 +1,87 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.rest;
import cn.ysk.cashier.mnt.domain.App;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import cn.ysk.cashier.annotation.Log;
import cn.ysk.cashier.mnt.service.AppService;
import cn.ysk.cashier.mnt.service.dto.AppQueryCriteria;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Set;
/**
* @author zhanghouying
* @date 2019-08-24
*/
@RestController
@RequiredArgsConstructor
@Api(tags = "运维:应用管理")
@RequestMapping("/api/app")
public class AppController {
private final AppService appService;
@ApiOperation("导出应用数据")
@GetMapping(value = "/download")
@PreAuthorize("@el.check('app:list')")
public void exportApp(HttpServletResponse response, AppQueryCriteria criteria) throws IOException {
appService.download(appService.queryAll(criteria), response);
}
@ApiOperation(value = "查询应用")
@GetMapping
@PreAuthorize("@el.check('app:list')")
public ResponseEntity<Object> queryApp(AppQueryCriteria criteria, Pageable pageable){
return new ResponseEntity<>(appService.queryAll(criteria,pageable),HttpStatus.OK);
}
@Log("新增应用")
@ApiOperation(value = "新增应用")
@PostMapping
@PreAuthorize("@el.check('app:add')")
public ResponseEntity<Object> createApp(@Validated @RequestBody App resources){
appService.create(resources);
return new ResponseEntity<>(HttpStatus.CREATED);
}
@Log("修改应用")
@ApiOperation(value = "修改应用")
@PutMapping
@PreAuthorize("@el.check('app:edit')")
public ResponseEntity<Object> updateApp(@Validated @RequestBody App resources){
appService.update(resources);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@Log("删除应用")
@ApiOperation(value = "删除应用")
@DeleteMapping
@PreAuthorize("@el.check('app:del')")
public ResponseEntity<Object> deleteApp(@RequestBody Set<Long> ids){
appService.delete(ids);
return new ResponseEntity<>(HttpStatus.OK);
}
}

View File

@@ -0,0 +1,123 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.rest;
import cn.ysk.cashier.mnt.util.SqlUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import cn.ysk.cashier.annotation.Log;
import cn.ysk.cashier.exception.BadRequestException;
import cn.ysk.cashier.mnt.domain.Database;
import cn.ysk.cashier.mnt.service.DatabaseService;
import cn.ysk.cashier.mnt.service.dto.DatabaseDto;
import cn.ysk.cashier.mnt.service.dto.DatabaseQueryCriteria;
import cn.ysk.cashier.utils.FileUtil;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Set;
/**
* @author zhanghouying
* @date 2019-08-24
*/
@Api(tags = "运维:数据库管理")
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/database")
public class DatabaseController {
private final String fileSavePath = FileUtil.getTmpDirPath()+"/";
private final DatabaseService databaseService;
@ApiOperation("导出数据库数据")
@GetMapping(value = "/download")
@PreAuthorize("@el.check('database:list')")
public void exportDatabase(HttpServletResponse response, DatabaseQueryCriteria criteria) throws IOException {
databaseService.download(databaseService.queryAll(criteria), response);
}
@ApiOperation(value = "查询数据库")
@GetMapping
@PreAuthorize("@el.check('database:list')")
public ResponseEntity<Object> queryDatabase(DatabaseQueryCriteria criteria, Pageable pageable){
return new ResponseEntity<>(databaseService.queryAll(criteria,pageable),HttpStatus.OK);
}
@Log("新增数据库")
@ApiOperation(value = "新增数据库")
@PostMapping
@PreAuthorize("@el.check('database:add')")
public ResponseEntity<Object> createDatabase(@Validated @RequestBody Database resources){
databaseService.create(resources);
return new ResponseEntity<>(HttpStatus.CREATED);
}
@Log("修改数据库")
@ApiOperation(value = "修改数据库")
@PutMapping
@PreAuthorize("@el.check('database:edit')")
public ResponseEntity<Object> updateDatabase(@Validated @RequestBody Database resources){
databaseService.update(resources);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@Log("删除数据库")
@ApiOperation(value = "删除数据库")
@DeleteMapping
@PreAuthorize("@el.check('database:del')")
public ResponseEntity<Object> deleteDatabase(@RequestBody Set<String> ids){
databaseService.delete(ids);
return new ResponseEntity<>(HttpStatus.OK);
}
@Log("测试数据库链接")
@ApiOperation(value = "测试数据库链接")
@PostMapping("/testConnect")
@PreAuthorize("@el.check('database:testConnect')")
public ResponseEntity<Object> testConnect(@Validated @RequestBody Database resources){
return new ResponseEntity<>(databaseService.testConnection(resources),HttpStatus.CREATED);
}
@Log("执行SQL脚本")
@ApiOperation(value = "执行SQL脚本")
@PostMapping(value = "/upload")
@PreAuthorize("@el.check('database:add')")
public ResponseEntity<Object> uploadDatabase(@RequestBody MultipartFile file, HttpServletRequest request)throws Exception{
String id = request.getParameter("id");
DatabaseDto database = databaseService.findById(id);
String fileName;
if(database != null){
fileName = file.getOriginalFilename();
File executeFile = new File(fileSavePath+fileName);
FileUtil.del(executeFile);
file.transferTo(executeFile);
String result = SqlUtils.executeFile(database.getJdbcUrl(), database.getUserName(), database.getPwd(), executeFile);
return new ResponseEntity<>(result,HttpStatus.OK);
}else{
throw new BadRequestException("Database not exist");
}
}
}

View File

@@ -0,0 +1,153 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.rest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import cn.ysk.cashier.annotation.Log;
import cn.ysk.cashier.mnt.domain.Deploy;
import cn.ysk.cashier.mnt.domain.DeployHistory;
import cn.ysk.cashier.mnt.service.DeployService;
import cn.ysk.cashier.mnt.service.dto.DeployQueryCriteria;
import cn.ysk.cashier.utils.FileUtil;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
/**
* @author zhanghouying
* @date 2019-08-24
*/
@RestController
@Api(tags = "运维:部署管理")
@RequiredArgsConstructor
@RequestMapping("/api/deploy")
public class DeployController {
private final String fileSavePath = FileUtil.getTmpDirPath()+"/";
private final DeployService deployService;
@ApiOperation("导出部署数据")
@GetMapping(value = "/download")
@PreAuthorize("@el.check('database:list')")
public void exportDeployData(HttpServletResponse response, DeployQueryCriteria criteria) throws IOException {
deployService.download(deployService.queryAll(criteria), response);
}
@ApiOperation(value = "查询部署")
@GetMapping
@PreAuthorize("@el.check('deploy:list')")
public ResponseEntity<Object> queryDeployData(DeployQueryCriteria criteria, Pageable pageable){
return new ResponseEntity<>(deployService.queryAll(criteria,pageable),HttpStatus.OK);
}
@Log("新增部署")
@ApiOperation(value = "新增部署")
@PostMapping
@PreAuthorize("@el.check('deploy:add')")
public ResponseEntity<Object> createDeploy(@Validated @RequestBody Deploy resources){
deployService.create(resources);
return new ResponseEntity<>(HttpStatus.CREATED);
}
@Log("修改部署")
@ApiOperation(value = "修改部署")
@PutMapping
@PreAuthorize("@el.check('deploy:edit')")
public ResponseEntity<Object> updateDeploy(@Validated @RequestBody Deploy resources){
deployService.update(resources);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@Log("删除部署")
@ApiOperation(value = "删除部署")
@DeleteMapping
@PreAuthorize("@el.check('deploy:del')")
public ResponseEntity<Object> deleteDeploy(@RequestBody Set<Long> ids){
deployService.delete(ids);
return new ResponseEntity<>(HttpStatus.OK);
}
@Log("上传文件部署")
@ApiOperation(value = "上传文件部署")
@PostMapping(value = "/upload")
@PreAuthorize("@el.check('deploy:edit')")
public ResponseEntity<Object> uploadDeploy(@RequestBody MultipartFile file, HttpServletRequest request)throws Exception{
Long id = Long.valueOf(request.getParameter("id"));
String fileName = "";
if(file != null){
fileName = file.getOriginalFilename();
File deployFile = new File(fileSavePath+fileName);
FileUtil.del(deployFile);
file.transferTo(deployFile);
//文件下一步要根据文件名字来
deployService.deploy(fileSavePath+fileName ,id);
}else{
System.out.println("没有找到相对应的文件");
}
System.out.println("文件上传的原名称为:"+ Objects.requireNonNull(file).getOriginalFilename());
Map<String,Object> map = new HashMap<>(2);
map.put("errno",0);
map.put("id",fileName);
return new ResponseEntity<>(map,HttpStatus.OK);
}
@Log("系统还原")
@ApiOperation(value = "系统还原")
@PostMapping(value = "/serverReduction")
@PreAuthorize("@el.check('deploy:edit')")
public ResponseEntity<Object> serverReduction(@Validated @RequestBody DeployHistory resources){
String result = deployService.serverReduction(resources);
return new ResponseEntity<>(result,HttpStatus.OK);
}
@Log("服务运行状态")
@ApiOperation(value = "服务运行状态")
@PostMapping(value = "/serverStatus")
@PreAuthorize("@el.check('deploy:edit')")
public ResponseEntity<Object> serverStatus(@Validated @RequestBody Deploy resources){
String result = deployService.serverStatus(resources);
return new ResponseEntity<>(result,HttpStatus.OK);
}
@Log("启动服务")
@ApiOperation(value = "启动服务")
@PostMapping(value = "/startServer")
@PreAuthorize("@el.check('deploy:edit')")
public ResponseEntity<Object> startServer(@Validated @RequestBody Deploy resources){
String result = deployService.startServer(resources);
return new ResponseEntity<>(result,HttpStatus.OK);
}
@Log("停止服务")
@ApiOperation(value = "停止服务")
@PostMapping(value = "/stopServer")
@PreAuthorize("@el.check('deploy:edit')")
public ResponseEntity<Object> stopServer(@Validated @RequestBody Deploy resources){
String result = deployService.stopServer(resources);
return new ResponseEntity<>(result,HttpStatus.OK);
}
}

View File

@@ -0,0 +1,67 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.rest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import cn.ysk.cashier.annotation.Log;
import cn.ysk.cashier.mnt.service.DeployHistoryService;
import cn.ysk.cashier.mnt.service.dto.DeployHistoryQueryCriteria;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Set;
/**
* @author zhanghouying
* @date 2019-08-24
*/
@RestController
@RequiredArgsConstructor
@Api(tags = "运维:部署历史管理")
@RequestMapping("/api/deployHistory")
public class DeployHistoryController {
private final DeployHistoryService deployhistoryService;
@ApiOperation("导出部署历史数据")
@GetMapping(value = "/download")
@PreAuthorize("@el.check('deployHistory:list')")
public void exportDeployHistory(HttpServletResponse response, DeployHistoryQueryCriteria criteria) throws IOException {
deployhistoryService.download(deployhistoryService.queryAll(criteria), response);
}
@ApiOperation(value = "查询部署历史")
@GetMapping
@PreAuthorize("@el.check('deployHistory:list')")
public ResponseEntity<Object> queryDeployHistory(DeployHistoryQueryCriteria criteria, Pageable pageable){
return new ResponseEntity<>(deployhistoryService.queryAll(criteria,pageable),HttpStatus.OK);
}
@Log("删除DeployHistory")
@ApiOperation(value = "删除部署历史")
@DeleteMapping
@PreAuthorize("@el.check('deployHistory:del')")
public ResponseEntity<Object> deleteDeployHistory(@RequestBody Set<String> ids){
deployhistoryService.delete(ids);
return new ResponseEntity<>(HttpStatus.OK);
}
}

View File

@@ -0,0 +1,95 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.rest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import cn.ysk.cashier.annotation.Log;
import cn.ysk.cashier.mnt.domain.ServerDeploy;
import cn.ysk.cashier.mnt.service.ServerDeployService;
import cn.ysk.cashier.mnt.service.dto.ServerDeployQueryCriteria;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Set;
/**
* @author zhanghouying
* @date 2019-08-24
*/
@RestController
@Api(tags = "运维:服务器管理")
@RequiredArgsConstructor
@RequestMapping("/api/serverDeploy")
public class ServerDeployController {
private final ServerDeployService serverDeployService;
@ApiOperation("导出服务器数据")
@GetMapping(value = "/download")
@PreAuthorize("@el.check('serverDeploy:list')")
public void exportServerDeploy(HttpServletResponse response, ServerDeployQueryCriteria criteria) throws IOException {
serverDeployService.download(serverDeployService.queryAll(criteria), response);
}
@ApiOperation(value = "查询服务器")
@GetMapping
@PreAuthorize("@el.check('serverDeploy:list')")
public ResponseEntity<Object> queryServerDeploy(ServerDeployQueryCriteria criteria, Pageable pageable){
return new ResponseEntity<>(serverDeployService.queryAll(criteria,pageable),HttpStatus.OK);
}
@Log("新增服务器")
@ApiOperation(value = "新增服务器")
@PostMapping
@PreAuthorize("@el.check('serverDeploy:add')")
public ResponseEntity<Object> createServerDeploy(@Validated @RequestBody ServerDeploy resources){
serverDeployService.create(resources);
return new ResponseEntity<>(HttpStatus.CREATED);
}
@Log("修改服务器")
@ApiOperation(value = "修改服务器")
@PutMapping
@PreAuthorize("@el.check('serverDeploy:edit')")
public ResponseEntity<Object> updateServerDeploy(@Validated @RequestBody ServerDeploy resources){
serverDeployService.update(resources);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@Log("删除服务器")
@ApiOperation(value = "删除Server")
@DeleteMapping
@PreAuthorize("@el.check('serverDeploy:del')")
public ResponseEntity<Object> deleteServerDeploy(@RequestBody Set<Long> ids){
serverDeployService.delete(ids);
return new ResponseEntity<>(HttpStatus.OK);
}
@Log("测试连接服务器")
@ApiOperation(value = "测试连接服务器")
@PostMapping("/testConnect")
@PreAuthorize("@el.check('serverDeploy:add')")
public ResponseEntity<Object> testConnectServerDeploy(@Validated @RequestBody ServerDeploy resources){
return new ResponseEntity<>(serverDeployService.testConnect(resources),HttpStatus.CREATED);
}
}

View File

@@ -0,0 +1,81 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.service;
import cn.ysk.cashier.mnt.domain.App;
import cn.ysk.cashier.mnt.service.dto.AppDto;
import cn.ysk.cashier.mnt.service.dto.AppQueryCriteria;
import org.springframework.data.domain.Pageable;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Set;
/**
* @author zhanghouying
* @date 2019-08-24
*/
public interface AppService {
/**
* 分页查询
* @param criteria 条件
* @param pageable 分页参数
* @return /
*/
Object queryAll(AppQueryCriteria criteria, Pageable pageable);
/**
* 查询全部数据
* @param criteria 条件
* @return /
*/
List<AppDto> queryAll(AppQueryCriteria criteria);
/**
* 根据ID查询
* @param id /
* @return /
*/
AppDto findById(Long id);
/**
* 创建
* @param resources /
*/
void create(App resources);
/**
* 编辑
* @param resources /
*/
void update(App resources);
/**
* 删除
* @param ids /
*/
void delete(Set<Long> ids);
/**
* 导出数据
* @param queryAll /
* @param response /
* @throws IOException /
*/
void download(List<AppDto> queryAll, HttpServletResponse response) throws IOException;
}

View File

@@ -0,0 +1,88 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.service;
import cn.ysk.cashier.mnt.domain.Database;
import cn.ysk.cashier.mnt.service.dto.DatabaseDto;
import cn.ysk.cashier.mnt.service.dto.DatabaseQueryCriteria;
import org.springframework.data.domain.Pageable;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Set;
/**
* @author ZhangHouYing
* @date 2019-08-24
*/
public interface DatabaseService {
/**
* 分页查询
* @param criteria 条件
* @param pageable 分页参数
* @return /
*/
Object queryAll(DatabaseQueryCriteria criteria, Pageable pageable);
/**
* 查询全部
* @param criteria 条件
* @return /
*/
List<DatabaseDto> queryAll(DatabaseQueryCriteria criteria);
/**
* 根据ID查询
* @param id /
* @return /
*/
DatabaseDto findById(String id);
/**
* 创建
* @param resources /
*/
void create(Database resources);
/**
* 编辑
* @param resources /
*/
void update(Database resources);
/**
* 删除
* @param ids /
*/
void delete(Set<String> ids);
/**
* 测试连接数据库
* @param resources /
* @return /
*/
boolean testConnection(Database resources);
/**
* 导出数据
* @param queryAll /
* @param response /
* @throws IOException e
*/
void download(List<DatabaseDto> queryAll, HttpServletResponse response) throws IOException;
}

View File

@@ -0,0 +1,74 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.service;
import cn.ysk.cashier.mnt.domain.DeployHistory;
import cn.ysk.cashier.mnt.service.dto.DeployHistoryDto;
import cn.ysk.cashier.mnt.service.dto.DeployHistoryQueryCriteria;
import org.springframework.data.domain.Pageable;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Set;
/**
* @author zhanghouying
*/
public interface DeployHistoryService {
/**
* 分页查询
* @param criteria 条件
* @param pageable 分页参数
* @return /
*/
Object queryAll(DeployHistoryQueryCriteria criteria, Pageable pageable);
/**
* 查询全部
* @param criteria 条件
* @return /
*/
List<DeployHistoryDto> queryAll(DeployHistoryQueryCriteria criteria);
/**
* 根据ID查询
* @param id /
* @return /
*/
DeployHistoryDto findById(String id);
/**
* 创建
* @param resources /
*/
void create(DeployHistory resources);
/**
* 删除
* @param ids /
*/
void delete(Set<String> ids);
/**
* 导出数据
* @param queryAll /
* @param response /
* @throws IOException /
*/
void download(List<DeployHistoryDto> queryAll, HttpServletResponse response) throws IOException;
}

View File

@@ -0,0 +1,116 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.service;
import cn.ysk.cashier.mnt.domain.Deploy;
import cn.ysk.cashier.mnt.domain.DeployHistory;
import cn.ysk.cashier.mnt.service.dto.DeployDto;
import cn.ysk.cashier.mnt.service.dto.DeployQueryCriteria;
import org.springframework.data.domain.Pageable;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Set;
/**
* @author zhanghouying
* @date 2019-08-24
*/
public interface DeployService {
/**
* 分页查询
* @param criteria 条件
* @param pageable 分页参数
* @return /
*/
Object queryAll(DeployQueryCriteria criteria, Pageable pageable);
/**
* 查询全部数据
* @param criteria 条件
* @return /
*/
List<DeployDto> queryAll(DeployQueryCriteria criteria);
/**
* 根据ID查询
* @param id /
* @return /
*/
DeployDto findById(Long id);
/**
* 创建
* @param resources /
*/
void create(Deploy resources);
/**
* 编辑
* @param resources /
*/
void update(Deploy resources);
/**
* 删除
* @param ids /
*/
void delete(Set<Long> ids);
/**
* 部署文件到服务器
* @param fileSavePath 文件路径
* @param appId 应用ID
*/
void deploy(String fileSavePath, Long appId);
/**
* 查询部署状态
* @param resources /
* @return /
*/
String serverStatus(Deploy resources);
/**
* 启动服务
* @param resources /
* @return /
*/
String startServer(Deploy resources);
/**
* 停止服务
* @param resources /
* @return /
*/
String stopServer(Deploy resources);
/**
* 停止服务
* @param resources /
* @return /
*/
String serverReduction(DeployHistory resources);
/**
* 导出数据
* @param queryAll /
* @param response /
* @throws IOException /
*/
void download(List<DeployDto> queryAll, HttpServletResponse response) throws IOException;
}

View File

@@ -0,0 +1,95 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.service;
import cn.ysk.cashier.mnt.domain.ServerDeploy;
import cn.ysk.cashier.mnt.service.dto.ServerDeployDto;
import cn.ysk.cashier.mnt.service.dto.ServerDeployQueryCriteria;
import org.springframework.data.domain.Pageable;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Set;
/**
* @author zhanghouying
* @date 2019-08-24
*/
public interface ServerDeployService {
/**
* 分页查询
* @param criteria 条件
* @param pageable 分页参数
* @return /
*/
Object queryAll(ServerDeployQueryCriteria criteria, Pageable pageable);
/**
* 查询全部数据
* @param criteria 条件
* @return /
*/
List<ServerDeployDto> queryAll(ServerDeployQueryCriteria criteria);
/**
* 根据ID查询
* @param id /
* @return /
*/
ServerDeployDto findById(Long id);
/**
* 创建
* @param resources /
*/
void create(ServerDeploy resources);
/**
* 编辑
* @param resources /
*/
void update(ServerDeploy resources);
/**
* 删除
* @param ids /
*/
void delete(Set<Long> ids);
/**
* 根据IP查询
* @param ip /
* @return /
*/
ServerDeployDto findByIp(String ip);
/**
* 测试登录服务器
* @param resources /
* @return /
*/
Boolean testConnect(ServerDeploy resources);
/**
* 导出数据
* @param queryAll /
* @param response /
* @throws IOException /
*/
void download(List<ServerDeployDto> queryAll, HttpServletResponse response) throws IOException;
}

View File

@@ -0,0 +1,71 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.service.dto;
import lombok.Getter;
import lombok.Setter;
import cn.ysk.cashier.base.BaseDTO;
import java.io.Serializable;
/**
* @author zhanghouying
* @date 2019-08-24
*/
@Getter
@Setter
public class AppDto extends BaseDTO implements Serializable {
/**
* 应用编号
*/
private Long id;
/**
* 应用名称
*/
private String name;
/**
* 端口
*/
private Integer port;
/**
* 上传目录
*/
private String uploadPath;
/**
* 部署目录
*/
private String deployPath;
/**
* 备份目录
*/
private String backupPath;
/**
* 启动脚本
*/
private String startScript;
/**
* 部署脚本
*/
private String deployScript;
}

View File

@@ -0,0 +1,38 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.service.dto;
import lombok.Data;
import cn.ysk.cashier.annotation.Query;
import java.sql.Timestamp;
import java.util.List;
/**
* @author zhanghouying
* @date 2019-08-24
*/
@Data
public class AppQueryCriteria{
/**
* 模糊
*/
@Query(type = Query.Type.INNER_LIKE)
private String name;
@Query(type = Query.Type.BETWEEN)
private List<Timestamp> createTime;
}

View File

@@ -0,0 +1,55 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.service.dto;
import lombok.Getter;
import lombok.Setter;
import cn.ysk.cashier.base.BaseDTO;
import java.io.Serializable;
/**
* @author zhanghouying
* @date 2019-08-24
*/
@Getter
@Setter
public class DatabaseDto extends BaseDTO implements Serializable {
/**
* id
*/
private String id;
/**
* 数据库名称
*/
private String name;
/**
* 数据库连接地址
*/
private String jdbcUrl;
/**
* 数据库密码
*/
private String pwd;
/**
* 用户名
*/
private String userName;
}

View File

@@ -0,0 +1,44 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.service.dto;
import lombok.Data;
import cn.ysk.cashier.annotation.Query;
import java.sql.Timestamp;
import java.util.List;
/**
* @author zhanghouying
* @date 2019-08-24
*/
@Data
public class DatabaseQueryCriteria{
/**
* 模糊
*/
@Query(type = Query.Type.INNER_LIKE)
private String name;
/**
* 精确
*/
@Query
private String jdbcUrl;
@Query(type = Query.Type.BETWEEN)
private List<Timestamp> createTime;
}

View File

@@ -0,0 +1,78 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.service.dto;
import cn.hutool.core.collection.CollectionUtil;
import lombok.Getter;
import lombok.Setter;
import cn.ysk.cashier.base.BaseDTO;
import java.io.Serializable;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
/**
* @author zhanghouying
* @date 2019-08-24
*/
@Getter
@Setter
public class DeployDto extends BaseDTO implements Serializable {
/**
* 部署编号
*/
private String id;
private AppDto app;
/**
* 服务器
*/
private Set<ServerDeployDto> deploys;
private String servers;
/**
* 服务状态
*/
private String status;
public String getServers() {
if(CollectionUtil.isNotEmpty(deploys)){
return deploys.stream().map(ServerDeployDto::getName).collect(Collectors.joining(","));
}
return servers;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DeployDto deployDto = (DeployDto) o;
return Objects.equals(id, deployDto.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}

View File

@@ -0,0 +1,58 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.service.dto;
import lombok.Data;
import java.io.Serializable;
import java.sql.Timestamp;
/**
* @author zhanghouying
* @date 2019-08-24
*/
@Data
public class DeployHistoryDto implements Serializable {
/**
* 编号
*/
private String id;
/**
* 应用名称
*/
private String appName;
/**
* 部署IP
*/
private String ip;
/**
* 部署时间
*/
private Timestamp deployDate;
/**
* 部署人员
*/
private String deployUser;
/**
* 部署编号
*/
private Long deployId;
}

View File

@@ -0,0 +1,41 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.service.dto;
import lombok.Data;
import cn.ysk.cashier.annotation.Query;
import java.sql.Timestamp;
import java.util.List;
/**
* @author zhanghouying
* @date 2019-08-24
*/
@Data
public class DeployHistoryQueryCriteria{
/**
* 精确
*/
@Query(blurry = "appName,ip,deployUser")
private String blurry;
@Query
private Long deployId;
@Query(type = Query.Type.BETWEEN)
private List<Timestamp> deployDate;
}

View File

@@ -0,0 +1,39 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.service.dto;
import lombok.Data;
import cn.ysk.cashier.annotation.Query;
import java.sql.Timestamp;
import java.util.List;
/**
* @author zhanghouying
* @date 2019-08-24
*/
@Data
public class DeployQueryCriteria{
/**
* 模糊
*/
@Query(type = Query.Type.INNER_LIKE, propName = "name", joinName = "app")
private String appName;
@Query(type = Query.Type.BETWEEN)
private List<Timestamp> createTime;
}

View File

@@ -0,0 +1,61 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.service.dto;
import lombok.Getter;
import lombok.Setter;
import cn.ysk.cashier.base.BaseDTO;
import java.io.Serializable;
import java.util.Objects;
/**
* @author zhanghouying
* @date 2019-08-24
*/
@Getter
@Setter
public class ServerDeployDto extends BaseDTO implements Serializable {
private Long id;
private String name;
private String ip;
private Integer port;
private String account;
private String password;
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ServerDeployDto that = (ServerDeployDto) o;
return Objects.equals(id, that.id) &&
Objects.equals(name, that.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
}

View File

@@ -0,0 +1,38 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.service.dto;
import lombok.Data;
import cn.ysk.cashier.annotation.Query;
import java.sql.Timestamp;
import java.util.List;
/**
* @author zhanghouying
* @date 2019-08-24
*/
@Data
public class ServerDeployQueryCriteria{
/**
* 模糊
*/
@Query(blurry = "name,ip,account")
private String blurry;
@Query(type = Query.Type.BETWEEN)
private List<Timestamp> createTime;
}

View File

@@ -0,0 +1,123 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.service.impl;
import cn.ysk.cashier.mnt.domain.App;
import cn.ysk.cashier.mnt.repository.AppRepository;
import cn.ysk.cashier.mnt.service.AppService;
import cn.ysk.cashier.mnt.service.dto.AppQueryCriteria;
import cn.ysk.cashier.mnt.service.mapstruct.AppMapper;
import lombok.RequiredArgsConstructor;
import cn.ysk.cashier.exception.BadRequestException;
import cn.ysk.cashier.mnt.service.dto.AppDto;
import cn.ysk.cashier.utils.FileUtil;
import cn.ysk.cashier.utils.PageUtil;
import cn.ysk.cashier.utils.QueryHelp;
import cn.ysk.cashier.utils.ValidationUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
/**
* @author zhanghouying
* @date 2019-08-24
*/
@Service
@RequiredArgsConstructor
public class AppServiceImpl implements AppService {
private final AppRepository appRepository;
private final AppMapper appMapper;
@Override
public Object queryAll(AppQueryCriteria criteria, Pageable pageable){
Page<App> page = appRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
return PageUtil.toPage(page.map(appMapper::toDto));
}
@Override
public List<AppDto> queryAll(AppQueryCriteria criteria){
return appMapper.toDto(appRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
}
@Override
public AppDto findById(Long id) {
App app = appRepository.findById(id).orElseGet(App::new);
ValidationUtil.isNull(app.getId(),"App","id",id);
return appMapper.toDto(app);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void create(App resources) {
verification(resources);
appRepository.save(resources);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void update(App resources) {
verification(resources);
App app = appRepository.findById(resources.getId()).orElseGet(App::new);
ValidationUtil.isNull(app.getId(),"App","id",resources.getId());
app.copy(resources);
appRepository.save(app);
}
private void verification(App resources){
String opt = "/opt";
String home = "/home";
if (!(resources.getUploadPath().startsWith(opt) || resources.getUploadPath().startsWith(home))) {
throw new BadRequestException("文件只能上传在opt目录或者home目录 ");
}
if (!(resources.getDeployPath().startsWith(opt) || resources.getDeployPath().startsWith(home))) {
throw new BadRequestException("文件只能部署在opt目录或者home目录 ");
}
if (!(resources.getBackupPath().startsWith(opt) || resources.getBackupPath().startsWith(home))) {
throw new BadRequestException("文件只能备份在opt目录或者home目录 ");
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public void delete(Set<Long> ids) {
for (Long id : ids) {
appRepository.deleteById(id);
}
}
@Override
public void download(List<AppDto> queryAll, HttpServletResponse response) throws IOException {
List<Map<String, Object>> list = new ArrayList<>();
for (AppDto appDto : queryAll) {
Map<String,Object> map = new LinkedHashMap<>();
map.put("应用名称", appDto.getName());
map.put("端口", appDto.getPort());
map.put("上传目录", appDto.getUploadPath());
map.put("部署目录", appDto.getDeployPath());
map.put("备份目录", appDto.getBackupPath());
map.put("启动脚本", appDto.getStartScript());
map.put("部署脚本", appDto.getDeployScript());
map.put("创建日期", appDto.getCreateTime());
list.add(map);
}
FileUtil.downloadExcel(list, response);
}
}

View File

@@ -0,0 +1,117 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.service.impl;
import cn.hutool.core.util.IdUtil;
import cn.ysk.cashier.mnt.domain.Database;
import cn.ysk.cashier.mnt.repository.DatabaseRepository;
import cn.ysk.cashier.mnt.service.DatabaseService;
import cn.ysk.cashier.mnt.service.mapstruct.DatabaseMapper;
import cn.ysk.cashier.mnt.util.SqlUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import cn.ysk.cashier.mnt.service.dto.DatabaseDto;
import cn.ysk.cashier.mnt.service.dto.DatabaseQueryCriteria;
import cn.ysk.cashier.utils.FileUtil;
import cn.ysk.cashier.utils.PageUtil;
import cn.ysk.cashier.utils.QueryHelp;
import cn.ysk.cashier.utils.ValidationUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
/**
* @author zhanghouying
* @date 2019-08-24
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class DatabaseServiceImpl implements DatabaseService {
private final DatabaseRepository databaseRepository;
private final DatabaseMapper databaseMapper;
@Override
public Object queryAll(DatabaseQueryCriteria criteria, Pageable pageable){
Page<Database> page = databaseRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
return PageUtil.toPage(page.map(databaseMapper::toDto));
}
@Override
public List<DatabaseDto> queryAll(DatabaseQueryCriteria criteria){
return databaseMapper.toDto(databaseRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
}
@Override
public DatabaseDto findById(String id) {
Database database = databaseRepository.findById(id).orElseGet(Database::new);
ValidationUtil.isNull(database.getId(),"Database","id",id);
return databaseMapper.toDto(database);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void create(Database resources) {
resources.setId(IdUtil.simpleUUID());
databaseRepository.save(resources);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void update(Database resources) {
Database database = databaseRepository.findById(resources.getId()).orElseGet(Database::new);
ValidationUtil.isNull(database.getId(),"Database","id",resources.getId());
database.copy(resources);
databaseRepository.save(database);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void delete(Set<String> ids) {
for (String id : ids) {
databaseRepository.deleteById(id);
}
}
@Override
public boolean testConnection(Database resources) {
try {
return SqlUtils.testConnection(resources.getJdbcUrl(), resources.getUserName(), resources.getPwd());
} catch (Exception e) {
log.error(e.getMessage());
return false;
}
}
@Override
public void download(List<DatabaseDto> queryAll, HttpServletResponse response) throws IOException {
List<Map<String, Object>> list = new ArrayList<>();
for (DatabaseDto databaseDto : queryAll) {
Map<String,Object> map = new LinkedHashMap<>();
map.put("数据库名称", databaseDto.getName());
map.put("数据库连接地址", databaseDto.getJdbcUrl());
map.put("用户名", databaseDto.getUserName());
map.put("创建日期", databaseDto.getCreateTime());
list.add(map);
}
FileUtil.downloadExcel(list, response);
}
}

View File

@@ -0,0 +1,96 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.service.impl;
import cn.hutool.core.util.IdUtil;
import cn.ysk.cashier.mnt.domain.DeployHistory;
import cn.ysk.cashier.mnt.repository.DeployHistoryRepository;
import cn.ysk.cashier.mnt.service.mapstruct.DeployHistoryMapper;
import lombok.RequiredArgsConstructor;
import cn.ysk.cashier.mnt.service.DeployHistoryService;
import cn.ysk.cashier.mnt.service.dto.DeployHistoryDto;
import cn.ysk.cashier.mnt.service.dto.DeployHistoryQueryCriteria;
import cn.ysk.cashier.utils.FileUtil;
import cn.ysk.cashier.utils.PageUtil;
import cn.ysk.cashier.utils.QueryHelp;
import cn.ysk.cashier.utils.ValidationUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
/**
* @author zhanghouying
* @date 2019-08-24
*/
@Service
@RequiredArgsConstructor
public class DeployHistoryServiceImpl implements DeployHistoryService {
private final DeployHistoryRepository deployhistoryRepository;
private final DeployHistoryMapper deployhistoryMapper;
@Override
public Object queryAll(DeployHistoryQueryCriteria criteria, Pageable pageable){
Page<DeployHistory> page = deployhistoryRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
return PageUtil.toPage(page.map(deployhistoryMapper::toDto));
}
@Override
public List<DeployHistoryDto> queryAll(DeployHistoryQueryCriteria criteria){
return deployhistoryMapper.toDto(deployhistoryRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
}
@Override
public DeployHistoryDto findById(String id) {
DeployHistory deployhistory = deployhistoryRepository.findById(id).orElseGet(DeployHistory::new);
ValidationUtil.isNull(deployhistory.getId(),"DeployHistory","id",id);
return deployhistoryMapper.toDto(deployhistory);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void create(DeployHistory resources) {
resources.setId(IdUtil.simpleUUID());
deployhistoryRepository.save(resources);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void delete(Set<String> ids) {
for (String id : ids) {
deployhistoryRepository.deleteById(id);
}
}
@Override
public void download(List<DeployHistoryDto> queryAll, HttpServletResponse response) throws IOException {
List<Map<String, Object>> list = new ArrayList<>();
for (DeployHistoryDto deployHistoryDto : queryAll) {
Map<String,Object> map = new LinkedHashMap<>();
map.put("部署编号", deployHistoryDto.getDeployId());
map.put("应用名称", deployHistoryDto.getAppName());
map.put("部署IP", deployHistoryDto.getIp());
map.put("部署时间", deployHistoryDto.getDeployDate());
map.put("部署人员", deployHistoryDto.getDeployUser());
list.add(map);
}
FileUtil.downloadExcel(list, response);
}
}

View File

@@ -0,0 +1,430 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.service.impl;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.ysk.cashier.mnt.domain.App;
import cn.ysk.cashier.mnt.domain.Deploy;
import cn.ysk.cashier.mnt.domain.DeployHistory;
import cn.ysk.cashier.mnt.domain.ServerDeploy;
import cn.ysk.cashier.mnt.repository.DeployRepository;
import cn.ysk.cashier.mnt.service.DeployHistoryService;
import cn.ysk.cashier.mnt.service.DeployService;
import cn.ysk.cashier.mnt.service.ServerDeployService;
import cn.ysk.cashier.mnt.service.dto.DeployDto;
import cn.ysk.cashier.mnt.service.dto.DeployQueryCriteria;
import cn.ysk.cashier.mnt.service.dto.ServerDeployDto;
import cn.ysk.cashier.mnt.service.mapstruct.DeployMapper;
import cn.ysk.cashier.mnt.util.ExecuteShellUtil;
import cn.ysk.cashier.mnt.util.ScpClientUtil;
import cn.ysk.cashier.mnt.websocket.WebSocketServer;
import cn.ysk.cashier.utils.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import cn.ysk.cashier.exception.BadRequestException;
import cn.ysk.cashier.mnt.service.dto.AppDto;
import cn.ysk.cashier.mnt.websocket.MsgType;
import cn.ysk.cashier.mnt.websocket.SocketMsg;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
/**
* @author zhanghouying
* @date 2019-08-24
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class DeployServiceImpl implements DeployService {
private final String FILE_SEPARATOR = "/";
private final DeployRepository deployRepository;
private final DeployMapper deployMapper;
private final ServerDeployService serverDeployService;
private final DeployHistoryService deployHistoryService;
/**
* 循环次数
*/
private final Integer count = 30;
@Override
public Object queryAll(DeployQueryCriteria criteria, Pageable pageable) {
Page<Deploy> page = deployRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
return PageUtil.toPage(page.map(deployMapper::toDto));
}
@Override
public List<DeployDto> queryAll(DeployQueryCriteria criteria) {
return deployMapper.toDto(deployRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
}
@Override
public DeployDto findById(Long id) {
Deploy deploy = deployRepository.findById(id).orElseGet(Deploy::new);
ValidationUtil.isNull(deploy.getId(), "Deploy", "id", id);
return deployMapper.toDto(deploy);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void create(Deploy resources) {
deployRepository.save(resources);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void update(Deploy resources) {
Deploy deploy = deployRepository.findById(resources.getId()).orElseGet(Deploy::new);
ValidationUtil.isNull(deploy.getId(), "Deploy", "id", resources.getId());
deploy.copy(resources);
deployRepository.save(deploy);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void delete(Set<Long> ids) {
for (Long id : ids) {
deployRepository.deleteById(id);
}
}
@Override
public void deploy(String fileSavePath, Long id) {
deployApp(fileSavePath, id);
}
/**
* @param fileSavePath 本机路径
* @param id ID
*/
private void deployApp(String fileSavePath, Long id) {
DeployDto deploy = findById(id);
if (deploy == null) {
sendMsg("部署信息不存在", MsgType.ERROR);
throw new BadRequestException("部署信息不存在");
}
AppDto app = deploy.getApp();
if (app == null) {
sendMsg("包对应应用信息不存在", MsgType.ERROR);
throw new BadRequestException("包对应应用信息不存在");
}
int port = app.getPort();
//这个是服务器部署路径
String uploadPath = app.getUploadPath();
StringBuilder sb = new StringBuilder();
String msg;
Set<ServerDeployDto> deploys = deploy.getDeploys();
for (ServerDeployDto deployDTO : deploys) {
String ip = deployDTO.getIp();
ExecuteShellUtil executeShellUtil = getExecuteShellUtil(ip);
//判断是否第一次部署
boolean flag = checkFile(executeShellUtil, app);
//第一步要确认服务器上有这个目录
executeShellUtil.execute("mkdir -p " + app.getUploadPath());
executeShellUtil.execute("mkdir -p " + app.getBackupPath());
executeShellUtil.execute("mkdir -p " + app.getDeployPath());
//上传文件
msg = String.format("登陆到服务器:%s", ip);
ScpClientUtil scpClientUtil = getScpClientUtil(ip);
log.info(msg);
sendMsg(msg, MsgType.INFO);
msg = String.format("上传文件到服务器:%s<br>目录:%s下请稍等...", ip, uploadPath);
sendMsg(msg, MsgType.INFO);
scpClientUtil.putFile(fileSavePath, uploadPath);
if (flag) {
sendMsg("停止原来应用", MsgType.INFO);
//停止应用
stopApp(port, executeShellUtil);
sendMsg("备份原来应用", MsgType.INFO);
//备份应用
backupApp(executeShellUtil, ip, app.getDeployPath()+FILE_SEPARATOR, app.getName(), app.getBackupPath()+FILE_SEPARATOR, id);
}
sendMsg("部署应用", MsgType.INFO);
//部署文件,并启动应用
String deployScript = app.getDeployScript();
executeShellUtil.execute(deployScript);
sleep(3);
sendMsg("应用部署中,请耐心等待部署结果,或者稍后手动查看部署状态", MsgType.INFO);
int i = 0;
boolean result = false;
// 由于启动应用需要时间所以需要循环获取状态如果超过30次则认为是启动失败
while (i++ < count){
result = checkIsRunningStatus(port, executeShellUtil);
if(result){
break;
}
// 休眠6秒
sleep(6);
}
sb.append("服务器:").append(deployDTO.getName()).append("<br>应用:").append(app.getName());
sendResultMsg(result, sb);
executeShellUtil.close();
}
}
private void sleep(int second) {
try {
Thread.sleep(second * 1000);
} catch (InterruptedException e) {
log.error(e.getMessage(),e);
}
}
private void backupApp(ExecuteShellUtil executeShellUtil, String ip, String fileSavePath, String appName, String backupPath, Long id) {
String deployDate = DateUtil.format(new Date(), DatePattern.PURE_DATETIME_PATTERN);
StringBuilder sb = new StringBuilder();
backupPath += appName + FILE_SEPARATOR + deployDate + "\n";
sb.append("mkdir -p ").append(backupPath);
sb.append("mv -f ").append(fileSavePath);
sb.append(appName).append(" ").append(backupPath);
log.info("备份应用脚本:" + sb.toString());
executeShellUtil.execute(sb.toString());
//还原信息入库
DeployHistory deployHistory = new DeployHistory();
deployHistory.setAppName(appName);
deployHistory.setDeployUser(SecurityUtils.getCurrentUsername());
deployHistory.setIp(ip);
deployHistory.setDeployId(id);
deployHistoryService.create(deployHistory);
}
/**
* 停App
*
* @param port 端口
* @param executeShellUtil /
*/
private void stopApp(int port, ExecuteShellUtil executeShellUtil) {
//发送停止命令
executeShellUtil.execute(String.format("lsof -i :%d|grep -v \"PID\"|awk '{print \"kill -9\",$2}'|sh", port));
}
/**
* 指定端口程序是否在运行
*
* @param port 端口
* @param executeShellUtil /
* @return true 正在运行 false 已经停止
*/
private boolean checkIsRunningStatus(int port, ExecuteShellUtil executeShellUtil) {
String result = executeShellUtil.executeForResult(String.format("fuser -n tcp %d", port));
return result.indexOf("/tcp:")>0;
}
private void sendMsg(String msg, MsgType msgType) {
try {
WebSocketServer.sendInfo(new SocketMsg(msg, msgType), "deploy");
} catch (IOException e) {
log.error(e.getMessage(),e);
}
}
@Override
public String serverStatus(Deploy resources) {
Set<ServerDeploy> serverDeploys = resources.getDeploys();
App app = resources.getApp();
for (ServerDeploy serverDeploy : serverDeploys) {
StringBuilder sb = new StringBuilder();
ExecuteShellUtil executeShellUtil = getExecuteShellUtil(serverDeploy.getIp());
sb.append("服务器:").append(serverDeploy.getName()).append("<br>应用:").append(app.getName());
boolean result = checkIsRunningStatus(app.getPort(), executeShellUtil);
if (result) {
sb.append("<br>正在运行");
sendMsg(sb.toString(), MsgType.INFO);
} else {
sb.append("<br>已停止!");
sendMsg(sb.toString(), MsgType.ERROR);
}
log.info(sb.toString());
executeShellUtil.close();
}
return "执行完毕";
}
private boolean checkFile(ExecuteShellUtil executeShellUtil, AppDto appDTO) {
String result = executeShellUtil.executeForResult("find " + appDTO.getDeployPath() + " -name " + appDTO.getName());
return result.indexOf(appDTO.getName())>0;
}
/**
* 启动服务
* @param resources /
* @return /
*/
@Override
public String startServer(Deploy resources) {
Set<ServerDeploy> deploys = resources.getDeploys();
App app = resources.getApp();
for (ServerDeploy deploy : deploys) {
StringBuilder sb = new StringBuilder();
ExecuteShellUtil executeShellUtil = getExecuteShellUtil(deploy.getIp());
//为了防止重复启动,这里先停止应用
stopApp(app.getPort(), executeShellUtil);
sb.append("服务器:").append(deploy.getName()).append("<br>应用:").append(app.getName());
sendMsg("下发启动命令", MsgType.INFO);
executeShellUtil.execute(app.getStartScript());
sleep(3);
sendMsg("应用启动中,请耐心等待启动结果,或者稍后手动查看运行状态", MsgType.INFO);
int i = 0;
boolean result = false;
// 由于启动应用需要时间所以需要循环获取状态如果超过30次则认为是启动失败
while (i++ < count){
result = checkIsRunningStatus(app.getPort(), executeShellUtil);
if(result){
break;
}
// 休眠6秒
sleep(6);
}
sendResultMsg(result, sb);
log.info(sb.toString());
executeShellUtil.close();
}
return "执行完毕";
}
/**
* 停止服务
* @param resources /
* @return /
*/
@Override
public String stopServer(Deploy resources) {
Set<ServerDeploy> deploys = resources.getDeploys();
App app = resources.getApp();
for (ServerDeploy deploy : deploys) {
StringBuilder sb = new StringBuilder();
ExecuteShellUtil executeShellUtil = getExecuteShellUtil(deploy.getIp());
sb.append("服务器:").append(deploy.getName()).append("<br>应用:").append(app.getName());
sendMsg("下发停止命令", MsgType.INFO);
//停止应用
stopApp(app.getPort(), executeShellUtil);
sleep(1);
boolean result = checkIsRunningStatus(app.getPort(), executeShellUtil);
if (result) {
sb.append("<br>关闭失败!");
sendMsg(sb.toString(), MsgType.ERROR);
} else {
sb.append("<br>关闭成功!");
sendMsg(sb.toString(), MsgType.INFO);
}
log.info(sb.toString());
executeShellUtil.close();
}
return "执行完毕";
}
@Override
public String serverReduction(DeployHistory resources) {
Long deployId = resources.getDeployId();
Deploy deployInfo = deployRepository.findById(deployId).orElseGet(Deploy::new);
String deployDate = DateUtil.format(resources.getDeployDate(), DatePattern.PURE_DATETIME_PATTERN);
App app = deployInfo.getApp();
if (app == null) {
sendMsg("应用信息不存在:" + resources.getAppName(), MsgType.ERROR);
throw new BadRequestException("应用信息不存在:" + resources.getAppName());
}
String backupPath = app.getBackupPath()+FILE_SEPARATOR;
backupPath += resources.getAppName() + FILE_SEPARATOR + deployDate;
//这个是服务器部署路径
String deployPath = app.getDeployPath();
String ip = resources.getIp();
ExecuteShellUtil executeShellUtil = getExecuteShellUtil(ip);
String msg;
msg = String.format("登陆到服务器:%s", ip);
log.info(msg);
sendMsg(msg, MsgType.INFO);
sendMsg("停止原来应用", MsgType.INFO);
//停止应用
stopApp(app.getPort(), executeShellUtil);
//删除原来应用
sendMsg("删除应用", MsgType.INFO);
executeShellUtil.execute("rm -rf " + deployPath + FILE_SEPARATOR + resources.getAppName());
//还原应用
sendMsg("还原应用", MsgType.INFO);
executeShellUtil.execute("cp -r " + backupPath + "/. " + deployPath);
sendMsg("启动应用", MsgType.INFO);
executeShellUtil.execute(app.getStartScript());
sendMsg("应用启动中,请耐心等待启动结果,或者稍后手动查看启动状态", MsgType.INFO);
int i = 0;
boolean result = false;
// 由于启动应用需要时间所以需要循环获取状态如果超过30次则认为是启动失败
while (i++ < count){
result = checkIsRunningStatus(app.getPort(), executeShellUtil);
if(result){
break;
}
// 休眠6秒
sleep(6);
}
StringBuilder sb = new StringBuilder();
sb.append("服务器:").append(ip).append("<br>应用:").append(resources.getAppName());
sendResultMsg(result, sb);
executeShellUtil.close();
return "";
}
private ExecuteShellUtil getExecuteShellUtil(String ip) {
ServerDeployDto serverDeployDTO = serverDeployService.findByIp(ip);
if (serverDeployDTO == null) {
sendMsg("IP对应服务器信息不存在" + ip, MsgType.ERROR);
throw new BadRequestException("IP对应服务器信息不存在" + ip);
}
return new ExecuteShellUtil(ip, serverDeployDTO.getAccount(), serverDeployDTO.getPassword(),serverDeployDTO.getPort());
}
private ScpClientUtil getScpClientUtil(String ip) {
ServerDeployDto serverDeployDTO = serverDeployService.findByIp(ip);
if (serverDeployDTO == null) {
sendMsg("IP对应服务器信息不存在" + ip, MsgType.ERROR);
throw new BadRequestException("IP对应服务器信息不存在" + ip);
}
return ScpClientUtil.getInstance(ip, serverDeployDTO.getPort(), serverDeployDTO.getAccount(), serverDeployDTO.getPassword());
}
private void sendResultMsg(boolean result, StringBuilder sb) {
if (result) {
sb.append("<br>启动成功!");
sendMsg(sb.toString(), MsgType.INFO);
} else {
sb.append("<br>启动失败!");
sendMsg(sb.toString(), MsgType.ERROR);
}
}
@Override
public void download(List<DeployDto> queryAll, HttpServletResponse response) throws IOException {
List<Map<String, Object>> list = new ArrayList<>();
for (DeployDto deployDto : queryAll) {
Map<String,Object> map = new LinkedHashMap<>();
map.put("应用名称", deployDto.getApp().getName());
map.put("服务器", deployDto.getServers());
map.put("部署日期", deployDto.getCreateTime());
list.add(map);
}
FileUtil.downloadExcel(list, response);
}
}

View File

@@ -0,0 +1,125 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.service.impl;
import cn.ysk.cashier.mnt.domain.ServerDeploy;
import cn.ysk.cashier.mnt.repository.ServerDeployRepository;
import cn.ysk.cashier.mnt.service.ServerDeployService;
import cn.ysk.cashier.mnt.service.dto.ServerDeployDto;
import cn.ysk.cashier.mnt.service.mapstruct.ServerDeployMapper;
import cn.ysk.cashier.mnt.util.ExecuteShellUtil;
import lombok.RequiredArgsConstructor;
import cn.ysk.cashier.mnt.service.dto.ServerDeployQueryCriteria;
import cn.ysk.cashier.utils.FileUtil;
import cn.ysk.cashier.utils.PageUtil;
import cn.ysk.cashier.utils.QueryHelp;
import cn.ysk.cashier.utils.ValidationUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
/**
* @author zhanghouying
* @date 2019-08-24
*/
@Service
@RequiredArgsConstructor
public class ServerDeployServiceImpl implements ServerDeployService {
private final ServerDeployRepository serverDeployRepository;
private final ServerDeployMapper serverDeployMapper;
@Override
public Object queryAll(ServerDeployQueryCriteria criteria, Pageable pageable){
Page<ServerDeploy> page = serverDeployRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
return PageUtil.toPage(page.map(serverDeployMapper::toDto));
}
@Override
public List<ServerDeployDto> queryAll(ServerDeployQueryCriteria criteria){
return serverDeployMapper.toDto(serverDeployRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
}
@Override
public ServerDeployDto findById(Long id) {
ServerDeploy server = serverDeployRepository.findById(id).orElseGet(ServerDeploy::new);
ValidationUtil.isNull(server.getId(),"ServerDeploy","id",id);
return serverDeployMapper.toDto(server);
}
@Override
public ServerDeployDto findByIp(String ip) {
ServerDeploy deploy = serverDeployRepository.findByIp(ip);
return serverDeployMapper.toDto(deploy);
}
@Override
public Boolean testConnect(ServerDeploy resources) {
ExecuteShellUtil executeShellUtil = null;
try {
executeShellUtil = new ExecuteShellUtil(resources.getIp(), resources.getAccount(), resources.getPassword(),resources.getPort());
return executeShellUtil.execute("ls")==0;
} catch (Exception e) {
return false;
}finally {
if (executeShellUtil != null) {
executeShellUtil.close();
}
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public void create(ServerDeploy resources) {
serverDeployRepository.save(resources);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void update(ServerDeploy resources) {
ServerDeploy serverDeploy = serverDeployRepository.findById(resources.getId()).orElseGet(ServerDeploy::new);
ValidationUtil.isNull( serverDeploy.getId(),"ServerDeploy","id",resources.getId());
serverDeploy.copy(resources);
serverDeployRepository.save(serverDeploy);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void delete(Set<Long> ids) {
for (Long id : ids) {
serverDeployRepository.deleteById(id);
}
}
@Override
public void download(List<ServerDeployDto> queryAll, HttpServletResponse response) throws IOException {
List<Map<String, Object>> list = new ArrayList<>();
for (ServerDeployDto deployDto : queryAll) {
Map<String,Object> map = new LinkedHashMap<>();
map.put("服务器名称", deployDto.getName());
map.put("服务器IP", deployDto.getIp());
map.put("端口", deployDto.getPort());
map.put("账号", deployDto.getAccount());
map.put("创建日期", deployDto.getCreateTime());
list.add(map);
}
FileUtil.downloadExcel(list, response);
}
}

View File

@@ -0,0 +1,31 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.service.mapstruct;
import cn.ysk.cashier.mnt.domain.App;
import cn.ysk.cashier.base.BaseMapper;
import cn.ysk.cashier.mnt.service.dto.AppDto;
import org.mapstruct.Mapper;
import org.mapstruct.ReportingPolicy;
/**
* @author zhanghouying
* @date 2019-08-24
*/
@Mapper(componentModel = "spring",uses = {},unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface AppMapper extends BaseMapper<AppDto, App> {
}

View File

@@ -0,0 +1,31 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.service.mapstruct;
import cn.ysk.cashier.mnt.domain.Database;
import cn.ysk.cashier.base.BaseMapper;
import cn.ysk.cashier.mnt.service.dto.DatabaseDto;
import org.mapstruct.Mapper;
import org.mapstruct.ReportingPolicy;
/**
* @author zhanghouying
* @date 2019-08-24
*/
@Mapper(componentModel = "spring",unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface DatabaseMapper extends BaseMapper<DatabaseDto, Database> {
}

View File

@@ -0,0 +1,31 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.service.mapstruct;
import cn.ysk.cashier.mnt.domain.DeployHistory;
import cn.ysk.cashier.base.BaseMapper;
import cn.ysk.cashier.mnt.service.dto.DeployHistoryDto;
import org.mapstruct.Mapper;
import org.mapstruct.ReportingPolicy;
/**
* @author zhanghouying
* @date 2019-08-24
*/
@Mapper(componentModel = "spring",uses = {},unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface DeployHistoryMapper extends BaseMapper<DeployHistoryDto, DeployHistory> {
}

View File

@@ -0,0 +1,31 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.service.mapstruct;
import cn.ysk.cashier.mnt.domain.Deploy;
import cn.ysk.cashier.base.BaseMapper;
import cn.ysk.cashier.mnt.service.dto.DeployDto;
import org.mapstruct.Mapper;
import org.mapstruct.ReportingPolicy;
/**
* @author zhanghouying
* @date 2019-08-24
*/
@Mapper(componentModel = "spring",uses = {AppMapper.class, ServerDeployMapper.class},unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface DeployMapper extends BaseMapper<DeployDto, Deploy> {
}

View File

@@ -0,0 +1,31 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.service.mapstruct;
import cn.ysk.cashier.mnt.domain.ServerDeploy;
import cn.ysk.cashier.base.BaseMapper;
import cn.ysk.cashier.mnt.service.dto.ServerDeployDto;
import org.mapstruct.Mapper;
import org.mapstruct.ReportingPolicy;
/**
* @author zhanghouying
* @date 2019-08-24
*/
@Mapper(componentModel = "spring",uses = {},unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface ServerDeployMapper extends BaseMapper<ServerDeployDto, ServerDeploy> {
}

View File

@@ -0,0 +1,140 @@
/*
* <<
* Davinci
* ==
* Copyright (C) 2016 - 2019 EDP
* ==
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* >>
*
*/
package cn.ysk.cashier.mnt.util;
import lombok.extern.slf4j.Slf4j;
/**
* @author /
*/
@Slf4j
@SuppressWarnings({"unchecked","all"})
public enum DataTypeEnum {
/** mysql */
MYSQL("mysql", "mysql", "com.mysql.jdbc.Driver", "`", "`", "'", "'"),
/** oracle */
ORACLE("oracle", "oracle", "oracle.jdbc.driver.OracleDriver", "\"", "\"", "\"", "\""),
/** sql server */
SQLSERVER("sqlserver", "sqlserver", "com.microsoft.sqlserver.jdbc.SQLServerDriver", "\"", "\"", "\"", "\""),
/** h2 */
H2("h2", "h2", "org.h2.Driver", "`", "`", "\"", "\""),
/** phoenix */
PHOENIX("phoenix", "hbase phoenix", "org.apache.phoenix.jdbc.PhoenixDriver", "", "", "\"", "\""),
/** mongo */
MONGODB("mongo", "mongodb", "mongodb.jdbc.MongoDriver", "`", "`", "\"", "\""),
/** sql4es */
ELASTICSEARCH("sql4es", "elasticsearch", "nl.anchormen.sql4es.jdbc.ESDriver", "", "", "'", "'"),
/** presto */
PRESTO("presto", "presto", "com.facebook.presto.jdbc.PrestoDriver", "", "", "\"", "\""),
/** moonbox */
MOONBOX("moonbox", "moonbox", "moonbox.jdbc.MbDriver", "`", "`", "`", "`"),
/** cassandra */
CASSANDRA("cassandra", "cassandra", "com.github.adejanovski.cassandra.jdbc.CassandraDriver", "", "", "'", "'"),
/** click house */
CLICKHOUSE("clickhouse", "clickhouse", "ru.yandex.clickhouse.ClickHouseDriver", "", "", "\"", "\""),
/** kylin */
KYLIN("kylin", "kylin", "org.apache.kylin.jdbc.Driver", "\"", "\"", "\"", "\""),
/** vertica */
VERTICA("vertica", "vertica", "com.vertica.jdbc.Driver", "", "", "'", "'"),
/** sap */
HANA("sap", "sap hana", "com.sap.db.jdbc.Driver", "", "", "'", "'"),
/** impala */
IMPALA("impala", "impala", "com.cloudera.impala.jdbc41.Driver", "", "", "'", "'");
private String feature;
private String desc;
private String driver;
private String keywordPrefix;
private String keywordSuffix;
private String aliasPrefix;
private String aliasSuffix;
private static final String JDBC_URL_PREFIX = "jdbc:";
DataTypeEnum(String feature, String desc, String driver, String keywordPrefix, String keywordSuffix, String aliasPrefix, String aliasSuffix) {
this.feature = feature;
this.desc = desc;
this.driver = driver;
this.keywordPrefix = keywordPrefix;
this.keywordSuffix = keywordSuffix;
this.aliasPrefix = aliasPrefix;
this.aliasSuffix = aliasSuffix;
}
public static DataTypeEnum urlOf(String jdbcUrl) {
String url = jdbcUrl.toLowerCase().trim();
for (DataTypeEnum dataTypeEnum : values()) {
if (url.startsWith(JDBC_URL_PREFIX + dataTypeEnum.feature)) {
try {
Class<?> aClass = Class.forName(dataTypeEnum.getDriver());
if (null == aClass) {
throw new RuntimeException("Unable to get driver instance for jdbcUrl: " + jdbcUrl);
}
} catch (ClassNotFoundException e) {
throw new RuntimeException("Unable to get driver instance: " + jdbcUrl);
}
return dataTypeEnum;
}
}
return null;
}
public String getFeature() {
return feature;
}
public String getDesc() {
return desc;
}
public String getDriver() {
return driver;
}
public String getKeywordPrefix() {
return keywordPrefix;
}
public String getKeywordSuffix() {
return keywordSuffix;
}
public String getAliasPrefix() {
return aliasPrefix;
}
public String getAliasSuffix() {
return aliasSuffix;
}
}

View File

@@ -0,0 +1,101 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.util;
import cn.hutool.core.io.IoUtil;
import com.jcraft.jsch.ChannelShell;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.util.Vector;
/**
* 执行shell命令
*
* @author: ZhangHouYing
* @date: 2019/8/10
*/
@Slf4j
public class ExecuteShellUtil {
private Vector<String> stdout;
Session session;
public ExecuteShellUtil(final String ipAddress, final String username, final String password,int port) {
try {
JSch jsch = new JSch();
session = jsch.getSession(username, ipAddress, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect(3000);
} catch (Exception e) {
log.error(e.getMessage(),e);
}
}
public int execute(final String command) {
int returnCode = 0;
ChannelShell channel = null;
PrintWriter printWriter = null;
BufferedReader input = null;
stdout = new Vector<String>();
try {
channel = (ChannelShell) session.openChannel("shell");
channel.connect();
input = new BufferedReader(new InputStreamReader(channel.getInputStream()));
printWriter = new PrintWriter(channel.getOutputStream());
printWriter.println(command);
printWriter.println("exit");
printWriter.flush();
log.info("The remote command is: ");
String line;
while ((line = input.readLine()) != null) {
stdout.add(line);
System.out.println(line);
}
} catch (Exception e) {
log.error(e.getMessage(),e);
return -1;
}finally {
IoUtil.close(printWriter);
IoUtil.close(input);
if (channel != null) {
channel.disconnect();
}
}
return returnCode;
}
public void close(){
if (session != null) {
session.disconnect();
}
}
public String executeForResult(String command) {
execute(command);
StringBuilder sb = new StringBuilder();
for (String str : stdout) {
sb.append(str);
}
return sb.toString();
}
}

View File

@@ -0,0 +1,105 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.util;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
import com.google.common.collect.Maps;
import java.io.IOException;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* 远程执行linux命令
* @author: ZhangHouYing
* @date: 2019-08-10 10:06
*/
public class ScpClientUtil {
static private Map<String,ScpClientUtil> instance = Maps.newHashMap();
static synchronized public ScpClientUtil getInstance(String ip, int port, String username, String password) {
if (instance.get(ip) == null) {
instance.put(ip, new ScpClientUtil(ip, port, username, password));
}
return instance.get(ip);
}
public ScpClientUtil(String ip, int port, String username, String password) {
this.ip = ip;
this.port = port;
this.username = username;
this.password = password;
}
public void getFile(String remoteFile, String localTargetDirectory) {
Connection conn = new Connection(ip, port);
try {
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword(username, password);
if (!isAuthenticated) {
System.err.println("authentication failed");
}
SCPClient client = new SCPClient(conn);
client.get(remoteFile, localTargetDirectory);
} catch (IOException ex) {
Logger.getLogger(SCPClient.class.getName()).log(Level.SEVERE, null, ex);
}finally{
conn.close();
}
}
public void putFile(String localFile, String remoteTargetDirectory) {
putFile(localFile, null, remoteTargetDirectory);
}
public void putFile(String localFile, String remoteFileName, String remoteTargetDirectory) {
putFile(localFile, remoteFileName, remoteTargetDirectory,null);
}
public void putFile(String localFile, String remoteFileName, String remoteTargetDirectory, String mode) {
Connection conn = new Connection(ip, port);
try {
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword(username, password);
if (!isAuthenticated) {
System.err.println("authentication failed");
}
SCPClient client = new SCPClient(conn);
if ((mode == null) || (mode.length() == 0)) {
mode = "0600";
}
if (remoteFileName == null) {
client.put(localFile, remoteTargetDirectory);
} else {
client.put(localFile, remoteFileName, remoteTargetDirectory, mode);
}
} catch (IOException ex) {
Logger.getLogger(ScpClientUtil.class.getName()).log(Level.SEVERE, null, ex);
}finally{
conn.close();
}
}
private String ip;
private int port;
private String username;
private String password;
}

View File

@@ -0,0 +1,202 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.util;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.util.StringUtils;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import cn.ysk.cashier.utils.CloseUtil;
import cn.ysk.cashier.mnt.util.DataTypeEnum;
import javax.sql.DataSource;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.sql.*;
import java.util.List;
/**
* @author /
*/
@Slf4j
public class SqlUtils {
/**
* 获取数据源
*
* @param jdbcUrl /
* @param userName /
* @param password /
* @return DataSource
*/
private static DataSource getDataSource(String jdbcUrl, String userName, String password) {
DruidDataSource druidDataSource = new DruidDataSource();
String className;
try {
className = DriverManager.getDriver(jdbcUrl.trim()).getClass().getName();
} catch (SQLException e) {
throw new RuntimeException("Get class name error: =" + jdbcUrl);
}
if (StringUtils.isEmpty(className)) {
DataTypeEnum dataTypeEnum = DataTypeEnum.urlOf(jdbcUrl);
if (null == dataTypeEnum) {
throw new RuntimeException("Not supported data type: jdbcUrl=" + jdbcUrl);
}
druidDataSource.setDriverClassName(dataTypeEnum.getDriver());
} else {
druidDataSource.setDriverClassName(className);
}
druidDataSource.setUrl(jdbcUrl);
druidDataSource.setUsername(userName);
druidDataSource.setPassword(password);
// 配置获取连接等待超时的时间
druidDataSource.setMaxWait(3000);
// 配置初始化大小、最小、最大
druidDataSource.setInitialSize(1);
druidDataSource.setMinIdle(1);
druidDataSource.setMaxActive(1);
// 如果链接出现异常则直接判定为失败而不是一直重试
druidDataSource.setBreakAfterAcquireFailure(true);
try {
druidDataSource.init();
} catch (SQLException e) {
log.error("Exception during pool initialization", e);
throw new RuntimeException(e.getMessage());
}
return druidDataSource;
}
private static Connection getConnection(String jdbcUrl, String userName, String password) {
DataSource dataSource = getDataSource(jdbcUrl, userName, password);
Connection connection = null;
try {
connection = dataSource.getConnection();
} catch (Exception ignored) {}
try {
int timeOut = 5;
if (null == connection || connection.isClosed() || !connection.isValid(timeOut)) {
log.info("connection is closed or invalid, retry get connection!");
connection = dataSource.getConnection();
}
} catch (Exception e) {
log.error("create connection error, jdbcUrl: {}", jdbcUrl);
throw new RuntimeException("create connection error, jdbcUrl: " + jdbcUrl);
} finally {
CloseUtil.close(connection);
}
return connection;
}
private static void releaseConnection(Connection connection) {
if (null != connection) {
try {
connection.close();
} catch (Exception e) {
log.error(e.getMessage(),e);
log.error("connection close error" + e.getMessage());
}
}
}
public static boolean testConnection(String jdbcUrl, String userName, String password) {
Connection connection = null;
try {
connection = getConnection(jdbcUrl, userName, password);
if (null != connection) {
return true;
}
} catch (Exception e) {
log.info("Get connection failed:" + e.getMessage());
} finally {
releaseConnection(connection);
}
return false;
}
public static String executeFile(String jdbcUrl, String userName, String password, File sqlFile) {
Connection connection = getConnection(jdbcUrl, userName, password);
try {
batchExecute(connection, readSqlList(sqlFile));
} catch (Exception e) {
log.error("sql脚本执行发生异常:{}",e.getMessage());
return e.getMessage();
}finally {
releaseConnection(connection);
}
return "success";
}
/**
* 批量执行sql
* @param connection /
* @param sqlList /
*/
public static void batchExecute(Connection connection, List<String> sqlList) {
Statement st = null;
try {
st = connection.createStatement();
for (String sql : sqlList) {
if (sql.endsWith(";")) {
sql = sql.substring(0, sql.length() - 1);
}
st.addBatch(sql);
}
st.executeBatch();
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
CloseUtil.close(st);
}
}
/**
* 将文件中的sql语句以为单位读取到列表中
* @param sqlFile /
* @return /
* @throws Exception e
*/
private static List<String> readSqlList(File sqlFile) throws Exception {
List<String> sqlList = Lists.newArrayList();
StringBuilder sb = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(sqlFile), StandardCharsets.UTF_8))) {
String tmp;
while ((tmp = reader.readLine()) != null) {
log.info("line:{}", tmp);
if (tmp.endsWith(";")) {
sb.append(tmp);
sqlList.add(sb.toString());
sb.delete(0, sb.length());
} else {
sb.append(tmp);
}
}
if (!"".endsWith(sb.toString().trim())) {
sqlList.add(sb.toString());
}
}
return sqlList;
}
}

View File

@@ -0,0 +1,31 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.websocket;
/**
* @author ZhangHouYing
* @date 2019-08-10 9:56
*/
public enum MsgType {
/** 连接 */
CONNECT,
/** 关闭 */
CLOSE,
/** 信息 */
INFO,
/** 错误 */
ERROR
}

View File

@@ -0,0 +1,33 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.websocket;
import lombok.Data;
/**
* @author ZhangHouYing
* @date 2019-08-10 9:55
*/
@Data
public class SocketMsg {
private String msg;
private MsgType msgType;
public SocketMsg(String msg, MsgType msgType) {
this.msg = msg;
this.msgType = msgType;
}
}

View File

@@ -0,0 +1,139 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.ysk.cashier.mnt.websocket;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* @author ZhangHouYing
* @date 2019-08-10 15:46
*/
@ServerEndpoint("/webSocket/{sid}")
@Slf4j
@Component
public class WebSocketServer {
/**
* concurrent包的线程安全Set用来存放每个客户端对应的MyWebSocket对象。
*/
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
/**
* 与某个客户端的连接会话,需要通过它来给客户端发送数据
*/
private Session session;
/**
* 接收sid
*/
private String sid="";
/**
* 连接建立成功调用的方法
* */
@OnOpen
public void onOpen(Session session,@PathParam("sid") String sid) {
this.session = session;
//如果存在就先删除一个,防止重复推送消息
for (WebSocketServer webSocket:webSocketSet) {
if (webSocket.sid.equals(sid)) {
webSocketSet.remove(webSocket);
}
}
webSocketSet.add(this);
this.sid=sid;
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this);
}
/**
* 收到客户端消息后调用的方法
* @param message 客户端发送过来的消息*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("收到来"+sid+"的信息:"+message);
//群发消息
for (WebSocketServer item : webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
log.error(e.getMessage(),e);
}
}
}
@OnError
public void onError(Session session, Throwable error) {
log.error("发生错误");
error.printStackTrace();
}
/**
* 实现服务器主动推送
*/
private void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 群发自定义消息
* */
public static void sendInfo(SocketMsg socketMsg,@PathParam("sid") String sid) throws IOException {
String message = JSONObject.toJSONString(socketMsg);
log.info("推送消息到"+sid+",推送内容:"+message);
for (WebSocketServer item : webSocketSet) {
try {
//这里可以设定只推送给这个sid的为null则全部推送
if(sid==null) {
item.sendMessage(message);
}else if(item.sid.equals(sid)){
item.sendMessage(message);
}
} catch (IOException ignored) { }
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
WebSocketServer that = (WebSocketServer) o;
return Objects.equals(session, that.session) &&
Objects.equals(sid, that.sid);
}
@Override
public int hashCode() {
return Objects.hash(session, sid);
}
}