Skip to content

Instantly share code, notes, and snippets.

@darinpope
Last active April 28, 2024 07:38
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save darinpope/ae8fd8432b173fbe507336e2746e206d to your computer and use it in GitHub Desktop.
Save darinpope/ae8fd8432b173fbe507336e2746e206d to your computer and use it in GitHub Desktop.

Gist for https://www.youtube.com/watch?v=MTLgbp0GH8w

Documentation

Steps from the video

mkdir -p $HOME/cronjobs/reconnect-agents
cd $HOME/cronjobs/reconnect-agents
wget http://jenkins:8080/jnlpJars/jenkins-cli.jar

crontab

* * * * * /home/vagrant/cronjobs/reconnect-agents/reconnect.sh > /dev/null 2>&1

reconnect.sh

#!/bin/bash
/usr/bin/java -jar /home/vagrant/cronjobs/reconnect-agents/jenkins-cli.jar -s http://jenkins:8080/ -webSocket -auth @/home/vagrant/.jenkins-cli groovy = < /home/vagrant/cronjobs/reconnect-agents/reconnect.groovy

reconnect.groovy

import jenkins.*
import jenkins.model.*
import hudson.*
import hudson.model.*
import hudson.node_monitors.*
import hudson.slaves.*
import java.util.concurrent.*

jenkins = Jenkins.instance

def getEnviron(computer) {
   def env
   def thread = Thread.start("Getting env from ${computer.name}", { env = computer.environment })
   thread.join(2000)
   if (thread.isAlive()) thread.interrupt()
   env
}

def agentAccessible(computer) {
    getEnviron(computer)?.get('PATH') != null
}

def numberOfflineNodes = 0
def numberNodes = 0
for (agent in jenkins.getNodes()) {
   def computer = agent.computer
   numberNodes ++
   println ""
   println "Checking computer ${computer.name}:"
   def isOK = (agentAccessible(computer) && !computer.offline)
   if (isOK) {
     println "\t\tOK, got PATH back from agent ${computer.name}."
     println('\tcomputer.isOffline: ' + computer.isOffline());
     println('\tcomputer.isTemporarilyOffline: ' + computer.isTemporarilyOffline());
     println('\tcomputer.getOfflineCause: ' + computer.getOfflineCause());
     println('\tcomputer.offline: ' + computer.offline);
   } else {
     numberOfflineNodes ++
     println "  ERROR: can't get PATH from agent ${computer.name}."
     println('\tcomputer.isOffline: ' + computer.isOffline());
     println('\tcomputer.isTemporarilyOffline: ' + computer.isTemporarilyOffline());
     println('\tcomputer.getOfflineCause: ' + computer.getOfflineCause());
     println('\tcomputer.offline: ' + computer.offline);
     if (computer.isTemporarilyOffline()) {
       if (!computer.getOfflineCause().toString().contains("Disconnected by")) {
         computer.setTemporarilyOffline(false, agent.getComputer().getOfflineCause())
       }
     } else {
         computer.connect(true)
     }
   }
 }
println ("Number of Offline Nodes: " + numberOfflineNodes)
println ("Number of Nodes: " + numberNodes)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment