blob: e71a551529edb0939a33b6269b386af5b2191960 [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){
Jakub Josef9a836ac2017-04-24 12:26:02 +0200147 // if debug property exists on env, debug is enabled
Jakub Josef66976f62017-04-24 16:32:23 +0200148 if(env.getEnvironment().containsKey('DEBUG') && env['DEBUG'] == "true"){
Jakub Josef74b34692017-03-15 12:10:57 +0100149 printMsg("[DEBUG] ${msg}", "red")
Jakub Josef952ae0b2017-03-14 19:04:21 +0100150 }
151}
152
153/**
Jakub Josef79ecec32017-02-17 14:36:28 +0100154 * Print message
155 *
156 * @param msg Message to be printed
157 * @param level Level of message (default INFO)
158 * @param color Color to use for output or false (default)
159 */
160def printMsg(msg, color = false) {
161 colors = [
162 'red' : '\u001B[31m',
163 'black' : '\u001B[30m',
164 'green' : '\u001B[32m',
165 'yellow': '\u001B[33m',
166 'blue' : '\u001B[34m',
167 'purple': '\u001B[35m',
168 'cyan' : '\u001B[36m',
169 'white' : '\u001B[37m',
170 'reset' : '\u001B[0m'
171 ]
172 if (color != false) {
173 wrap([$class: 'AnsiColorBuildWrapper']) {
174 print "${colors[color]}${msg}${colors.reset}"
175 }
176 } else {
177 print "[${level}] ${msg}"
178 }
179}
180
181/**
182 * Traverse directory structure and return list of files
183 *
184 * @param path Path to search
185 * @param type Type of files to search (groovy.io.FileType.FILES)
186 */
187@NonCPS
188def getFiles(path, type=groovy.io.FileType.FILES) {
189 files = []
190 new File(path).eachFile(type) {
191 files[] = it
192 }
193 return files
194}
195
196/**
197 * Helper method to convert map into form of list of [key,value] to avoid
198 * unserializable exceptions
199 *
200 * @param m Map
201 */
202@NonCPS
203def entries(m) {
204 m.collect {k, v -> [k, v]}
205}
206
207/**
208 * Opposite of build-in parallel, run map of steps in serial
209 *
210 * @param steps Map of String<name>: CPSClosure2<step>
211 */
212def serial(steps) {
213 stepsArray = entries(steps)
214 for (i=0; i < stepsArray.size; i++) {
215 s = stepsArray[i]
216 dummySteps = ["${s[0]}": s[1]]
217 parallel dummySteps
218 }
219}
220
221/**
222 * Get password credentials from store
223 *
224 * @param id Credentials name
225 */
226def getPasswordCredentials(id) {
227 def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
228 com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials.class,
229 jenkins.model.Jenkins.instance
230 )
231
232 for (Iterator<String> credsIter = creds.iterator(); credsIter.hasNext();) {
233 c = credsIter.next();
234 if ( c.id == id ) {
235 return c;
236 }
237 }
238
239 throw new Exception("Could not find credentials for ID ${id}")
240}
241
242/**
243 * Get SSH credentials from store
244 *
245 * @param id Credentials name
246 */
247def getSshCredentials(id) {
248 def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
249 com.cloudbees.plugins.credentials.common.StandardUsernameCredentials.class,
250 jenkins.model.Jenkins.instance
251 )
252
253 for (Iterator<String> credsIter = creds.iterator(); credsIter.hasNext();) {
254 c = credsIter.next();
255 if ( c.id == id ) {
256 return c;
257 }
258 }
259
260 throw new Exception("Could not find credentials for ID ${id}")
261}
Jakub Josef79ecec32017-02-17 14:36:28 +0100262
263/**
264 * Tests Jenkins instance for existence of plugin with given name
265 * @param pluginName plugin short name to test
266 * @return boolean result
267 */
268@NonCPS
269def jenkinsHasPlugin(pluginName){
270 return Jenkins.instance.pluginManager.plugins.collect{p -> p.shortName}.contains(pluginName)
271}
272
273@NonCPS
274def _needNotification(notificatedTypes, buildStatus, jobName) {
275 if(notificatedTypes && notificatedTypes.contains("onchange")){
276 if(jobName){
277 def job = Jenkins.instance.getItem(jobName)
278 def numbuilds = job.builds.size()
279 if (numbuilds > 0){
280 //actual build is first for some reasons, so last finished build is second
281 def lastBuild = job.builds[1]
282 if(lastBuild){
283 if(lastBuild.result.toString().toLowerCase().equals(buildStatus)){
284 println("Build status didn't changed since last build, not sending notifications")
285 return false;
286 }
287 }
288 }
289 }
290 }else if(!notificatedTypes.contains(buildStatus)){
291 return false;
292 }
293 return true;
294}
295
296/**
297 * Send notification to all enabled notifications services
298 * @param buildStatus message type (success, warning, error), null means SUCCESSFUL
299 * @param msgText message text
300 * @param enabledNotifications list of enabled notification types, types: slack, hipchat, email, default empty
301 * @param notificatedTypes types of notifications will be sent, default onchange - notificate if current build result not equal last result;
302 * otherwise use - ["success","unstable","failed"]
303 * @param jobName optional job name param, if empty env.JOB_NAME will be used
304 * @param buildNumber build number param, if empty env.JOB_NAME will be used
305 * @param buildUrl build url param, if empty env.JOB_NAME will be used
306 * @param mailFrom mail FROM param, if empty "jenkins" will be used, it's mandatory for sending email notifications
307 * @param mailTo mail TO param, it's mandatory for sending email notifications
308 */
309def sendNotification(buildStatus, msgText="", enabledNotifications = [], notificatedTypes=["onchange"], jobName=null, buildNumber=null, buildUrl=null, mailFrom="jenkins", mailTo=null){
310 // Default values
311 def colorName = 'blue'
312 def colorCode = '#0000FF'
313 def buildStatusParam = buildStatus != null && buildStatus != "" ? buildStatus : "SUCCESS"
314 def jobNameParam = jobName != null && jobName != "" ? jobName : env.JOB_NAME
315 def buildNumberParam = buildNumber != null && buildNumber != "" ? buildNumber : env.BUILD_NUMBER
316 def buildUrlParam = buildUrl != null && buildUrl != "" ? buildUrl : env.BUILD_URL
317 def subject = "${buildStatusParam}: Job '${jobNameParam} [${buildNumberParam}]'"
318 def summary = "${subject} (${buildUrlParam})"
319
320 if(msgText != null && msgText != ""){
321 summary+="\n${msgText}"
322 }
323 if(buildStatusParam.toLowerCase().equals("success")){
324 colorCode = "#00FF00"
325 colorName = "green"
326 }else if(buildStatusParam.toLowerCase().equals("unstable")){
327 colorCode = "#FFFF00"
328 colorName = "yellow"
329 }else if(buildStatusParam.toLowerCase().equals("failure")){
330 colorCode = "#FF0000"
331 colorName = "red"
332 }
333 if(_needNotification(notificatedTypes, buildStatusParam.toLowerCase(), jobNameParam)){
334 if(enabledNotifications.contains("slack") && jenkinsHasPlugin("slack")){
335 try{
336 slackSend color: colorCode, message: summary
337 }catch(Exception e){
338 println("Calling slack plugin failed")
339 e.printStackTrace()
340 }
341 }
342 if(enabledNotifications.contains("hipchat") && jenkinsHasPlugin("hipchat")){
343 try{
344 hipchatSend color: colorName.toUpperCase(), message: summary
345 }catch(Exception e){
346 println("Calling hipchat plugin failed")
347 e.printStackTrace()
348 }
349 }
350 if(enabledNotifications.contains("email") && mailTo != null && mailTo != "" && mailFrom != null && mailFrom != ""){
351 try{
352 mail body: summary, from: mailFrom, subject: subject, to: mailTo
353 }catch(Exception e){
354 println("Sending mail plugin failed")
355 e.printStackTrace()
356 }
357 }
358 }
Filip Pytloun49d66302017-03-06 10:26:22 +0100359}
chnyda4e5ac792017-03-14 15:24:18 +0100360
361/**
362 * Execute linux command and catch nth element
363 * @param cmd command to execute
364 * @param index index to retrieve
365 * @return index-th element
366 */
367
368def cutOrDie(cmd, index)
369{
370 def common = new com.mirantis.mk.Common()
371 def output
372 try {
373 output = sh(script: cmd, returnStdout: true)
374 def result = output.tokenize(" ")[index]
375 return result;
376 } catch (Exception e) {
377 common.errorMsg("Failed to execute cmd: ${cmd}\n output: ${output}")
378 }
Filip Pytloun81c864d2017-03-21 15:19:30 +0100379}
Tomáš Kukrál767dd732017-03-23 10:38:59 +0100380
381/**
382 * Check variable contains keyword
383 * @param variable keywork is searched (contains) here
384 * @param keyword string to look for
385 * @return True if variable contains keyword (case insensitive), False if do not contains or any of input isn't a string
386 */
387
388def checkContains(variable, keyword) {
Jakub Josef7a8dea22017-03-23 19:51:32 +0100389 if(env.getEnvironment().containsKey(variable)){
390 return env[variable] && env[variable].toLowerCase().contains(keyword.toLowerCase())
Tomáš Kukrál767dd732017-03-23 10:38:59 +0100391 } else {
Tomáš Kukrálc76c1e02017-03-23 19:06:59 +0100392 return false
Tomáš Kukrál767dd732017-03-23 10:38:59 +0100393 }
394}
Jakub Josefa877db52017-04-05 14:22:30 +0200395
396/**
397 * Parse JSON string to hashmap
398 * @param jsonString input JSON string
399 * @return created hashmap
400 */
401def parseJSON(jsonString){
402 def m = [:]
Jakub Josefb7ab8472017-04-05 14:56:53 +0200403 def lazyMap = new JsonSlurperClassic().parseText(jsonString)
Jakub Josefa877db52017-04-05 14:22:30 +0200404 m.putAll(lazyMap)
405 return m
406}
Jakub Josefed239cd2017-05-09 15:27:33 +0200407
408/**
409 * Test pipeline input parameter existence and validity (not null and not empty string)
410 * @param paramName input parameter name (usually uppercase)
411 */
412def validInputParam(paramName){
413 return env.getEnvironment().containsKey(paramName) && env[paramName] != null && env[paramName] != ""
414}