Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import hudson.model.*;
- import hudson.util.*;
- import jenkins.model.*;
- import hudson.FilePath.FileCallable;
- import hudson.slaves.OfflineCause;
- import hudson.node_monitors.*;
- def DEBUG_MODE = (build.getEnvironment(listener).get('DEBUG_MODE') == "true")
- def nodesToCheck = []
- println "Scanning for slave nodes..."
- for(node in Jenkins.instance.nodes){
- println "Check node ***${node.name}***"
- node.computer.connect(true)
- println " label:" + node.getAssignedLabels()
- for(label in node.getAssignedLabels()){
- if(label.toString().equals("_autoClean")){
- nodesToCheck << node
- println " BINGO!! This slave is marked as _autoClean! It will be checked to see if its workspaces need to be removed"
- }
- }
- }
- for (node in nodesToCheck) {
- println("=== Begin to handle node ${node.name} ===")
- computer = node.toComputer()
- if (computer.getChannel() == null) continue
- rootPath = node.getRootPath()
- size = DiskSpaceMonitor.DESCRIPTOR.get(computer).size
- roundedSize = size / (1024 * 1024 * 1024) as int
- println("node: " + node.getDisplayName() + ", free space: " + roundedSize + "GB")
- if (roundedSize < 10) {
- computer.setTemporarilyOffline(true, new hudson.slaves.OfflineCause.ByCLI("Temporarily offline for disk cleanup."))
- for (job in Jenkins.instance.items) {
- if (!(job instanceof hudson.model.FreeStyleProject)) {
- continue;
- }
- jobName = job.getFullDisplayName()
- try{
- if (job.isBuilding()) {
- if(DEBUG_MODE) println(".. job " + jobName + " is currently running, skipped")
- continue
- }
- } catch(ex) {
- println()
- println(".. WARNING: fail to get 'isBuilding' status of job ${jobName}, skipped")
- println(".... class: ${job.getClass()}")
- println(".... exception: ${ex}")
- println()
- continue
- }
- workspacePath = node.getWorkspaceFor(job)
- if (workspacePath == null) {
- continue
- }
- try {
- customWorkspace = job.getCustomWorkspace()
- if (customWorkspace != null) {
- workspacePath = node.getRootPath().child(customWorkspace)
- }
- } catch(ex) {
- println()
- println(".. WARNING: fail to get custom workspace of job ${jobName}")
- println(".... exception: ${ex}")
- println()
- }
- pathAsString = workspacePath.getRemote()
- if (workspacePath.exists()) {
- println(".. wiping out workspaces of job " + jobName)
- println(".... workspace = " + workspacePath)
- if (DEBUG_MODE) {
- println(".... under debug mode, ${pathAsString} won't actually be deleted!!!")
- } else {
- println(".... delete from location ${pathAsString}!!!")
- workspacePath.deleteRecursive()
- println(".... deleted from location ${pathAsString}!!!")
- }
- }
- }
- computer.setTemporarilyOffline(false, null)
- }
- }
Add Comment
Please, Sign In to add comment