I have been trying to find a lightweight method in a Groovy scriptler script to list all currently running jobs of any type. The only method I have found to be reliable is this:
start = System.currentTimeMillis()
def jobsFound = []
def buildingJobs = Jenkins.instance.getAllItems(Job.class).findAll {
it.isBuilding()
}
buildingJobs.each { job->
allRuns = job._getRuns()
allRuns.each { item->
if (!item.isBuilding()) { return } // This job is not building
jobsFound.push(item.getUrl())
}
}
timespent = (System.currentTimeMillis() - start ) / 1000
println "Time: ${timespent} seconds"
println "{jobsFound.size} jobs"
// RESULTS:
// Time: 2.015 seconds. 15 jobs
The problem is that the above enumerates ALL currently running jobs - we have thousands! - then enumerate all builds of each of those running jobs (some jobs have as many as 300 builds). The above can take as long as FIVE minutes to complete depending on how many jobs are currently building.
A much more efficient method is to enumerate the active executors but this method MISSES the pipeline (aka Workflow) jobs running on the master:
start = System.currentTimeMillis()
def busyExecutors = Jenkins.instance.computers.collect {
c -> c.executors.findAll { it.isBusy() }
}.flatten()
def jobsFound = []
busyExecutors.each { e ->
job = e.getCurrentExecutable()
jobsFound.push(job.getUrl())
}
timespent = (System.currentTimeMillis() - start ) / 1000
println "Time: ${timespent} seconds. ${jobsFound.size} jobs"
// RESULTS:
// Time: 0.005 seconds. 12 jobs
Sure enough the discrepancy between the two counts are pipeline jobs running on the master.
I guess my question boils down to:
Is there a way to efficiently enumerate all jobs running on the master?
Clearly Jenkins does not include the master in computers
, and although there is a MasterComputer
class, its not clear how to get it or the OffByOneExecutors
on which flyweight (pipeline) jobs run.