This commit is contained in:
wangwei10061 2017-04-13 22:55:17 +08:00
commit 137f74e8e8
50 changed files with 1200 additions and 6 deletions

View File

@ -32,8 +32,9 @@ import com.offbytwo.jenkins.model.JobWithDetails;
public class FirstTest {
public static void main(String[] args) {
try {
// JenkinsServer jenkins = new JenkinsServer(new URI("http://106.75.33.219:30001"), "root", "root");
JenkinsServer jenkins = new JenkinsServer(new URI("http://106.75.78.183:9999/jenkins"), "guange", "123456");
JenkinsServer jenkins = new JenkinsServer(new URI("http://106.75.33.219:30001"), "root", "root");
// JenkinsServer jenkins = new JenkinsServer(new URI("http://106.75.78.183:9999/jenkins"), "guange", "123456");
System.out.println(jenkins.createJob("123", ""));
Map<String, Job> jobs = jenkins.getJobs();
JobWithDetails job = jobs.get("3").details();
Map<String, String> params = new HashMap<String, String>();

View File

@ -0,0 +1,105 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<artifactId>jenkins</artifactId>
<groupId>cn.guange.app</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>jenkins-exec</artifactId>
<packaging>war</packaging>
<name>jenkins-exec</name>
<build>
<plugins>
<plugin>
<artifactId>maven-shade-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer>
<resource>META-INF/spring.handlers</resource>
</transformer>
<transformer>
<resource>META-INF/spring.schemas</resource>
</transformer>
<transformer>
<mainClass>cn.guange.app.jenkins.App</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<address>0.0.0.0</address>
<port>9001</port>
<path>/</path>
<uriEncoding>UTF-8</uriEncoding>
<finalName>jenkins-exec</finalName>
<server>tomcat7</server>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>testCompile</id>
<phase>test-compile</phase>
<goals>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
<exclusions>
<exclusion>
<artifactId>javax.mail</artifactId>
<groupId>com.sun.mail</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
<exclusions>
<exclusion>
<artifactId>hamcrest-core</artifactId>
<groupId>org.hamcrest</groupId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
</project>

178
jenkins-exec/bin/pom.xml Normal file
View File

@ -0,0 +1,178 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>cn.guange.app</groupId>
<artifactId>jenkins</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>jenkins-exec</artifactId>
<packaging>war</packaging>
<name>jenkins-exec</name>
<dependencies>
<dependency>
<groupId>cn.guange.app</groupId>
<artifactId>jenkins-client</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.20</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
<resource>META-INF/spring.handlers</resource>
</transformer>
<transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
<resource>META-INF/spring.schemas</resource>
</transformer>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>cn.guange.app.jenkins.App</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<address>0.0.0.0</address>
<port>9001</port>
<path>/</path>
<uriEncoding>UTF-8</uriEncoding>
<finalName>jenkins-exec</finalName>
<server>tomcat7</server>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>testCompile</id>
<phase>test-compile</phase>
<goals>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:annotation-config></context:annotation-config>
<context:component-scan base-package="com.educoder.jenkins.api"/>
<context:component-scan base-package="com.educoder.jenkins.settings"/>
<context:component-scan base-package="com.educoder.jenkins.controller"/>
<!--导入配置-->
<context:property-placeholder location="classpath:config.properties"/>
</beans>

View File

@ -0,0 +1,16 @@
# trustieUrl=http://www.trustie.net/callback
# trustieUrl=http://ucloudtest.trustie.net/shixuns/training_task_status
trustieUrl=http://192.168.0.238:8888/myshixuns/training_task_status
#jenkinsUrl
#jenkinsUrl=http://localhost:8080/
#jenkisUserName=admin
#jenkisPassWord=wang199637
jenkinsUrl=http://123.59.135.74:9999/jenkins
jenkisUserName=guange
jenkisPassWord=123456
#jenkinsUrl=http://192.168.0.238:9999
#jenkisUserName=guange
#jenkisPassWord=123456

View File

@ -0,0 +1,22 @@
if (nowStep == STEP) {
// 读取输入和预期输出
def in = readFile '/home/pdl/.jenkins/workspace/testCases/SHIXUNID_STEP_In'
def expectedOut = readFile '/home/pdl/.jenkins/workspace/testCases/SHIXUNID_STEP_Out'
// 编译程序
sh script: 'echo "$(javac FILEPATH 2>&1)" > compile_result.txt'
compileResult = readFile ('compile_result.txt')
// 如果编译错误
if (compileResult.trim() == '') {
postResultToBDWeb(compileResult: compileResult, out: '', in:in, expectedOut:expectedOut)
return ;
}
// 从in.txt读入程序运行输出重定向到out.txt
sh script: 'echo "$(java SOURCECLASSNAME < /home/pdl/.jenkins/workspace/testCases/SHIXUNID_STEP_In 2>&1)" > out.txt'
def out = readFile "out.txt"
// 由中间层判断结果之后发送给BDWeb
postResultToBDWeb(compileResult: compileResult, out: out, in:in, expectedOut:expectedOut)
}

View File

@ -0,0 +1,20 @@
node() {
git url: gitUrl
withDockerContainer(language) {
def nowStep = Integer.parseInt(step)
}
}
// 传送运行结果到BDWeb
def postResultToBDWeb(def arg){
def s = 'compileResult=' + arg.compileResult + '&out=' + arg.out +
'&in=' + arg.in + '&expectedOut=' + arg.expectedOut
def response = httpRequest acceptType: 'APPLICATION_JSON_UTF8', consoleLogResponseBody: true, contentType: 'APPLICATION_FORM',
httpMode: 'POST', requestBody: s, url: "http://123.59.135.74:9999/jenkins-exec/pipeline/call?taskId=${taskId}"
if (response.status==299){
error response.content
}
}

View File

@ -0,0 +1,21 @@
<?xml version='1.0' encoding='UTF-8'?>
<flow-definition plugin="workflow-job@2.10">
<actions/>
<description></description>
<keepDependencies>false</keepDependencies>
<properties>
<hudson.model.ParametersDefinitionProperty>
<parameterDefinitions>
PARAMS_CONTENT
</parameterDefinitions>
</hudson.model.ParametersDefinitionProperty>
<org.jenkinsci.plugins.workflow.job.properties.PipelineTriggersJobProperty>
<triggers/>
</org.jenkinsci.plugins.workflow.job.properties.PipelineTriggersJobProperty>
</properties>
<definition class="org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition" plugin="workflow-cps@2.26">
<script>PIPELINE_CONTENT</script>
<sandbox>false</sandbox>
</definition>
<triggers/>
</flow-definition>

View File

@ -0,0 +1,11 @@
### 设置###
log4j.rootLogger = debug,stdout
### 输出信息到控制抬 ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
#log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n
log4j.appender.stdout.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} %m%n
log4j.logger.org.springframework=INFO

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--指明 controller 所在包,并扫描其中的注解-->
<context:component-scan base-package="cn.guange.app.jenkins.controller"/>
<!-- 静态资源(js、image等)的访问 -->
<mvc:default-servlet-handler/>
<!-- 开启注解 -->
<mvc:annotation-driven/>
<bean class="springfox.documentation.swagger2.configuration.Swagger2DocumentationConfiguration" id="swagger2Config"/>
<mvc:resources location="classpath:/META-INF/resources/" mapping="swagger-ui.html"/>
<mvc:resources location="classpath:/META-INF/resources/webjars/" mapping="/webjars/**"/>
</beans>

View File

@ -0,0 +1,50 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>SpringMVCDemo Web Application</display-name>
<!-- Spring 上下文参数 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

View File

@ -0,0 +1 @@
<meta http-equiv="refresh" content="0; url=/swagger-ui.html" />

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:annotation-config></context:annotation-config>
<context:component-scan base-package="com.educoder.jenkins.api"/>
<context:component-scan base-package="com.educoder.jenkins.settings"/>
<context:component-scan base-package="com.educoder.jenkins.controller"/>
<!--导入配置-->
<context:property-placeholder location="classpath:config.properties"/>
</beans>

View File

@ -0,0 +1,18 @@
# trustieUrl=http://www.trustie.net/callback
# trustieUrl=http://ucloudtest.trustie.net/shixuns/training_task_status
trustieUrl=http://192.168.0.238:8888/myshixuns/training_task_status
#jenkinsUrl
#jenkinsUrl=http://localhost:8080/
#jenkisUserName=admin
#jenkisPassWord=wang199637
#jenkinsUrl=http://106.75.33.219:30001
#jenkisUserName=root
#jenkisPassWord=root
jenkinsUrl=http://123.59.135.74:9999/jenkins
jenkisUserName=guange
jenkisPassWord=123456
#jenkinsUrl=http://106.75.78.183:8888
#jenkisUserName=root
#jenkisPassWord=root

View File

@ -0,0 +1,21 @@
<?xml version='1.0' encoding='UTF-8'?>
<flow-definition plugin="workflow-job@2.10">
<actions/>
<description></description>
<keepDependencies>false</keepDependencies>
<properties>
<hudson.model.ParametersDefinitionProperty>
<parameterDefinitions>
PARAMS_CONTENT
</parameterDefinitions>
</hudson.model.ParametersDefinitionProperty>
<org.jenkinsci.plugins.workflow.job.properties.PipelineTriggersJobProperty>
<triggers/>
</org.jenkinsci.plugins.workflow.job.properties.PipelineTriggersJobProperty>
</properties>
<definition class="org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition" plugin="workflow-cps@2.26">
<script>PIPELINE_CONTENT</script>
<sandbox>false</sandbox>
</definition>
<triggers/>
</flow-definition>

View File

@ -0,0 +1,11 @@
### 设置###
log4j.rootLogger = stdout
### 输出信息到控制抬 ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
#log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n
log4j.appender.stdout.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} %m%n
log4j.logger.org.springframework=INFO

View File

@ -0,0 +1,3 @@
node(){
echo "helloworld"
}

View File

@ -0,0 +1,26 @@
import com.fasterxml.jackson.databind.*
import java.io.*
import java.text.SimpleDateFormat;
import java.util.Date;
node(){
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
println("jenkins start build time:" + df.format(new Date()) + " taskId:" + taskId);
Thread.sleep(10000);
executeCmd(commitType:'commitSuccess',
jsonTypeArg: '{"msg":"' + '1' + '", "outPut": "' + '1' + '"}')
println("jenkins build finished time:" + df.format(new Date()) + " taskId:" + taskId);
}
def executeCmd(def arg){
def s = 'commitType=' + arg.commitType + "&jsonTypeArg=" + arg.jsonTypeArg
println(s)
def response = httpRequest acceptType: 'APPLICATION_JSON_UTF8', consoleLogResponseBody: true, contentType: 'APPLICATION_FORM',
httpMode: 'POST', requestBody: s, url: "http://123.59.135.74:9999/jenkins-exec/pipeline/call?taskId=${taskId}"
if (response.status==299){
error response.content
}
}

View File

@ -0,0 +1 @@
WEB-INF/classes/config.properties

View File

@ -0,0 +1 @@
rsync --stats --exclude-from="`pwd`/sync_exclude.list" --rsh=ssh -P -r target/jenkins-exec-1.0-SNAPSHOT/ jenkins:/home/pdl/apache-tomcat-8.5.11/webapps/jenkins-exec/

View File

@ -107,6 +107,17 @@ public class JenkinsApi {
job.build(buildParams);
}
public void buildJob(String jobName, String taskId, String step, String gitUrl) throws IOException {
JobWithDetails job = jenkins.getJob(jobName);
Map<String, String> buildParams = new HashMap();
buildParams.put("taskId", taskId);
buildParams.put("step", step);
buildParams.put("gitUrl", gitUrl);
job.build(buildParams);
}
/**
* 获取job的xml配置文件
* @param jobName

View File

@ -32,6 +32,89 @@ public class JenkinsController {
@Autowired
JenkinsApi jenkinsApi;
@ApiOperation(value = "开始一个实训", httpMethod = "POST", produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
@ApiResponse(code = 200, message = "success", response = JSONObject.class)
@RequestMapping(path="/openGameTraining",method = RequestMethod.POST)
public JSONObject openTrainingInstance(String jobNameForInstance, String gamePipelineScript, String InstanceGitURL){
JSONObject response = new JSONObject();
return response;
}
@ApiOperation(value = "保存输入输出到文件", httpMethod = "POST", produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public JSONObject saveTestCases (String shixunId, String cases){
JSONObject response = new JSONObject();
return response;
}
@ApiOperation(value = "创建一个job", httpMethod = "POST", produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
@ApiResponse(code = 200, message = "success", response = JSONObject.class)
@RequestMapping(path="/createJob",method = RequestMethod.POST)
public JSONObject createJobForInstance(@ApiParam(name = "jobNameForInstance", required = true, value = "job的名字不能重复") @RequestParam String jobNameForInstance,
@ApiParam(name = "gamePipelineScript", required = true, value = "pipeLine脚本用base64编码") @RequestParam String gamePipelineScript,
@ApiParam(name = "jobParams", required = true, value = "job的参数以json字符串的形式") @RequestParam String jobParams
){
JSONObject response = new JSONObject();
try {
Map jobParamsMap = JSONObject.parseObject(jobParams, Map.class);
for (Object key : jobParamsMap.keySet()) {
jobParamsMap.put(key, "");
}
logger.debug("调用[createJob]: jobName=" + jobNameForInstance + " pipeLine=" + gamePipelineScript + JSONObject.toJSONString(jobParams));
gamePipelineScript = Base64Helper.decode(gamePipelineScript);
String result = jenkinsApi.createJob(jobNameForInstance, gamePipelineScript, jobParamsMap);
logger.debug(result);
}catch (Exception e){
logger.error("createJob", e);
if (e.getMessage().startsWith("A job already exists")){
// 这里后续考虑是不是也替换成status
response.put("code", -2);
response.put("msg", jobNameForInstance+" already exists");
return response;
}
response.put("code", -1);
response.put("msg", e.getMessage());
return response;
}
response.put("code", 0);
response.put("msg", "create job success.");
return response;
}
@ApiOperation(value = "构建一个job", httpMethod = "POST", produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
@RequestMapping(path="/buildJob")
public JSONObject buildJob(@ApiParam(name = "jobNameForInstance", required = true, value = "job的名字") @RequestParam String jobNameForInstance,
@ApiParam(name = "instanceGitURL", required = true, value = "学员对应当前实训版本库地址") @RequestParam String instanceGitURL,
@ApiParam(name = "buildID", required = true, value = "本次评测ID") @RequestParam String buildID,
@ApiParam(name = "instanceStage", required = true, value = "当前处在第几关") @RequestParam String instanceStage
){
JSONObject response = new JSONObject();
try {
logger.debug("调用[buildJob]: jobName=" + jobNameForInstance + "taskId "+buildID+" step "+instanceStage+" gitUrl "+instanceGitURL);
instanceGitURL = Base64Helper.decode(instanceGitURL);
jenkinsApi.buildJob(jobNameForInstance, buildID, instanceStage, instanceGitURL);
}catch (Exception e){
logger.error("buildJob", e);
response.put("code", -1);
response.put("msg", e.getMessage());
return response;
}
response.put("code", 0);
response.put("msg", "run job success");
return response;
}
/**
@ApiOperation(value = "创建一个job", httpMethod = "POST", produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
@ApiResponse(code = 200, message = "success", response = JSONObject.class)
@RequestMapping(path="/createJob",method = RequestMethod.POST)
@ -70,6 +153,30 @@ public class JenkinsController {
return response;
}
@ApiOperation(value = "构建一个job", httpMethod = "POST", produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
@RequestMapping(path="/buildJob")
public JSONObject buildJob(@ApiParam(name = "jobName", required = true, value = "job的名字") @RequestParam String jobName,
@ApiParam(name = "gitUrl", required = true, value = "学员对应当前实训版本库地址") @RequestParam String gitUrl,
@ApiParam(name = "taskId", required = true, value = "本次评测ID") @RequestParam String taskId,
@ApiParam(name = "step", required = true, value = "当前处在第几关") @RequestParam String step
){
JSONObject response = new JSONObject();
try {
logger.debug("调用[buildJob]: jobName=" + jobName + "taskId "+taskId+" step "+step+" gitUrl "+gitUrl);
gitUrl = Base64Helper.decode(gitUrl);
jenkinsApi.buildJob(jobName, taskId, step, gitUrl);
}catch (Exception e){
logger.error("buildJob", e);
response.put("code", -1);
response.put("msg", e.getMessage());
return response;
}
response.put("code", 0);
response.put("msg", "run job success");
return response;
}
@ApiOperation(value = "构建一个job", httpMethod = "POST", produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
@RequestMapping(path="/buildJob")
public JSONObject buildJob(@ApiParam(name = "jobName", required = true, value = "job的名字") @RequestParam String jobName,
@ -93,4 +200,5 @@ public class JenkinsController {
response.put("msg", "run job success");
return response;
}
**/
}

