Skip to content

Instantly share code, notes, and snippets.

@vadikgo
Last active September 16, 2019 11:45
Show Gist options
  • Select an option

  • Save vadikgo/3454a054c1ffdfc2a46260400308defc to your computer and use it in GitHub Desktop.

Select an option

Save vadikgo/3454a054c1ffdfc2a46260400308defc to your computer and use it in GitHub Desktop.
Wipe workspace folder on Jenkins master server
def isBuilding(job) {
for (comp in Jenkins.instance.computers) {
for (ex in comp.executors){
if (ex.isBusy() && (ex.getCurrentExecutable().getParent().getOwnerTask().getName() == job.name)) {
return true
}
}
}
return false
}
def wipeJobs(cls) {
jenkins.model.Jenkins.instance.getAllItems().findAll{
!(it instanceof com.cloudbees.hudson.plugins.folder.Folder) &&
!(it instanceof jenkins.branch.OrganizationFolder) &&
!(it instanceof org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject) &&
!(it instanceof hudson.matrix.MatrixConfiguration)
}.each { job ->
String wkdir = ''
if (!(job instanceof hudson.maven.MavenModule)) {
wkdir = jenkins.model.Jenkins.instance.getWorkspaceFor(job).toString()
}
if (job.building || isBuilding(job)) {
println "Skipping job ${job.name}, at ${wkdir} is currently building"
} else if (job instanceof hudson.maven.MavenModule) {
println "Wiping out job ${job.name}"
job.doDoWipeOutWorkspace()
} else {
File pdir = new File(wkdir).getParentFile()
if (pdir.exists()) {
pdir.eachFile(groovy.io.FileType.DIRECTORIES) {
if (it.getPath().startsWith(wkdir)) {
println "Remove directory ${it.getPath()}"
new ProcessBuilder("/bin/rm", "-rf", it.getPath()).redirectErrorStream(true).start()
}
}
}
}
}
}
def findLostJobs(String workspace){
def jobDirs = []
jenkins.model.Jenkins.instance.getAllItems().findAll{
!(it instanceof com.cloudbees.hudson.plugins.folder.Folder) &&
!(it instanceof jenkins.branch.OrganizationFolder) &&
!(it instanceof org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject) &&
!(it instanceof hudson.matrix.MatrixConfiguration) &&
!(it instanceof hudson.maven.MavenModule)
}.each { job ->
jobDirs.add(jenkins.model.Jenkins.instance.getWorkspaceFor(job).toString())
}
def delPath = []
new File(workspace).eachFileRecurse(groovy.io.FileType.DIRECTORIES) { fld ->
if (delPath.find{ dp-> fld.getPath().startsWith(dp) } == null){
if (jobDirs.find{ jd-> fld.getPath().startsWith(jd) || jd.startsWith(fld.getPath()) } == null) {
delPath.add(fld.getPath())
println "Delete lost job directory ${fld.getPath()}"
new ProcessBuilder("/bin/rm", "-rf", fld.getPath()).redirectErrorStream(true).start()
}
}
}
}
wipeJobs()
findLostJobs("${jenkins.model.Jenkins.instance.getRootDir()}/workspace")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment