-
-
Save EvilBeaver/35ebded526fb53ecb9716889c1de11df to your computer and use it in GitHub Desktop.
A jenkins script to clean up workspaces on slaves
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 hudson.FilePath.FileCallable; | |
import hudson.slaves.OfflineCause; | |
import hudson.node_monitors.*; | |
def performCleanup(def node, def items) { | |
for (item in items) { | |
jobName = item.getFullDisplayName() | |
println("Cleaning " + jobName) | |
if(item instanceof com.cloudbees.hudson.plugins.folder.AbstractFolder) { | |
performCleanup(node, item.items) | |
continue | |
} | |
if (item.isBuilding()) { | |
println(".. job " + jobName + " is currently running, skipped") | |
continue | |
} | |
println(".. wiping out workspaces of job " + jobName) | |
workspacePath = node.getWorkspaceFor(item) | |
if (workspacePath == null) { | |
println(".... could not get workspace path") | |
continue | |
} | |
println(".... workspace = " + workspacePath) | |
pathAsString = workspacePath.getRemote() | |
if (workspacePath.exists()) { | |
workspacePath.deleteRecursive() | |
println(".... deleted from location " + pathAsString) | |
} else { | |
println(".... nothing to delete at " + pathAsString) | |
} | |
} | |
} | |
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") | |
computer.setTemporarilyOffline(true, new hudson.slaves.OfflineCause.ByCLI("disk cleanup")) | |
performCleanup(node, Jenkins.instance.items) | |
computer.setTemporarilyOffline(false, null) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The built-in cleanup is time based, but the cleanup should happen when disk space is used up. Jenkins has no means to schedule jobs based on agents with enough disk space, which causes multiple large workspaces to be allocated on the same agent, leading to build failures. There are also situations, when large jobs are run in a quick succession, making time based retainment useless.
Also, keeping old workspaces is usefull, if agent disk space in underused (for debugging).