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 | def MAX_ALLOWED_DURATION_IN_SECONDS = 3600 * Integer.parseInt(MAX_DURATION_IN_HOURS) |
| 9 | node{ |
| 10 | stage("Kill long running jobs"){ |
| 11 | def jobKilled = false |
| 12 | for (int i=0; i < Jenkins.instance.items.size(); i++) { |
| 13 | def job = Jenkins.instance.items[i] |
| 14 | def runningBuilds = _getRunningBuilds(job) |
| 15 | def jobName = job.name |
| 16 | for(int j=0; j < runningBuilds.size(); j++){ |
| 17 | def build = runningBuilds[j] |
| 18 | int durationInSeconds = (System.currentTimeMillis() - build.getTimeInMillis())/1000.0 |
| 19 | if(durationInSeconds > MAX_ALLOWED_DURATION_IN_SECONDS){ |
| 20 | common.infoMsg("Aborting ${job.name}-${build.id} which is running for ${durationInSeconds}s") |
| 21 | try{ |
| 22 | build.finish(hudson.model.Result.ABORTED, new java.io.IOException("Aborting build by long running jobs killer")); |
| 23 | }catch(e){ |
| 24 | common.errorMsg("Error occured during aborting build: Exception: ${e}") |
| 25 | } |
| 26 | } |
Jakub Josef | f7283ee | 2017-03-20 19:10:13 +0100 | [diff] [blame] | 27 | } |
| 28 | } |
Jakub Josef | 05c8a4e | 2017-03-23 16:40:59 +0100 | [diff] [blame] | 29 | if(!jobKilled){ |
| 30 | common.infoMsg("No job aborted") |
| 31 | } |
Jakub Josef | f7283ee | 2017-03-20 19:10:13 +0100 | [diff] [blame] | 32 | } |
| 33 | } |
| 34 | |
Jakub Josef | 05c8a4e | 2017-03-23 16:40:59 +0100 | [diff] [blame] | 35 | @NonCPS |
| 36 | def _getRunningBuilds(job){ |
| 37 | return job.builds.findAll{build -> build.isBuilding()} |
| 38 | } |