Jenkins 远程调用Java实现方式有两种,一种是REST API,一种是使用 jenkins-client
参考链接:https://www.cnblogs.com/zjsupermanblog/archive/2017/07/26/7238422.html
jenkins-client 实现方式
jenkins-client 底层是使用 HttpClient HttpPost 发送post 请求实现的,是将 REST API 封装了一下
添加依赖
<!-- jenkins -->
<dependency>
<groupId>com.offbytwo.jenkins</groupId>
<artifactId>jenkins-client</artifactId>
<version>0.3.7</version>
</dependency>
连接服务器
public synchronized static JenkinsServer getInstance() {
if (jenkinsServer == null) {
try {
jenkinsServer = new JenkinsServer(new URI(EnvParam.getInstance().getJenkinsURL()), EnvParam.getInstance().getJenkinsUserId(),
EnvParam.getInstance().getJenkinsToken());
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
return jenkinsServer;
}
new JenkinsServer() 底层 使用了HttpClient 底层代码如下
BasicCredentialsProvider provider = new BasicCredentialsProvider();
AuthScope scope = new AuthScope(uri.getHost(), uri.getPort(), "realm");
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username,
password);
provider.setCredentials(scope, credentials);
builder.setDefaultCredentialsProvider(provider);
builder.addInterceptorFirst(new PreemptiveAuth());
if (StringUtils.isNotBlank(username)) {
this.localContext = new BasicHttpContext();
this.localContext.setAttribute("preemptive-auth", new BasicScheme());
}
获取所有的job信息
JenkinsServer jenkins = getInstance();
Map<String, Job> jobs = jenkins.getJobs();
jenkins.getJobs(); 返回的是以jobName为key的map对象
获取某次构建的日志信息
public static String getJobLog(int buildNumber, String jobName) throws IOException {
JenkinsServer jenkins = getInstance();
JobWithDetails job = jenkins.getJob(jobName);
JobWithDetails details = job.details();
Build buildByNumber = details.getBuildByNumber(buildNumber);
BuildWithDetails details2 = buildByNumber.details();
String outputText = details2.getConsoleOutputText();
return outputText;
}
获取某次构建的开始时间和持续时间
public static Map<String, Long> getStartTImeAndEndTime(String jobName, int number) throws IOException {
JenkinsServer jenkins = getInstance();
Map<String, Job> jobs = jenkins.getJobs();
JobWithDetails job = jobs.get(jobName).details();
Build buildByNumber = job.getBuildByNumber(number);
long startTime = buildByNumber.details().getTimestamp();
long duration = buildByNumber.details().getDuration();
Map<String, Long> data = new HashMap<>();
data.put("startTime", startTime);
data.put("duration", duration);
return data;
}
获取最后一次构建是否成功
number: 构建号 jobName: job 名称 通过获取最后的成功,失败的构建号,来判断是否相等
public static boolean isSuccess(String jobName, int number) throws IOException {
JenkinsServer jenkins = getInstance();
Map<String, Job> jobs = jenkins.getJobs();
JobWithDetails job = jobs.get(jobName).details();
int LastSuccessfulNumber = job.getLastSuccessfulBuild().getNumber();
int LastUnsuccessfulNumber = job.getLastUnsuccessfulBuild().getNumber();
boolean flag = false;
if (LastSuccessfulNumber == number) {
flag = true;
}
if (LastUnsuccessfulNumber == number) {
flag = false;
}
return flag;
}
通过获取构建的最终的结果来判断最终的结果
返回结果:SUCCESS, FAILURE
public static String isSuccess(String jobName, int number) throws IOException {
JenkinsServer jenkins = getInstance();
Map<String, Job> jobs = jenkins.getJobs();
JobWithDetails job = jobs.get(jobName).details();
Build buildByNumber = job.getBuildByNumber(number);
BuildWithDetails details = buildByNumber.details();
return details.getResult().toString();
}
判断job是否执行完
public static boolean isFinished(int number, String jobName) {
boolean isBuilding = false;
if (number <= 0) {
throw new IllegalArgumentException("jodId must greater than 0!");
}
try {
JenkinsServer jenkins = getInstance();
Map<String, Job> jobs = jenkins.getJobs();
JobWithDetails job = jobs.get(jobName).details();
Build buildByNumber = job.getBuildByNumber(number);
if (null != buildByNumber) {
BuildWithDetails details = buildByNumber.details();
if (null != details) {
isBuilding = details.isBuilding();
} else {
isBuilding = true;
}
} else {
isBuilding = true;
}
return !isBuilding;
} catch (Exception e) {
e.printStackTrace();
} finally {
}
return false;
}
通过上面的调用Jenkins-Client 相关的函数,可以获取相关的Jenkins的操作,如 日志,构建时间,job构建时长,构建号,是否成功,是否正在构建等等, 也发现一些问题 如
Jenkins中配置了view,并且view下面还有view,还有view,Jenkins-client 只能获取两层view,第三层的view获取不到
如果Jenkins中使用了build with parameters 插件 在使用 check box 选择多个参数的话,通过Jenkins-client 传参是 无法实现的
REST API 实现方式
Jenkins Web 每个页面 右下角都有一个REST API 点击一下 可以查看JSON API,通过JSONAPI 获取获取Jenkins的相关信息
构建
url: http://IP:PORT/job/${jobName}/buildWithParameters/ params:需要传递的参数
public static String buildJob(String url, Map<String, String> params)
throws ClientProtocolException, IOException {
URI uri = URI.create(url);
HttpHost host = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(uri.getHost(), uri.getPort()),
new UsernamePasswordCredentials("username", "password"));
// Create AuthCache instance
AuthCache authCache = new BasicAuthCache();
// Generate BASIC scheme object and add it to the local auth cache
BasicScheme basicAuth = new BasicScheme();
authCache.put(host, basicAuth);
CloseableHttpClient httpClient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider).build();
HttpPost httpPost = new HttpPost(uri);
//遍历map 将其中的数据转化为表单数据
if (null != params && !params.isEmpty()) {
ArrayList<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();//用于存放表单数据.
for (Map.Entry<String, String> entry : params.entrySet()) {
pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(pairs);
httpPost.setEntity(urlEncodedFormEntity);
}
// Add AuthCache to the execution context
HttpClientContext localContext = HttpClientContext.create();
localContext.setAuthCache(authCache);
HttpResponse response = httpClient.execute(host, httpPost, localContext);
String result = EntityUtils.toString(response.getEntity());
return result;
}
REST API 实现方式都是通过调用Jenkins提供的接口发送post请求,具体的接口信息,如下面的CURL命令所示
CURL 方式调用
无参构建任务
curl -X POST http://IP:PORT/jenkins/job/${jobName}/build --user admin:admin
不设置参数/使用默认参数
curl -X POST http://IP:PORT/jenkins/job/${jobName}/buildWithParameters --user admin:admin
设置参数
curl -X POST http://localhost:8080/jenkins/job/commandTest/buildWithParameters
-d port=80 --data-urlencode json=‘"{\"parameter\": [{\"name\": \"port\", \"value\": \"80\"}]}”‘
设置多个参数
curl -X POST http://localhost:8080/jenkins/job/commandTest/buildWithParameters -d param1=value1¶m2=value --user admin:admin
删除job
curl -X POST http://localhost:8080/jenkins/job/${jobName}/doDelete --user admin:admin
查询job的状态
curl --silent http://localhost:8080/jenkins/job/${jobName}/lastBuild/api/json
获取最后一次成功
curl --silent http://localhost:8080/jenkins/job/zdyy-yijijiakai-log-deploy/lastStableBuild/buildNumber --user admin:admin
获取最后一次构建失败构建号
curl --silent http://localhost:8080/jenkins/job/zdyy-yijijiakai-log-deploy/lastFailedBuild/buildNumber --user admin:admin
获取最后一次构建成功
curl --silent http://localhost:8080/jenkins/job/zdyy-yijijiakai-log-deploy/lastSuccessfulBuild/buildNumber --user admin:admin
获取job的相关信息 包括参数信息,每次构建信息等, 数据以JOSN返回
curl -X POST http://localhost:8080/jenkins/job/CSGL-deploy/api/json?pretty=true
获取某一次构建的具体信息
curl -X POST http://localhost:8080/jenkins/job/${jobName}/${buildNumber}/api/json?pretty=true
获取job中的某些字段信息
curl -X POST http://localhost:8080/jenkins/job/${jobName}/api/json?pretty=true&tree=${获取的字段名称}
禁用job
curl -X POST http://localhost:8080/jenkins/job/${jobName}/disable
启用job
curl -X POST http://localhost:8080/job/${jobName}/enable
获取job config 文件
curl -X POST http://localhost:8080/job/${jobName}/config.xml