Browse Source

优化代码

reghao 5 years ago
parent
commit
5cd6838b9b
28 changed files with 348 additions and 160 deletions
  1. 5 0
      common/pom.xml
  2. 2 2
      common/src/main/java/cn/reghao/autodop/common/notifier/DingNotify.java
  3. 83 0
      common/src/main/java/cn/reghao/autodop/common/notifier/EmailNotify.java
  4. 1 1
      common/src/main/java/cn/reghao/autodop/common/notifier/Notify.java
  5. 46 0
      common/src/main/java/cn/reghao/autodop/common/notifier/SmsNotify.java
  6. 1 1
      common/src/main/java/cn/reghao/autodop/common/notifier/ding/DingMsg.java
  7. 1 1
      common/src/main/java/cn/reghao/autodop/common/notifier/ding/DingText.java
  8. 1 2
      common/src/main/java/cn/reghao/autodop/common/utils/DatetimeConverter.java
  9. 6 5
      dmaster/src/main/java/cn/reghao/autodop/dmaster/app/controller/BuildController.java
  10. 4 4
      dmaster/src/main/java/cn/reghao/autodop/dmaster/app/controller/crud/GlobalCrudController.java
  11. 2 2
      dmaster/src/main/java/cn/reghao/autodop/dmaster/app/entity/BuildDir.java
  12. 0 25
      dmaster/src/main/java/cn/reghao/autodop/dmaster/app/entity/log/BuildResult.java
  13. 3 0
      dmaster/src/main/java/cn/reghao/autodop/dmaster/app/entity/log/DeployLog.java
  14. 13 0
      dmaster/src/main/java/cn/reghao/autodop/dmaster/app/exception/GitException.java
  15. 11 0
      dmaster/src/main/java/cn/reghao/autodop/dmaster/app/exception/UpdateException.java
  16. 13 0
      dmaster/src/main/java/cn/reghao/autodop/dmaster/app/repository/build/BuildDirRepository.java
  17. 0 13
      dmaster/src/main/java/cn/reghao/autodop/dmaster/app/repository/orchestration/LocalDirRepository.java
  18. 21 6
      dmaster/src/main/java/cn/reghao/autodop/dmaster/app/service/BuildDeployDispatcher.java
  19. 9 0
      dmaster/src/main/java/cn/reghao/autodop/dmaster/app/service/NotifyTask.java
  20. 1 0
      dmaster/src/main/java/cn/reghao/autodop/dmaster/app/service/build/AppIntegrate.java
  21. 5 2
      dmaster/src/main/java/cn/reghao/autodop/dmaster/app/service/build/tools/repo/GitImpl.java
  22. 23 23
      dmaster/src/main/java/cn/reghao/autodop/dmaster/app/service/crud/global/LocalDirCrudService.java
  23. 1 1
      dmaster/src/main/java/cn/reghao/autodop/dmaster/app/service/deploy/NotifyTask.java
  24. 20 50
      dmaster/src/main/java/cn/reghao/autodop/dmaster/app/vo/log/BuildDeployResult.java
  25. 21 21
      dmaster/src/main/java/cn/reghao/autodop/dmaster/utils/AfterAppStart.java
  26. 17 0
      dmaster/src/main/java/cn/reghao/autodop/dmaster/ws/WebsocketConfig.java
  27. 36 0
      dmaster/src/main/java/cn/reghao/autodop/dmaster/ws/WebsocketController.java
  28. 2 1
      scripts/test1.json

+ 5 - 0
common/pom.xml

@@ -69,6 +69,11 @@
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-data-mongodb</artifactId>
         </dependency>
+
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-websocket</artifactId>
+        </dependency>
     </dependencies>
 
     <build>

+ 2 - 2
common/src/main/java/cn/reghao/autodop/common/notification/DingNotify.java → common/src/main/java/cn/reghao/autodop/common/notifier/DingNotify.java

@@ -1,9 +1,9 @@
-package cn.reghao.autodop.common.notification;
+package cn.reghao.autodop.common.notifier;
 
 import cn.reghao.autodop.common.httpc.DefaultWebRequest;
 import cn.reghao.autodop.common.httpc.WebRequest;
 import cn.reghao.autodop.common.httpc.WebResponse;
