I have this unique requirement to check if the given node is running a job or not. I am thinking of using groovy as it looks easiest option.
I have found this answer
To get the name of the node, that is running the current build, just use System.getenv("NODE_NAME")
When a Jenkins job executes, it sets some environment variables..
You may find these variables very useful. Check this link
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.
Let me propose a very simple and efficient way
Each node stores the information related to if it example : idle or not , offline or not etc
You can get those details using below command
curl -X GET --silent -u jenkins_user:${jenkins_pwd} "http://your_jenkins_url:8080/computer/node_name/api/json"
or directly from browser
http://your_jenkins_url:8080/computer/node_name/api/jso
This result provides valuable information related to slave.
If you want narrow down the search to a specific thing like , is the slave idle or not then you can append it with below logic
curl -X GET --silent -u jenkins_user:${jenkins_pwd} "http://jenkins_domanin:8080/computer/node_name/api/json" | python -c 'import json,sys,os;obj=json.load(sys.stdin);print obj["idle"]'