How to collect build history by using Jenkins Shared Libraries

378 Views Asked by At

We would like to analyze the build history in a Jenkins job. We don't want to approve any dangerous signatures, so the logic should be implemented as a step in a Jenkins Shared Library. We use folders and multibranch jobs, so the mechanism has to analyze items recursively.

How to implement it?

1

There are 1 best solutions below

0
On BEST ANSWER

To collect all builds the following code could be used.

import hudson.model.Job
import hudson.model.Run
import jenkins.model.Jenkins

List<Map<String, Object>> call() {
    def builds = []
    for (def job in findAllJobs()) {
        for (def build in job.builds) {
            builds << [
                name: build.parent.name,
                fullName: build.parent.fullName,
                result: build.result?.toString(),
                number: build.number as String,
                date: build.time,
                timestamp: build.timeInMillis,
                url: "${build.parent.absoluteUrl}${build.number}/"
            ]
        }
    }
    return builds
}

List<Job> findAllJobs() {
    def jobs = []
    jobs.addAll(jenkins.getItems(Job))
    def folderClass = loadClass('com.cloudbees.hudson.plugins.folder.AbstractFolder')
    for (def folder in jenkins.getItems(folderClass)) {
        jobs.addAll(findNestedJobs(folder, folderClass))
    }
    return jobs
}

List<Job> findNestedJobs(def folder, Class<?> folderClass) {
    def jobs = []
    for (def item in folder.items) {
        if (folderClass.isAssignableFrom(item.class)) {
            jobs.addAll(findNestedJobs(item, folderClass))
        } else if (item instanceof Job) {
            jobs << item
        }
    }
    return jobs
}

Class<?> loadClass(String className) {
    return Class.forName(className, true, jenkins.pluginManager.uberClassLoader)
}

Jenkins getJenkins() {
    return Jenkins.get()
}

It returns for every build:

  • full name (e.g. <folder>/<job>/<branch name|PR number>)
  • name (e.g. branch name|PR number)
  • result (SUCCESS, FAILURE etc.)
  • number
  • date - the execution date (java.util.Date)
  • timestamp - the execution date (long)
  • url - absolute URL to the build page

If for example only builds executed within 24 hours must be executed, two approach could be used:

  1. execute step and next filter results
  2. modify the Jenkins Shared Library step, to stop collecting jobs when the date is older

The second option is better because it doesn't force the logic to iterate through old builds.