-import cn.reghao.autodop.common.notification.ding.DingText;
+import cn.reghao.autodop.common.notifier.ding.DingText;
 import cn.reghao.autodop.common.utils.data.serializer.JsonConverter;
 
 /**

+ 83 - 0
common/src/main/java/cn/reghao/autodop/common/notifier/EmailNotify.java

@@ -0,0 +1,83 @@
+package cn.reghao.autodop.common.notifier;
+
+import javax.mail.Session;
+import javax.mail.Transport;
+import javax.mail.internet.InternetAddress;
+import javax.mail.internet.MimeMessage;
+import java.io.UnsupportedEncodingException;
+import java.util.Date;
+import java.util.Properties;
+
+/**
+ * @author reghao
+ * @date 2020-05-05 12:46:30
+ */
+public class EmailNotify implements Notify {
+    private InternetAddress from;
+    private Session session;
+    private String emailAccount;
+    private String emailPassword;
+
+    public EmailNotify(String emailAccount, String emailPassword, String emailSmtp) throws Exception {
+        this.emailAccount = emailAccount;
+        this.emailPassword = emailPassword;
+        this.from = new InternetAddress(emailAccount, "admin@emall", "UTF-8");
+        initSessioin(emailSmtp);
+    }
+
+    private void initSessioin(String emailSmtp) {
+        Properties props = new Properties();
+        props.setProperty("mail.transport.protocol", "smtp");
+        props.setProperty("mail.smtp.host", emailSmtp);
+        props.setProperty("mail.smtp.auth", "true");
+
+        session = Session.getInstance(props);
+        session.setDebug(true);
+    }
+
+    @Override
+    public void send(String dest, Object content) {
+        try {
+            MimeMessage message = message(emailDestinations(dest), "来自远方的问候", (String) content);
+            Transport transport = session.getTransport();
+            transport.connect(emailAccount, emailPassword);
+            transport.sendMessage(message, message.getAllRecipients());
+            transport.close();
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+    private InternetAddress[] emailDestinations(String dest) throws UnsupportedEncodingException {
+        String[] strs = dest.split(",");
+        int len = strs.length;
+        InternetAddress[] addresses = new InternetAddress[len];
+        for (int i = 0; i < len; i++) {
+            addresses[i] = new InternetAddress(strs[i], "", "UTF-8");
+        }
+
+        return addresses;
+    }
+
+    private MimeMessage message(InternetAddress[] addresses, String subject, String content) throws Exception {
+        MimeMessage message = new MimeMessage(session);
+        message.setFrom(from);
+        message.setRecipients(MimeMessage.RecipientType.TO, addresses);
+        message.setSubject(subject, "UTF-8");
+        message.setContent(content, "text/html;charset=UTF-8");
+        message.setSentDate(new Date());
+
+        return message;
+    }
+
+    public static void main(String[] args) throws Exception {
+        String account = "gisgit@163.com";
+        String password = "gjs@gsh1990";
+        String smtp = "smtp.163.com";
+        EmailNotify emailNotify = new EmailNotify(account, password, smtp);
+
+        String dest = "reghaodev@gmail.com";
+        String content = "据可靠消息,火箭军将于本月 15 日在西北试射一枚 DF-41 导弹,目的地位于美国西部外海。";
+        emailNotify.send(dest, content);
+    }
+}

+ 1 - 1
common/src/main/java/cn/reghao/autodop/common/notification/Notify.java → common/src/main/java/cn/reghao/autodop/common/notifier/Notify.java

@@ -1,4 +1,4 @@
-package cn.reghao.autodop.common.notification;
+package cn.reghao.autodop.common.notifier;
 
 /**
  * @author reghao

+ 46 - 0
common/src/main/java/cn/reghao/autodop/common/notifier/SmsNotify.java

@@ -0,0 +1,46 @@
+package cn.reghao.autodop.common.notifier;
+
+import cn.reghao.autodop.common.httpc.DefaultWebRequest;
+import cn.reghao.autodop.common.httpc.WebRequest;
+import cn.reghao.autodop.common.httpc.WebResponse;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * @author reghao
+ * @date 2020-05-07 01:30:43
+ */
+public class SmsNotify implements Notify {
+    private WebRequest webRequest = new DefaultWebRequest();
+    private Map<String, String> params;
+
+    public SmsNotify() {
+        this.params = new HashMap<>();
+        params.put("sname", "dlazykj0");
+        params.put("spwd", "azy2018Iquizoo");
+        params.put("scorpid", "");
+        params.put("sprdid", "1012818");
+    }
+
+    @Override
+    public void send(String dst, Object content) {
+        try {
+            params.put("sdst", dst);
+            params.put("smsg", (String) content);
+            String url = "http://cf.51welink.com/submitdata/service.asmx/g_Submit";
+            WebResponse webResponse = webRequest.postFormData(url, params);
+            if (webResponse.getStatusCode() == 200) {
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+    public static void main(String[] args) throws Exception {
+        String mobilePhone = "15682110907";
+        SmsNotify smsNotify = new SmsNotify();
+        String content = "【大脑课堂】验证码:191599,您正在通过兑换码开通帐号,验证码15分钟内有效。大脑课堂,让大脑更自由!";
+        smsNotify.send(mobilePhone, content);
+    }
+}

+ 1 - 1
common/src/main/java/cn/reghao/autodop/common/notification/ding/DingMsg.java → common/src/main/java/cn/reghao/autodop/common/notifier/ding/DingMsg.java

@@ -1,4 +1,4 @@
-package cn.reghao.autodop.common.notification.ding;
+package cn.reghao.autodop.common.notifier.ding;
 
 import lombok.Data;
 

+ 1 - 1
common/src/main/java/cn/reghao/autodop/common/notification/ding/DingText.java → common/src/main/java/cn/reghao/autodop/common/notifier/ding/DingText.java

@@ -1,4 +1,4 @@
-package cn.reghao.autodop.common.notification.ding;
+package cn.reghao.autodop.common.notifier.ding;
 
 import lombok.Data;
 import lombok.EqualsAndHashCode;

+ 1 - 2
common/src/main/java/cn/reghao/autodop/common/utils/DatetimeConverter.java

@@ -2,10 +2,9 @@ package cn.reghao.autodop.common.utils;
 
 import java.time.*;
 import java.time.format.DateTimeFormatter;
-import java.util.Date;
 
 /**
- * 时间日期转换器
+ * 时间日期格式转换器
  *
  * @author reghao
  * @date 2020-03-20 10:20:01

+ 6 - 5
dmaster/src/main/java/cn/reghao/autodop/dmaster/app/controller/BuildController.java

@@ -1,5 +1,6 @@
 package cn.reghao.autodop.dmaster.app.controller;
 
+import cn.reghao.autodop.common.utils.data.serializer.JsonConverter;
 import cn.reghao.autodop.dmaster.app.constant.EnvType;
 import cn.reghao.autodop.dmaster.app.vo.SuccessfullyBuildVO;
 import cn.reghao.autodop.dmaster.app.vo.log.BuildDeployResult;
@@ -47,10 +48,10 @@ public class BuildController {
     @ApiImplicitParams(
             @ApiImplicitParam(name="appId", value="应用 ID", paramType="query", dataType = "String")
     )
-    @PostMapping("/pipeline")
+    @PostMapping("/update")
     public String buildAndDeploy(@RequestParam("appId") String appId) throws Exception {
-        buildDeployDispatcher.buildAndDeploy(appId, true);
-        return WebResult.success("pipeline");
+        BuildDeployResult buildDeployResult = buildDeployDispatcher.buildAndDeploy(appId, true);
+        return WebResult.success(buildDeployResult);
     }
 
     @ApiOperation(value = "构建应用")
@@ -59,8 +60,8 @@ public class BuildController {
     )
     @PostMapping("/build")
     public String build(@RequestParam("appId") String appId) throws Exception {
-        buildDeployDispatcher.buildAndDeploy(appId, false);
-        return WebResult.success("build");
+        BuildDeployResult buildDeployResult = buildDeployDispatcher.buildAndDeploy(appId, false);
+        return WebResult.success(buildDeployResult);
     }
 
     @ApiOperation(value = "部署应用")

+ 4 - 4
dmaster/src/main/java/cn/reghao/autodop/dmaster/app/controller/crud/GlobalCrudController.java

@@ -3,7 +3,7 @@ package cn.reghao.autodop.dmaster.app.controller.crud;
 import cn.reghao.autodop.common.result.WebResult;
 import cn.reghao.autodop.common.utils.data.db.PageList;
 import cn.reghao.autodop.common.utils.data.serializer.JsonConverter;
-import cn.reghao.autodop.dmaster.app.entity.LocalDir;
+import cn.reghao.autodop.dmaster.app.entity.BuildDir;
 import cn.reghao.autodop.dmaster.app.entity.config.NotifierConfig;
 import cn.reghao.autodop.dmaster.app.service.crud.global.LocalDirCrudService;
 import cn.reghao.autodop.dmaster.app.service.crud.global.NotifierCrudService;
@@ -71,15 +71,15 @@ public class GlobalCrudController {
     @ApiOperation(value = "分页获取本地目录配置")
     @GetMapping("/localdir")
     public ResponseEntity<String> getLocalDirByPage(@RequestParam("page") int page, @RequestParam("size") int size) {
-        PageList<LocalDir> pageList = localDirCrudService.getByPage(page, size);
+        PageList<BuildDir> pageList = localDirCrudService.getByPage(page, size);
         return ResponseEntity.ok().body(WebResult.success(pageList));
     }
 
     @ApiOperation(value = "修改本地目录配置")
     @PutMapping("/localdir")
     public ResponseEntity<String> modifyLocalDir(@RequestBody String json) throws Exception {
-        LocalDir localDir = (LocalDir) JsonConverter.jsonToObject(json, LocalDir.class);
-        localDirCrudService.addOrModify(localDir);
+        BuildDir buildDir = (BuildDir) JsonConverter.jsonToObject(json, BuildDir.class);
+        localDirCrudService.addOrModify(buildDir);
         return ResponseEntity.ok().body(WebResult.success("ok"));
     }
 

+ 2 - 2
dmaster/src/main/java/cn/reghao/autodop/dmaster/app/entity/LocalDir.java → dmaster/src/main/java/cn/reghao/autodop/dmaster/app/entity/BuildDir.java

@@ -16,7 +16,7 @@ import javax.persistence.Entity;
 @Data
 @EqualsAndHashCode(callSuper = false)
 @Entity
-public class LocalDir extends BaseEntity {
+public class BuildDir extends BaseEntity {
     // 主机唯一标识
     @Column(nullable = false, unique = true)
     private String machineId;
@@ -33,7 +33,7 @@ public class LocalDir extends BaseEntity {
     @Column(nullable = false)
     private String available;
 
-    public LocalDir vo() {
+    public BuildDir vo() {
         this.setId(null);
         this.setIsDelete(null);
         this.setCreateTime(null);

+ 0 - 25
dmaster/src/main/java/cn/reghao/autodop/dmaster/app/entity/log/BuildResult.java

@@ -1,25 +0,0 @@
-package cn.reghao.autodop.dmaster.app.entity.log;
-
-import cn.reghao.autodop.dmaster.app.constant.BuildStage;
-import lombok.Data;
-
-import java.time.LocalDateTime;
-
-/**
- * 应用构建结果
- *
- * @author reghao
- * @date 2021-02-05 23:49:55
- */
-@Data
-public class BuildResult {
-    private String appId;
-    private BuildStage stage;
-    private boolean isUpdate;
-    private String commitId;
-    private String packagePath;
-    private long updateTotalTime;
-    private long compileTotalTime;
-    private long packTotalTime;
-    private LocalDateTime buildTime;
-}

+ 3 - 0
dmaster/src/main/java/cn/reghao/autodop/dmaster/app/entity/log/DeployLog.java

@@ -3,6 +3,7 @@ package cn.reghao.autodop.dmaster.app.entity.log;
 import cn.reghao.autodop.common.orm.BaseDocument;
 import lombok.Data;
 import lombok.EqualsAndHashCode;
+import org.springframework.data.domain.PageRequest;
 import org.springframework.data.mongodb.core.mapping.Document;
 
 import java.util.List;
@@ -18,5 +19,7 @@ import java.util.List;
 @Document("DeployLog")
 public class DeployLog extends BaseDocument {
     private String appId;
+    private String commitId;
+    private String deployTime;
     private List<DeployResult> deployResults;
 }

+ 13 - 0
dmaster/src/main/java/cn/reghao/autodop/dmaster/app/exception/GitException.java

@@ -0,0 +1,13 @@
+package cn.reghao.autodop.dmaster.app.exception;
+
+import org.eclipse.jgit.api.errors.GitAPIException;
+
+/**
+ * @author reghao
+ * @date 2021-02-11 10:14:36
+ */
+public class GitException extends GitAPIException {
+    public GitException(String msg) {
+        super(msg);
+    }
+}

+ 11 - 0
dmaster/src/main/java/cn/reghao/autodop/dmaster/app/exception/UpdateException.java

@@ -0,0 +1,11 @@
+package cn.reghao.autodop.dmaster.app.exception;
+
+/**
+ * @author reghao
+ * @date 2021-02-11 10:14:36
+ */
+public class UpdateException extends GitException {
+    public UpdateException(String msg) {
+        super(msg);
+    }
+}

+ 13 - 0
dmaster/src/main/java/cn/reghao/autodop/dmaster/app/repository/build/BuildDirRepository.java

@@ -0,0 +1,13 @@
+package cn.reghao.autodop.dmaster.app.repository.build;
+
+import cn.reghao.autodop.dmaster.app.entity.BuildDir;
+import org.springframework.data.jpa.repository.JpaRepository;
+
+/**
+ *
+ * @author reghao
+ * @date 2020-01-21 14:53:03
+ */
+public interface BuildDirRepository extends JpaRepository<BuildDir, Long> {
+    BuildDir findByMachineId(String machineId);
+}

+ 0 - 13
dmaster/src/main/java/cn/reghao/autodop/dmaster/app/repository/orchestration/LocalDirRepository.java

@@ -1,13 +0,0 @@
-package cn.reghao.autodop.dmaster.app.repository.orchestration;
-
-import cn.reghao.autodop.dmaster.app.entity.LocalDir;
-import org.springframework.data.jpa.repository.JpaRepository;
-
-/**
- *
- * @author reghao
- * @date 2020-01-21 14:53:03
- */
-public interface LocalDirRepository extends JpaRepository<LocalDir, Long> {
-    LocalDir findByMachineId(String machineId);
-}

+ 21 - 6
dmaster/src/main/java/cn/reghao/autodop/dmaster/app/service/BuildDeployDispatcher.java

@@ -2,9 +2,11 @@ package cn.reghao.autodop.dmaster.app.service;
 
 import cn.reghao.autodop.dmaster.app.cache.OrchestrationCache;
 import cn.reghao.autodop.dmaster.app.constant.BuildStage;
+import cn.reghao.autodop.dmaster.app.constant.NotifierType;
+import cn.reghao.autodop.dmaster.app.entity.config.NotifierConfig;
 import cn.reghao.autodop.dmaster.app.entity.deploy.DeployConfig;
 import cn.reghao.autodop.dmaster.app.entity.log.BuildLog;
-import cn.reghao.autodop.dmaster.app.entity.log.BuildResult;
+import cn.reghao.autodop.dmaster.app.vo.log.BuildDeployResult;
 import cn.reghao.autodop.dmaster.app.entity.log.DeployLog;
 import cn.reghao.autodop.dmaster.app.service.build.AppIntegrate;
 import cn.reghao.autodop.dmaster.app.service.deploy.AppDeployer;
@@ -55,7 +57,7 @@ public class BuildDeployDispatcher {
      * @return
      * @date 2021-02-06 上午1:46
      */
-    public BuildResult buildAndDeploy(String appId, boolean isDeploy) throws Exception {
+    public BuildDeployResult buildAndDeploy(String appId, boolean isDeploy) throws Exception {
         if (!onBuilding.add(appId)) {
             // TODO 应用正在构建中...
             return null;
@@ -76,12 +78,13 @@ public class BuildDeployDispatcher {
 
         // TODO 抛出异常时从 onBuilding 中移除当前应用
         BuildLog buildLog = buildTask(appIntegrate);
+        onBuilding.remove(appId);
         if (buildLog.getStatusCode() == 0 && isDeploy) {
-            DeployLog deployLog = deploy(buildLog.getAppId(), buildLog.getPackagePath());
+            DeployLog deployLog = deploy(appId, buildLog.getPackagePath());
+            return BuildDeployResult.fromDeployLog(deployLog);
+        } else {
+            return BuildDeployResult.fromBuildLog(buildLog);
         }
-
-        onBuilding.remove(appId);
-        return null;
     }
 
     /**
@@ -166,4 +169,16 @@ public class BuildDeployDispatcher {
 
     public void deploy1(String appId, String commitId) {
     }
+
+    public void deployNotify(NotifierConfig notifierConfig, DeployLog deployLog) {
+        switch (NotifierType.valueOf(notifierConfig.getType())) {
+            case webhook:
+                break;
+            case sms:
+                break;
+            case email:
+                break;
+            default:
+        }
+    }
 }

+ 9 - 0
dmaster/src/main/java/cn/reghao/autodop/dmaster/app/service/NotifyTask.java

@@ -0,0 +1,9 @@
+package cn.reghao.autodop.dmaster.app.service;
+
+/**
+ * @author reghao
+ * @date 2021-02-10 02:31:12
+ */
+public class NotifyTask {
+
+}

+ 1 - 0
dmaster/src/main/java/cn/reghao/autodop/dmaster/app/service/build/AppIntegrate.java

@@ -6,6 +6,7 @@ import cn.reghao.autodop.dmaster.app.entity.config.build.BuildConfig;
 import cn.reghao.autodop.dmaster.app.entity.config.build.tools.*;
 import cn.reghao.autodop.dmaster.app.entity.config.orchestration.AppOrchestration;
 import cn.reghao.autodop.dmaster.app.entity.config.orchestration.ProjOrchestration;
+import cn.reghao.autodop.dmaster.app.exception.UpdateException;
 import cn.reghao.autodop.dmaster.app.service.build.tools.compiler.CodeCompiler;
 import cn.reghao.autodop.dmaster.app.service.build.tools.compiler.MavenCompiler;
 import cn.reghao.autodop.dmaster.app.service.build.tools.compiler.NullCompiler;

+ 5 - 2
dmaster/src/main/java/cn/reghao/autodop/dmaster/app/service/build/tools/repo/GitImpl.java

@@ -3,6 +3,8 @@ package cn.reghao.autodop.dmaster.app.service.build.tools.repo;
 import cn.reghao.autodop.common.utils.text.TextFile;
 import cn.reghao.autodop.dmaster.app.constant.RepoAuthType;
 import cn.reghao.autodop.dmaster.app.entity.config.build.tools.RepoConfig;
+import cn.reghao.autodop.dmaster.app.exception.GitException;
+import cn.reghao.autodop.dmaster.app.exception.UpdateException;
 import com.jcraft.jsch.JSch;
 import com.jcraft.jsch.JSchException;
 import com.jcraft.jsch.Session;
@@ -10,6 +12,7 @@ import org.eclipse.jgit.api.CloneCommand;
 import org.eclipse.jgit.api.Git;
 import org.eclipse.jgit.api.PullCommand;
 import org.eclipse.jgit.api.TransportConfigCallback;
+import org.eclipse.jgit.api.errors.GitAPIException;
 import org.eclipse.jgit.diff.DiffEntry;
 import org.eclipse.jgit.internal.storage.file.FileRepository;
 import org.eclipse.jgit.lib.ObjectId;
@@ -96,7 +99,7 @@ public class GitImpl implements CodeUpdater {
         String localRepoDir = local + dirname(remote);
         File file = new File(localRepoDir);
         if (!file.exists() && !file.mkdirs()) {
-            throw new Exception();
+            throw new UpdateException("创建 " + localRepoDir + " 目录失败...");
         }
 
         File localRepo = new File(localRepoDir + "/.git");
@@ -158,7 +161,7 @@ public class GitImpl implements CodeUpdater {
         }
     }
 
-    private CommitLog commitInfo(Repository repo, String branch) throws IOException {
+    private CommitLog commitInfo(Repository repo, String branch) throws Exception {
         Ref head = repo.findRef("refs/heads/" + branch);
         ObjectId objectId = head.getObjectId();
         try (RevWalk walk = new RevWalk(repo)) {

+ 23 - 23
dmaster/src/main/java/cn/reghao/autodop/dmaster/app/service/crud/global/LocalDirCrudService.java

@@ -2,8 +2,8 @@ package cn.reghao.autodop.dmaster.app.service.crud.global;
 
 import cn.reghao.autodop.common.utils.data.db.CrudOps;
 import cn.reghao.autodop.common.utils.data.db.PageList;
-import cn.reghao.autodop.dmaster.app.entity.LocalDir;
-import cn.reghao.autodop.dmaster.app.repository.orchestration.LocalDirRepository;
+import cn.reghao.autodop.dmaster.app.entity.BuildDir;
+import cn.reghao.autodop.dmaster.app.repository.build.BuildDirRepository;
 import cn.reghao.autodop.dmaster.common.config.SysConfig;
 import org.springframework.data.domain.Page;
 import org.springframework.data.domain.PageRequest;
@@ -19,31 +19,31 @@ import java.util.stream.Collectors;
  * @date 2020-11-10 21:58:00
  */
 @Service
-public class LocalDirCrudService implements CrudOps<LocalDir> {
-    private LocalDirRepository localDirRepository;
+public class LocalDirCrudService implements CrudOps<BuildDir> {
+    private BuildDirRepository buildDirRepository;
 
-    public LocalDirCrudService(LocalDirRepository localDirRepository) {
-        this.localDirRepository = localDirRepository;
+    public LocalDirCrudService(BuildDirRepository buildDirRepository) {
+        this.buildDirRepository = buildDirRepository;
     }
 
     @Override
-    public void addOrModify(LocalDir localDir) throws Exception {
+    public void addOrModify(BuildDir buildDir) throws Exception {
         // 检查并创建目录
-        checkOrMkdir(localDir.getLocalDir());
+        checkOrMkdir(buildDir.getLocalDir());
         // 只做修改,不新增
-        String hostId = localDir.getMachineId();
-        LocalDir localDirEntity = localDirRepository.findByMachineId(hostId);
-        if (localDirEntity != null) {
-            localDir.setId(localDirEntity.getId());
-            localDir.setCreateTime(localDirEntity.getCreateTime());
-            localDir.setUpdateTime(LocalDateTime.now());
-            localDir.setIsDelete(localDirEntity.getIsDelete());
+        String hostId = buildDir.getMachineId();
+        BuildDir buildDirEntity = buildDirRepository.findByMachineId(hostId);
+        if (buildDirEntity != null) {
+            buildDir.setId(buildDirEntity.getId());
+            buildDir.setCreateTime(buildDirEntity.getCreateTime());
+            buildDir.setUpdateTime(LocalDateTime.now());
+            buildDir.setIsDelete(buildDirEntity.getIsDelete());
 
-            localDirRepository.save(localDir);
+            buildDirRepository.save(buildDir);
 
-            SysConfig.localRepo = localDir.getLocalDir() + "/local-repo";
-            SysConfig.compileDir = localDir.getLocalDir() + "/compile-dir";
-            SysConfig.packDir = localDir.getLocalDir() + "/pack-dir";
+            SysConfig.localRepo = buildDir.getLocalDir() + "/local-repo";
+            SysConfig.compileDir = buildDir.getLocalDir() + "/compile-dir";
+            SysConfig.packDir = buildDir.getLocalDir() + "/pack-dir";
         } else {
             throw new Exception(hostId + " 不存在...");
         }
@@ -72,16 +72,16 @@ public class LocalDirCrudService implements CrudOps<LocalDir> {
     }
 
     @Override
-    public PageList<LocalDir> getByPage(int page, int size) {
+    public PageList<BuildDir> getByPage(int page, int size) {
         // 默认按更新时间倒序
         PageRequest pageRequest =
                 PageRequest.of(page-1, size, Sort.by(Sort.Direction.DESC, "updateTime"));
-        Page<LocalDir> page1 = localDirRepository.findAll(pageRequest);
+        Page<BuildDir> page1 = buildDirRepository.findAll(pageRequest);
 
-        PageList<LocalDir> pageList = new PageList<>();
+        PageList<BuildDir> pageList = new PageList<>();
         pageList.setTotalSize(page1.getTotalElements());
         pageList.setTotalPages(page1.getTotalPages());
-        pageList.setList(page1.getContent().stream().map(LocalDir::vo).collect(Collectors.toList()));
+        pageList.setList(page1.getContent().stream().map(BuildDir::vo).collect(Collectors.toList()));
         return pageList;
     }
 

+ 1 - 1
dmaster/src/main/java/cn/reghao/autodop/dmaster/app/service/deploy/NotifyTask.java

@@ -1,6 +1,6 @@
 package cn.reghao.autodop.dmaster.app.service.deploy;
 
-import cn.reghao.autodop.common.notification.Notify;
+import cn.reghao.autodop.common.notifier.Notify;
 import java.util.concurrent.Callable;
 
 /**

+ 20 - 50
dmaster/src/main/java/cn/reghao/autodop/dmaster/app/vo/log/BuildDeployResult.java

@@ -1,5 +1,6 @@
 package cn.reghao.autodop.dmaster.app.vo.log;
 
+import cn.reghao.autodop.common.utils.DatetimeConverter;
 import cn.reghao.autodop.dmaster.app.entity.log.BuildLog;
 import cn.reghao.autodop.dmaster.app.entity.log.DeployLog;
 import lombok.Data;
@@ -16,74 +17,43 @@ import java.util.List;
 @Data
 @NoArgsConstructor
 public class BuildDeployResult {
-    private String appId;
-    private String commitId;
-    private String commitMsg;
-    private String buildTime;
-    private boolean isDeploy;
     // 0 - 成功 1 - 失败
     private int statusCode;
     private String msg;
+
+    private String appId;
+    private String commitId;
+    private String bdType;
+    private String bdTime;
     private List<String> deploySuccessed;
     private List<String> deployFailure;
 
-    public BuildDeployResult(String appId) {
-        this.appId = appId;
-        this.isDeploy = false;
-    }
-
     public static BuildDeployResult fromBuildLog(BuildLog buildLog) {
         BuildDeployResult buildDeployResult = new BuildDeployResult();
-        /*buildDeployResult.setAppId(buildLog.getAppId());
-        buildDeployResult.setBuildTime(DatetimeConverter.format(buildLog.getBuildTime()));
-        buildDeployResult.setDeploy(false);
+        buildDeployResult.setAppId(buildLog.getAppId());
+        buildDeployResult.setCommitId(buildLog.getCommitId());
+        buildDeployResult.setBdType("构建");
+        buildDeployResult.setBdTime(DatetimeConverter.format(buildLog.getBuildTime()));
         buildDeployResult.setStatusCode(buildLog.getStatusCode());
-        buildDeployResult.setMsg(buildLog.getMsg());
         if (buildLog.getStatusCode() == 0) {
-            buildDeployResult.setCommitId(buildLog.getCommitLog().getCommitId());
-            buildDeployResult.setCommitMsg(buildLog.getCommitLog().getCommitMsg());
-            return buildDeployResult;
+            buildDeployResult.setMsg("构建成功");
         } else {
-            if (buildLog.getCommitLog() != null) {
-                buildDeployResult.setCommitId(buildLog.getCommitLog().getCommitId());
-                buildDeployResult.setCommitMsg(buildLog.getCommitLog().getCommitMsg());
-            }
-            return buildDeployResult;
-        }*/
+            buildDeployResult.setMsg(buildLog.getErrDetail());
+        }
 
         return buildDeployResult;
     }
 
-    public static BuildDeployResult fromDeployLogs(List<DeployLog> deployLogs) {
+    public static BuildDeployResult fromDeployLog(DeployLog deployLog) {
         BuildDeployResult buildDeployResult = new BuildDeployResult();
-        //BuildLog buildLog = deployLogs.get(0).getBuildLog();
-        /*buildDeployResult.setAppId(buildLog.getAppId());
-        buildDeployResult.setBuildTime(DatetimeConverter.format(buildLog.getBuildTime()));
-        buildDeployResult.setDeploy(true);
-        buildDeployResult.setCommitId(buildLog.getCommitLog().getCommitId());
-        buildDeployResult.setCommitMsg(buildLog.getCommitLog().getCommitMsg());
-
-        List<String> successedHosts = deployLogs.stream()
-                .filter(deployLog -> deployLog.getStatusCode() == 0)
-                .map(DeployLog::getHost)
-                .collect(Collectors.toList());
-        buildDeployResult.setDeploySuccessed(successedHosts);
+        buildDeployResult.setAppId(deployLog.getAppId());
+        buildDeployResult.setCommitId(deployLog.getCommitId());
+        buildDeployResult.setBdType("部署");
+        buildDeployResult.setBdTime(deployLog.getDeployTime());
 
-        List<String> failedHosts = deployLogs.stream()
-                .filter(deployLog -> deployLog.getStatusCode() != 0)
-                .map(DeployLog::getHost)
-                .collect(Collectors.toList());
-        buildDeployResult.setDeployFailure(failedHosts);
+        deployLog.getDeployResults().forEach(deployResult -> {
 
-
-        // 根据部署结果中成功的数量设置返回结果
-        if (failedHosts.isEmpty()) {
-            buildDeployResult.setStatusCode(0);
-            buildDeployResult.setMsg("所有节点部署成功");
-        } else {
-            buildDeployResult.setStatusCode(1);
-            buildDeployResult.setMsg("节点 " + failedHosts.toString() + " 部署失败");
-        }*/
+        });
 
         return buildDeployResult;
     }

+ 21 - 21
dmaster/src/main/java/cn/reghao/autodop/dmaster/utils/AfterAppStart.java

@@ -4,8 +4,8 @@ import cn.reghao.autodop.common.dagent.machine.hardware.disk.Disk;
 import cn.reghao.autodop.common.dagent.machine.hardware.disk.DiskInfo;
 import cn.reghao.autodop.common.utils.FileOps;
 import cn.reghao.autodop.common.utils.text.TextFile;
-import cn.reghao.autodop.dmaster.app.entity.LocalDir;
-import cn.reghao.autodop.dmaster.app.repository.orchestration.LocalDirRepository;
+import cn.reghao.autodop.dmaster.app.entity.BuildDir;
+import cn.reghao.autodop.dmaster.app.repository.build.BuildDirRepository;
 import cn.reghao.autodop.dmaster.auth.service.UserService;
 import cn.reghao.autodop.dmaster.common.config.SysConfig;
 import lombok.extern.slf4j.Slf4j;
@@ -26,49 +26,49 @@ import java.io.File;
 @Slf4j
 @Component
 public class AfterAppStart implements ApplicationRunner {
-    private LocalDirRepository localDirRepository;
+    private BuildDirRepository buildDirRepository;
     private UserService userService;
 
-    public AfterAppStart(LocalDirRepository localDirRepository, UserService userService) {
-        this.localDirRepository = localDirRepository;
+    public AfterAppStart(BuildDirRepository buildDirRepository, UserService userService) {
+        this.buildDirRepository = buildDirRepository;
         this.userService = userService;
     }
 
     @Override
     public void run(ApplicationArguments args) {
         String machineId = new TextFile().read("/etc/machine-id").get(0);
-        LocalDir localDir = localDirRepository.findByMachineId(machineId);
-        if (localDir == null) {
+        BuildDir buildDir = buildDirRepository.findByMachineId(machineId);
+        if (buildDir == null) {
             String home = System.getProperty("user.home");
             Disk disk = new Disk();
             DiskInfo diskInfo = disk.diskInfo(home);
             if (diskInfo != null) {
-                localDir = new LocalDir();
-                localDir.setMachineId(machineId);
-                localDir.setLocalDir(home + "/autodop");
-                localDir.setCapacity(diskInfo.getSize());
-                localDir.setUsed(diskInfo.getUsed());
-                localDir.setAvailable(diskInfo.getAvail());
-                localDir.setIsDelete(false);
-                localDirRepository.save(localDir);
+                buildDir = new BuildDir();
+                buildDir.setMachineId(machineId);
+                buildDir.setLocalDir(home + "/autodop");
+                buildDir.setCapacity(diskInfo.getSize());
+                buildDir.setUsed(diskInfo.getUsed());
+                buildDir.setAvailable(diskInfo.getAvail());
+                buildDir.setIsDelete(false);
+                buildDirRepository.save(buildDir);
 
-                initialize(localDir);
+                initialize(buildDir);
                 log.info("autodop-master 初始化完成...");
             } else {
                 log.error("{} 不合法,autodop-master 启动失败...", home);
                 System.exit(1);
             }
         } else {
-            initialize(localDir);
+            initialize(buildDir);
             log.info("autodop-master 初始化完成...");
         }
     }
 
-    public void initialize(LocalDir localDir) {
+    public void initialize(BuildDir buildDir) {
         // TODO 放入缓存
-        SysConfig.localRepo = localDir.getLocalDir() + "/local-repo";
-        SysConfig.compileDir = localDir.getLocalDir() + "/compile-dir";
-        SysConfig.packDir = localDir.getLocalDir() + "/pack-dir";
+        SysConfig.localRepo = buildDir.getLocalDir() + "/local-repo";
+        SysConfig.compileDir = buildDir.getLocalDir() + "/compile-dir";
+        SysConfig.packDir = buildDir.getLocalDir() + "/pack-dir";
         checkAndSetLocalDir();
         userService.checkOrSetAdmin();
     }

+ 17 - 0
dmaster/src/main/java/cn/reghao/autodop/dmaster/ws/WebsocketConfig.java

@@ -0,0 +1,17 @@
+package cn.reghao.autodop.dmaster.ws;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.socket.server.standard.ServerEndpointExporter;
+
+/**
+ * @author reghao
+ * @date 2021-02-10 22:34:36
+ */
+@Configuration
+public class WebsocketConfig {
+    @Bean
+    public ServerEndpointExporter serverEndpointExporter() {
+        return new ServerEndpointExporter();
+    }
+}

+ 36 - 0
dmaster/src/main/java/cn/reghao/autodop/dmaster/ws/WebsocketController.java

@@ -0,0 +1,36 @@
+package cn.reghao.autodop.dmaster.ws;
+
+import org.springframework.stereotype.Controller;
+
+import javax.websocket.*;
+import javax.websocket.server.ServerEndpoint;
+
+/**
+ * @author reghao
+ * @date 2021-02-10 22:33:52
+ */
+@ServerEndpoint(value = "/ws")
+@Controller
+public class WebsocketController {
+    @OnOpen
+    public void onOpen(Session session) {
+        // 先鉴权,如果鉴权通过则存储WebsocketSession,否则关闭连接,这里省略了鉴权的代码
+        //WebSocketSupport.storageSession(session);
+        System.out.println("session open. ID:" + session.getId());
+    }
+
+    @OnClose
+    public void onClose(Session session) {
+        System.out.println("session close. ID:" + session.getId());
+    }
+
+    @OnMessage
+    public void onMessage(String message, Session session) {
+        System.out.println("get client msg. ID:" + session.getId() + ". msg:" + message);
+    }
+
+    @OnError
+    public void onError(Session session, Throwable error) {
+        error.printStackTrace();
+    }
+}

+ 2 - 1
scripts/test1.json

@@ -1,6 +1,7 @@
 {
   "env":[
-    "appName=dnkt"
+    "ASPNETCORE_ENVIRONMENT=Staging",
+    "ASPNETCORE_URLS=http://192.168.0.172:8002;https://192.168.0.172:8102"
   ],
   "hostConfig":{
     "networkMode":"host",