Skip to content

Instantly share code, notes, and snippets.

@yogeshlonkar
Forked from rb2k/gist:8372402
Last active June 8, 2017 15:54
Show Gist options
  • Save yogeshlonkar/15ec2441e27c0fac3dbf10fbe4cf36bc to your computer and use it in GitHub Desktop.
Save yogeshlonkar/15ec2441e27c0fac3dbf10fbe4cf36bc 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
import hudson.model.*;
import hudson.util.*;
import jenkins.model.*;
import jenkins.branch.*;
import hudson.FilePath.FileCallable;
import hudson.slaves.OfflineCause;
import hudson.node_monitors.*;
def freeSpaceLimit = 10 // in 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 < freeSpaceLimit) {
computer.setTemporarilyOffline(true, new hudson.slaves.OfflineCause.ByCLI("disk cleanup"))
for (item in Jenkins.instance.items) {
if (item.metaClass.respondsTo(item, "isBuilding") && item.isBuilding()) {
println(".. job " + item.getFullDisplayName() + " is currently running, skipped")
continue
}
if(item instanceof MultiBranchProject || item instanceof OrganizationFolder) { //clean organization folder
println("Total Subjobs for " + item.getFullDisplayName() + ": " +item.getAllJobs().size())
for (subJob in item.getAllJobs()) {
println(". "+subJob.getFullDisplayName())
deleteWorkspaceOf(subJob, node)
}
} else {
deleteWorkspaceOf(item, node)
}
}
computer.setTemporarilyOffline(false, null)
}
}
def deleteWorkspaceOf(def item, def node) {
def jobName = item.getFullDisplayName()
println(".. wiping out workspaces of job " + jobName)
def workspacePath = node.getWorkspaceFor(item)
if (workspacePath == null) {
println(".... could not get workspace path")
return
}
println(".... workspace = " + workspacePath)
def customWorkspace = item.metaClass.respondsTo(item, "getCustomWorkspace") ? item.getCustomWorkspace() : null
if (customWorkspace != null) {
workspacePath = node.getRootPath().child(customWorkspace)
println(".... custom workspace = " + workspacePath)
}
def pathAsString = workspacePath.getRemote()
if (workspacePath.exists()) {
workspacePath.deleteRecursive()
println(".... deleted from location " + pathAsString)
} else {
println(".... nothing to delete at " + pathAsString)
}
}
@yogeshlonkar
Copy link
Author

Ability to delete work space for MultiBranchProject & OrganizationFolder

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment