blob: 43be87bdf021f0e5bb7c578e50b1018643da4b31 [file] [log] [blame]
Jakub Josef4edd7432017-05-10 17:58:56 +02001package com.mirantis.mk
Jakub Josef93f08e22017-06-05 19:14:53 +02002import com.cloudbees.groovy.cps.NonCPS
Jakub Josef4edd7432017-05-10 17:58:56 +02003
4/**
5 *
6 * Jenkins common functions
7 *
8 */
9
10/**
Jakub Josefd44b6972018-01-23 17:55:57 +010011 * 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 */
15def 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 Josef4edd7432017-05-10 17:58:56 +020030 * Get Jenkins job running builds
31 * @param jobName job name
32 * @return list of running builds
33 */
Jakub Joseffbe8c7c2017-05-11 13:35:11 +020034@NonCPS
Jakub Josef4edd7432017-05-10 17:58:56 +020035def getJobRunningBuilds(jobName){
Jakub Joseffbe8c7c2017-05-11 13:35:11 +020036 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 Josef93f08e22017-06-05 19:14:53 +020041}
42
43@NonCPS
44def getRunningBuilds(job){
45 return job.builds.findAll{build -> build.isBuilding()}
46}
47
48@NonCPS
49def 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 Josefd44b6972018-01-23 17:55:57 +010069}