| Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 1 | package com.mirantis.mk | 
|  | 2 |  | 
| Jakub Josef | b41c8d5 | 2017-03-24 13:52:24 +0100 | [diff] [blame] | 3 | import static groovy.json.JsonOutput.prettyPrint | 
|  | 4 | import static groovy.json.JsonOutput.toJson | 
| Jakub Josef | b7ab847 | 2017-04-05 14:56:53 +0200 | [diff] [blame] | 5 | import groovy.json.JsonSlurperClassic | 
| Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 6 | /** | 
|  | 7 | * | 
|  | 8 | * Common functions | 
|  | 9 | * | 
|  | 10 | */ | 
|  | 11 |  | 
|  | 12 | /** | 
|  | 13 | * Generate current timestamp | 
|  | 14 | * | 
|  | 15 | * @param format    Defaults to yyyyMMddHHmmss | 
|  | 16 | */ | 
|  | 17 | def getDatetime(format="yyyyMMddHHmmss") { | 
|  | 18 | def now = new Date(); | 
|  | 19 | return now.format(format, TimeZone.getTimeZone('UTC')); | 
|  | 20 | } | 
|  | 21 |  | 
|  | 22 | /** | 
| Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 23 | * Return workspace. | 
|  | 24 | * Currently implemented by calling pwd so it won't return relevant result in | 
|  | 25 | * dir context | 
|  | 26 | */ | 
|  | 27 | def getWorkspace() { | 
|  | 28 | def workspace = sh script: 'pwd', returnStdout: true | 
|  | 29 | workspace = workspace.trim() | 
|  | 30 | return workspace | 
|  | 31 | } | 
|  | 32 |  | 
|  | 33 | /** | 
| Filip Pytloun | 81c864d | 2017-03-21 15:19:30 +0100 | [diff] [blame] | 34 | * Get UID of jenkins user. | 
|  | 35 | * Must be run from context of node | 
|  | 36 | */ | 
|  | 37 | def 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 | */ | 
|  | 48 | def getJenkinsGid() { | 
|  | 49 | return sh ( | 
|  | 50 | script: 'id -g', | 
|  | 51 | returnStdout: true | 
|  | 52 | ).trim() | 
|  | 53 | } | 
|  | 54 |  | 
|  | 55 | /** | 
| Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 56 | * Get credentials from store | 
|  | 57 | * | 
|  | 58 | * @param id    Credentials name | 
|  | 59 | */ | 
| Jakub Josef | 3d9d9ab | 2017-03-14 15:09:03 +0100 | [diff] [blame] | 60 | def 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 Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 67 | def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials( | 
| Jakub Josef | 3d9d9ab | 2017-03-14 15:09:03 +0100 | [diff] [blame] | 68 | credClass, | 
| Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 69 | 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 | */ | 
|  | 85 | def abortBuild() { | 
|  | 86 | currentBuild.build().doStop() | 
|  | 87 | sleep(180) | 
|  | 88 | // just to be sure we will terminate | 
|  | 89 | throw new InterruptedException() | 
|  | 90 | } | 
|  | 91 |  | 
|  | 92 | /** | 
| Jakub Josef | b41c8d5 | 2017-03-24 13:52:24 +0100 | [diff] [blame] | 93 | * 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 | */ | 
|  | 97 | def prettyPrint(item){ | 
|  | 98 | return prettyPrint(toJson(item)).replace('\\n', System.getProperty('line.separator')) | 
|  | 99 | } | 
|  | 100 |  | 
|  | 101 | /** | 
| Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 102 | * Print informational message | 
|  | 103 | * | 
|  | 104 | * @param msg | 
|  | 105 | * @param color Colorful output or not | 
|  | 106 | */ | 
|  | 107 | def 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 | */ | 
|  | 117 | def 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 | */ | 
|  | 127 | def 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 | */ | 
|  | 137 | def warningMsg(msg, color = true) { | 
| Jakub Josef | 0e7bd63 | 2017-03-16 16:25:05 +0100 | [diff] [blame] | 138 | printMsg(msg, "yellow") | 
| Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 139 | } | 
|  | 140 |  | 
|  | 141 | /** | 
| Jakub Josef | 952ae0b | 2017-03-14 19:04:21 +0100 | [diff] [blame] | 142 | * 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 | */ | 
|  | 146 | def debugMsg(msg, color = true){ | 
| Jakub Josef | 9a836ac | 2017-04-24 12:26:02 +0200 | [diff] [blame] | 147 | // if debug property exists on env, debug is enabled | 
| Jakub Josef | 66976f6 | 2017-04-24 16:32:23 +0200 | [diff] [blame^] | 148 | if(env.getEnvironment().containsKey('DEBUG') && env['DEBUG'] == "true"){ | 
| Jakub Josef | 74b3469 | 2017-03-15 12:10:57 +0100 | [diff] [blame] | 149 | printMsg("[DEBUG] ${msg}", "red") | 
| Jakub Josef | 952ae0b | 2017-03-14 19:04:21 +0100 | [diff] [blame] | 150 | } | 
|  | 151 | } | 
|  | 152 |  | 
|  | 153 | /** | 
| Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 154 | * 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 | */ | 
|  | 160 | def 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 | 
|  | 188 | def 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 | 
|  | 203 | def 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 | */ | 
|  | 212 | def 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 | */ | 
|  | 226 | def 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 | */ | 
|  | 247 | def 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 Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 262 |  | 
|  | 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 | 
|  | 269 | def jenkinsHasPlugin(pluginName){ | 
|  | 270 | return Jenkins.instance.pluginManager.plugins.collect{p -> p.shortName}.contains(pluginName) | 
|  | 271 | } | 
|  | 272 |  | 
|  | 273 | @NonCPS | 
|  | 274 | def _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 | */ | 
|  | 309 | def 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 Pytloun | 49d6630 | 2017-03-06 10:26:22 +0100 | [diff] [blame] | 359 | } | 
| chnyda | 4e5ac79 | 2017-03-14 15:24:18 +0100 | [diff] [blame] | 360 |  | 
|  | 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 |  | 
|  | 368 | def 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 Pytloun | 81c864d | 2017-03-21 15:19:30 +0100 | [diff] [blame] | 379 | } | 
| Tomáš Kukrál | 767dd73 | 2017-03-23 10:38:59 +0100 | [diff] [blame] | 380 |  | 
|  | 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 |  | 
|  | 388 | def checkContains(variable, keyword) { | 
| Jakub Josef | 7a8dea2 | 2017-03-23 19:51:32 +0100 | [diff] [blame] | 389 | if(env.getEnvironment().containsKey(variable)){ | 
|  | 390 | return env[variable] && env[variable].toLowerCase().contains(keyword.toLowerCase()) | 
| Tomáš Kukrál | 767dd73 | 2017-03-23 10:38:59 +0100 | [diff] [blame] | 391 | } else { | 
| Tomáš Kukrál | c76c1e0 | 2017-03-23 19:06:59 +0100 | [diff] [blame] | 392 | return false | 
| Tomáš Kukrál | 767dd73 | 2017-03-23 10:38:59 +0100 | [diff] [blame] | 393 | } | 
|  | 394 | } | 
| Jakub Josef | a877db5 | 2017-04-05 14:22:30 +0200 | [diff] [blame] | 395 |  | 
|  | 396 | /** | 
|  | 397 | * Parse JSON string to hashmap | 
|  | 398 | * @param jsonString input JSON string | 
|  | 399 | * @return created hashmap | 
|  | 400 | */ | 
|  | 401 | def parseJSON(jsonString){ | 
|  | 402 | def m = [:] | 
| Jakub Josef | b7ab847 | 2017-04-05 14:56:53 +0200 | [diff] [blame] | 403 | def lazyMap = new JsonSlurperClassic().parseText(jsonString) | 
| Jakub Josef | a877db5 | 2017-04-05 14:22:30 +0200 | [diff] [blame] | 404 | m.putAll(lazyMap) | 
|  | 405 | return m | 
|  | 406 | } |