Skip to content

Instantly share code, notes, and snippets.

@frederic-meyrou
Forked from rb2k/gist:8372402
Last active September 8, 2016 13:09
Show Gist options
  • Save frederic-meyrou/36cf507866438adb8c44 to your computer and use it in GitHub Desktop.
Save frederic-meyrou/36cf507866438adb8c44 to your computer and use it in GitHub Desktop.
A jenkins script to clean up workspaces on slaves
// Check if a slave has < 10 GB of free space, wipe out workspaces if it does --skipping folders, preserving offline status
import hudson.model.*;
import hudson.util.*;
import jenkins.model.*;
import hudson.FilePath.FileCallable;
import hudson.slaves.OfflineCause;
import hudson.node_monitors.*;
def sizeLimit = 10 // GB
for (node in Jenkins.instance.nodes) {
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 < sizeLimit) {
prevOffline = computer.isOffline()
if (!prevOffline) {
computer.setTemporarilyOffline(true, new hudson.slaves.OfflineCause.ByCLI("disk cleanup"))
}
function(node, Hudson.instance.items)
if (!prevOffline) {
computer.setTemporarilyOffline(false, null)
}
}
}
def function(curentnode, items) {
for (item in items) {
if (item.class.canonicalName != 'com.cloudbees.hudson.plugins.folder.Folder') {
println("----------------------------------------------------------------------------------------------------------")
println("JOB: " + item.name)
jobName = item.getFullDisplayName()
if (item.isBuilding()) {
println(".. job " + jobName + " is currently running, skipped")
continue
}
println(".. Reporting on workspaces of job " + jobName)
workspacePath = curentnode.getWorkspaceFor(item)
if (workspacePath == null) {
println(".... could not get workspace path")
continue
}
println(".... workspace = " + workspacePath)
customWorkspace = item.getCustomWorkspace()
if (customWorkspace != null) {
workspacePath = curentnode.getRootPath().child(customWorkspace)
println(".... custom workspace = " + workspacePath)
}
pathAsString = workspacePath.getRemote()
if (workspacePath.exists()) {
workspacePath.deleteRecursive()
//item.doDoWipeOutWorkspace()
println(".... deleted from location : " + pathAsString )
} else {
println(".... nothing to delete at " + pathAsString)
}
if (!item.isBuildable()) {
println("This Job can't be built ...")
}
}
else {
println("===========================================================================================================")
println("FOLDER : " + item.name)
function(curentnode, ((com.cloudbees.hudson.plugins.folder.Folder) item).getItems())
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment