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 | /** |
Jakub Josef | d44b697 | 2018-01-23 17:55:57 +0100 | [diff] [blame^] | 11 | * Tests if current user belongs to given group |
| 12 | * @param groupName name of the group you want to verify user presence |
| 13 | * @return boolean result |
| 14 | */ |
| 15 | def currentUserInGroup(groupName){ |
| 16 | def hasAccess = false |
| 17 | wrap([$class: 'BuildUser']) { |
| 18 | def authorities = Jenkins.instance.securityRealm.loadUserByUsername(BUILD_USER).getAuthorities() |
| 19 | for(int i=0;i < authorities.size();i++){ |
| 20 | if(authorities[i].equals(groupName)){ |
| 21 | hasAccess=true |
| 22 | break |
| 23 | } |
| 24 | } |
| 25 | } |
| 26 | return hasAccess |
| 27 | } |
| 28 | |
| 29 | /** |
Jakub Josef | 4edd743 | 2017-05-10 17:58:56 +0200 | [diff] [blame] | 30 | * Get Jenkins job running builds |
| 31 | * @param jobName job name |
| 32 | * @return list of running builds |
| 33 | */ |
Jakub Josef | fbe8c7c | 2017-05-11 13:35:11 +0200 | [diff] [blame] | 34 | @NonCPS |
Jakub Josef | 4edd743 | 2017-05-10 17:58:56 +0200 | [diff] [blame] | 35 | def getJobRunningBuilds(jobName){ |
Jakub Josef | fbe8c7c | 2017-05-11 13:35:11 +0200 | [diff] [blame] | 36 | def job = Jenkins.instance.items.find{it -> it.name.equals(jobName)} |
| 37 | if(job){ |
| 38 | return job.builds.findAll{build -> build.isBuilding()} |
| 39 | } |
| 40 | return [] |
Jakub Josef | 93f08e2 | 2017-06-05 19:14:53 +0200 | [diff] [blame] | 41 | } |
| 42 | |
| 43 | @NonCPS |
| 44 | def getRunningBuilds(job){ |
| 45 | return job.builds.findAll{build -> build.isBuilding()} |
| 46 | } |
| 47 | |
| 48 | @NonCPS |
| 49 | def killStuckBuilds(maxSeconds, job){ |
| 50 | def common = new com.mirantis.mk.Common() |
| 51 | def result = true |
| 52 | def runningBuilds = getRunningBuilds(job) |
| 53 | def jobName = job.name |
| 54 | for(int j=0; j < runningBuilds.size(); j++){ |
| 55 | int durationInSeconds = (System.currentTimeMillis() - runningBuilds[j].getTimeInMillis())/1000.0 |
| 56 | if(durationInSeconds > maxSeconds){ |
| 57 | result = false |
| 58 | def buildId = runningBuilds[j].id |
| 59 | common.infoMsg("Aborting ${jobName}-${buildId} which is running for ${durationInSeconds}s") |
| 60 | try{ |
| 61 | runningBuilds[j].finish(hudson.model.Result.ABORTED, new java.io.IOException("Aborting build by long running jobs killer")); |
| 62 | result = true |
| 63 | }catch(e){ |
| 64 | common.errorMsg("Error occured during aborting build: Exception: ${e}") |
| 65 | } |
| 66 | } |
| 67 | } |
| 68 | return result |
Jakub Josef | d44b697 | 2018-01-23 17:55:57 +0100 | [diff] [blame^] | 69 | } |