Jenkins Jenkinx-client Curl operation jenkins

Keywords: jenkins curl JSON REST

There are two ways for Jenkins to call Java remotely, one is REST API, the other is to use jenkins-client.
Reference link: https://www.cnblogs.com/zjsupermanblog/archive/2017/07/26/7238422.html

Implementation of jenkins-client

The bottom layer of jenkins-client is implemented by sending post requests using HttpClient HttpPost, which encapsulates the REST API.

Add dependency
<!-- jenkins -->
<dependency>
	<groupId>com.offbytwo.jenkins</groupId>
	<artifactId>jenkins-client</artifactId>
	<version>0.3.7</version>
</dependency>
Connecting servers
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;
}

The new Jenkins Server () underlying uses the HttpClient underlying code as follows

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());
}
Get all job information
JenkinsServer jenkins = getInstance();
Map<String, Job> jobs = jenkins.getJobs();

jenkins.getJobs(); returns a map object with jobName as the key

Get log information for a build
 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;
}
Get the start time and duration of a build
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;
}
Get the success of the last build

Number: build number jobName: job name Determine equality by achieving the final success or failure build number

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;
    }

Judge the final result by capturing the final result of the build
Return result: 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();
    }
Judging whether the job has been executed
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;
    }

By calling Jenkins-Client related functions above, you can get the relevant Jenkins operations, such as log, build time, job build time, build number, success, whether it is being built, and so on. Some problems are also found, such as
View is configured in Jenkins, and there is view under view, and view. Jenkins-client can only get two-tier view, but the third-tier view can not.

If Jenkins uses the build with parameters plug-in to select multiple parameters using check box, passing parameters through Jenkins-client is not possible.

REST API Implementation

Jenkins Web has a REST API in the lower right corner of each page to click on to view the JSON API and obtain Jenkins information through the JSONAPI.

structure

url: http://IP:PORT/job/${jobName}/buildWithParameters/ params: Parameters to be passed

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);

        //Traversing the map converts the data into form data
        if (null != params && !params.isEmpty()) {
            ArrayList<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();//Used to store form data.
            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 is implemented by calling the interface provided by Jenkins to send post requests, specific interface information, as shown in the following CURL command

CURL mode call

No Reference Construction Task

curl -X POST http://IP:PORT/jenkins/job/${jobName}/build --user admin:admin

No parameters set / default parameters used

curl -X POST http://IP:PORT/jenkins/job/${jobName}/buildWithParameters  --user admin:admin

Setting parameters

curl -X POST http://localhost:8080/jenkins/job/commandTest/buildWithParameters  
-d port=80 --data-urlencode json='"{\"parameter\": [{\"name\": \"port\", \"value\": \"80\"}]}"'

Setting multiple parameters

curl -X POST http://localhost:8080/jenkins/job/commandTest/buildWithParameters -d param1=value1&param2=value --user admin:admin

Delete job

curl -X POST http://localhost:8080/jenkins/job/${jobName}/doDelete --user admin:admin

Query the status of job

curl --silent http://localhost:8080/jenkins/job/${jobName}/lastBuild/api/json

Achieve the Last Success
curl --silent http://localhost:8080/jenkins/job/zdyy-yijijiakai-log-deploy/lastStableBuild/buildNumber --user admin:admin

Get the last build failure build number
curl --silent http://localhost:8080/jenkins/job/zdyy-yijijiakai-log-deploy/lastFailedBuild/buildNumber --user admin:admin  

Achieve the last build success
curl --silent http://localhost:8080/jenkins/job/zdyy-yijijiakai-log-deploy/lastSuccessfulBuild/buildNumber --user admin:admin  

Get information about job Including parameter information, each build information, etc., data returned in JOSN

curl -X POST  http://172.23.31.59:8080/jenkins/job/CSGL-deploy/api/json?pretty=true

Get specific information about a build

curl -X POST http://172.23.31.59:8080/jenkins/job/${jobName}/${buildNumber}/api/json?pretty=true

Get some field information in job

curl -X POST http://172.23.31.59:8080/jenkins/job/${jobName}/api/json?Pretty=true&tree=${the name of the field obtained}

Disable job

curl -X POST  http://172.23.31.59:8080/jenkins/job/${jobName}/disable

Enable job

curl -X POST  http://172.23.31.59:8080/job/${jobName}/enable 

Get the job config file

curl -X POST  http://172.23.31.59:8080/job/${jobName}/config.xml

Posted by Jpauls104 on Fri, 17 May 2019 14:27:57 -0700