How to get Build statistics of Jenkins job

In this article, let us take a problem statement and see how we can solve it using Jenkins Remote Access API.

Problem Statement:

Assume that there are many jobs running in Jenkins and one particular job is running at every hour. We want to check how many times a particular job has been executed and success/failue count in last 24 hours along with time.

Solution:

We can achieve this using Jenkins Remote Access API. In general, url of Jenkins job would be like <jenkins-url>/job/<job_name>. One can see more available options by appending /api to above url.

Jenkins exposes many details through remote access API and one can see a job metadata in JSON/XML format by appending json or xml to above url.

Example:

  1. <jenkins-url>/job/<Job_name>/api/json
  2. <jenkins-url>/job/<Job_name>/api/xml

The ‘tree‘ query parameter allows users to explicitly specify and retrieve only the information they are looking for.

In your case, <jenkins-url>/job/<Job_name>/api/json?tree=allBuilds[result,number,url,timestamp] api will give you the details in json format from which you can calculate all the data you wanted like number of builds triggered, passed and/or failed in last 24 hours.

Sample response for above url would be like below.

{
  "_class": "hudson.model.FreeStyleProject",
  "allBuilds": [
    {
      "_class": "hudson.model.FreeStyleBuild",
      "number": 7,
      "result": "SUCCESS",
      "timestamp": 1545661232289,
      "url": "http://localhost:8080/job/RegressionTest/7/"
    },
    {
      "_class": "hudson.model.FreeStyleBuild",
      "number": 6,
      "result": "SUCCESS",
      "timestamp": 1545658820048,
      "url": "http://localhost:8080/job/RegressionTest/6/"
    },
    {
      "_class": "hudson.model.FreeStyleBuild",
      "number": 5,
      "result": "SUCCESS",
      "timestamp": 1545658814132,
      "url": "http://localhost:8080/job/RegressionTest/5/"
    },
    {
      "_class": "hudson.model.FreeStyleBuild",
      "number": 4,
      "result": "FAILURE",
      "timestamp": 1545658799754,
      "url": "http://localhost:8080/job/RegressionTest/4/"
    },
    {
      "_class": "hudson.model.FreeStyleBuild",
      "number": 3,
      "result": "FAILURE",
      "timestamp": 1545658784937,
      "url": "http://localhost:8080/job/RegressionTest/3/"
    }
  ]
}

You can use Java json libraries to parse and manipulate data in the way you wanted.

Use api <jenkins-url>/job/<Job_name>/api/xml?tree=allBuilds[result,number,url,timestamp] to get same data in xml format.

Please note that everything specified here is at job level. For more details about Remote Access API features, read our article ‘Working with Jenkins Remote Access API

Leave a Reply

avatar
  Subscribe  
Notify of