项目中有一块功能是发布,而发布的时候希望完成两个操作:
1. 在gitlab相应的项目中自动打上tag
2. 触发Jenkins的Job自动build发布
如果用ssh完成,分分钟的事情,python也很多示例,Java相对少。对于Jenkins这一块的文档,写的感觉有点次,很多找不到,或许是我太次找的方式不对。
whatever,事情还是完成。
1. 对于操作gitlab这一部分,我们都知道需要remote server--pull-->local--push-->remote server. 有一段时间想不pull直接操作remote server,发现行不通,对于一些查看tag的操作是可以直接操作remote server,
但是需要添加tag不得不先pull.
首先在pom.xml添加依赖:
<!--JGIT-->
<dependency>
<groupId>org.eclipse.jgit</groupId>
<artifactId>org.eclipse.jgit</artifactId>
<version>5.0.0.201805301535-rc2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>20030203.000550</version>
<scope>compile</scope>
</dependency>
相关添加tag的代码:
public String addTag(GitOperationInfo gio) {
Git git = null;
File localPath = null;
File gitDir = null;
String result = null;
try {
localPath = File.createTempFile("YPPGitRepository", "");
gitDir = new File(localPath, ".git");
if (!localPath.delete()) {
throw new IOException("Could not delete temporary file " + localPath);
}
// then clone
logger.info("Cloning from " + gio.getServerURL() + " to " + localPath);
git = Git.cloneRepository()
.setURI(gio.getServerURL()) //git server 链接
.setDirectory(localPath)
.setCredentialsProvider(gio.getCp()) //gitlab帐号密码信息
.setBranch(gio.getBranchName()) //指定分支
.call();
// Note: the call() returns an opened repository already which needs to be closed to avoid file handle leaks!
logger.info("Having repository: " + git.getRepository().getDirectory());
//执行添加的tag的操作
git.tag().setMessage(gio.getTagDesc()).setName(gio.getTagName()).setForceUpdate(true).call();
//提交到服务器
Iterable<PushResult> prs = git.push().setPushTags().setCredentialsProvider(gio.getCp()).call();
for (PushResult pr : prs) {
result = pr.getMessages();
System.out.println(pr.getMessages());
}
} catch (Exception ex) {
System.err.println(ex.getMessage());
logger.error("auto git tag to server failed:" + ex.getMessage());
logger.error(gio.toString());
} finally {
if (null != git) {
git.close();
}
// clean up here to not keep using more and more disk-space for these samples
if (null != localPath){
try {
FileUtils.deleteDirectory(localPath);
} catch (IOException ioe) {
logger.error("deleting directory: " + ioe.getMessage());
}
}
return result;
}
}
可能会出现连接服务失败,最可能的你的gitlab帐号信息不对,像我就是本地配置了好几个帐号导致的,可参与另一篇“git多用户配置多server配置”
2. 操作Jenkins,让Jenkins的任务自动build.
一般我们都会从这个页面开始看帮助: https://{Jenkins'Server}/{JobPath}/api/,
但这里面的Perform a build,If the build has parameters, post to this URL and provide the parameters as form data.却把我坑了一天多时间,
对,就是参数构建的时候,按那个URL的提示说要POST,但事实上,Jenkins很多都会装一些插件,估计是这些插件导致了POST不能用吧,要用GET,GET,GET!
当时用curl的方式POST也没有问题,但就是在JAVA里POST的时候Jenkins build的获取到的参数不对,或者说,根本没有获取到参数,当时搞得我都有点绝望,
明明代码都没有问题,手动cur请求也可以正常工作。
后来发现除了刚才说的要用GET方法,另一个必须要做的就是在任务的配置里有个“构建触发器”,这里需要选中"触发远程构建",身份验证令牌中随便填入
一字符串,然后以 /buildWithParameters?token=TOKEN_NAME方式GET请求就可以了。
大致如下:
1): 带参数触发任务自动Build
String jenkins_url = base_url + url + "/buildWithParameters";
String param = "token=" + JENKINS_TOKEN + "&BRANCH=" + info.getCodeBranch();
result = HttpRequestHelper.sendGet(jenkins_url, param, BASIC_AUTHORIZATION, true);
2): 获取最后一次构信息:
jenkinsUrl = base_url + serviceName + "/lastBuild/api/json?&pretty=true&tree=number,result,fullDisplayName";
3): 获取历史多个构建的信息,成功和失败的:
subPrdJobUrl= base_url + jobUrlArr[i] + "/api/json?tree=builds[number,timestamp,result]";
4): 获取Jenkins上所有任务的信息:
jenkins_url + /api/json?tree=jobs[name,color]
5): 构建进度:
jenkins_url + /job/${job_name}/lastBuild/api/json?tree=result,timestamp,estimatedDuration
6): 获取最后失败版本:
jenkins_url + /lastFailedBuild/buildNumber