View File

@ -1,5 +1,6 @@
package com.educoder.jenkins.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.educoder.jenkins.api.TrustieApi;
@ -7,6 +8,8 @@ import com.educoder.jenkins.utils.Base64Helper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import springfox.documentation.spring.web.json.Json;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -19,6 +22,7 @@ import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Set;
/**
@ -98,14 +102,14 @@ public class PipeLineController extends BaseController {
@ApiOperation(value = "处理结果并将结果回传到BDWeb", httpMethod = "POST", produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
@RequestMapping(path = "/commitToBDWeb ")
public JSONObject commitToBDWeb (@RequestParam String taskId,
public JSONObject commitToBDWeb (@RequestParam String buildID,
@RequestParam String result,
@RequestParam String jsonTypeDetails) {
logger.debug("/pipeline/commitToBDWeb taskId: " + taskId + " result: " + result + " jsonTypeDetails: " + jsonTypeDetails);
logger.debug("/pipeline/commitToBDWeb buildID: " + buildID + " result: " + result + " jsonTypeDetails: " + jsonTypeDetails);
JSONObject callResult = new JSONObject();
try {
trustieApi.commitResultToTrustie(taskId, result, jsonTypeDetails);
trustieApi.commitResultToTrustie(buildID, result, jsonTypeDetails);
} catch (Exception e) {
e.printStackTrace();
this.response.setStatus(299); //自定义code
@ -114,4 +118,31 @@ public class PipeLineController extends BaseController {
}
return callResult;
}
@ApiOperation(value = "处理结果并将结果回传到BDWeb", httpMethod = "POST", produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
@RequestMapping(path = "/postTrainingGameInstanceResultToBDWeb ")
public void postTrainingGameInstanceResultToBDWeb(String buildID, String compileResult, String out, String in, String expectedOut){
List<String> inputs=JSON.parseArray(in, String.class);
List<String> outputs=JSON.parseArray(out, String.class);
List<String> expectedOuts=JSON.parseArray(expectedOut, String.class);
TestInfo testInfo=new TestInfo();
testInfo.buildID=buildID;
}
}
class TestInfo{
String buildID;
String status;
String outPut;
List<EveryOutput> msg;
}
class EveryOutput{
String caseId;
String input;
String output;
String expectedOutput;
String passed;
}

View File

@ -43,7 +43,8 @@ public class JenkinsApiTest extends SpringTestBase {
params.put("taskId", "1");
params.put("testCode", "");
jenkinsApi.createJob( "test", pipeLine, params);
String reString=jenkinsApi.createJob( "test", pipeLine, params);
System.out.println(reString);
}
@Test

View File

@ -0,0 +1,132 @@
/**
* 文件名 : JenkinsApi.java
* 版权 : <版权/公司名>
* 描述 : <描述>
* @author liliy
* 版本 : <版本>
* 修改时间 2017年3月17日
* 修改内容 <修改内容>
*/
package cn.lili.test;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.PostConstruct;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.offbytwo.jenkins.JenkinsServer;
import com.offbytwo.jenkins.model.JobWithDetails;
/**
* <一句话功能简述>
* <功能详细描述>
* @author liliy
* @version [版本号2017年3月17日]
* @see [相关类/方法]
* @since [产品/模块版本]
*/
public class JenkinsApi {
public JenkinsServer jenkins = null;
/**
* 创建 job
* @param jobName 不能重复
* @param pipeLine pipeline配置文件
* @param params 参数配置用来传projectid,学生id之类的
*/
public void createJob(String jobName, String pipeLine, Map<String, String> params) throws IOException {
//首先得对pipeline转义
String xml = makeJobXml(pipeLine, params);
jenkins.createJob(jobName, xml);
}
public void updateJob(String jobName, String pipeLine, Map<String, String> params) throws IOException {
//首先得对pipeline转义
String xml = makeJobXml(pipeLine, params);
jenkins.updateJob(jobName, xml);
}
/**
* 生成jobXML
* @param pipeLine
* @param params
* @return
*/
private String makeJobXml(String pipeLine, Map<String, String> params) throws IOException {
//template
InputStream resourceAsStream = JenkinsApi.class.getResourceAsStream("job.template.xml");
String s = IOUtils.toString(resourceAsStream,Charset.forName("UTF-8"));
//处理pipeline
s = s.replace("PIPELINE_CONTENT", StringUtil.escapeXml(pipeLine));
//处理params
StringBuffer stringBuffer = new StringBuffer();
for (String key : params.keySet()) {
stringBuffer.append("<hudson.model.StringParameterDefinition>\n" +
" <name>"+key+"</name>\n" +
" <description>"+params.get(key)+"</description>\n" +
" <defaultValue></defaultValue>\n" +
" </hudson.model.StringParameterDefinition>");
}
s = s.replace("PARAMS_CONTENT", stringBuffer.toString());
return s;
}
/**
* 主动构建任务
* @param jobName
*/
public void buildJob(String jobName, String taskId, String step, String gitUrl) throws IOException {
JobWithDetails job = jenkins.getJob(jobName);
Map<String, String> params = new HashMap();
params.put("taskId", taskId);
params.put("step", step);
params.put("gitUrl", gitUrl);
job.build(params);
}
public void buildJob(String jobName, String taskId) throws IOException {
JobWithDetails job = jenkins.getJob(jobName);
Map<String, String> params = new HashMap();
params.put("taskId", taskId);
job.build(params);
}
public void buildJob(String jobName) throws IOException {
JobWithDetails job = jenkins.getJob(jobName);
job.build();
}
public void deleteJob(String jobName) throws IOException {
jenkins.deleteJob(jobName);
}
/**
* 获取job的xml配置文件
* @param jobName
* @return
*/
public String getJobXml(String jobName) throws IOException {
String jobXml = jenkins.getJobXml(jobName);
return jobXml;
}
}

