Skip to content

Instantly share code, notes, and snippets.

@CedricGatay
Created May 22, 2017 12:39
Show Gist options
  • Save CedricGatay/ab964d03ef9b265ee27236bd6b91b14c to your computer and use it in GitHub Desktop.
Save CedricGatay/ab964d03ef9b265ee27236bd6b91b14c to your computer and use it in GitHub Desktop.
Workspaces cleanup Jenkinsfile
import hudson.model.*;
import hudson.util.*;
import jenkins.model.*;
import hudson.FilePath.FileCallable;
import hudson.slaves.OfflineCause;
import hudson.node_monitors.*;
node('master'){
stage('Cleanup nodes'){
clean()
}
}
@NonCPS
def cleanup(node){
computer = node.toComputer()
if (computer.getChannel() == null) return
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) {
def wasOffline = computer.isOffline()
computer.setTemporarilyOffline(true, new hudson.slaves.OfflineCause.ByCLI("disk cleanup"))
for (item in Jenkins.instance.getAllItems(Job.class)) {
jobName = item.getFullDisplayName()
try{
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)
customWorkspace = item.getCustomWorkspace()
if (customWorkspace != null) {
workspacePath = node.getRootPath().child(customWorkspace)
println(".... custom workspace = " + workspacePath)
}
pathAsString = workspacePath.getRemote()
if (workspacePath.exists()) {
workspacePath.deleteRecursive()
println(".... deleted from location " + pathAsString)
} else {
println(".... nothing to delete at " + pathAsString)
}
}catch(e){
println("Unable to clean up job ${jobName}")
e.printStackTrace()
}
}
computer.setTemporarilyOffline(wasOffline, null) //respect offline status
}
}
@NonCPS
def clean(){
cleanup(Jenkins.getInstance())
for (node in Jenkins.instance.nodes) {
cleanup(node)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment