Unverified Commit 3e021550 authored by ZackYoung's avatar ZackYoung Committed by GitHub

[Feature-1906][git] add git project (#1907)

* add git project * update query * add git Sse build * update mapper * update sql * update sql * update mvn cmd * update mvn cmd * update analysis format
parent 7465088f
......@@ -22,7 +22,7 @@
<groupId>org.dinky</groupId>
<artifactId>dinky</artifactId>
<version>0.8.0</version>
<relativePath>..</relativePath>
<relativePath>../</relativePath>
</parent>
<artifactId>dinky-admin</artifactId>
......@@ -32,6 +32,7 @@
<properties>
<expand.scope>provided</expand.scope>
<jgit.version>5.13.1.202206130422-r</jgit.version>
</properties>
<dependencies>
......@@ -369,6 +370,38 @@
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jgit</groupId>
<artifactId>org.eclipse.jgit.archive</artifactId>
<version>${jgit.version}</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.eclipse.jgit</groupId>
<artifactId>org.eclipse.jgit.ssh.jsch</artifactId>
<version>${jgit.version}</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.maven.shared</groupId>
<artifactId>maven-invoker</artifactId>
<version>3.2.0</version>
</dependency>
<!--<dependency>-->
<!-- <groupId>org.apache.maven</groupId>-->
<!-- <artifactId>maven-model</artifactId>-->
<!-- <version>3.9.1</version>-->
<!--</dependency>-->
</dependencies>
<build>
......
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.dinky.common.result;
import java.io.Serializable;
import cn.hutool.json.JSONUtil;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
* @author ZackYoung
* @since 0.8.0
*/
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class StepResult implements Serializable {
/** message type (1-stepInfo 2-log) */
private Integer type;
private Integer currentStep;
private Object data;
/** 0-fail , 1-process , 2-success */
private Integer status;
public static StepResult getStepInfo(Integer currentStep, Object data) {
return StepResult.builder()
.type(1)
.currentStep(currentStep)
.data(JSONUtil.toJsonStr(data))
.build();
}
@Override
public String toString() {
return JSONUtil.toJsonStr(this);
}
}
......@@ -74,6 +74,7 @@ public class MybatisPlusConfig {
"dinky_savepoints",
"dinky_task",
"dinky_task_statement",
// "dinky_git_project",
"dinky_task_version");
@Bean
......
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.dinky.controller;
import org.dinky.common.result.ProTableResult;
import org.dinky.common.result.Result;
import org.dinky.dto.GitProjectDTO;
import org.dinky.model.GitProject;
import org.dinky.service.GitProjectService;
import org.dinky.utils.GitProjectStepSseFactory;
import org.dinky.utils.GitRepository;
import java.io.File;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import com.fasterxml.jackson.databind.JsonNode;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Dict;
import lombok.AllArgsConstructor;
/**
* @author ZackYoung
* @since 0.8.0
*/
@RestController
@RequestMapping("/api/git")
@AllArgsConstructor
public class GitController {
final GitProjectService gitProjectService;
@PostMapping("/saveOrUpdate")
public Result<Void> saveOrUpdate(@Validated @RequestBody GitProjectDTO gitProjectDTO) {
gitProjectService.saveOrUpdate(gitProjectDTO);
GitRepository gitRepository = new GitRepository(gitProjectDTO);
gitRepository.cloneAndPull(gitProjectDTO.getName(), gitProjectDTO.getBranches());
return Result.succeed();
}
@GetMapping("/getBranchList")
public Result<List<String>> getBranchList(GitProjectDTO gitProjectDTO) {
GitRepository gitRepository = new GitRepository(gitProjectDTO);
return Result.succeed(gitRepository.getBranchList());
}
@DeleteMapping("/deleteProject")
public Result<Void> deleteProject(Long id) {
gitProjectService.removeById(id);
return Result.succeed();
}
@PostMapping("/updateEnable")
public Result<Void> updateEnable(Long id, boolean enable) {
gitProjectService.updateState(id, enable);
return Result.succeed();
}
@PostMapping("/getProjectList")
public Result<ProTableResult<GitProject>> getAllProject(@RequestBody JsonNode params) {
return Result.succeed(gitProjectService.selectForProTable(params));
}
@PostMapping("/getOneDetails")
public Result<GitProject> getOneDetails(Long id) {
return Result.succeed(gitProjectService.getById(id));
}
@GetMapping(path = "/build")
public Result<Void> build(Long id) {
GitProject gitProject = gitProjectService.getById(id);
if (gitProject.getBuildState().equals(1)) {
return Result.failed("此任务正在构建");
}
Dict params = new Dict();
File logDir =
FileUtil.file(
GitRepository.getProjectDir(gitProject.getName()),
gitProject.getBranch() + "_log");
params.set("gitProject", gitProject).set("logDir", logDir);
GitProjectStepSseFactory.build(gitProject, params);
return Result.succeed();
}
@GetMapping(path = "/build-step-logs", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public SseEmitter buildStepLogs(Long id) {
SseEmitter emitter = new SseEmitter(TimeUnit.MINUTES.toMillis(30));
GitProject gitProject = gitProjectService.getById(id);
Dict params = new Dict();
File logDir =
FileUtil.file(
GitRepository.getProjectDir(gitProject.getName()),
gitProject.getBranch() + "_log");
params.set("gitProject", gitProject).set("logDir", logDir);
GitProjectStepSseFactory.observe(emitter, gitProject, params);
return emitter;
}
}
......@@ -19,7 +19,6 @@
package org.dinky.db.service.impl;
import org.dinky.assertion.Asserts;
import org.dinky.common.result.ProTableResult;
import org.dinky.db.mapper.SuperMapper;
import org.dinky.db.service.ISuperService;
......@@ -34,6 +33,8 @@ import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import cn.hutool.core.lang.Opt;
/**
* SuperServiceImpl
*
......@@ -42,14 +43,17 @@ import com.fasterxml.jackson.databind.ObjectMapper;
public class SuperServiceImpl<M extends SuperMapper<T>, T> extends ServiceImpl<M, T>
implements ISuperService<T> {
@Override
public ProTableResult<T> selectForProTable(JsonNode para) {
Integer current = para.has("current") ? para.get("current").asInt() : 1;
Integer pageSize = para.has("pageSize") ? para.get("pageSize").asInt() : 10;
private ProTableResult<T> selectForProTable(
JsonNode params, boolean isDelete, Map<String, Object> paramsMap) {
Integer current = params.has("current") ? params.get("current").asInt() : 1;
Integer pageSize = params.has("pageSize") ? params.get("pageSize").asInt() : 10;
QueryWrapper<T> queryWrapper = new QueryWrapper<>();
ProTableUtil.autoQueryDefalut(para, queryWrapper);
ProTableUtil.autoQueryDefalut(params, queryWrapper, isDelete);
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> param = mapper.convertValue(para, Map.class);
Map<String, Object> param = mapper.convertValue(params, Map.class);
Opt.ofNullable(paramsMap).ifPresent(x -> param.putAll(paramsMap));
Page<T> page = new Page<>(current, pageSize);
List<T> list = baseMapper.selectForProTable(page, queryWrapper, param);
return ProTableResult.<T>builder()
......@@ -62,45 +66,17 @@ public class SuperServiceImpl<M extends SuperMapper<T>, T> extends ServiceImpl<M
}
@Override
public ProTableResult<T> selectForProTable(JsonNode para, boolean isDelete) {
Integer current = para.has("current") ? para.get("current").asInt() : 1;
Integer pageSize = para.has("pageSize") ? para.get("pageSize").asInt() : 10;
QueryWrapper<T> queryWrapper = new QueryWrapper<>();
ProTableUtil.autoQueryDefalut(para, queryWrapper, isDelete);
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> param = mapper.convertValue(para, Map.class);
Page<T> page = new Page<>(current, pageSize);
List<T> list = baseMapper.selectForProTable(page, queryWrapper, param);
return ProTableResult.<T>builder()
.success(true)
.data(list)
.total(page.getTotal())
.current(current)
.pageSize(pageSize)
.build();
public ProTableResult<T> selectForProTable(JsonNode params) {
return selectForProTable(params, false, null);
}
@Override
public ProTableResult<T> selectForProTable(JsonNode para, Map<String, Object> paraMap) {
Integer current = para.has("current") ? para.get("current").asInt() : 1;
Integer pageSize = para.has("pageSize") ? para.get("pageSize").asInt() : 10;
QueryWrapper<T> queryWrapper = new QueryWrapper<>();
ProTableUtil.autoQueryDefalut(para, queryWrapper);
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> param = mapper.convertValue(para, Map.class);
if (Asserts.isNotNull(paraMap)) {
for (Map.Entry<String, Object> entry : paraMap.entrySet()) {
param.put(entry.getKey(), entry.getValue());
}
}
Page<T> page = new Page<>(current, pageSize);
List<T> list = baseMapper.selectForProTable(page, queryWrapper, param);
return ProTableResult.<T>builder()
.success(true)
.data(list)
.total(page.getTotal())
.current(current)
.pageSize(pageSize)
.build();
public ProTableResult<T> selectForProTable(JsonNode params, boolean isDelete) {
return selectForProTable(params, isDelete, null);
}
@Override
public ProTableResult<T> selectForProTable(JsonNode params, Map<String, Object> paramMap) {
return selectForProTable(params, false, paramMap);
}
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.dinky.dto;
import java.util.List;
import lombok.Getter;
import lombok.Setter;
/** @since 0.8.0 */
@Getter
@Setter
public class GitAnalysisJarDTO {
private String jarPath;
private List<String> classList;
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.dinky.dto;
import javax.validation.constraints.NotNull;
import lombok.Getter;
import lombok.Setter;
/**
* @author ZackYoung
* @since 0.8.0
*/
@Getter
@Setter
public class GitProjectDTO {
private Long id;
/** */
@NotNull private String name;
@NotNull private String url;
/** */
@NotNull private String branches;
/** */
private String username;
/** */
private String password;
private String privateKey;
/** */
private String pom;
/** */
private String buildArgs;
/** */
private Integer codeType;
/** */
private String description;
/** */
@NotNull private Integer enable;
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.dinky.mapper;
import org.dinky.db.mapper.SuperMapper;
import org.dinky.model.GitProject;
import org.apache.ibatis.annotations.Mapper;
/**
* GitProjectMapper
*
* @since 2022/2/24 19:59
*/
@Mapper
public interface GitProjectMapper extends SuperMapper<GitProject> {}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.dinky.model;
import org.dinky.db.model.SuperEntity;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
/**
* @author ZackYoung
* @since 0.8.0
*/
@TableName(value = "dinky_git_project")
@Data
public class GitProject extends SuperEntity<GitProject> {
/** */
@TableField(value = "tenant_id")
private Long tenantId;
/** */
@TableField(value = "url")
private String url;
/** */
@TableField(value = "branch")
private String branch;
/** */
@TableField(value = "username")
private String username;
/** */
@TableField(value = "password")
private String password;
private String privateKey;
/** */
@TableField(value = "pom")
private String pom;
/** */
@TableField(value = "build_args")
private String buildArgs;
/** */
@TableField(value = "code_type")
private Integer codeType;
/** */
@TableField(value = "type")
private Integer type;
/** */
@TableField(value = "last_build")
private Date lastBuild;
/** */
@TableField(value = "description")
private String description;
/** */
@TableField(value = "build_state")
private Integer buildState;
@TableField(value = "build_step")
private Integer buildStep;
/** scan udf class */
@TableField(value = "udf_class_map_list")
private String udfClassMapList;
@TableField(exist = false)
private static final long serialVersionUID = 1L;
public Integer getExecState() {
switch (getBuildState()) {
case 1:
return 1;
case 3:
return 2;
case 0:
case 2:
default:
return 0;
}
}
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.dinky.service;
import org.dinky.db.service.ISuperService;
import org.dinky.dto.GitProjectDTO;
import org.dinky.model.GitProject;
/**
* @author ZackYoung
* @since 0.8.0
*/
public interface GitProjectService extends ISuperService<GitProject> {
/**
* 保存或更新
*
* @param gitProjectDTO gitProjectDTO
*/
void saveOrUpdate(GitProjectDTO gitProjectDTO);
/**
* 更新状态
*
* @param id id
* @param state state
*/
void updateState(Long id, boolean state);
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.dinky.service.impl;
import org.dinky.db.service.impl.SuperServiceImpl;
import org.dinky.dto.GitProjectDTO;
import org.dinky.mapper.GitProjectMapper;
import org.dinky.model.GitProject;
import org.dinky.process.exception.DinkyException;
import org.dinky.service.GitProjectService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import cn.hutool.core.bean.BeanUtil;
/**
* @author ZackYoung
* @since 0.8.0
*/
@Service
public class GitProjectServiceImpl extends SuperServiceImpl<GitProjectMapper, GitProject>
implements GitProjectService {
@Override
public void saveOrUpdate(GitProjectDTO gitProjectDTO) {
// select * from d where name == '' and id <> 1
Long id = gitProjectDTO.getId();
LambdaQueryWrapper<GitProject> isExistsSameName =
new LambdaQueryWrapper<GitProject>()
.eq(GitProject::getName, gitProjectDTO.getName())
.ne(id != null, GitProject::getId, id);
if (baseMapper.exists(isExistsSameName)) {
throw new DinkyException("project name is exists.");
}
GitProject gitProject = BeanUtil.toBean(gitProjectDTO, GitProject.class);
BeanUtil.copyProperties(gitProjectDTO, gitProject);
gitProject.insertOrUpdate();
}
@Override
public void updateState(Long id, boolean state) {
GitProject gitProject = baseMapper.selectById(id);
gitProject.setEnabled(state);
gitProject.updateById();
}
}
......@@ -176,8 +176,8 @@ public class RoleServiceImpl extends SuperServiceImpl<RoleMapper, Role> implemen
}
@Override
public ProTableResult<Role> selectForProTable(JsonNode para, boolean isDelete) {
ProTableResult<Role> roleProTableResult = super.selectForProTable(para, isDelete);
public ProTableResult<Role> selectForProTable(JsonNode params, boolean isDelete) {
ProTableResult<Role> roleProTableResult = super.selectForProTable(params, isDelete);
roleProTableResult
.getData()
.forEach(
......
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.dinky.sse;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import cn.hutool.core.lang.Dict;
/**
* @author ZackYoung
* @since 0.8.0
*/
public class DoneStepSse extends StepSse {
public DoneStepSse(
int sleep,
List<SseEmitter> emitterList,
Dict params,
AtomicInteger msgId,
AtomicInteger stepAtomic,
ExecutorService cachedThreadPool) {
super("done", sleep, emitterList, params, msgId, stepAtomic, cachedThreadPool);
}
@Override
public void exec() {
addFileMsgLog("finished");
}
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.dinky.sse;
import org.dinky.model.GitProject;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
/**
* @author ZackYoung
* @since 0.8.0
*/
@Slf4j
public abstract class StepSse {
protected final String name;
protected final int sleep;
protected int step = 0;
protected final List<SseEmitter> emitterList;
protected final Dict params;
protected final AtomicInteger msgId;
protected final AtomicInteger stepAtomic;
protected final ExecutorService cachedThreadPool;
protected final LinkedList<String> msgList = new LinkedList<>();
protected StepSse nexStepSse = null;
/** 0-fail , 1-process , 2-success */
protected int status = 0;
public StepSse(
String name,
int sleep,
List<SseEmitter> emitterList,
Dict params,
AtomicInteger msgId,
AtomicInteger stepAtomic,
ExecutorService cachedThreadPool) {
this.name = name;
this.sleep = sleep;
this.emitterList = emitterList;
this.params = params;
this.msgId = msgId;
this.stepAtomic = stepAtomic;
this.cachedThreadPool = cachedThreadPool;
}
public abstract void exec();
public synchronized void addMsg(String msg) {
msgList.add(msg);
}
public synchronized void sendMsg(Object msg) {
List<SseEmitter> loseLise = new ArrayList<>();
Opt.ofEmptyAble(CollUtil.removeNull(emitterList))
.ifPresent(
x -> {
x.forEach(
emitter -> {
try {
emitter.send(
SseEmitter.event()
.id(
String.valueOf(
msgId
.getAndIncrement()))
.data(msg));
} catch (IOException e) {
loseLise.add(emitter);
}
});
emitterList.removeAll(loseLise);
});
}
public synchronized void addFileMsg(Object msg) {
FileUtil.appendString(Convert.toStr(msg), getLogFile(), StandardCharsets.UTF_8);
}
public synchronized void addFileMsgLog(String msg) {
String content = "============= " + Convert.toStr(msg) + " =============\n";
msgList.add(content);
FileUtil.appendString(content, getLogFile(), StandardCharsets.UTF_8);
}
public synchronized void addFileLog(List<?> data) {
sendMsg(getList(data));
FileUtil.appendString(StrUtil.join("\n", data), getLogFile(), StandardCharsets.UTF_8);
}
protected File getLogFile() {
File logDir = (File) params.get("logDir");
return new File(logDir, getStep() + ".log");
}
public void sendSync() {
if (CollUtil.isNotEmpty(msgList)) {
sendMsg(getLogObj(msgList));
}
msgList.clear();
}
public void send() {
cachedThreadPool.execute(this::sendSync);
}
public void main() {
this.status = 1;
getStep();
FileUtil.del(getLogFile());
FileUtil.touch(getLogFile());
cachedThreadPool.execute(
() -> {
while (status == 1) {
ThreadUtil.sleep(sleep);
send();
}
});
try {
exec();
setFinish(true);
} catch (Exception e) {
addMsg(ExceptionUtil.stacktraceToString(e));
send();
setFinish(false);
}
}
public void setFinish(boolean status) {
this.status = status ? 2 : 0;
sendSync();
sendMsg(getEndLog());
GitProject gitProject = (GitProject) params.get("gitProject");
if (!status) {
gitProject.setBuildState(2);
close();
} else if (nexStepSse == null) {
gitProject.setBuildState(3);
close();
}
gitProject.setBuildStep(getStep());
gitProject.updateById();
if (status && nexStepSse != null) {
gitProject.setBuildState(1);
gitProject.setBuildStep(nexStepSse.getStep());
gitProject.updateById();
nexStepSse.main();
}
}
private void close() {
CollUtil.removeNull(emitterList)
.forEach(
emitter -> {
try {
emitter.complete();
} catch (Exception e) {
e.printStackTrace();
}
});
}
public int getStep() {
if (step != 0) {
return step;
}
this.step = stepAtomic.getAndIncrement();
return step;
}
public void setNexStepSse(StepSse nexStepSse) {
this.nexStepSse = nexStepSse;
}
protected Dict getLogObj(Object data) {
// {
// "type":"2",
// "currentStep":1,
// "resultType":"1", 1日志 2list
// "data":"log",
// "status":1 # 2完成 1进行中 0失败
//
// }
return Dict.create()
.set("type", 2)
.set("currentStep", getStep())
.set("resultType", 1)
.set("data", JSONUtil.toJsonStr(data))
.set("currentStepName", name)
.set("status", status);
}
protected Dict getLog(String data) {
return Dict.create()
.set("type", 2)
.set("currentStep", getStep())
.set("resultType", 1)
.set("data", data)
.set("currentStepName", name)
.set("status", status);
}
protected Dict getLogObj() {
return getLogObj(msgList);
}
protected Dict getEndLog() {
return Dict.create()
.set("type", 3)
.set("currentStep", getStep())
.set("resultType", 1)
.set("currentStepName", name)
.set("status", status);
}
protected Dict getList(List<?> dataList) {
return Dict.create()
.set("type", 2)
.set("currentStep", getStep())
.set("resultType", 2)
.set("data", dataList)
.set("currentStepName", name)
.set("status", status);
}
public void getStatus(int step, int status, List<Dict> data) {
Dict result = new Dict().set("step", getStep()).set("name", name);
if (getStep() <= step) {
Instant instant =
FileUtil.getAttributes(getLogFile().toPath(), true).creationTime().toInstant();
result.set(
"startTime",
new DateTime(instant).toString(DatePattern.NORM_DATETIME_PATTERN))
.set("status", getStep() < step ? 2 : status);
} else {
result.set("startTime", null).set("status", null);
}
data.add(result);
if (nexStepSse != null) {
nexStepSse.getStatus(step, status, data);
}
}
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.dinky.sse;
import java.io.Serializable;
import lombok.Getter;
import lombok.Setter;
/**
* @author ZackYoung
* @since 0.8.0
*/
@Setter
@Getter
public class StepState implements Serializable {
private Integer currentStep;
/** 2-success 1-process 0-failed */
private Integer status;
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.dinky.sse.git;
import org.dinky.dto.GitAnalysisJarDTO;
import org.dinky.function.util.UDFUtil;
import org.dinky.model.GitProject;
import org.dinky.sse.StepSse;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.json.JSONUtil;
/**
* @author ZackYoung
* @since 0.8.0
*/
public class AnalysisUdfClassStepSse extends StepSse {
public AnalysisUdfClassStepSse(
int sleep,
List<SseEmitter> emitterList,
Dict params,
AtomicInteger msgId,
AtomicInteger stepAtomic,
ExecutorService cachedThreadPool) {
super(
"analysis udf class",
sleep,
emitterList,
params,
msgId,
stepAtomic,
cachedThreadPool);
}
@Override
public void exec() {
List<String> pathList = (List<String>) params.get("jarPath");
List<GitAnalysisJarDTO> dataList = new ArrayList<>();
Map<String, List<Class<?>>> udfMap = new TreeMap<>();
pathList.parallelStream()
.forEach(
jar -> {
List<Class<?>> udfClassByJar = UDFUtil.getUdfClassByJar(new File(jar));
udfMap.put(jar, udfClassByJar);
sendMsg(Dict.create().set(jar, udfClassByJar));
});
udfMap.forEach(
(k, v) -> {
GitAnalysisJarDTO gitAnalysisJarDTO = new GitAnalysisJarDTO();
gitAnalysisJarDTO.setJarPath(k);
gitAnalysisJarDTO.setClassList(
v.stream().map(Class::getName).collect(Collectors.toList()));
dataList.add(gitAnalysisJarDTO);
});
String data = JSONUtil.toJsonStr(dataList);
sendMsg(getList(null).set("data", data));
FileUtil.appendString(data, getLogFile(), StandardCharsets.UTF_8);
// write result
GitProject gitProject = (GitProject) params.get("gitProject");
gitProject.setUdfClassMapList(data);
gitProject.updateById();
}
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.dinky.sse.git;
import org.dinky.model.GitProject;
import org.dinky.sse.StepSse;
import org.dinky.utils.GitRepository;
import org.dinky.utils.MavenUtil;
import java.io.File;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.lang.Opt;
/**
* @author ZackYoung
* @since 0.8.0
*/
public class GetJarsStepSse extends StepSse {
public GetJarsStepSse(
int sleep,
List<SseEmitter> emitterList,
Dict params,
AtomicInteger msgId,
AtomicInteger stepAtomic,
ExecutorService cachedThreadPool) {
super("get jars", sleep, emitterList, params, msgId, stepAtomic, cachedThreadPool);
}
@Override
public void exec() {
GitProject gitProject = (GitProject) params.get("gitProject");
String pom =
Opt.ofBlankAble(gitProject.getPom())
.orElse(
FileUtil.file(
GitRepository.getProjectDir(gitProject.getName()),
gitProject.getBranch())
.getAbsolutePath());
List<File> jars = MavenUtil.getJars(new File(pom));
List<String> pathList =
jars.stream().map(File::getAbsolutePath).collect(Collectors.toList());
addFileLog(pathList);
params.put("jarPath", pathList);
}
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.dinky.sse.git;
import org.dinky.dto.GitProjectDTO;
import org.dinky.model.GitProject;
import org.dinky.sse.StepSse;
import org.dinky.utils.GitRepository;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Dict;
/**
* @author ZackYoung
* @since 0.8.0
*/
public class GitCloneStepSse extends StepSse {
public GitCloneStepSse(
int sleep,
List<SseEmitter> emitterList,
Dict params,
AtomicInteger msgId,
AtomicInteger stepAtomic,
ExecutorService cachedThreadPool) {
super("git clone", sleep, emitterList, params, msgId, stepAtomic, cachedThreadPool);
}
@Override
public void exec() {
addFileMsgLog("git clone start");
GitProject gitProject = (GitProject) params.get("gitProject");
GitRepository gitRepository =
new GitRepository(BeanUtil.toBean(gitProject, GitProjectDTO.class));
gitRepository.cloneAndPull(gitProject.getName(), gitProject.getBranch());
addFileMsgLog("git clone finish");
}
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.dinky.sse.git;
import org.dinky.sse.StepSse;
import org.dinky.utils.MavenUtil;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
/**
* @author ZackYoung
* @since 0.8.0
*/
public class HeadStepSse extends StepSse {
public HeadStepSse(
int sleep,
List<SseEmitter> emitterList,
Dict params,
AtomicInteger msgId,
AtomicInteger stepAtomic,
ExecutorService cachedThreadPool) {
super("checkEnv", sleep, emitterList, params, msgId, stepAtomic, cachedThreadPool);
}
@Override
public void exec() {
checkEnv();
}
private void checkEnv() {
String mavenHome = MavenUtil.getMavenHome();
if (StrUtil.isBlank(mavenHome)) {
addFileMsg("Please set the environment variable:MAVEN_HOME");
setFinish(false);
}
String mavenVersionMsg = MavenUtil.getMavenVersion();
addFileMsgLog(mavenVersionMsg);
}
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.dinky.sse.git;
import org.dinky.model.GitProject;
import org.dinky.sse.StepSse;
import org.dinky.utils.GitRepository;
import org.dinky.utils.MavenUtil;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.util.StrUtil;
/**
* @author ZackYoung
* @since 0.8.0
*/
public class MavenStepSse extends StepSse {
public MavenStepSse(
int sleep,
List<SseEmitter> emitterList,
Dict params,
AtomicInteger msgId,
AtomicInteger stepAtomic,
ExecutorService cachedThreadPool) {
super("maven build", sleep, emitterList, params, msgId, stepAtomic, cachedThreadPool);
}
@Override
public void exec() {
GitProject gitProject = (GitProject) params.get("gitProject");
String pom =
Opt.ofBlankAble(gitProject.getPom())
.orElse(
FileUtil.file(
GitRepository.getProjectDir(gitProject.getName()),
gitProject.getBranch())
.getAbsolutePath());
boolean state =
MavenUtil.build(
null,
pom,
null,
null,
getLogFile().getAbsolutePath(),
CollUtil.newArrayList("clean", "package"),
StrUtil.split(gitProject.getBuildArgs(), " "),
this::addMsg);
if (!state) {
setFinish(false);
}
}
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.dinky.utils;
import org.dinky.common.result.StepResult;
import org.dinky.model.GitProject;
import org.dinky.process.exception.DinkyException;
import org.dinky.sse.DoneStepSse;
import org.dinky.sse.StepSse;
import org.dinky.sse.git.AnalysisUdfClassStepSse;
import org.dinky.sse.git.GetJarsStepSse;
import org.dinky.sse.git.GitCloneStepSse;
import org.dinky.sse.git.HeadStepSse;
import org.dinky.sse.git.MavenStepSse;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
/**
* @author ZackYoung
* @since 0.8.0
*/
public final class GitProjectStepSseFactory {
private static Map<Integer, List<SseEmitter>> sseEmitterMap = new ConcurrentHashMap<>();
private static final ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
public static void build(GitProject gitProject, Dict params) {
int sleep = 500;
List<SseEmitter> emitterList = new ArrayList<>();
StepSse headStepSse = getHeadStepPlan(gitProject.getCodeType(), sleep, emitterList, params);
cachedThreadPool.execute(headStepSse::main);
sseEmitterMap.put(gitProject.getId(), emitterList);
}
private static StepSse getHeadStepPlan(
Integer codeType, int sleep, List<SseEmitter> emitterList, Dict params) {
AtomicInteger msgId = new AtomicInteger(1);
AtomicInteger stepAtomic = new AtomicInteger(1);
if (codeType.equals(1)) {
HeadStepSse headStepSse =
new HeadStepSse(
sleep, emitterList, params, msgId, stepAtomic, cachedThreadPool);
GitCloneStepSse gitCloneStepSse =
new GitCloneStepSse(
sleep, emitterList, params, msgId, stepAtomic, cachedThreadPool);
MavenStepSse mavenStepSse =
new MavenStepSse(
sleep, emitterList, params, msgId, stepAtomic, cachedThreadPool);
GetJarsStepSse getJarsStepSse =
new GetJarsStepSse(
sleep, emitterList, params, msgId, stepAtomic, cachedThreadPool);
AnalysisUdfClassStepSse analysisUdfClassStepSse =
new AnalysisUdfClassStepSse(
sleep, emitterList, params, msgId, stepAtomic, cachedThreadPool);
DoneStepSse doneStepSse =
new DoneStepSse(
sleep, emitterList, params, msgId, stepAtomic, cachedThreadPool);
headStepSse.setNexStepSse(gitCloneStepSse);
gitCloneStepSse.setNexStepSse(mavenStepSse);
mavenStepSse.setNexStepSse(getJarsStepSse);
getJarsStepSse.setNexStepSse(analysisUdfClassStepSse);
analysisUdfClassStepSse.setNexStepSse(doneStepSse);
return headStepSse;
} else {
throw new DinkyException("only support java!");
}
}
public static void observe(SseEmitter emitter, GitProject gitProject, Dict params) {
List<Dict> dataList = new ArrayList<>();
Integer state = gitProject.getExecState();
Integer step = gitProject.getBuildStep();
getHeadStepPlan(gitProject.getCodeType(), 0, null, params).getStatus(step, state, dataList);
try {
emitter.send(SseEmitter.event().data(StepResult.getStepInfo(step, dataList)));
File logDir = getLogDir(gitProject.getName(), gitProject.getBranch());
List<String> msgList =
FileUtil.readLines(new File(logDir, step + ".log"), StandardCharsets.UTF_8);
StepResult stepResult =
StepResult.builder()
.currentStep(step)
.status(state)
.data(StrUtil.join("\n", msgList))
.type(2)
.build();
emitter.send(SseEmitter.event().id("2").data(stepResult));
} catch (Exception e) {
e.printStackTrace();
}
if (state.equals(1)) {
sseEmitterMap.get(gitProject.getId()).add(emitter);
} else {
emitter.complete();
}
}
public static File getLogDir(String projectName, String branch) {
return FileUtil.file(GitRepository.getProjectDir(projectName), branch + "_log");
}
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.dinky.utils;
import org.dinky.dto.GitProjectDTO;
import org.dinky.function.constant.PathConstant;
import org.dinky.process.exception.DinkyException;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.jgit.api.CloneCommand;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.LsRemoteCommand;
import org.eclipse.jgit.api.TransportCommand;
import org.eclipse.jgit.api.TransportConfigCallback;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
import org.eclipse.jgit.transport.JschConfigSessionFactory;
import org.eclipse.jgit.transport.OpenSshConfig;
import org.eclipse.jgit.transport.SshTransport;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
import org.eclipse.jgit.util.FS;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
/**
* @author ZackYoung
* @since 0.8.0
*/
@AllArgsConstructor
@Slf4j
public class GitRepository {
private static final String BRANCH_PREFIX = "refs/heads/";
/** 匹配 ssh格式 git 地址 */
private static final String SSH_REGEX = "^git@[\\w\\.]+:([\\w_]+)/(.*?)\\.git$";
private String url;
private String username;
private String password;
private String privateKey;
public GitRepository(GitProjectDTO gitProjectDTO) {
this.url = gitProjectDTO.getUrl();
this.username = gitProjectDTO.getUsername();
this.password = gitProjectDTO.getPassword();
this.privateKey = gitProjectDTO.getPrivateKey();
}
public File cloneAndPull(String projectName, String branch) {
List<String> branchList = getBranchList();
if (!branchList.contains(branch)) {
throw new DinkyException(
StrUtil.format(
"Branch: {} does not exist, optional branch is: {}",
branch,
branchList));
}
File targetFile = getProjectDir(projectName);
FileUtil.mkdir(targetFile);
File writeFile = new File(targetFile, branch);
Git git;
try {
CloneCommand cloneCommand =
Git.cloneRepository().setURI(url).setBranch(branch).setDirectory(writeFile);
initCommand(cloneCommand);
if (writeFile.exists()) {
FileRepositoryBuilder builder = new FileRepositoryBuilder();
Repository repository =
builder.setGitDir(
new File(
writeFile.getAbsolutePath()
+ File.separator
+ ".git"))
.readEnvironment()
.findGitDir()
.build();
git = new Git(repository);
git.pull().call();
git.close();
} else {
cloneCommand.call().close();
}
return writeFile;
} catch (Exception e) {
e.printStackTrace();
throw new DinkyException(e);
}
}
public static File getProjectDir(String projectName) {
return FileUtil.file(PathConstant.TMP_PATH, "git", projectName);
}
/**
* 获取分支列表(提供拼音排序)
*
* @return {@link List}<{@link String}>
*/
public List<String> getBranchList() {
List<String> branchList = new ArrayList<>();
LsRemoteCommand lsRemoteCommand = initCommand(Git.lsRemoteRepository().setRemote(url));
try {
lsRemoteCommand
.call()
.forEach(
x -> {
if (StrUtil.contains(x.getName(), BRANCH_PREFIX)) {
branchList.add(
StrUtil.removePrefix(x.getName(), BRANCH_PREFIX));
}
});
} catch (GitAPIException e) {
throw new RuntimeException(e);
}
return CollUtil.reverse(CollUtil.sortByPinyin(branchList));
}
private static TransportConfigCallback getTransportConfigCallback(
String sshKey, String password) {
JschConfigSessionFactory jschConfigSessionFactory =
new JschConfigSessionFactory() {
@Override
protected void configure(OpenSshConfig.Host host, Session session) {
session.setConfig("StrictHostKeyChecking", "no");
}
@Override
protected JSch createDefaultJSch(FS fs) throws JSchException {
JSch defaultJSch = super.createDefaultJSch(fs);
// 配置 ssh key
defaultJSch.addIdentity(sshKey, sshKey + ".pub", StrUtil.bytes(password));
return defaultJSch;
}
};
return transport -> {
SshTransport sshTransport = (SshTransport) transport;
sshTransport.setSshSessionFactory(jschConfigSessionFactory);
};
}
/**
* 初始化git指令,设置账密信息
*
* @param command 命令
* @return command
*/
private <T extends TransportCommand<T, ?>> T initCommand(T command) {
if (isSshGitUrl(url)) {
TransportConfigCallback sshSessionFactory =
getTransportConfigCallback(privateKey, password);
command.setTransportConfigCallback(sshSessionFactory);
return command;
} else if (HttpUtil.isHttp(url) || HttpUtil.isHttps(url)) {
if (StrUtil.isAllNotBlank(username, password)) {
command.setCredentialsProvider(
new UsernamePasswordCredentialsProvider(username, password));
return command;
}
} else {
throw new UnsupportedOperationException(
"This format is not supported. Specify as http, git. your url is -> " + url);
}
return command;
}
/**
* 判断是否为ssh格式的git地址
*
* @param url git地址
* @return true表示是ssh格式的git地址,false表示不是ssh格式的git地址
*/
public static boolean isSshGitUrl(String url) {
return ReUtil.isMatch(SSH_REGEX, url);
}
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.dinky.utils;
import org.dinky.process.exception.DinkyException;
import org.apache.maven.shared.invoker.DefaultInvocationRequest;
import org.apache.maven.shared.invoker.DefaultInvoker;
import org.apache.maven.shared.invoker.InvocationRequest;
import org.apache.maven.shared.invoker.Invoker;
import org.apache.maven.shared.invoker.MavenInvocationException;
import org.apache.maven.shared.invoker.PrintStreamHandler;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.function.Consumer;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.util.StrUtil;
import cn.hutool.system.SystemUtil;
/**
* @author ZackYoung
* @since 0.8.0
*/
public class MavenUtil {
private static final List<String> COMMON_BIN_PATH = CollUtil.newArrayList("/usr", "/usr/local");
public static boolean build(String setting, String pom, String logFile, List<String> args) {
return build(
setting, pom, null, null, logFile, CollUtil.newArrayList("package"), args, null);
}
public static boolean build(
String setting,
String pom,
String mavenHome,
String repositoryDir,
String logFile,
List<String> goals,
List<String> args,
Consumer<String> consumer) {
Assert.notBlank(pom, "the project pom file cannot be empty");
// maven安装路径
mavenHome = Opt.ofBlankAble(mavenHome).orElse(getMavenHome());
Opt.ofBlankAble(mavenHome)
.orElseThrow(
() -> new DinkyException("Please set the environment variable:MAVEN_HOME"));
InvocationRequest request = new DefaultInvocationRequest();
request.addArg("-DskipTests=true");
Opt.ofEmptyAble(args).ifPresent(c -> CollUtil.removeBlank(args).forEach(request::addArg));
if (StrUtil.isBlank(setting)) {
repositoryDir = Opt.ofBlankAble(repositoryDir).orElse("/usr/local/resp");
// 设置仓库地址
request.setLocalRepositoryDirectory(new File(repositoryDir));
} else {
request.setGlobalSettingsFile(new File(setting));
Opt.ofBlankAble(repositoryDir)
.ifPresent(x -> request.setLocalRepositoryDirectory(new File(x)));
}
// 设置pom文件路径
request.setPomFile(new File(pom));
// 执行的maven命令
request.setGoals(goals);
request.setMavenHome(new File(mavenHome));
try {
FileUtil.touch(logFile);
// 日志处理
PrintStream out = new PrintStream(logFile);
PrintStreamHandler printStreamHandler =
new PrintStreamHandler(out, true) {
@Override
public void consumeLine(String line) {
// 2023-04-21 18:24:37.613 INFO -
line = DateUtil.date().toMsStr() + " - " + line;
if (consumer != null) {
consumer.accept(line);
}
super.consumeLine(line);
}
};
request.setOutputHandler(printStreamHandler);
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
}
Invoker invoker = new DefaultInvoker();
try {
// 判断是否执行成功
return invoker.execute(request).getExitCode() == 0;
} catch (MavenInvocationException e) {
e.printStackTrace();
return false;
}
}
public static String getMavenVersion() {
String mavenHome = getMavenHome();
InvocationRequest request = new DefaultInvocationRequest();
request.setMavenHome(new File(mavenHome));
request.addArg("-v");
List<String> msg = new LinkedList<>();
request.setOutputHandler(msg::add);
Invoker invoker = new DefaultInvoker();
try {
invoker.execute(request);
} catch (MavenInvocationException e) {
throw new RuntimeException(e);
}
return StrUtil.join("\n", msg);
}
public static String getMavenHome() {
String mavenHome = SystemUtil.get("MAVEN_HOME");
if (StrUtil.isNotBlank(mavenHome)) {
return mavenHome;
}
if (SystemUtil.getOsInfo().isLinux() || SystemUtil.getOsInfo().isMac()) {
for (String path : COMMON_BIN_PATH) {
if (FileUtil.exist(path + "/bin/mvn")) {
return path;
}
}
}
return null;
}
public static List<File> getJars(File pom) {
List<File> jarFileList = new ArrayList<>();
getJarList(pom, jarFileList);
return jarFileList;
}
private static void getJarList(File pom, List<File> jarFileList) {
File pomParentDir = FileUtil.getParent(pom, 1);
File targetDir = new File(pomParentDir, "target");
if (FileUtil.exist(targetDir) && FileUtil.isDirectory(targetDir)) {
File[] buildFile = targetDir.listFiles();
for (File build : buildFile) {
if ("jar".equals(FileUtil.extName(build))) {
if (build.getName().length() > 13
&& "original-".equals(build.getName().substring(0, 9))) {
continue;
}
jarFileList.add(build);
}
}
}
File[] files = FileUtil.file(pomParentDir).listFiles();
for (File file : files) {
File pomFile = new File(file, "pom.xml");
if (file.isDirectory() && FileUtil.exist(pomFile)) {
getJarList(pomFile, jarFileList);
}
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.dinky.mapper.AlertGroupMapper">
<select id="selectForProTable" resultType="org.dinky.model.GitProject">
select
a.*
from
dinky_git_project a
<where>
1=1
<if test='param.name!=null and param.name!=""'>
and a.name like CONCAT('%', #{param.name}, '%')
</if>
<if test='param.branch!=null and param.branch!=""'>
and a.branch = #{param.branch}
</if>
<if test='param.type!=null and param.type!=""'>
and a.type = #{param.type}
</if>
<if test='param.code_type!=null and param.code_type!=""'>
and a.code_type = #{param.code_type}
</if>
<if test='param.build_state!=null and param.build_state!=""'>
and a.build_state = #{param.build_state}
</if>
<if test='param.url!=null and param.url!=""'>
and a.url like CONCAT('%', #{param.url}, '%')
</if>
<if test='param.createTime!=null and param.createTime!=""'>
and a.create_time <![CDATA[>=]]> str_to_date( #{param.createTime},'%Y-%m-%d %H:%i:%s')
</if>
<if test='param.updateTime!=null and param.updateTime!=""'>
and a.update_time <![CDATA[>=]]> str_to_date( #{param.updateTime},'%Y-%m-%d %H:%i:%s')
</if>
<if test='ew.sqlSegment!=null and ew.sqlSegment!="" and !ew.sqlSegment.startsWith(" ORDER BY")'>
and
</if>
<if test='ew.sqlSegment!=null and ew.sqlSegment!=""'>
${ew.sqlSegment}
</if>
</where>
order by enable desc
</select>
</mapper>
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.dinky.utils;
import java.io.File;
import java.util.List;
import org.junit.jupiter.api.Test;
/**
* @author ZackYoung
* @since 0.8.0
*/
public class GitRepositoryTests {
GitRepository sshRepository =
new GitRepository("git@gitee.com:DataLinkDC/dinky.git", null, null, "");
GitRepository httpRepository =
new GitRepository("https://github.com/DataLinkDC/dinky", null, null, null);
@Test
public void httpTest() {
List<String> branchList1 = httpRepository.getBranchList();
System.out.println(branchList1);
File dinky = httpRepository.cloneAndPull("dinky", "0.7");
}
}
......@@ -48,7 +48,6 @@ public class JavaCompiler implements FunctionCompiler {
public boolean compiler(UDF udf, ReadableConfig conf, Integer missionId) {
ProcessEntity process = ProcessContextHolder.getProcess();
process.info("正在编译 java 代码 , class: " + udf.getClassName());
CustomStringJavaCompiler compiler = new CustomStringJavaCompiler(udf.getCode());
boolean res = compiler.compilerToTmpPath(PathConstant.getUdfCompilerJavaPath(missionId));
String className = compiler.getFullClassName();
......
......@@ -35,8 +35,12 @@ import org.dinky.pool.ClassPool;
import org.dinky.process.exception.DinkyException;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.table.api.ValidationException;
import org.apache.flink.table.catalog.FunctionLanguage;
import org.apache.flink.table.functions.UserDefinedFunction;
import org.apache.flink.table.functions.UserDefinedFunctionHelper;
import java.io.File;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
......@@ -45,6 +49,8 @@ import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.JarFile;
import java.util.regex.Pattern;
import org.slf4j.Logger;
......@@ -53,11 +59,16 @@ import org.slf4j.LoggerFactory;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.ClassScanner;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.lang.JarClassLoader;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ClassLoaderUtil;
import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.extra.template.TemplateConfig;
......@@ -350,4 +361,36 @@ public class UDFUtil {
}
return null;
}
public static List<Class<?>> getUdfClassByJar(File jarPath) {
Assert.notNull(jarPath);
List<Class<?>> classList = new ArrayList<>();
try (JarClassLoader loader = new JarClassLoader()) {
loader.addJar(jarPath);
ClassScanner classScanner =
new ClassScanner(
"",
aClass -> ClassUtil.isAssignable(UserDefinedFunction.class, aClass));
classScanner.setClassLoader(loader);
ReflectUtil.invoke(classScanner, "scanJar", new JarFile(jarPath));
Set<Class<? extends UserDefinedFunction>> classes =
(Set<Class<? extends UserDefinedFunction>>)
ReflectUtil.getFieldValue(classScanner, "classes");
for (Class<? extends UserDefinedFunction> aClass : classes) {
try {
UserDefinedFunctionHelper.validateClass(aClass);
classList.add(aClass);
} catch (Exception ex) {
throw new DinkyException();
}
}
} catch (ValidationException e) {
throw e;
} catch (Exception e) {
}
return classList;
}
}
......@@ -1046,3 +1046,34 @@ CREATE TABLE dinky_role_select_permissions
COMMENT '角色数据查询权限' COLLATE = utf8mb4_general_ci;
SET FOREIGN_KEY_CHECKS = 1;
-- ----------------------------
-- Table structure for dinky_git_project
-- ----------------------------
DROP TABLE IF EXISTS `dinky_git_project`;
CREATE TABLE `dinky_git_project` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`tenant_id` bigint(20) NOT NULL,
`name` varchar(255) NOT NULL,
`url` varchar(1000) NOT NULL,
`branch` varchar(1000) NOT NULL,
`username` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`private_key` varchar(255) DEFAULT NULL COMMENT 'keypath',
`pom` varchar(255) DEFAULT NULL,
`build_args` varchar(255) DEFAULT NULL,
`code_type` tinyint(4) DEFAULT NULL COMMENT 'code type(1-java,2-python)',
`type` tinyint(4) NOT NULL COMMENT '1-http ,2-ssh',
`last_build` datetime DEFAULT NULL,
`description` varchar(255) DEFAULT NULL,
`build_state` tinyint(2) NOT NULL DEFAULT '0' COMMENT '0-notStart 1-process 2-failed 3-success',
`build_step` tinyint(2) NOT NULL DEFAULT '0',
`enabled` tinyint(1) NOT NULL DEFAULT '1' COMMENT '0-disable 1-enable',
`udf_class_map_list` text COMMENT 'scan udf class',
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'create time',
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'update time',
PRIMARY KEY (`id`) USING BTREE,
KEY `tenant_id` (`tenant_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4;
INSERT INTO `dinky_git_project` (`id`, `tenant_id`, `name`, `url`, `branch`, `username`, `password`, `private_key`, `pom`, `build_args`, `code_type`, `type`, `last_build`, `description`, `build_state`, `build_step`, `enabled`, `udf_class_map_list`, `create_time`, `update_time`) VALUES (1, 1, 'java-udf', 'https://github.com/zackyoungh/dinky-quickstart-java.git', 'master', NULL, NULL, NULL, NULL, '-P flink-1.14', 1, 1, NULL, NULL, 1, 0, 1, '', '2023-04-26 15:10:13', '2023-04-26 15:10:43');
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment