Jakub Josef | 4edd743 | 2017-05-10 17:58:56 +0200 | [diff] [blame] | 1 | package com.mirantis.mk |
Jakub Josef | 93f08e2 | 2017-06-05 19:14:53 +0200 | [diff] [blame] | 2 | import com.cloudbees.groovy.cps.NonCPS |
Jakub Josef | 4edd743 | 2017-05-10 17:58:56 +0200 | [diff] [blame] | 3 | |
| 4 | /** |
| 5 | * |
| 6 | * Jenkins common functions |
| 7 | * |
| 8 | */ |
| 9 | |
| 10 | /** |
| 11 | * Get Jenkins job running builds |
| 12 | * @param jobName job name |
| 13 | * @return list of running builds |
| 14 | */ |
Jakub Josef | fbe8c7c | 2017-05-11 13:35:11 +0200 | [diff] [blame] | 15 | @NonCPS |
Jakub Josef | 4edd743 | 2017-05-10 17:58:56 +0200 | [diff] [blame] | 16 | def getJobRunningBuilds(jobName){ |
Jakub Josef | fbe8c7c | 2017-05-11 13:35:11 +0200 | [diff] [blame] | 17 | def job = Jenkins.instance.items.find{it -> it.name.equals(jobName)} |
| 18 | if(job){ |
| 19 | return job.builds.findAll{build -> build.isBuilding()} |
| 20 | } |
| 21 | return [] |
Jakub Josef | 93f08e2 | 2017-06-05 19:14:53 +0200 | [diff] [blame] | 22 | } |
| 23 | |
| 24 | @NonCPS |
| 25 | def getRunningBuilds(job){ |
| 26 | return job.builds.findAll{build -> build.isBuilding()} |
| 27 | } |
| 28 | |
| 29 | @NonCPS |
| 30 | def killStuckBuilds(maxSeconds, job){ |
| 31 | def common = new com.mirantis.mk.Common() |
| 32 | def result = true |
| 33 | def runningBuilds = getRunningBuilds(job) |
| 34 | def jobName = job.name |
| 35 | for(int j=0; j < runningBuilds.size(); j++){ |
| 36 | int durationInSeconds = (System.currentTimeMillis() - runningBuilds[j].getTimeInMillis())/1000.0 |
| 37 | if(durationInSeconds > maxSeconds){ |
| 38 | result = false |
| 39 | def buildId = runningBuilds[j].id |
| 40 | common.infoMsg("Aborting ${jobName}-${buildId} which is running for ${durationInSeconds}s") |
| 41 | try{ |
| 42 | runningBuilds[j].finish(hudson.model.Result.ABORTED, new java.io.IOException("Aborting build by long running jobs killer")); |
| 43 | result = true |
| 44 | }catch(e){ |
| 45 | common.errorMsg("Error occured during aborting build: Exception: ${e}") |
| 46 | } |
| 47 | } |
| 48 | } |
| 49 | return result |
Jakub Josef | 4edd743 | 2017-05-10 17:58:56 +0200 | [diff] [blame] | 50 | } |