Jenkins How to find if a given slave is running a Job
Here is the hackish way I was able to do it. I changed my workflow to find the available free slave rather than finding if a slave was busy and then checking the next one to see it is free. This groovy script counts the number of busy executors on the Slave. It polls continuously till it finds an online slave with zero number of busy executors. I hate polling and will request knowledgeable members to chip in with suggestions to somehow plug into Jenkins event based notification.
import hudson.FilePath
import hudson.model.Node
import hudson.model.Slave
import jenkins.model.Jenkins
import groovy.time.*
Jenkins jenkins = Jenkins.instance
def jenkinsNodes =jenkins.nodes
while(1)
{
for (Node node in jenkinsNodes)
{
sleep(1000)
// Make sure slave is online
if (!node.getComputer().isOffline())
{
//Make sure that the slave busy executor number is 0.
if(node.getComputer().countBusy()==0)
{
println "'$node.nodeName' can take jobs !!!"
return 0
}
else
{
println "$node.nodeName' is busy !!!"
}
}
else
{
println "'$node.nodeName' is offline !!!"
}
}
sleep(1000)
}
This runs as job and returns as soon as it finds a suitable slave. Return 0 is a success in Jenkins.
If there is any better way of doing it please chip in. I am not really happy with this continuous polling I have to to. Also I am not an expert on executors. So any flaws if there, please correct me.