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