NS
import jenkins.model.*
import hudson.*
import hudson.model.*
import groovy.time.TimeCategory
use ( TimeCategory ) {
// e.g. find jobs not run in last 3 months
sometimeago = (new Date() - 2.days)
println(sometimeago)
}
//helper variables
jobs = Jenkins.instance.getAllItems()
lastabort = null
job2delete = []
night = false
//files to write
file_result = new FilePath(build.workspace, 'job_result.txt')
file = new FilePath(build.workspace, 'job_to_delete.txt')
//getting times for night calculation
nBegin = Integer.parseInt(nightlybegin)
nEnd = Integer.parseInt(nightlyend)
current = new Date()
//Checking for night hours
if (current.getHours() >= nBegin){
night = true
}
if (current.getHours() < nEnd ) {
night = true
}
//running through jobs
jobs.each { j ->
if (j.fullName.contains(ProjectPrefix+'preRel')) {
check=true
}
else if (j.fullName.contains(ProjectPrefix+'preInt')) {
check=true
}
else {
check=false
}
if (check) {
numbuilds = j.builds.size()
if (numbuilds == 0) {
println 'JOB: ' + j.fullName
println ' -> no build'
if(!night) {
println ' -> it is day : Job will not be deleted yet'
}
if(night) {
if(j.isBuilding()) {
println 'Job is building, I do not delete it'
} else {
job2delete.add(j.fullName)
}
}
return
}
lastbuild = j.lastBuild
println(lastbuild.timestamp.getTime())
if (lastbuild.timestamp.getTime() < sometimeago) {
println 'JOB: ' + j.fullName
println ' -> lastbuild: ' + lastbuild.displayName + ' = ' + lastbuild.result + ', time: ' + lastbuild.timestampString2
if(j.isBuilding()) {
println 'Job is building, I do not delete it'
} else {
job2delete.add(j.fullName)
}
return
}
}
}
if (job2delete.size() > 0) {
listOfJobsAsString = ""
job2delete.each {
job = "$it"
println "wrote: $job to job to delete"
listOfJobsAsString = listOfJobsAsString + "$job\n"
}
file.write("$listOfJobsAsString", null)
file_result.write("NUMBER_OF_JOBS=" + job2delete.size(), null)
}
else {
file.write('JOB2DELETE=NONE', null)
file_result.write('NUMBER_OF_JOBS=0',null)
}