Jenkins Jenkinx

Stella981
• 阅读 855

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&param2=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
点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
待兔 待兔
4个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Easter79 Easter79
3年前
Twitter的分布式自增ID算法snowflake (Java版)
概述分布式系统中,有一些需要使用全局唯一ID的场景,这种时候为了防止ID冲突可以使用36位的UUID,但是UUID有一些缺点,首先他相对比较长,另外UUID一般是无序的。有些时候我们希望能使用一种简单一些的ID,并且希望ID能够按照时间有序生成。而twitter的snowflake解决了这种需求,最初Twitter把存储系统从MySQL迁移
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
3年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
10个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这