blob: d4b817c0bb44213c45f057f46e08ea4d356715c2 [file] [log] [blame]
Jakub Josef79ecec32017-02-17 14:36:28 +01001package com.mirantis.mk
2
Jakub Josefb41c8d52017-03-24 13:52:24 +01003import static groovy.json.JsonOutput.prettyPrint
4import static groovy.json.JsonOutput.toJson
Jakub Josefb7ab8472017-04-05 14:56:53 +02005import groovy.json.JsonSlurperClassic
Jakub Josef79ecec32017-02-17 14:36:28 +01006/**
7 *
8 * Common functions
9 *
10 */
11
12/**
13 * Generate current timestamp
14 *
15 * @param format Defaults to yyyyMMddHHmmss
16 */
17def getDatetime(format="yyyyMMddHHmmss") {
18 def now = new Date();
19 return now.format(format, TimeZone.getTimeZone('UTC'));
20}
21
22/**
Jakub Josef79ecec32017-02-17 14:36:28 +010023 * Return workspace.
24 * Currently implemented by calling pwd so it won't return relevant result in
25 * dir context
26 */
27def getWorkspace() {
28 def workspace = sh script: 'pwd', returnStdout: true
29 workspace = workspace.trim()
30 return workspace
31}
32
33/**
Filip Pytloun81c864d2017-03-21 15:19:30 +010034 * Get UID of jenkins user.
35 * Must be run from context of node
36 */
37def getJenkinsUid() {
38 return sh (
39 script: 'id -u',
40 returnStdout: true
41 ).trim()
42}
43
44/**
45 * Get GID of jenkins user.
46 * Must be run from context of node
47 */
48def getJenkinsGid() {
49 return sh (
50 script: 'id -g',
51 returnStdout: true
52 ).trim()
53}
54
55/**
Jakub Josef79ecec32017-02-17 14:36:28 +010056 * Get credentials from store
57 *
58 * @param id Credentials name
59 */
Jakub Josef3d9d9ab2017-03-14 15:09:03 +010060def getCredentials(id, cred_type = "username_password") {
61 def credClass;
62 if(cred_type == "username_password"){
63 credClass = com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials.class
64 }else if(cred_type == "key"){
65 credClass = com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey.class
66 }
Jakub Josef79ecec32017-02-17 14:36:28 +010067 def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
Jakub Josef3d9d9ab2017-03-14 15:09:03 +010068 credClass,
Jakub Josef79ecec32017-02-17 14:36:28 +010069 jenkins.model.Jenkins.instance
70 )
71
72 for (Iterator<String> credsIter = creds.iterator(); credsIter.hasNext();) {
73 c = credsIter.next();
74 if ( c.id == id ) {
75 return c;
76 }
77 }
78
79 throw new Exception("Could not find credentials for ID ${id}")
80}
81
82/**
83 * Abort build, wait for some time and ensure we will terminate
84 */
85def abortBuild() {
86 currentBuild.build().doStop()
87 sleep(180)
88 // just to be sure we will terminate
89 throw new InterruptedException()
90}
91
92/**
Jakub Josefb41c8d52017-03-24 13:52:24 +010093 * Return pretty-printed string representation of given item
94 * @param item item to be pretty-printed (list, map, whatever)
95 * @return pretty-printed string
96 */
97def prettyPrint(item){
98 return prettyPrint(toJson(item)).replace('\\n', System.getProperty('line.separator'))
99}
100
101/**
Jakub Josef79ecec32017-02-17 14:36:28 +0100102 * Print informational message
103 *
104 * @param msg
105 * @param color Colorful output or not
106 */
107def infoMsg(msg, color = true) {
108 printMsg(msg, "cyan")
109}
110
111/**
112 * Print error message
113 *
114 * @param msg
115 * @param color Colorful output or not
116 */
117def errorMsg(msg, color = true) {
118 printMsg(msg, "red")
119}
120
121/**
122 * Print success message
123 *
124 * @param msg
125 * @param color Colorful output or not
126 */
127def successMsg(msg, color = true) {
128 printMsg(msg, "green")
129}
130
131/**
132 * Print warning message
133 *
134 * @param msg
135 * @param color Colorful output or not
136 */
137def warningMsg(msg, color = true) {
Jakub Josef0e7bd632017-03-16 16:25:05 +0100138 printMsg(msg, "yellow")
Jakub Josef79ecec32017-02-17 14:36:28 +0100139}
140
141/**
Jakub Josef952ae0b2017-03-14 19:04:21 +0100142 * Print debug message, this message will show only if DEBUG global variable is present
143 * @param msg
144 * @param color Colorful output or not
145 */
146def debugMsg(msg, color = true){
147 def debugEnabled
148 try {
149 debugEnabled = DEBUG
150 } catch (MissingPropertyException e) {
151 debugEnabled = false
152 }
153 if(debugEnabled){
Jakub Josef74b34692017-03-15 12:10:57 +0100154 printMsg("[DEBUG] ${msg}", "red")
Jakub Josef952ae0b2017-03-14 19:04:21 +0100155 }
156}
157
158/**
Jakub Josef79ecec32017-02-17 14:36:28 +0100159 * Print message
160 *
161 * @param msg Message to be printed
162 * @param level Level of message (default INFO)
163 * @param color Color to use for output or false (default)
164 */
165def printMsg(msg, color = false) {
166 colors = [
167 'red' : '\u001B[31m',
168 'black' : '\u001B[30m',
169 'green' : '\u001B[32m',
170 'yellow': '\u001B[33m',
171 'blue' : '\u001B[34m',
172 'purple': '\u001B[35m',
173 'cyan' : '\u001B[36m',
174 'white' : '\u001B[37m',
175 'reset' : '\u001B[0m'
176 ]
177 if (color != false) {
178 wrap([$class: 'AnsiColorBuildWrapper']) {
179 print "${colors[color]}${msg}${colors.reset}"
180 }
181 } else {
182 print "[${level}] ${msg}"
183 }
184}
185
186/**
187 * Traverse directory structure and return list of files
188 *
189 * @param path Path to search
190 * @param type Type of files to search (groovy.io.FileType.FILES)
191 */
192@NonCPS
193def getFiles(path, type=groovy.io.FileType.FILES) {
194 files = []
195 new File(path).eachFile(type) {
196 files[] = it
197 }
198 return files
199}
200
201/**
202 * Helper method to convert map into form of list of [key,value] to avoid
203 * unserializable exceptions
204 *
205 * @param m Map
206 */
207@NonCPS
208def entries(m) {
209 m.collect {k, v -> [k, v]}
210}
211
212/**
213 * Opposite of build-in parallel, run map of steps in serial
214 *
215 * @param steps Map of String<name>: CPSClosure2<step>
216 */
217def serial(steps) {
218 stepsArray = entries(steps)
219 for (i=0; i < stepsArray.size; i++) {
220 s = stepsArray[i]
221 dummySteps = ["${s[0]}": s[1]]
222 parallel dummySteps
223 }
224}
225
226/**
227 * Get password credentials from store
228 *
229 * @param id Credentials name
230 */
231def getPasswordCredentials(id) {
232 def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
233 com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials.class,
234 jenkins.model.Jenkins.instance
235 )
236
237 for (Iterator<String> credsIter = creds.iterator(); credsIter.hasNext();) {
238 c = credsIter.next();
239 if ( c.id == id ) {
240 return c;
241 }
242 }
243
244 throw new Exception("Could not find credentials for ID ${id}")
245}
246
247/**
248 * Get SSH credentials from store
249 *
250 * @param id Credentials name
251 */
252def getSshCredentials(id) {
253 def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
254 com.cloudbees.plugins.credentials.common.StandardUsernameCredentials.class,
255 jenkins.model.Jenkins.instance
256 )
257
258 for (Iterator<String> credsIter = creds.iterator(); credsIter.hasNext();) {
259 c = credsIter.next();
260 if ( c.id == id ) {
261 return c;
262 }
263 }
264
265 throw new Exception("Could not find credentials for ID ${id}")
266}
Jakub Josef79ecec32017-02-17 14:36:28 +0100267
268/**
269 * Tests Jenkins instance for existence of plugin with given name
270 * @param pluginName plugin short name to test
271 * @return boolean result
272 */
273@NonCPS
274def jenkinsHasPlugin(pluginName){
275 return Jenkins.instance.pluginManager.plugins.collect{p -> p.shortName}.contains(pluginName)
276}
277
278@NonCPS
279def _needNotification(notificatedTypes, buildStatus, jobName) {
280 if(notificatedTypes && notificatedTypes.contains("onchange")){
281 if(jobName){
282 def job = Jenkins.instance.getItem(jobName)
283 def numbuilds = job.builds.size()
284 if (numbuilds > 0){
285 //actual build is first for some reasons, so last finished build is second
286 def lastBuild = job.builds[1]
287 if(lastBuild){
288 if(lastBuild.result.toString().toLowerCase().equals(buildStatus)){
289 println("Build status didn't changed since last build, not sending notifications")
290 return false;
291 }
292 }
293 }
294 }
295 }else if(!notificatedTypes.contains(buildStatus)){
296 return false;
297 }
298 return true;
299}
300
301/**
302 * Send notification to all enabled notifications services
303 * @param buildStatus message type (success, warning, error), null means SUCCESSFUL
304 * @param msgText message text
305 * @param enabledNotifications list of enabled notification types, types: slack, hipchat, email, default empty
306 * @param notificatedTypes types of notifications will be sent, default onchange - notificate if current build result not equal last result;
307 * otherwise use - ["success","unstable","failed"]
308 * @param jobName optional job name param, if empty env.JOB_NAME will be used
309 * @param buildNumber build number param, if empty env.JOB_NAME will be used
310 * @param buildUrl build url param, if empty env.JOB_NAME will be used
311 * @param mailFrom mail FROM param, if empty "jenkins" will be used, it's mandatory for sending email notifications
312 * @param mailTo mail TO param, it's mandatory for sending email notifications
313 */
314def sendNotification(buildStatus, msgText="", enabledNotifications = [], notificatedTypes=["onchange"], jobName=null, buildNumber=null, buildUrl=null, mailFrom="jenkins", mailTo=null){
315 // Default values
316 def colorName = 'blue'
317 def colorCode = '#0000FF'
318 def buildStatusParam = buildStatus != null && buildStatus != "" ? buildStatus : "SUCCESS"
319 def jobNameParam = jobName != null && jobName != "" ? jobName : env.JOB_NAME
320 def buildNumberParam = buildNumber != null && buildNumber != "" ? buildNumber : env.BUILD_NUMBER
321 def buildUrlParam = buildUrl != null && buildUrl != "" ? buildUrl : env.BUILD_URL
322 def subject = "${buildStatusParam}: Job '${jobNameParam} [${buildNumberParam}]'"
323 def summary = "${subject} (${buildUrlParam})"
324
325 if(msgText != null && msgText != ""){
326 summary+="\n${msgText}"
327 }
328 if(buildStatusParam.toLowerCase().equals("success")){
329 colorCode = "#00FF00"
330 colorName = "green"
331 }else if(buildStatusParam.toLowerCase().equals("unstable")){
332 colorCode = "#FFFF00"
333 colorName = "yellow"
334 }else if(buildStatusParam.toLowerCase().equals("failure")){
335 colorCode = "#FF0000"
336 colorName = "red"
337 }
338 if(_needNotification(notificatedTypes, buildStatusParam.toLowerCase(), jobNameParam)){
339 if(enabledNotifications.contains("slack") && jenkinsHasPlugin("slack")){
340 try{
341 slackSend color: colorCode, message: summary
342 }catch(Exception e){
343 println("Calling slack plugin failed")
344 e.printStackTrace()
345 }
346 }
347 if(enabledNotifications.contains("hipchat") && jenkinsHasPlugin("hipchat")){
348 try{
349 hipchatSend color: colorName.toUpperCase(), message: summary
350 }catch(Exception e){
351 println("Calling hipchat plugin failed")
352 e.printStackTrace()
353 }
354 }
355 if(enabledNotifications.contains("email") && mailTo != null && mailTo != "" && mailFrom != null && mailFrom != ""){
356 try{
357 mail body: summary, from: mailFrom, subject: subject, to: mailTo
358 }catch(Exception e){
359 println("Sending mail plugin failed")
360 e.printStackTrace()
361 }
362 }
363 }
Filip Pytloun49d66302017-03-06 10:26:22 +0100364}
chnyda4e5ac792017-03-14 15:24:18 +0100365
366/**
367 * Execute linux command and catch nth element
368 * @param cmd command to execute
369 * @param index index to retrieve
370 * @return index-th element
371 */
372
373def cutOrDie(cmd, index)
374{
375 def common = new com.mirantis.mk.Common()
376 def output
377 try {
378 output = sh(script: cmd, returnStdout: true)
379 def result = output.tokenize(" ")[index]
380 return result;
381 } catch (Exception e) {
382 common.errorMsg("Failed to execute cmd: ${cmd}\n output: ${output}")
383 }
Filip Pytloun81c864d2017-03-21 15:19:30 +0100384}
Tomáš Kukrál767dd732017-03-23 10:38:59 +0100385
386/**
387 * Check variable contains keyword
388 * @param variable keywork is searched (contains) here
389 * @param keyword string to look for
390 * @return True if variable contains keyword (case insensitive), False if do not contains or any of input isn't a string
391 */
392
393def checkContains(variable, keyword) {
Jakub Josef7a8dea22017-03-23 19:51:32 +0100394 if(env.getEnvironment().containsKey(variable)){
395 return env[variable] && env[variable].toLowerCase().contains(keyword.toLowerCase())
Tomáš Kukrál767dd732017-03-23 10:38:59 +0100396 } else {
Tomáš Kukrálc76c1e02017-03-23 19:06:59 +0100397 return false
Tomáš Kukrál767dd732017-03-23 10:38:59 +0100398 }
399}
Jakub Josefa877db52017-04-05 14:22:30 +0200400
401/**
402 * Parse JSON string to hashmap
403 * @param jsonString input JSON string
404 * @return created hashmap
405 */
406def parseJSON(jsonString){
407 def m = [:]
Jakub Josefb7ab8472017-04-05 14:56:53 +0200408 def lazyMap = new JsonSlurperClassic().parseText(jsonString)
Jakub Josefa877db52017-04-05 14:22:30 +0200409 m.putAll(lazyMap)
410 return m
411}