Jakub Josef | f7283ee | 2017-03-20 19:10:13 +0100 | [diff] [blame] | 1 | /** |
| 2 | * Long running jobs killer |
| 3 | * |
| 4 | * MAX_DURATION_IN_HOURS - max permitted job duration in hours |
| 5 | */ |
| 6 | common = new com.mirantis.mk.Common() |
| 7 | |
Jakub Josef | 05c8a4e | 2017-03-23 16:40:59 +0100 | [diff] [blame] | 8 | node{ |
| 9 | stage("Kill long running jobs"){ |
| 10 | def jobKilled = false |
| 11 | for (int i=0; i < Jenkins.instance.items.size(); i++) { |
Jakub Josef | b49c162 | 2017-04-18 18:07:00 +0200 | [diff] [blame] | 12 | killStuckBuilds(3600 * Integer.parseInt(MAX_DURATION_IN_HOURS), Jenkins.instance.items[i]) |
Jakub Josef | 05c8a4e | 2017-03-23 16:40:59 +0100 | [diff] [blame] | 13 | } |
Jakub Josef | f7283ee | 2017-03-20 19:10:13 +0100 | [diff] [blame] | 14 | } |
| 15 | } |
| 16 | |
Jakub Josef | 05c8a4e | 2017-03-23 16:40:59 +0100 | [diff] [blame] | 17 | @NonCPS |
Jakub Josef | b49c162 | 2017-04-18 18:07:00 +0200 | [diff] [blame] | 18 | def getRunningBuilds(job){ |
Jakub Josef | 05c8a4e | 2017-03-23 16:40:59 +0100 | [diff] [blame] | 19 | return job.builds.findAll{build -> build.isBuilding()} |
Jakub Josef | b49c162 | 2017-04-18 18:07:00 +0200 | [diff] [blame] | 20 | } |
| 21 | |
| 22 | @NonCPS |
| 23 | def 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 Josef | 05c8a4e | 2017-03-23 16:40:59 +0100 | [diff] [blame] | 41 | } |