blob: f4b4d36440b992aebdf028bedfd3b8f13bdbd08f [file] [log] [blame]
Jakub Joseff7283ee2017-03-20 19:10:13 +01001/**
2 * Long running jobs killer
3 *
4 * MAX_DURATION_IN_HOURS - max permitted job duration in hours
5 */
6common = new com.mirantis.mk.Common()
7
Jakub Josef05c8a4e2017-03-23 16:40:59 +01008node{
9 stage("Kill long running jobs"){
10 def jobKilled = false
11 for (int i=0; i < Jenkins.instance.items.size(); i++) {
Jakub Josefb49c1622017-04-18 18:07:00 +020012 killStuckBuilds(3600 * Integer.parseInt(MAX_DURATION_IN_HOURS), Jenkins.instance.items[i])
Jakub Josef05c8a4e2017-03-23 16:40:59 +010013 }
Jakub Joseff7283ee2017-03-20 19:10:13 +010014 }
15}
16
Jakub Josef05c8a4e2017-03-23 16:40:59 +010017@NonCPS
Jakub Josefb49c1622017-04-18 18:07:00 +020018def getRunningBuilds(job){
Jakub Josef05c8a4e2017-03-23 16:40:59 +010019 return job.builds.findAll{build -> build.isBuilding()}
Jakub Josefb49c1622017-04-18 18:07:00 +020020}
21
22@NonCPS
23def killStuckBuilds(maxSeconds, job){
24 def result = false
25 def runningBuilds = getRunningBuilds(job)
26 def jobName = job.name
27 for(int j=0; j < runningBuilds.size(); j++){
28 int durationInSeconds = (System.currentTimeMillis() - runningBuilds[j].getTimeInMillis())/1000.0
29 if(durationInSeconds > maxSeconds){
30 def buildId = runningBuilds[j].id
31 common.infoMsg("Aborting ${jobName}-${buildId} which is running for ${durationInSeconds}s")
32 try{
33 runningBuilds[j].finish(hudson.model.Result.ABORTED, new java.io.IOException("Aborting build by long running jobs killer"));
34 }catch(e){
35 common.errorMsg("Error occured during aborting build: Exception: ${e}")
36 }
37 result = true
38 }
39 }
40 return result
Jakub Josef05c8a4e2017-03-23 16:40:59 +010041}