View File

@ -0,0 +1,250 @@
/**
* 文件名 : TestOneJob.java 版权 : <版权/公司名> 描述 : <描述>
*
* @author liliy 版本 : <版本> 修改时间 2017年3月16日 修改内容 <修改内容>
*/
package cn.lili.test;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.junit.Test;
import com.offbytwo.jenkins.JenkinsServer;
import com.offbytwo.jenkins.model.Build;
import com.offbytwo.jenkins.model.BuildWithDetails;
import com.offbytwo.jenkins.model.Job;
import com.offbytwo.jenkins.model.JobWithDetails;
/**
* <一句话功能简述> <功能详细描述>
*
* @author liliy
* @version [版本号2017年3月16日]
* @see [相关类/方法]
* @since [产品/模块版本]
*/
public class MyTest {
public String url = "http://106.75.33.219:30001";
public String username = "root";
public String password = "root";
// public String url = "http://106.75.78.183:8888/";
// public String username = "root";
// public String password = "root";
// public String url = "http://106.75.78.183:9999/jenkins";
// public String username = "guange";
// public String password = "123456";
public String time=TimeHandle.printNowTime().replace('/', '-').replace(":", "-");
// public String fileName1=time+"-series.txt";
// public String fileName2=time+"-parallel.txt";
public String fileName2=time.split(" ")[0];
// public String filePath=System.getProperty("user.dir")+"\\"+fileName1;
public String filePath=System.getProperty("user.dir")+"\\"+fileName2;
public static void main(String[] args) {
try {
// JenkinsServer jenkins = new JenkinsServer(new URI("http://106.75.33.219:30001"), "root", "root");
// Map<String, Job> jobs = jenkins.getJobs();
// JobWithDetails job = jobs.get("test").details();
//// job.build();
// System.out.println(job.getName());
System.out.println(System.getProperty("user.dir"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// @Test
public void getAllJobs() throws Exception {
JenkinsServer jenkins = new JenkinsServer(new URI(url), username, password);
Map<String, Job> jobs = jenkins.getJobs();
for (Entry<String, Job> entry : jobs.entrySet()) {
System.out.println(entry.getKey());
}
}
// @Test
public void createJob() throws Exception {
int count = 20;
for (int i = 0; i < count; i++) {
String jobname = i + "";
System.out.println(jobname);
createOneJob(jobname);
}
}
// @Test
public void deleteJob() throws Exception {
int count = 20;
JenkinsServer jenkins = new JenkinsServer(new URI(url), username, password);
Map<String, Job> jobs = jenkins.getJobs();
for (int i = 0; i < count; i++) {
String jobname = i + "";
if (jobs.containsKey(jobname)) {
System.out.println(jobname);
deleteOneJob(jobname);
}
}
}
// @Test
public void buildJob() throws Exception {
JenkinsServer jenkins = new JenkinsServer(new URI(url), username, password);
PrintStream ps=new PrintStream(new FileOutputStream(filePath,true));
System.setOut(ps);
int count = 20;
for (int i = 0; i < count; i++) {
buildOneJob(i + "");
// buildOneJob("3");
Thread.sleep(30 * 1000);
getOneBuild(i + "", new JenkinsServer(new URI(url), username, password));
}
}
// @Test
public void buildJobParallel() throws Exception {
PrintStream ps=new PrintStream(new FileOutputStream(filePath,true));
System.setOut(ps);
int count = 10;
for (int i = 0; i < count; i++) {
buildOneJob(i + "");
// buildOneJob("3");
}
}
// @Test
public void buildJobNoparam() throws Exception {
int count = 1;
for (int i = 0; i < count; i++) {
buildOneJobNoparam("1");
}
}
// @Test
public void getBuilds() throws Exception {
JenkinsServer jenkins = new JenkinsServer(new URI(url), username, password);
PrintStream ps=new PrintStream(new FileOutputStream(filePath,true));
System.setOut(ps);
int count = 20;
for (int i = 0; i < count;i++) {
String name = i+"";
getOneBuild(name, jenkins);
}
}
public void getOneBuild(String jobName, JenkinsServer jenkins) throws Exception {
Map<String, Job> jobs = jenkins.getJobs();
JobWithDetails job = jobs.get(jobName).details();
try {
BuildWithDetails buildWithDetails = job.getLastBuild().details();
while (buildWithDetails.getResult() == null || buildWithDetails.getResult().name() == null) {
buildWithDetails = job.getLastBuild().details();
}
String buildId = buildWithDetails.getId();
long startTime = buildWithDetails.getTimestamp();
long duration = buildWithDetails.getDuration();
long estimatedDuration = buildWithDetails.getEstimatedDuration();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String startDate = simpleDateFormat.format(new Date(startTime));
// String durationDate = simpleDateFormat.format(new
// Date(startTime));
String endDate = simpleDateFormat.format(new Date(startTime + duration));
String salveName=StringUtil.getSalveName(buildWithDetails);
System.out.println(
"taskId: " + jobName + "#" + buildId + "," +startDate + "," + endDate+ "," + salveName);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
Thread.sleep(1 * 1000);
}
}
public void createOneJob(String jobName) {
try {
String pipeLine = "podTemplate(label: 'mypod', containers: ["
+ "containerTemplate(name: 'ubuntu', image: 'ubuntu', ttyEnabled: true)]) \n "
+ "{ \n node('mypod'){ \n container('ubuntu') { \n" + "stage 'first' \n"
+ "echo 'hello Word'\n }}}";
Map<String, String> params = new HashMap<String, String>();
params.put("taskId", jobName);
JenkinsApi jenkinsApi = new JenkinsApi();
jenkinsApi.jenkins = new JenkinsServer(new URI(url), username, password);
jenkinsApi.createJob(jobName, pipeLine, params);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public void buildOneJob(String jobName) {
try {
JenkinsServer jenkins = new JenkinsServer(new URI(url), username, password);
JobWithDetails job = jenkins.getJob(jobName);
System.out.print(jobName + "\t");
TimeHandle.printNowTime();
Map<String, String> params = new HashMap<String, String>();
params.put("taskId", jobName);
job.build(params);
TimeHandle.printNowTime();
System.out.println("");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public void buildOneJobNoparam(String jobName) {
try {
JenkinsServer jenkins = new JenkinsServer(new URI(url), username, password);
JobWithDetails job = jenkins.getJob(jobName);
System.out.print(jobName + "\t");
TimeHandle.printNowTime();
job.build();
TimeHandle.printNowTime();
System.out.println("");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public void deleteOneJob(String jobName) {
try {
JenkinsServer jenkins = new JenkinsServer(new URI(url), username, password);
jenkins.deleteJob(jobName);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,39 @@
package cn.lili.test;
import java.io.IOException;
import org.apache.commons.lang.StringEscapeUtils;
import com.offbytwo.jenkins.model.BuildWithDetails;
/**
* Created by guange on 18/02/2017.
*/
public class StringUtil {
public static String KUBERNETES="kubernetes-";
public static void main(String[] args) {
}
public static String escapeXml(String content){
String xml = StringEscapeUtils.escapeXml(content);
return xml;
}
public static String getSalveName(BuildWithDetails buildWithDetails){
String out;
try {
out = buildWithDetails.getConsoleOutputText();
for(String line:out.split("\n")){
for(String item:line.split(" ")){
if(item.startsWith(KUBERNETES)){
return item;
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "master";
}
}

View File

@ -0,0 +1,39 @@
/**
* 文件名 : TimeHandle.java
* 版权 : <版权/公司名>
* 描述 : <描述>
* @author liliy
* 版本 : <版本>
* 修改时间 2017年3月24日
* 修改内容 <修改内容>
*/
package cn.lili.test;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.junit.Test;
/**
* <一句话功能简述>
* <功能详细描述>
* @author liliy
* @version [版本号2017年3月24日]
* @see [相关类/方法]
* @since [产品/模块版本]
*/
public class TimeHandle {
public static void main(String[] args) {
printNowTime();
}
// @Test
public static String printNowTime(){
Date now = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");//可以方便地修改日期格式
String hehe = dateFormat.format( now );
System.out.print(hehe+"\t");
return hehe;
}
}

View File

@ -0,0 +1,21 @@
<?xml version='1.0' encoding='UTF-8'?>
<flow-definition plugin="workflow-job@2.10">
<actions/>
<description></description>
<keepDependencies>false</keepDependencies>
<properties>
<hudson.model.ParametersDefinitionProperty>
<parameterDefinitions>
PARAMS_CONTENT
</parameterDefinitions>
</hudson.model.ParametersDefinitionProperty>
<org.jenkinsci.plugins.workflow.job.properties.PipelineTriggersJobProperty>
<triggers/>
</org.jenkinsci.plugins.workflow.job.properties.PipelineTriggersJobProperty>
</properties>
<definition class="org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition" plugin="workflow-cps@2.26">
<script>PIPELINE_CONTENT</script>
<sandbox>true</sandbox>
</definition>
<triggers/>
</flow-definition>