Jenkins Jenkinx-client Curl 操做jenkins

Jenkins 遠程調用Java實現方式有兩種,一種是REST API,一種是使用 jenkins-client
參考連接:https://www.cnblogs.com/zjsupermanblog/archive/2017/07/26/7238422.htmlhtml

jenkins-client 實現方式

jenkins-client 底層是使用 HttpClient HttpPost 發送post 請求實現的,是將 REST API 封裝了一下json

添加依賴
<!-- 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 底層代碼以下api

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 名稱 經過獲取最後的成功,失敗的構建號,來判斷是否相等curl

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, FAILUREide

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 傳參是 沒法實現的post

REST API 實現方式

Jenkins Web 每一個頁面 右下角都有一個REST API 點擊一下 能夠查看JSON API,經過JSONAPI 獲取獲取Jenkins的相關信息ui

構建

url: http://IP:PORT/job/${jobName}/buildWithParameters/ params:須要傳遞的參數this

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
相關文章
相關標籤/搜索