Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 1 | package com.mirantis.mk |
Jakub Josef | 6d8082b | 2017-08-09 12:40:50 +0200 | [diff] [blame] | 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 | 6d8082b | 2017-08-09 12:40:50 +0200 | [diff] [blame] | 5 | |
Alexandr Lovtsov | 2b668e5 | 2020-12-16 15:58:24 +0300 | [diff] [blame] | 6 | import groovy.time.TimeCategory |
| 7 | |
Jakub Josef | bceaa32 | 2017-06-13 18:28:27 +0200 | [diff] [blame] | 8 | import com.cloudbees.groovy.cps.NonCPS |
Jakub Josef | b7ab847 | 2017-04-05 14:56:53 +0200 | [diff] [blame] | 9 | import groovy.json.JsonSlurperClassic |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 10 | |
Dmitry Teselkin | 4badf83 | 2020-05-27 17:48:36 +0300 | [diff] [blame] | 11 | import org.jenkinsci.plugins.workflow.cps.EnvActionImpl |
| 12 | |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 13 | /** |
| 14 | * |
| 15 | * Common functions |
| 16 | * |
| 17 | */ |
| 18 | |
| 19 | /** |
| 20 | * Generate current timestamp |
| 21 | * |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 22 | * @param format Defaults to yyyyMMddHHmmss |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 23 | */ |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 24 | def getDatetime(format = "yyyyMMddHHmmss") { |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 25 | def now = new Date(); |
| 26 | return now.format(format, TimeZone.getTimeZone('UTC')); |
| 27 | } |
| 28 | |
| 29 | /** |
Alexandr Lovtsov | 2b668e5 | 2020-12-16 15:58:24 +0300 | [diff] [blame] | 30 | * Return Duration for given datetime period with suffix |
| 31 | * |
| 32 | * @param input String in format '\d+[smhd]', to convert given number into seconds, minutes, hours |
| 33 | * and days duration respectively. For example: '7d' is for 7 days, '10m' - 10 minutes |
| 34 | * and so on. Return null if input in incorrect format |
| 35 | */ |
| 36 | def getDuration(String input) { |
| 37 | // Verify input format |
| 38 | if (!input.matches('[0-9]+[smhd]')) { |
| 39 | errorMsg("Incorrect input data for getDuration(): ${input}") |
| 40 | return |
| 41 | } |
| 42 | switch (input[-1]) { |
| 43 | case 's': |
| 44 | return TimeCategory.getSeconds(input[0..-2].toInteger()) |
| 45 | case 'm': |
| 46 | return TimeCategory.getMinutes(input[0..-2].toInteger()) |
| 47 | case 'h': |
| 48 | return TimeCategory.getHours(input[0..-2].toInteger()) |
| 49 | case 'd': |
| 50 | return TimeCategory.getDays(input[0..-2].toInteger()) |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | /** |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 55 | * Return workspace. |
| 56 | * Currently implemented by calling pwd so it won't return relevant result in |
| 57 | * dir context |
| 58 | */ |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 59 | def getWorkspace(includeBuildNum = false) { |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 60 | def workspace = sh script: 'pwd', returnStdout: true |
| 61 | workspace = workspace.trim() |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 62 | if (includeBuildNum) { |
| 63 | if (!workspace.endsWith("/")) { |
| 64 | workspace += "/" |
| 65 | } |
| 66 | workspace += env.BUILD_NUMBER |
Jakub Josef | a661b8c | 2018-01-17 14:51:25 +0100 | [diff] [blame] | 67 | } |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 68 | return workspace |
| 69 | } |
| 70 | |
| 71 | /** |
Dmitry Teselkin | d4adf97 | 2020-02-13 18:24:59 +0300 | [diff] [blame] | 72 | * Get absolute path via 'realink' |
| 73 | * -m, --canonicalize-missing |
| 74 | * canonicalize by following every symlink in every component of the given name recursively, |
| 75 | * without requirements on components existence |
| 76 | */ |
| 77 | def getAbsolutePath(String path) { |
| 78 | def absPath = sh script: "readlink -m ${path}", returnStdout: true |
| 79 | return absPath.trim() |
| 80 | } |
| 81 | |
| 82 | /** |
Filip Pytloun | 81c864d | 2017-03-21 15:19:30 +0100 | [diff] [blame] | 83 | * Get UID of jenkins user. |
| 84 | * Must be run from context of node |
| 85 | */ |
| 86 | def getJenkinsUid() { |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 87 | return sh( |
Filip Pytloun | 81c864d | 2017-03-21 15:19:30 +0100 | [diff] [blame] | 88 | script: 'id -u', |
| 89 | returnStdout: true |
| 90 | ).trim() |
| 91 | } |
| 92 | |
| 93 | /** |
| 94 | * Get GID of jenkins user. |
| 95 | * Must be run from context of node |
| 96 | */ |
| 97 | def getJenkinsGid() { |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 98 | return sh( |
Filip Pytloun | 81c864d | 2017-03-21 15:19:30 +0100 | [diff] [blame] | 99 | script: 'id -g', |
| 100 | returnStdout: true |
| 101 | ).trim() |
| 102 | } |
| 103 | |
| 104 | /** |
Jakub Josef | c8074db | 2018-01-30 13:33:20 +0100 | [diff] [blame] | 105 | * Returns Jenkins user uid and gid in one list (in that order) |
| 106 | * Must be run from context of node |
| 107 | */ |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 108 | def getJenkinsUserIds() { |
Jakub Josef | c8074db | 2018-01-30 13:33:20 +0100 | [diff] [blame] | 109 | return sh(script: "id -u && id -g", returnStdout: true).tokenize("\n") |
| 110 | } |
| 111 | |
| 112 | /** |
Alexander Evseev | bc1fea4 | 2017-12-13 10:03:03 +0100 | [diff] [blame] | 113 | * |
| 114 | * Find credentials by ID |
| 115 | * |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 116 | * @param credsId Credentials ID |
| 117 | * @param credsType Credentials type (optional) |
Alexander Evseev | bc1fea4 | 2017-12-13 10:03:03 +0100 | [diff] [blame] | 118 | * |
| 119 | */ |
| 120 | def getCredentialsById(String credsId, String credsType = 'any') { |
| 121 | def credClasses = [ // ordered by class name |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 122 | sshKey : com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey.class, |
| 123 | cert : com.cloudbees.plugins.credentials.common.CertificateCredentials.class, |
| 124 | password : com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials.class, |
| 125 | any : com.cloudbees.plugins.credentials.impl.BaseStandardCredentials.class, |
| 126 | dockerCert: org.jenkinsci.plugins.docker.commons.credentials.DockerServerCredentials.class, |
| 127 | file : org.jenkinsci.plugins.plaincredentials.FileCredentials.class, |
| 128 | string : org.jenkinsci.plugins.plaincredentials.StringCredentials.class, |
Alexander Evseev | bc1fea4 | 2017-12-13 10:03:03 +0100 | [diff] [blame] | 129 | ] |
| 130 | return com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials( |
| 131 | credClasses[credsType], |
| 132 | jenkins.model.Jenkins.instance |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 133 | ).findAll { cred -> cred.id == credsId }[0] |
Alexander Evseev | bc1fea4 | 2017-12-13 10:03:03 +0100 | [diff] [blame] | 134 | } |
| 135 | |
| 136 | /** |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 137 | * Get credentials from store |
| 138 | * |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 139 | * @param id Credentials name |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 140 | */ |
Jakub Josef | 3d9d9ab | 2017-03-14 15:09:03 +0100 | [diff] [blame] | 141 | def getCredentials(id, cred_type = "username_password") { |
Alexander Evseev | bc1fea4 | 2017-12-13 10:03:03 +0100 | [diff] [blame] | 142 | warningMsg('You are using obsolete function. Please switch to use `getCredentialsById()`') |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 143 | |
Alexander Evseev | bc1fea4 | 2017-12-13 10:03:03 +0100 | [diff] [blame] | 144 | type_map = [ |
| 145 | username_password: 'password', |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 146 | key : 'sshKey', |
Alexander Evseev | bc1fea4 | 2017-12-13 10:03:03 +0100 | [diff] [blame] | 147 | ] |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 148 | |
Alexander Evseev | bc1fea4 | 2017-12-13 10:03:03 +0100 | [diff] [blame] | 149 | return getCredentialsById(id, type_map[cred_type]) |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 150 | } |
| 151 | |
| 152 | /** |
| 153 | * Abort build, wait for some time and ensure we will terminate |
| 154 | */ |
| 155 | def abortBuild() { |
| 156 | currentBuild.build().doStop() |
| 157 | sleep(180) |
| 158 | // just to be sure we will terminate |
| 159 | throw new InterruptedException() |
| 160 | } |
| 161 | |
| 162 | /** |
Jakub Josef | bceaa32 | 2017-06-13 18:28:27 +0200 | [diff] [blame] | 163 | * Print pretty-printed string representation of given item |
| 164 | * @param item item to be pretty-printed (list, map, whatever) |
| 165 | */ |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 166 | def prettyPrint(item) { |
Jakub Josef | bceaa32 | 2017-06-13 18:28:27 +0200 | [diff] [blame] | 167 | println prettify(item) |
| 168 | } |
| 169 | |
| 170 | /** |
Jakub Josef | b41c8d5 | 2017-03-24 13:52:24 +0100 | [diff] [blame] | 171 | * Return pretty-printed string representation of given item |
| 172 | * @param item item to be pretty-printed (list, map, whatever) |
| 173 | * @return pretty-printed string |
| 174 | */ |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 175 | def prettify(item) { |
Jakub Josef | bceaa32 | 2017-06-13 18:28:27 +0200 | [diff] [blame] | 176 | return groovy.json.JsonOutput.prettyPrint(toJson(item)).replace('\\n', System.getProperty('line.separator')) |
Jakub Josef | b41c8d5 | 2017-03-24 13:52:24 +0100 | [diff] [blame] | 177 | } |
| 178 | |
| 179 | /** |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 180 | * Print informational message |
| 181 | * |
| 182 | * @param msg |
| 183 | * @param color Colorful output or not |
| 184 | */ |
| 185 | def infoMsg(msg, color = true) { |
| 186 | printMsg(msg, "cyan") |
| 187 | } |
| 188 | |
| 189 | /** |
Sergey Galkin | 7137ad0 | 2019-11-07 14:52:13 +0400 | [diff] [blame] | 190 | * Print informational message |
| 191 | * |
| 192 | * @param msg |
| 193 | * @param color Colorful output or not |
| 194 | */ |
| 195 | def infoSensitivityMsg(msg, color = true, replacing = []) { |
| 196 | printSensitivityMsg(msg, "cyan", replacing) |
| 197 | } |
| 198 | |
| 199 | /** |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 200 | * Print error message |
| 201 | * |
| 202 | * @param msg |
| 203 | * @param color Colorful output or not |
| 204 | */ |
| 205 | def errorMsg(msg, color = true) { |
| 206 | printMsg(msg, "red") |
| 207 | } |
| 208 | |
| 209 | /** |
| 210 | * Print success message |
| 211 | * |
| 212 | * @param msg |
| 213 | * @param color Colorful output or not |
| 214 | */ |
| 215 | def successMsg(msg, color = true) { |
| 216 | printMsg(msg, "green") |
| 217 | } |
| 218 | |
| 219 | /** |
| 220 | * Print warning message |
| 221 | * |
| 222 | * @param msg |
| 223 | * @param color Colorful output or not |
| 224 | */ |
| 225 | def warningMsg(msg, color = true) { |
Jakub Josef | 0e7bd63 | 2017-03-16 16:25:05 +0100 | [diff] [blame] | 226 | printMsg(msg, "yellow") |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 227 | } |
| 228 | |
| 229 | /** |
Jakub Josef | 952ae0b | 2017-03-14 19:04:21 +0100 | [diff] [blame] | 230 | * Print debug message, this message will show only if DEBUG global variable is present |
| 231 | * @param msg |
| 232 | * @param color Colorful output or not |
| 233 | */ |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 234 | def debugMsg(msg, color = true) { |
Jakub Josef | 9a836ac | 2017-04-24 12:26:02 +0200 | [diff] [blame] | 235 | // if debug property exists on env, debug is enabled |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 236 | if (env.getEnvironment().containsKey('DEBUG') && env['DEBUG'] == "true") { |
Jakub Josef | 74b3469 | 2017-03-15 12:10:57 +0100 | [diff] [blame] | 237 | printMsg("[DEBUG] ${msg}", "red") |
Jakub Josef | 952ae0b | 2017-03-14 19:04:21 +0100 | [diff] [blame] | 238 | } |
| 239 | } |
| 240 | |
azvyagintsev | f6e7791 | 2018-09-07 15:41:09 +0300 | [diff] [blame] | 241 | def getColorizedString(msg, color) { |
| 242 | def colorMap = [ |
| 243 | 'red' : '\u001B[31m', |
| 244 | 'black' : '\u001B[30m', |
| 245 | 'green' : '\u001B[32m', |
| 246 | 'yellow': '\u001B[33m', |
| 247 | 'blue' : '\u001B[34m', |
| 248 | 'purple': '\u001B[35m', |
| 249 | 'cyan' : '\u001B[36m', |
| 250 | 'white' : '\u001B[37m', |
| 251 | 'reset' : '\u001B[0m' |
| 252 | ] |
Vasyl Saienko | 00ef98b | 2018-09-05 10:34:32 +0300 | [diff] [blame] | 253 | |
azvyagintsev | f6e7791 | 2018-09-07 15:41:09 +0300 | [diff] [blame] | 254 | return "${colorMap[color]}${msg}${colorMap.reset}" |
Vasyl Saienko | 00ef98b | 2018-09-05 10:34:32 +0300 | [diff] [blame] | 255 | } |
| 256 | |
Jakub Josef | 952ae0b | 2017-03-14 19:04:21 +0100 | [diff] [blame] | 257 | /** |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 258 | * Print message |
| 259 | * |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 260 | * @param msg Message to be printed |
Vasyl Saienko | 00ef98b | 2018-09-05 10:34:32 +0300 | [diff] [blame] | 261 | * @param color Color to use for output |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 262 | */ |
Vasyl Saienko | 00ef98b | 2018-09-05 10:34:32 +0300 | [diff] [blame] | 263 | def printMsg(msg, color) { |
| 264 | print getColorizedString(msg, color) |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 265 | } |
| 266 | |
| 267 | /** |
Sergey Galkin | 7137ad0 | 2019-11-07 14:52:13 +0400 | [diff] [blame] | 268 | * Print sensitivity message |
| 269 | * |
| 270 | * @param msg Message to be printed |
| 271 | * @param color Color to use for output |
| 272 | * @param replacing List with maps for deletion (passwords, logins, etc). |
| 273 | * The first () matching is mandatory ! |
| 274 | * Example: |
| 275 | * [/ (OS_PASSWORD=)(.*?)+ /, |
| 276 | * / (password = )(.*?)+ /, |
| 277 | * / (password )(.*?) / ] |
| 278 | */ |
| 279 | def printSensitivityMsg(msg, color, replacing = []) { |
| 280 | for (i in replacing) { |
| 281 | msg = msg.replaceAll(i, ' $1XXXXXX ') |
| 282 | } |
| 283 | printMsg(msg, color) |
| 284 | } |
| 285 | |
| 286 | /** |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 287 | * Traverse directory structure and return list of files |
| 288 | * |
| 289 | * @param path Path to search |
| 290 | * @param type Type of files to search (groovy.io.FileType.FILES) |
| 291 | */ |
| 292 | @NonCPS |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 293 | def getFiles(path, type = groovy.io.FileType.FILES) { |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 294 | files = [] |
| 295 | new File(path).eachFile(type) { |
| 296 | files[] = it |
| 297 | } |
| 298 | return files |
| 299 | } |
| 300 | |
| 301 | /** |
| 302 | * Helper method to convert map into form of list of [key,value] to avoid |
| 303 | * unserializable exceptions |
| 304 | * |
| 305 | * @param m Map |
| 306 | */ |
| 307 | @NonCPS |
| 308 | def entries(m) { |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 309 | m.collect { k, v -> [k, v] } |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 310 | } |
| 311 | |
| 312 | /** |
| 313 | * Opposite of build-in parallel, run map of steps in serial |
| 314 | * |
Jakub Josef | 7fb8bbd | 2017-05-15 16:02:44 +0200 | [diff] [blame] | 315 | * @param steps Map of String<name>: CPSClosure2<step> (or list of closures) |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 316 | */ |
| 317 | def serial(steps) { |
| 318 | stepsArray = entries(steps) |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 319 | for (i = 0; i < stepsArray.size; i++) { |
Jakub Josef | d31de30 | 2017-05-15 13:59:18 +0200 | [diff] [blame] | 320 | def step = stepsArray[i] |
Jakub Josef | 7fb8bbd | 2017-05-15 16:02:44 +0200 | [diff] [blame] | 321 | def dummySteps = [:] |
| 322 | def stepKey |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 323 | if (step[1] instanceof List || step[1] instanceof Map) { |
| 324 | for (j = 0; j < step[1].size(); j++) { |
| 325 | if (step[1] instanceof List) { |
Jakub Josef | 7fb8bbd | 2017-05-15 16:02:44 +0200 | [diff] [blame] | 326 | stepKey = j |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 327 | } else if (step[1] instanceof Map) { |
Jakub Josef | 7fb8bbd | 2017-05-15 16:02:44 +0200 | [diff] [blame] | 328 | stepKey = step[1].keySet()[j] |
| 329 | } |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 330 | dummySteps.put("step-${step[0]}-${stepKey}", step[1][stepKey]) |
Jakub Josef | d31de30 | 2017-05-15 13:59:18 +0200 | [diff] [blame] | 331 | } |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 332 | } else { |
Jakub Josef | d31de30 | 2017-05-15 13:59:18 +0200 | [diff] [blame] | 333 | dummySteps.put(step[0], step[1]) |
| 334 | } |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 335 | parallel dummySteps |
| 336 | } |
| 337 | } |
| 338 | |
| 339 | /** |
Jakub Josef | 7fb8bbd | 2017-05-15 16:02:44 +0200 | [diff] [blame] | 340 | * Partition given list to list of small lists |
| 341 | * @param inputList input list |
| 342 | * @param partitionSize (partition size, optional, default 5) |
| 343 | */ |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 344 | def partitionList(inputList, partitionSize = 5) { |
| 345 | List<List<String>> partitions = new ArrayList<>(); |
| 346 | for (int i = 0; i < inputList.size(); i += partitionSize) { |
| 347 | partitions.add(new ArrayList<String>(inputList.subList(i, Math.min(i + partitionSize, inputList.size())))); |
| 348 | } |
| 349 | return partitions |
Jakub Josef | 7fb8bbd | 2017-05-15 16:02:44 +0200 | [diff] [blame] | 350 | } |
| 351 | |
| 352 | /** |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 353 | * Get password credentials from store |
| 354 | * |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 355 | * @param id Credentials name |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 356 | */ |
| 357 | def getPasswordCredentials(id) { |
Alexander Evseev | bc1fea4 | 2017-12-13 10:03:03 +0100 | [diff] [blame] | 358 | return getCredentialsById(id, 'password') |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 359 | } |
| 360 | |
| 361 | /** |
| 362 | * Get SSH credentials from store |
| 363 | * |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 364 | * @param id Credentials name |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 365 | */ |
| 366 | def getSshCredentials(id) { |
Alexander Evseev | bc1fea4 | 2017-12-13 10:03:03 +0100 | [diff] [blame] | 367 | return getCredentialsById(id, 'sshKey') |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 368 | } |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 369 | |
| 370 | /** |
| 371 | * Tests Jenkins instance for existence of plugin with given name |
| 372 | * @param pluginName plugin short name to test |
| 373 | * @return boolean result |
| 374 | */ |
| 375 | @NonCPS |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 376 | def jenkinsHasPlugin(pluginName) { |
| 377 | return Jenkins.instance.pluginManager.plugins.collect { p -> p.shortName }.contains(pluginName) |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 378 | } |
| 379 | |
| 380 | @NonCPS |
| 381 | def _needNotification(notificatedTypes, buildStatus, jobName) { |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 382 | if (notificatedTypes && notificatedTypes.contains("onchange")) { |
| 383 | if (jobName) { |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 384 | def job = Jenkins.instance.getItem(jobName) |
| 385 | def numbuilds = job.builds.size() |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 386 | if (numbuilds > 0) { |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 387 | //actual build is first for some reasons, so last finished build is second |
| 388 | def lastBuild = job.builds[1] |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 389 | if (lastBuild) { |
| 390 | if (lastBuild.result.toString().toLowerCase().equals(buildStatus)) { |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 391 | println("Build status didn't changed since last build, not sending notifications") |
| 392 | return false; |
| 393 | } |
| 394 | } |
| 395 | } |
| 396 | } |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 397 | } else if (!notificatedTypes.contains(buildStatus)) { |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 398 | return false; |
| 399 | } |
| 400 | return true; |
| 401 | } |
| 402 | |
| 403 | /** |
| 404 | * Send notification to all enabled notifications services |
| 405 | * @param buildStatus message type (success, warning, error), null means SUCCESSFUL |
| 406 | * @param msgText message text |
| 407 | * @param enabledNotifications list of enabled notification types, types: slack, hipchat, email, default empty |
| 408 | * @param notificatedTypes types of notifications will be sent, default onchange - notificate if current build result not equal last result; |
| 409 | * otherwise use - ["success","unstable","failed"] |
| 410 | * @param jobName optional job name param, if empty env.JOB_NAME will be used |
Jakub Josef | d057115 | 2017-07-17 14:11:39 +0200 | [diff] [blame] | 411 | * @param buildNumber build number param, if empty env.BUILD_NUM will be used |
| 412 | * @param buildUrl build url param, if empty env.BUILD_URL will be used |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 413 | * @param mailFrom mail FROM param, if empty "jenkins" will be used, it's mandatory for sending email notifications |
Jakub Josef | d057115 | 2017-07-17 14:11:39 +0200 | [diff] [blame] | 414 | * @param mailTo mail TO param, it's mandatory for sending email notifications, this option enable mail notification |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 415 | */ |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 416 | def sendNotification(buildStatus, msgText = "", enabledNotifications = [], notificatedTypes = ["onchange"], jobName = null, buildNumber = null, buildUrl = null, mailFrom = "jenkins", mailTo = null) { |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 417 | // Default values |
| 418 | def colorName = 'blue' |
| 419 | def colorCode = '#0000FF' |
| 420 | def buildStatusParam = buildStatus != null && buildStatus != "" ? buildStatus : "SUCCESS" |
| 421 | def jobNameParam = jobName != null && jobName != "" ? jobName : env.JOB_NAME |
| 422 | def buildNumberParam = buildNumber != null && buildNumber != "" ? buildNumber : env.BUILD_NUMBER |
| 423 | def buildUrlParam = buildUrl != null && buildUrl != "" ? buildUrl : env.BUILD_URL |
| 424 | def subject = "${buildStatusParam}: Job '${jobNameParam} [${buildNumberParam}]'" |
| 425 | def summary = "${subject} (${buildUrlParam})" |
| 426 | |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 427 | if (msgText != null && msgText != "") { |
| 428 | summary += "\n${msgText}" |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 429 | } |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 430 | if (buildStatusParam.toLowerCase().equals("success")) { |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 431 | colorCode = "#00FF00" |
| 432 | colorName = "green" |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 433 | } else if (buildStatusParam.toLowerCase().equals("unstable")) { |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 434 | colorCode = "#FFFF00" |
| 435 | colorName = "yellow" |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 436 | } else if (buildStatusParam.toLowerCase().equals("failure")) { |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 437 | colorCode = "#FF0000" |
| 438 | colorName = "red" |
| 439 | } |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 440 | if (_needNotification(notificatedTypes, buildStatusParam.toLowerCase(), jobNameParam)) { |
| 441 | if (enabledNotifications.contains("slack") && jenkinsHasPlugin("slack")) { |
| 442 | try { |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 443 | slackSend color: colorCode, message: summary |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 444 | } catch (Exception e) { |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 445 | println("Calling slack plugin failed") |
| 446 | e.printStackTrace() |
| 447 | } |
| 448 | } |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 449 | if (enabledNotifications.contains("hipchat") && jenkinsHasPlugin("hipchat")) { |
| 450 | try { |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 451 | hipchatSend color: colorName.toUpperCase(), message: summary |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 452 | } catch (Exception e) { |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 453 | println("Calling hipchat plugin failed") |
| 454 | e.printStackTrace() |
| 455 | } |
| 456 | } |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 457 | if (enabledNotifications.contains("email") && mailTo != null && mailTo != "" && mailFrom != null && mailFrom != "") { |
| 458 | try { |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 459 | mail body: summary, from: mailFrom, subject: subject, to: mailTo |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 460 | } catch (Exception e) { |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 461 | println("Sending mail plugin failed") |
| 462 | e.printStackTrace() |
| 463 | } |
| 464 | } |
| 465 | } |
Filip Pytloun | 49d6630 | 2017-03-06 10:26:22 +0100 | [diff] [blame] | 466 | } |
chnyda | 4e5ac79 | 2017-03-14 15:24:18 +0100 | [diff] [blame] | 467 | |
| 468 | /** |
| 469 | * Execute linux command and catch nth element |
| 470 | * @param cmd command to execute |
| 471 | * @param index index to retrieve |
| 472 | * @return index-th element |
| 473 | */ |
| 474 | |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 475 | def cutOrDie(cmd, index) { |
chnyda | 4e5ac79 | 2017-03-14 15:24:18 +0100 | [diff] [blame] | 476 | def common = new com.mirantis.mk.Common() |
| 477 | def output |
| 478 | try { |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 479 | output = sh(script: cmd, returnStdout: true) |
| 480 | def result = output.tokenize(" ")[index] |
| 481 | return result; |
chnyda | 4e5ac79 | 2017-03-14 15:24:18 +0100 | [diff] [blame] | 482 | } catch (Exception e) { |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 483 | common.errorMsg("Failed to execute cmd: ${cmd}\n output: ${output}") |
chnyda | 4e5ac79 | 2017-03-14 15:24:18 +0100 | [diff] [blame] | 484 | } |
Filip Pytloun | 81c864d | 2017-03-21 15:19:30 +0100 | [diff] [blame] | 485 | } |
Tomáš Kukrál | 767dd73 | 2017-03-23 10:38:59 +0100 | [diff] [blame] | 486 | |
| 487 | /** |
| 488 | * Check variable contains keyword |
| 489 | * @param variable keywork is searched (contains) here |
| 490 | * @param keyword string to look for |
| 491 | * @return True if variable contains keyword (case insensitive), False if do not contains or any of input isn't a string |
| 492 | */ |
| 493 | |
| 494 | def checkContains(variable, keyword) { |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 495 | if (env.getEnvironment().containsKey(variable)) { |
Jakub Josef | 7a8dea2 | 2017-03-23 19:51:32 +0100 | [diff] [blame] | 496 | return env[variable] && env[variable].toLowerCase().contains(keyword.toLowerCase()) |
Tomáš Kukrál | 767dd73 | 2017-03-23 10:38:59 +0100 | [diff] [blame] | 497 | } else { |
Tomáš Kukrál | c76c1e0 | 2017-03-23 19:06:59 +0100 | [diff] [blame] | 498 | return false |
Tomáš Kukrál | 767dd73 | 2017-03-23 10:38:59 +0100 | [diff] [blame] | 499 | } |
| 500 | } |
Jakub Josef | a877db5 | 2017-04-05 14:22:30 +0200 | [diff] [blame] | 501 | |
| 502 | /** |
| 503 | * Parse JSON string to hashmap |
| 504 | * @param jsonString input JSON string |
| 505 | * @return created hashmap |
| 506 | */ |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 507 | def parseJSON(jsonString) { |
| 508 | def m = [:] |
| 509 | def lazyMap = new JsonSlurperClassic().parseText(jsonString) |
| 510 | m.putAll(lazyMap) |
| 511 | return m |
Jakub Josef | a877db5 | 2017-04-05 14:22:30 +0200 | [diff] [blame] | 512 | } |
Jakub Josef | ed239cd | 2017-05-09 15:27:33 +0200 | [diff] [blame] | 513 | |
| 514 | /** |
Vasyl Saienko | 79d6f3b | 2018-10-19 09:13:46 +0300 | [diff] [blame] | 515 | * |
| 516 | * Deep merge of Map items. Merges variable number of maps in to onto. |
| 517 | * Using the following rules: |
| 518 | * - Lists are appended |
| 519 | * - Maps are updated |
| 520 | * - other object types are replaced. |
| 521 | * |
| 522 | * |
| 523 | * @param onto Map object to merge in |
| 524 | * @param overrides Map objects to merge to onto |
| 525 | */ |
| 526 | def mergeMaps(Map onto, Map... overrides){ |
| 527 | if (!overrides){ |
| 528 | return onto |
| 529 | } |
| 530 | else if (overrides.length == 1) { |
| 531 | overrides[0]?.each { k, v -> |
Vasyl Saienko | f92cf4f | 2019-07-10 12:39:25 +0300 | [diff] [blame] | 532 | if (k in onto.keySet()) { |
| 533 | if (v in Map && onto[k] in Map){ |
| 534 | mergeMaps((Map) onto[k], (Map) v) |
| 535 | } else if (v in List) { |
| 536 | onto[k] += v |
| 537 | } else { |
| 538 | onto[k] = v |
| 539 | } |
Vasyl Saienko | 79d6f3b | 2018-10-19 09:13:46 +0300 | [diff] [blame] | 540 | } else { |
| 541 | onto[k] = v |
| 542 | } |
| 543 | } |
| 544 | return onto |
| 545 | } |
| 546 | return overrides.inject(onto, { acc, override -> mergeMaps(acc, override ?: [:]) }) |
| 547 | } |
| 548 | |
| 549 | /** |
Jakub Josef | ed239cd | 2017-05-09 15:27:33 +0200 | [diff] [blame] | 550 | * Test pipeline input parameter existence and validity (not null and not empty string) |
| 551 | * @param paramName input parameter name (usually uppercase) |
azvyagintsev | c8ecdfd | 2018-09-11 12:47:15 +0300 | [diff] [blame] | 552 | */ |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 553 | def validInputParam(paramName) { |
azvyagintsev | c8ecdfd | 2018-09-11 12:47:15 +0300 | [diff] [blame] | 554 | if (paramName instanceof java.lang.String) { |
| 555 | return env.getEnvironment().containsKey(paramName) && env[paramName] != null && env[paramName] != "" |
| 556 | } |
| 557 | return false |
Tomáš Kukrál | d34fe87 | 2017-06-13 10:50:50 +0200 | [diff] [blame] | 558 | } |
| 559 | |
| 560 | /** |
| 561 | * Take list of hashmaps and count number of hashmaps with parameter equals eq |
| 562 | * @param lm list of hashmaps |
| 563 | * @param param define parameter of hashmap to read and compare |
| 564 | * @param eq desired value of hashmap parameter |
| 565 | * @return count of hashmaps meeting defined condition |
| 566 | */ |
| 567 | |
| 568 | @NonCPS |
| 569 | def countHashMapEquals(lm, param, eq) { |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 570 | return lm.stream().filter { i -> i[param].equals(eq) }.collect(java.util.stream.Collectors.counting()) |
Tomáš Kukrál | d34fe87 | 2017-06-13 10:50:50 +0200 | [diff] [blame] | 571 | } |
Vasyl Saienko | fb055b1 | 2017-11-23 18:15:23 +0200 | [diff] [blame] | 572 | |
| 573 | /** |
| 574 | * Execute shell command and return stdout, stderr and status |
| 575 | * |
| 576 | * @param cmd Command to execute |
| 577 | * @return map with stdout, stderr, status keys |
| 578 | */ |
| 579 | |
| 580 | def shCmdStatus(cmd) { |
azvyagintsev | 386e94e | 2019-06-13 13:39:04 +0300 | [diff] [blame] | 581 | // Set +x , to hide odd messages about temp file manipulations |
Vasyl Saienko | fb055b1 | 2017-11-23 18:15:23 +0200 | [diff] [blame] | 582 | def res = [:] |
azvyagintsev | 386e94e | 2019-06-13 13:39:04 +0300 | [diff] [blame] | 583 | def stderr = sh(script: 'set +x ; mktemp', returnStdout: true).trim() |
| 584 | def stdout = sh(script: 'set +x ; mktemp', returnStdout: true).trim() |
Vasyl Saienko | fb055b1 | 2017-11-23 18:15:23 +0200 | [diff] [blame] | 585 | |
| 586 | try { |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 587 | def status = sh(script: "${cmd} 1>${stdout} 2>${stderr}", returnStatus: true) |
azvyagintsev | 386e94e | 2019-06-13 13:39:04 +0300 | [diff] [blame] | 588 | res['stderr'] = sh(script: "set +x; cat ${stderr}", returnStdout: true).trim() |
| 589 | res['stdout'] = sh(script: "set +x; cat ${stdout}", returnStdout: true).trim() |
Vasyl Saienko | fb055b1 | 2017-11-23 18:15:23 +0200 | [diff] [blame] | 590 | res['status'] = status |
| 591 | } finally { |
azvyagintsev | 386e94e | 2019-06-13 13:39:04 +0300 | [diff] [blame] | 592 | sh(script: "set +x; rm ${stderr}") |
| 593 | sh(script: "set +x; rm ${stdout}") |
Vasyl Saienko | fb055b1 | 2017-11-23 18:15:23 +0200 | [diff] [blame] | 594 | } |
| 595 | |
| 596 | return res |
| 597 | } |
Richard Felkl | 66a242d | 2018-01-25 15:27:15 +0100 | [diff] [blame] | 598 | |
Richard Felkl | 66a242d | 2018-01-25 15:27:15 +0100 | [diff] [blame] | 599 | /** |
| 600 | * Retry commands passed to body |
| 601 | * |
Martin Polreich | 331f2b6 | 2019-02-08 10:16:52 +0100 | [diff] [blame] | 602 | * Don't use common.retry method for retrying salt.enforceState method. Use retries parameter |
| 603 | * built-in the salt.enforceState method instead to ensure correct functionality. |
| 604 | * |
Richard Felkl | 66a242d | 2018-01-25 15:27:15 +0100 | [diff] [blame] | 605 | * @param times Number of retries |
Jakub Josef | 61463c7 | 2018-02-13 16:10:56 +0100 | [diff] [blame] | 606 | * @param delay Delay between retries (in seconds) |
Richard Felkl | 66a242d | 2018-01-25 15:27:15 +0100 | [diff] [blame] | 607 | * @param body Commands to be in retry block |
| 608 | * @return calling commands in body |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 609 | * @example retry ( 3 , 5 ) { function body }* retry{ function body } |
Richard Felkl | 66a242d | 2018-01-25 15:27:15 +0100 | [diff] [blame] | 610 | */ |
| 611 | |
| 612 | def retry(int times = 5, int delay = 0, Closure body) { |
| 613 | int retries = 0 |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 614 | while (retries++ < times) { |
Richard Felkl | 66a242d | 2018-01-25 15:27:15 +0100 | [diff] [blame] | 615 | try { |
| 616 | return body.call() |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 617 | } catch (e) { |
Denis Egorenko | 900a3af | 2019-01-14 12:54:56 +0400 | [diff] [blame] | 618 | errorMsg(e.toString()) |
Richard Felkl | 66a242d | 2018-01-25 15:27:15 +0100 | [diff] [blame] | 619 | sleep(delay) |
| 620 | } |
| 621 | } |
Richard Felkl | 66a242d | 2018-01-25 15:27:15 +0100 | [diff] [blame] | 622 | throw new Exception("Failed after $times retries") |
| 623 | } |
Dmitry Pyzhov | 0d0d852 | 2018-05-15 22:37:37 +0300 | [diff] [blame] | 624 | |
Dmitry Pyzhov | 0d0d852 | 2018-05-15 22:37:37 +0300 | [diff] [blame] | 625 | /** |
| 626 | * Wait for user input with timeout |
| 627 | * |
| 628 | * @param timeoutInSeconds Timeout |
| 629 | * @param options Options for input widget |
| 630 | */ |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 631 | def waitForInputThenPass(timeoutInSeconds, options = [message: 'Ready to go?']) { |
| 632 | def userInput = true |
| 633 | try { |
| 634 | timeout(time: timeoutInSeconds, unit: 'SECONDS') { |
| 635 | userInput = input options |
| 636 | } |
| 637 | } catch (err) { // timeout reached or input false |
| 638 | def user = err.getCauses()[0].getUser() |
| 639 | if ('SYSTEM' == user.toString()) { // SYSTEM means timeout. |
| 640 | println("Timeout, proceeding") |
| 641 | } else { |
| 642 | userInput = false |
| 643 | println("Aborted by: [${user}]") |
| 644 | throw err |
| 645 | } |
Dmitry Pyzhov | 0d0d852 | 2018-05-15 22:37:37 +0300 | [diff] [blame] | 646 | } |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 647 | return userInput |
Dmitry Pyzhov | 0d0d852 | 2018-05-15 22:37:37 +0300 | [diff] [blame] | 648 | } |
Oleksii Grudev | 9e1d97a | 2018-06-29 16:04:30 +0300 | [diff] [blame] | 649 | |
| 650 | /** |
| 651 | * Function receives Map variable as input and sorts it |
| 652 | * by values ascending. Returns sorted Map |
| 653 | * @param _map Map variable |
| 654 | */ |
| 655 | @NonCPS |
| 656 | def SortMapByValueAsc(_map) { |
azvyagintsev | 6bda942 | 2018-08-20 11:57:05 +0300 | [diff] [blame] | 657 | def sortedMap = _map.sort { it.value } |
Oleksii Grudev | 9e1d97a | 2018-06-29 16:04:30 +0300 | [diff] [blame] | 658 | return sortedMap |
| 659 | } |
azvyagintsev | 99d3584 | 2018-08-17 20:26:34 +0300 | [diff] [blame] | 660 | |
| 661 | /** |
| 662 | * Compare 'old' and 'new' dir's recursively |
| 663 | * @param diffData =' Only in new/XXX/infra: secrets.yml |
| 664 | Files old/XXX/init.yml and new/XXX/init.yml differ |
| 665 | Only in old/XXX/infra: secrets11.yml ' |
| 666 | * |
| 667 | * @return |
| 668 | * - new: |
| 669 | - XXX/secrets.yml |
| 670 | - diff: |
| 671 | - XXX/init.yml |
| 672 | - removed: |
| 673 | - XXX/secrets11.yml |
| 674 | |
| 675 | */ |
| 676 | def diffCheckMultidir(diffData) { |
azvyagintsev | ab5637b | 2018-08-20 18:18:15 +0300 | [diff] [blame] | 677 | common = new com.mirantis.mk.Common() |
| 678 | // Some global constants. Don't change\move them! |
| 679 | keyNew = 'new' |
| 680 | keyRemoved = 'removed' |
| 681 | keyDiff = 'diff' |
| 682 | def output = [ |
| 683 | new : [], |
| 684 | removed: [], |
| 685 | diff : [], |
| 686 | ] |
| 687 | String pathSep = '/' |
| 688 | diffData.each { line -> |
| 689 | def job_file = '' |
| 690 | def job_type = '' |
| 691 | if (line.startsWith('Files old/')) { |
| 692 | job_file = new File(line.replace('Files old/', '').tokenize()[0]) |
| 693 | job_type = keyDiff |
| 694 | } else if (line.startsWith('Only in new/')) { |
| 695 | // get clean normalized filepath, under new/ |
| 696 | job_file = new File(line.replace('Only in new/', '').replace(': ', pathSep)).toString() |
| 697 | job_type = keyNew |
| 698 | } else if (line.startsWith('Only in old/')) { |
| 699 | // get clean normalized filepath, under old/ |
| 700 | job_file = new File(line.replace('Only in old/', '').replace(': ', pathSep)).toString() |
| 701 | job_type = keyRemoved |
| 702 | } else { |
| 703 | common.warningMsg("Not parsed diff line: ${line}!") |
| 704 | } |
| 705 | if (job_file != '') { |
| 706 | output[job_type].push(job_file) |
| 707 | } |
azvyagintsev | 99d3584 | 2018-08-17 20:26:34 +0300 | [diff] [blame] | 708 | } |
azvyagintsev | ab5637b | 2018-08-20 18:18:15 +0300 | [diff] [blame] | 709 | return output |
azvyagintsev | 99d3584 | 2018-08-17 20:26:34 +0300 | [diff] [blame] | 710 | } |
| 711 | |
| 712 | /** |
| 713 | * Compare 2 folder, file by file |
| 714 | * Structure should be: |
| 715 | * ${compRoot}/ |
| 716 | └── diff - diff results will be save here |
| 717 | ├── new - input folder with data |
| 718 | ├── old - input folder with data |
| 719 | ├── pillar.diff - globall diff will be saved here |
| 720 | * b_url - usual env.BUILD_URL, to be add into description |
azvyagintsev | 3bbcafe | 2018-08-20 19:36:16 +0300 | [diff] [blame] | 721 | * grepOpts - General grep cmdline; Could be used to pass some magic |
| 722 | * regexp into after-diff listing file(pillar.diff) |
| 723 | * Example: '-Ev infra/secrets.yml' |
azvyagintsev | 99d3584 | 2018-08-17 20:26:34 +0300 | [diff] [blame] | 724 | * return - html-based string |
| 725 | * TODO: allow to specify subdir for results? |
azvyagintsev | 99d3584 | 2018-08-17 20:26:34 +0300 | [diff] [blame] | 726 | **/ |
Denis Egorenko | 4551f37 | 2018-09-11 16:36:13 +0400 | [diff] [blame] | 727 | |
azvyagintsev | 3bbcafe | 2018-08-20 19:36:16 +0300 | [diff] [blame] | 728 | def comparePillars(compRoot, b_url, grepOpts) { |
Aleksey Zvyagintsev | b20bd26 | 2018-10-05 15:09:06 +0000 | [diff] [blame] | 729 | |
azvyagintsev | ab5637b | 2018-08-20 18:18:15 +0300 | [diff] [blame] | 730 | // Some global constants. Don't change\move them! |
| 731 | keyNew = 'new' |
| 732 | keyRemoved = 'removed' |
| 733 | keyDiff = 'diff' |
| 734 | def diff_status = 0 |
| 735 | // FIXME |
| 736 | httpWS = b_url + '/artifact/' |
| 737 | dir(compRoot) { |
azvyagintsev | 3bbcafe | 2018-08-20 19:36:16 +0300 | [diff] [blame] | 738 | // If diff empty - exit 0 |
| 739 | diff_status = sh(script: 'diff -q -r old/ new/ > pillar.diff', |
azvyagintsev | ab5637b | 2018-08-20 18:18:15 +0300 | [diff] [blame] | 740 | returnStatus: true, |
| 741 | ) |
azvyagintsev | 24d4965 | 2018-08-21 19:33:51 +0300 | [diff] [blame] | 742 | } |
azvyagintsev | c0fe144 | 2018-08-21 20:01:34 +0300 | [diff] [blame] | 743 | // Unfortunately, diff not able to work with dir-based regexp |
| 744 | if (diff_status == 1 && grepOpts) { |
| 745 | dir(compRoot) { |
| 746 | grep_status = sh(script: """ |
azvyagintsev | 3bbcafe | 2018-08-20 19:36:16 +0300 | [diff] [blame] | 747 | cp -v pillar.diff pillar_orig.diff |
| 748 | grep ${grepOpts} pillar_orig.diff > pillar.diff |
| 749 | """, |
azvyagintsev | c0fe144 | 2018-08-21 20:01:34 +0300 | [diff] [blame] | 750 | returnStatus: true |
| 751 | ) |
azvyagintsev | f6e7791 | 2018-09-07 15:41:09 +0300 | [diff] [blame] | 752 | if (grep_status == 1) { |
Aleksey Zvyagintsev | b20bd26 | 2018-10-05 15:09:06 +0000 | [diff] [blame] | 753 | warningMsg("Grep regexp ${grepOpts} removed all diff!") |
azvyagintsev | c0fe144 | 2018-08-21 20:01:34 +0300 | [diff] [blame] | 754 | diff_status = 0 |
azvyagintsev | b99f87c | 2018-08-21 19:43:59 +0300 | [diff] [blame] | 755 | } |
azvyagintsev | 3bbcafe | 2018-08-20 19:36:16 +0300 | [diff] [blame] | 756 | } |
azvyagintsev | c0fe144 | 2018-08-21 20:01:34 +0300 | [diff] [blame] | 757 | } |
| 758 | // Set job description |
Denis Egorenko | 4551f37 | 2018-09-11 16:36:13 +0400 | [diff] [blame] | 759 | description = '' |
azvyagintsev | c0fe144 | 2018-08-21 20:01:34 +0300 | [diff] [blame] | 760 | if (diff_status == 1) { |
azvyagintsev | ab5637b | 2018-08-20 18:18:15 +0300 | [diff] [blame] | 761 | // Analyse output file and prepare array with results |
| 762 | String data_ = readFile file: "${compRoot}/pillar.diff" |
| 763 | def diff_list = diffCheckMultidir(data_.split("\\r?\\n")) |
Aleksey Zvyagintsev | b20bd26 | 2018-10-05 15:09:06 +0000 | [diff] [blame] | 764 | infoMsg(diff_list) |
azvyagintsev | ab5637b | 2018-08-20 18:18:15 +0300 | [diff] [blame] | 765 | dir(compRoot) { |
| 766 | if (diff_list[keyDiff].size() > 0) { |
| 767 | if (!fileExists('diff')) { |
| 768 | sh('mkdir -p diff') |
| 769 | } |
| 770 | description += '<b>CHANGED</b><ul>' |
Aleksey Zvyagintsev | b20bd26 | 2018-10-05 15:09:06 +0000 | [diff] [blame] | 771 | infoMsg('Changed items:') |
Denis Egorenko | 4551f37 | 2018-09-11 16:36:13 +0400 | [diff] [blame] | 772 | def stepsForParallel = [:] |
| 773 | stepsForParallel.failFast = true |
| 774 | diff_list[keyDiff].each { |
| 775 | stepsForParallel.put("Differ for:${it}", |
| 776 | { |
| 777 | // We don't want to handle sub-dirs structure. So, simply make diff 'flat' |
| 778 | def item_f = it.toString().replace('/', '_') |
| 779 | description += "<li><a href=\"${httpWS}/diff/${item_f}/*view*/\">${it}</a></li>" |
| 780 | // Generate diff file |
| 781 | def diff_exit_code = sh([ |
| 782 | script : "diff -U 50 old/${it} new/${it} > diff/${item_f}", |
| 783 | returnStdout: false, |
| 784 | returnStatus: true, |
| 785 | ]) |
| 786 | // catch normal errors, diff should always return 1 |
| 787 | if (diff_exit_code != 1) { |
| 788 | error 'Error with diff file generation' |
| 789 | } |
| 790 | }) |
azvyagintsev | ab5637b | 2018-08-20 18:18:15 +0300 | [diff] [blame] | 791 | } |
Denis Egorenko | 4551f37 | 2018-09-11 16:36:13 +0400 | [diff] [blame] | 792 | |
| 793 | parallel stepsForParallel |
azvyagintsev | ab5637b | 2018-08-20 18:18:15 +0300 | [diff] [blame] | 794 | } |
| 795 | if (diff_list[keyNew].size() > 0) { |
| 796 | description += '<b>ADDED</b><ul>' |
| 797 | for (item in diff_list[keyNew]) { |
| 798 | description += "<li><a href=\"${httpWS}/new/${item}/*view*/\">${item}</a></li>" |
| 799 | } |
| 800 | } |
| 801 | if (diff_list[keyRemoved].size() > 0) { |
| 802 | description += '<b>DELETED</b><ul>' |
| 803 | for (item in diff_list[keyRemoved]) { |
| 804 | description += "<li><a href=\"${httpWS}/old/${item}/*view*/\">${item}</a></li>" |
| 805 | } |
| 806 | } |
Denis Egorenko | 6212096 | 2019-03-15 11:24:32 +0400 | [diff] [blame] | 807 | def cwd = sh(script: 'basename $(pwd)', returnStdout: true).trim() |
| 808 | sh "tar -cf old_${cwd}.tar.gz old/ && rm -rf old/" |
| 809 | sh "tar -cf new_${cwd}.tar.gz new/ && rm -rf new/" |
azvyagintsev | ab5637b | 2018-08-20 18:18:15 +0300 | [diff] [blame] | 810 | } |
azvyagintsev | 99d3584 | 2018-08-17 20:26:34 +0300 | [diff] [blame] | 811 | } |
azvyagintsev | ab5637b | 2018-08-20 18:18:15 +0300 | [diff] [blame] | 812 | |
| 813 | if (description != '') { |
| 814 | dir(compRoot) { |
| 815 | archiveArtifacts([ |
| 816 | artifacts : '**', |
| 817 | allowEmptyArchive: true, |
| 818 | ]) |
| 819 | } |
| 820 | return description.toString() |
| 821 | } else { |
azvyagintsev | a57c82a | 2018-09-20 12:17:24 +0300 | [diff] [blame] | 822 | return '<b>No job changes</b>' |
azvyagintsev | ab5637b | 2018-08-20 18:18:15 +0300 | [diff] [blame] | 823 | } |
azvyagintsev | 99d3584 | 2018-08-17 20:26:34 +0300 | [diff] [blame] | 824 | } |
azvyagintsev | ab5637b | 2018-08-20 18:18:15 +0300 | [diff] [blame] | 825 | |
| 826 | /** |
| 827 | * Simple function, to get basename from string. |
| 828 | * line - path-string |
| 829 | * remove_ext - string, optionl. Drop file extenstion. |
| 830 | **/ |
| 831 | def GetBaseName(line, remove_ext) { |
| 832 | filename = line.toString().split('/').last() |
| 833 | if (remove_ext && filename.endsWith(remove_ext.toString())) { |
| 834 | filename = filename.take(filename.lastIndexOf(remove_ext.toString())) |
| 835 | } |
| 836 | return filename |
Vasyl Saienko | 00ef98b | 2018-09-05 10:34:32 +0300 | [diff] [blame] | 837 | } |
Vasyl Saienko | 723cbbc | 2018-09-05 11:08:52 +0300 | [diff] [blame] | 838 | |
| 839 | /** |
azvyagintsev | f6e7791 | 2018-09-07 15:41:09 +0300 | [diff] [blame] | 840 | * Return colored string of specific stage in stageMap |
| 841 | * |
| 842 | * @param stageMap LinkedHashMap object. |
| 843 | * @param stageName The name of current stage we are going to execute. |
| 844 | * @param color Text color |
| 845 | * */ |
| 846 | def getColoredStageView(stageMap, stageName, color) { |
| 847 | def stage = stageMap[stageName] |
| 848 | def banner = [] |
| 849 | def currentStageIndex = new ArrayList<String>(stageMap.keySet()).indexOf(stageName) |
| 850 | def numberOfStages = stageMap.keySet().size() - 1 |
Vasyl Saienko | 723cbbc | 2018-09-05 11:08:52 +0300 | [diff] [blame] | 851 | |
Vasyl Saienko | 723cbbc | 2018-09-05 11:08:52 +0300 | [diff] [blame] | 852 | banner.add(getColorizedString( |
azvyagintsev | f6e7791 | 2018-09-07 15:41:09 +0300 | [diff] [blame] | 853 | "=========== Stage ${currentStageIndex}/${numberOfStages}: ${stageName} ===========", color)) |
| 854 | for (stage_item in stage.keySet()) { |
| 855 | banner.add(getColorizedString( |
| 856 | "${stage_item}: ${stage[stage_item]}", color)) |
Vasyl Saienko | 723cbbc | 2018-09-05 11:08:52 +0300 | [diff] [blame] | 857 | } |
azvyagintsev | f6e7791 | 2018-09-07 15:41:09 +0300 | [diff] [blame] | 858 | banner.add('\n') |
| 859 | |
| 860 | return banner |
| 861 | } |
| 862 | |
| 863 | /** |
| 864 | * Pring stageMap to console with specified color |
| 865 | * |
| 866 | * @param stageMap LinkedHashMap object with stages information. |
| 867 | * @param currentStage The name of current stage we are going to execute. |
| 868 | * |
| 869 | * */ |
| 870 | def printCurrentStage(stageMap, currentStage) { |
| 871 | print getColoredStageView(stageMap, currentStage, "cyan").join('\n') |
| 872 | } |
| 873 | |
| 874 | /** |
| 875 | * Pring stageMap to console with specified color |
| 876 | * |
| 877 | * @param stageMap LinkedHashMap object. |
| 878 | * @param baseColor Text color (default white) |
| 879 | * */ |
| 880 | def printStageMap(stageMap, baseColor = "white") { |
| 881 | def banner = [] |
| 882 | def index = 0 |
| 883 | for (stage_name in stageMap.keySet()) { |
| 884 | banner.addAll(getColoredStageView(stageMap, stage_name, baseColor)) |
| 885 | } |
| 886 | print banner.join('\n') |
| 887 | } |
| 888 | |
| 889 | /** |
| 890 | * Wrap provided code in stage, and do interactive retires if needed. |
| 891 | * |
| 892 | * @param stageMap LinkedHashMap object with stages information. |
| 893 | * @param currentStage The name of current stage we are going to execute. |
| 894 | * @param target Target host to execute stage on. |
| 895 | * @param interactive Boolean flag to specify if interaction with user is enabled. |
| 896 | * @param body Command to be in stage block. |
| 897 | * */ |
| 898 | def stageWrapper(stageMap, currentStage, target, interactive = true, Closure body) { |
| 899 | def common = new com.mirantis.mk.Common() |
| 900 | def banner = [] |
| 901 | |
| 902 | printCurrentStage(stageMap, currentStage) |
| 903 | |
| 904 | stage(currentStage) { |
Vasyl Saienko | bc6debb | 2018-09-10 14:08:09 +0300 | [diff] [blame] | 905 | if (interactive){ |
azvyagintsev | f6e7791 | 2018-09-07 15:41:09 +0300 | [diff] [blame] | 906 | input message: getColorizedString("We are going to execute stage \'${currentStage}\' on the following target ${target}.\nPlease review stage information above.", "yellow") |
Vasyl Saienko | bc6debb | 2018-09-10 14:08:09 +0300 | [diff] [blame] | 907 | } |
| 908 | try { |
Vasyl Saienko | bc6debb | 2018-09-10 14:08:09 +0300 | [diff] [blame] | 909 | stageMap[currentStage]['Status'] = "SUCCESS" |
Victor Ryzhenkin | 49d6781 | 2019-01-09 15:28:21 +0400 | [diff] [blame] | 910 | return body.call() |
Vasyl Saienko | bc6debb | 2018-09-10 14:08:09 +0300 | [diff] [blame] | 911 | } catch (Exception err) { |
| 912 | def msg = "Stage ${currentStage} failed with the following exception:\n${err}" |
| 913 | print getColorizedString(msg, "yellow") |
| 914 | common.errorMsg(err) |
| 915 | if (interactive) { |
| 916 | input message: getColorizedString("Please make sure problem is fixed to proceed with retry. Ready to proceed?", "yellow") |
| 917 | stageMap[currentStage]['Status'] = "RETRYING" |
| 918 | stageWrapper(stageMap, currentStage, target, interactive, body) |
| 919 | } else { |
| 920 | error(msg) |
azvyagintsev | f6e7791 | 2018-09-07 15:41:09 +0300 | [diff] [blame] | 921 | } |
Vasyl Saienko | bc6debb | 2018-09-10 14:08:09 +0300 | [diff] [blame] | 922 | } |
azvyagintsev | f6e7791 | 2018-09-07 15:41:09 +0300 | [diff] [blame] | 923 | } |
| 924 | } |
| 925 | |
| 926 | /** |
| 927 | * Ugly transition solution for internal tests. |
| 928 | * 1) Check input => transform to static result, based on runtime and input |
| 929 | * 2) Check remote-binary repo for exact resource |
azvyagintsev | f6fce3d | 2018-12-28 15:30:33 +0200 | [diff] [blame] | 930 | * Return: changes each linux_system_* cto false, in case broken url in some of them |
| 931 | */ |
azvyagintsev | f6e7791 | 2018-09-07 15:41:09 +0300 | [diff] [blame] | 932 | |
| 933 | def checkRemoteBinary(LinkedHashMap config, List extraScmExtensions = []) { |
| 934 | def common = new com.mirantis.mk.Common() |
azvyagintsev | f6fce3d | 2018-12-28 15:30:33 +0200 | [diff] [blame] | 935 | def res = [:] |
azvyagintsev | f6e7791 | 2018-09-07 15:41:09 +0300 | [diff] [blame] | 936 | res['MirrorRoot'] = config.get('globalMirrorRoot', env["BIN_MIRROR_ROOT"] ? env["BIN_MIRROR_ROOT"] : "http://mirror.mirantis.com/") |
| 937 | // Reclass-like format's. To make life eazy! |
azvyagintsev | 603d95b | 2018-11-09 15:37:10 +0200 | [diff] [blame] | 938 | res['mcp_version'] = config.get('mcp_version', env["BIN_APT_MCP_VERSION"] ? env["BIN_APT_MCP_VERSION"] : 'nightly') |
azvyagintsev | f6fce3d | 2018-12-28 15:30:33 +0200 | [diff] [blame] | 939 | res['linux_system_repo_url'] = config.get('linux_system_repo_url', env['BIN_linux_system_repo_url'] ? env['BIN_linux_system_repo_url'] : "${res['MirrorRoot']}/${res['mcp_version']}/") |
| 940 | res['linux_system_repo_ubuntu_url'] = config.get('linux_system_repo_ubuntu_url', env['BIN_linux_system_repo_ubuntu_url'] ? env['BIN_linux_system_repo_ubuntu_url'] : "${res['MirrorRoot']}/${res['mcp_version']}/ubuntu/") |
| 941 | res['linux_system_repo_mcp_salt_url'] = config.get('linux_system_repo_mcp_salt_url', env['BIN_linux_system_repo_mcp_salt_url'] ? env['BIN_linux_system_repo_mcp_salt_url'] : "${res['MirrorRoot']}/${res['mcp_version']}/salt-formulas/") |
azvyagintsev | f6e7791 | 2018-09-07 15:41:09 +0300 | [diff] [blame] | 942 | |
| 943 | if (config.get('verify', true)) { |
azvyagintsev | f6fce3d | 2018-12-28 15:30:33 +0200 | [diff] [blame] | 944 | res.each { key, val -> |
| 945 | if (key.toString().startsWith('linux_system_repo')) { |
| 946 | def MirrorRootStatus = sh(script: "wget --auth-no-challenge --spider ${val} 2>/dev/null", returnStatus: true) |
| 947 | if (MirrorRootStatus != 0) { |
| 948 | common.warningMsg("Resource: '${key}' at '${val}' not exist!") |
| 949 | res[key] = false |
| 950 | } |
| 951 | } |
azvyagintsev | f6e7791 | 2018-09-07 15:41:09 +0300 | [diff] [blame] | 952 | } |
| 953 | } |
| 954 | return res |
Vasyl Saienko | 723cbbc | 2018-09-05 11:08:52 +0300 | [diff] [blame] | 955 | } |
Denis Egorenko | eded0d4 | 2018-09-26 13:25:49 +0400 | [diff] [blame] | 956 | |
| 957 | /** |
| 958 | * Workaround to update env properties, like GERRIT_* vars, |
| 959 | * which should be passed from upstream job to downstream. |
| 960 | * Will not fail entire job in case any issues. |
| 961 | * @param envVar - EnvActionImpl env job |
| 962 | * @param extraVars - Multiline YAML text with extra vars |
| 963 | */ |
| 964 | def mergeEnv(envVar, extraVars) { |
| 965 | try { |
| 966 | def extraParams = readYaml text: extraVars |
| 967 | for(String key in extraParams.keySet()) { |
| 968 | envVar[key] = extraParams[key] |
Dmitry Teselkin | 4badf83 | 2020-05-27 17:48:36 +0300 | [diff] [blame] | 969 | println("INFO: Parameter ${key} is updated from EXTRA vars.") |
Denis Egorenko | eded0d4 | 2018-09-26 13:25:49 +0400 | [diff] [blame] | 970 | } |
| 971 | } catch (Exception e) { |
Dmitry Teselkin | 4badf83 | 2020-05-27 17:48:36 +0300 | [diff] [blame] | 972 | println("ERR: Can't update env parameteres, because: ${e.toString()}") |
Denis Egorenko | eded0d4 | 2018-09-26 13:25:49 +0400 | [diff] [blame] | 973 | } |
| 974 | } |
Denis Egorenko | 599bd63 | 2018-09-28 15:24:37 +0400 | [diff] [blame] | 975 | |
azvyagintsev | 898e174 | 2020-05-12 12:40:44 +0300 | [diff] [blame] | 976 | def setMapDefaults(Object base, Object defaults, Boolean recursive = false) { |
| 977 | /** |
| 978 | * Function to update dict with params, if its not set yet |
| 979 | * Will not fail entire job in case any issues. |
| 980 | * Those function will not overwrite current options if already passed. |
| 981 | * @param base - dict |
| 982 | * @param defaults - dict |
| 983 | */ |
| 984 | if (base instanceof Map && defaults instanceof Map) { |
| 985 | defaults.inject(base) { result, key, value -> |
| 986 | if (result.containsKey(key)) { |
| 987 | setMapDefaults(result[key], value, recursive = true) |
| 988 | } else { |
| 989 | result.put(key, value) |
| 990 | } |
| 991 | return result |
| 992 | } |
| 993 | } else if (!recursive) { |
| 994 | echo("Can't update map parameters, wrong input data, skipping") |
| 995 | } |
| 996 | } |
| 997 | |
Dmitry Teselkin | 4badf83 | 2020-05-27 17:48:36 +0300 | [diff] [blame] | 998 | def setEnvDefaults(Object envVar, Object defaults) { |
| 999 | /** |
| 1000 | * Function to set default values of an environment variables object |
| 1001 | * at runtime(patches existing 'env' instance). |
| 1002 | * @param env - instance of either EnvActionImpl |
| 1003 | * @param defaults - Map with default values |
| 1004 | * Example: setEnvDefaults(env, ['ENV_NAME': 'newENV_NAME', 'newvar': 'newval']) |
| 1005 | * */ |
| 1006 | |
| 1007 | if (!(envVar instanceof EnvActionImpl)) { |
| 1008 | error("setEnvDefaults 'env' is not an instance of EnvActionImpl") |
| 1009 | } else if (!(defaults instanceof Map)) { |
| 1010 | error("setEnvDefaults 'defaults' is not a Map") |
| 1011 | } |
| 1012 | defaults.each { key, value -> |
| 1013 | if (envVar.getEnvironment().containsKey(key)) { |
| 1014 | println("INFO:setEnvDefaults env variable ${key} already exist, not overwriting") |
| 1015 | } else { |
| 1016 | envVar[key] = value |
| 1017 | println("INFO:setEnvDefaults env variable ${key} has been added") |
| 1018 | } |
| 1019 | } |
| 1020 | } |
azvyagintsev | 898e174 | 2020-05-12 12:40:44 +0300 | [diff] [blame] | 1021 | |
Denis Egorenko | 599bd63 | 2018-09-28 15:24:37 +0400 | [diff] [blame] | 1022 | /** |
| 1023 | * Wrapper around parallel pipeline function |
| 1024 | * with ability to restrict number of parallel threads |
| 1025 | * running simultaneously |
| 1026 | * |
| 1027 | * @param branches - Map with Clousers to be executed |
| 1028 | * @param maxParallelJob - Integer number of parallel threads allowed |
| 1029 | * to run simultaneously |
| 1030 | */ |
| 1031 | def runParallel(branches, maxParallelJob = 10) { |
| 1032 | def runningSteps = 0 |
| 1033 | branches.each { branchName, branchBody -> |
| 1034 | if (branchBody instanceof Closure) { |
| 1035 | branches[branchName] = { |
| 1036 | while (!(runningSteps < maxParallelJob)) { |
| 1037 | continue |
| 1038 | } |
| 1039 | runningSteps += 1 |
| 1040 | branchBody.call() |
| 1041 | runningSteps -= 1 |
| 1042 | } |
| 1043 | } |
| 1044 | } |
| 1045 | if (branches) { |
| 1046 | parallel branches |
| 1047 | } |
| 1048 | } |
Aleksey Zvyagintsev | b20bd26 | 2018-10-05 15:09:06 +0000 | [diff] [blame] | 1049 | |
| 1050 | /** |
| 1051 | * Ugly processing basic funcs with /etc/apt |
Denis Egorenko | 5cea141 | 2018-10-18 16:40:11 +0400 | [diff] [blame] | 1052 | * @param repoConfig YAML text or Map |
Aleksey Zvyagintsev | b20bd26 | 2018-10-05 15:09:06 +0000 | [diff] [blame] | 1053 | * Example : |
Denis Egorenko | 5cea141 | 2018-10-18 16:40:11 +0400 | [diff] [blame] | 1054 | repoConfig = ''' |
Aleksey Zvyagintsev | b20bd26 | 2018-10-05 15:09:06 +0000 | [diff] [blame] | 1055 | --- |
Aleksey Zvyagintsev | b20bd26 | 2018-10-05 15:09:06 +0000 | [diff] [blame] | 1056 | aprConfD: |- |
Denis Egorenko | e02a1b2 | 2018-10-19 17:47:53 +0400 | [diff] [blame] | 1057 | APT::Get::AllowUnauthenticated 'true'; |
Aleksey Zvyagintsev | b20bd26 | 2018-10-05 15:09:06 +0000 | [diff] [blame] | 1058 | repo: |
Denis Egorenko | e02a1b2 | 2018-10-19 17:47:53 +0400 | [diff] [blame] | 1059 | mcp_saltstack: |
| 1060 | source: "deb [arch=amd64] http://mirror.mirantis.com/nightly/saltstack-2017.7/xenial xenial main" |
| 1061 | pin: |
| 1062 | - package: "libsodium18" |
| 1063 | pin: "release o=SaltStack" |
| 1064 | priority: 50 |
| 1065 | - package: "*" |
| 1066 | pin: "release o=SaltStack" |
| 1067 | priority: "1100" |
| 1068 | repo_key: "http://mirror.mirantis.com/public.gpg" |
Aleksey Zvyagintsev | b20bd26 | 2018-10-05 15:09:06 +0000 | [diff] [blame] | 1069 | ''' |
| 1070 | * |
| 1071 | */ |
| 1072 | |
Denis Egorenko | 5cea141 | 2018-10-18 16:40:11 +0400 | [diff] [blame] | 1073 | def debianExtraRepos(repoConfig) { |
| 1074 | def config = null |
| 1075 | if (repoConfig instanceof Map) { |
| 1076 | config = repoConfig |
| 1077 | } else { |
| 1078 | config = readYaml text: repoConfig |
| 1079 | } |
Aleksey Zvyagintsev | b20bd26 | 2018-10-05 15:09:06 +0000 | [diff] [blame] | 1080 | if (config.get('repo', false)) { |
| 1081 | for (String repo in config['repo'].keySet()) { |
Denis Egorenko | 395aa21 | 2018-10-11 15:11:28 +0400 | [diff] [blame] | 1082 | source = config['repo'][repo]['source'] |
Aleksey Zvyagintsev | b20bd26 | 2018-10-05 15:09:06 +0000 | [diff] [blame] | 1083 | warningMsg("Write ${source} > /etc/apt/sources.list.d/${repo}.list") |
| 1084 | sh("echo '${source}' > /etc/apt/sources.list.d/${repo}.list") |
Denis Egorenko | 395aa21 | 2018-10-11 15:11:28 +0400 | [diff] [blame] | 1085 | if (config['repo'][repo].containsKey('repo_key')) { |
| 1086 | key = config['repo'][repo]['repo_key'] |
| 1087 | sh("wget -O - '${key}' | apt-key add -") |
| 1088 | } |
Denis Egorenko | e02a1b2 | 2018-10-19 17:47:53 +0400 | [diff] [blame] | 1089 | if (config['repo'][repo]['pin']) { |
| 1090 | def repoPins = [] |
| 1091 | for (Map pin in config['repo'][repo]['pin']) { |
| 1092 | repoPins.add("Package: ${pin['package']}") |
| 1093 | repoPins.add("Pin: ${pin['pin']}") |
| 1094 | repoPins.add("Pin-Priority: ${pin['priority']}") |
Denis Egorenko | 1c93d12 | 2018-11-02 12:14:05 +0400 | [diff] [blame] | 1095 | // additional empty line between pins |
| 1096 | repoPins.add('\n') |
Denis Egorenko | e02a1b2 | 2018-10-19 17:47:53 +0400 | [diff] [blame] | 1097 | } |
| 1098 | if (repoPins) { |
| 1099 | repoPins.add(0, "### Extra ${repo} repo pin start ###") |
| 1100 | repoPins.add("### Extra ${repo} repo pin end ###") |
| 1101 | repoPinning = repoPins.join('\n') |
| 1102 | warningMsg("Adding pinning \n${repoPinning}\n => /etc/apt/preferences.d/${repo}") |
| 1103 | sh("echo '${repoPinning}' > /etc/apt/preferences.d/${repo}") |
| 1104 | } |
| 1105 | } |
Aleksey Zvyagintsev | b20bd26 | 2018-10-05 15:09:06 +0000 | [diff] [blame] | 1106 | } |
| 1107 | } |
| 1108 | if (config.get('aprConfD', false)) { |
| 1109 | for (String pref in config['aprConfD'].tokenize('\n')) { |
| 1110 | warningMsg("Adding ${pref} => /etc/apt/apt.conf.d/99setupAndTestNode") |
| 1111 | sh("echo '${pref}' >> /etc/apt/apt.conf.d/99setupAndTestNode") |
| 1112 | } |
| 1113 | sh('cat /etc/apt/apt.conf.d/99setupAndTestNode') |
| 1114 | } |
| 1115 | } |
Denis Egorenko | eaf78db | 2019-02-06 17:01:38 +0400 | [diff] [blame] | 1116 | |
| 1117 | /** |
| 1118 | * Parse date from string |
| 1119 | * @param String date - date to parse |
| 1120 | * @param String format - date format in provided date string value |
| 1121 | * |
| 1122 | * return new Date() object |
| 1123 | */ |
| 1124 | Date parseDate(String date, String format) { |
| 1125 | return Date.parse(format, date) |
| 1126 | } |
Denis Egorenko | 815758d | 2019-07-08 15:54:08 +0400 | [diff] [blame] | 1127 | |
| 1128 | /** |
| 1129 | * Generate Random Hash string |
| 1130 | * @param n Hash length |
| 1131 | * @param pool Pool to use for hash generation |
| 1132 | */ |
| 1133 | def generateRandomHashString(int n, ArrayList pool = []) { |
| 1134 | if (!pool) { |
| 1135 | pool = ['a'..'z','A'..'Z',0..9,'_','+','='].flatten() |
| 1136 | } |
| 1137 | Random rand = new Random(System.currentTimeMillis()) |
| 1138 | return (1..n).collect { pool[rand.nextInt(pool.size())] }.join() |
| 1139 | } |
Mykyta Karpin | 70cd333 | 2019-09-16 18:31:03 +0300 | [diff] [blame] | 1140 | |
| 1141 | /** |
| 1142 | * Checks whether string is semver complaint version |
| 1143 | * @param string version |
| 1144 | */ |
| 1145 | |
| 1146 | def isSemVer(version){ |
| 1147 | // Official regex for Semver2 (https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string) |
| 1148 | String semVerRegex = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/ |
| 1149 | return version ==~ semVerRegex |
azvyagintsev | 898e174 | 2020-05-12 12:40:44 +0300 | [diff] [blame] | 1150 | } |
azvyagintsev | d987eb6 | 2020-06-19 15:19:05 +0300 | [diff] [blame] | 1151 | |
| 1152 | def readYaml2(LinkedHashMap kwargs) { |
| 1153 | /** |
| 1154 | * readYaml wrapper to workaround case when initial file contains |
| 1155 | * yaml data in text field so we need parse it twice. |
| 1156 | * * @param file String of filename to read |
| 1157 | * * @param text String to be read as Yaml |
| 1158 | * Parameters are mutually exclusive |
| 1159 | */ |
| 1160 | if ((kwargs.get('file') && kwargs.get('text'))) { |
| 1161 | error('readYaml2 function not able to cover both ["file","text"] opts in same time ') |
| 1162 | } |
| 1163 | if (kwargs.get('file')) { |
| 1164 | data = readYaml(file: kwargs['file']) |
| 1165 | if (data instanceof String) { |
| 1166 | return readYaml(text: data) |
| 1167 | } |
azvyagintsev | 255cadd | 2020-06-22 14:50:33 +0300 | [diff] [blame] | 1168 | return data |
azvyagintsev | d987eb6 | 2020-06-19 15:19:05 +0300 | [diff] [blame] | 1169 | } else if (kwargs.get('text')) { |
| 1170 | return readYaml(text: kwargs['text']) |
| 1171 | } |
azvyagintsev | 255cadd | 2020-06-22 14:50:33 +0300 | [diff] [blame] | 1172 | } |
Dmitry Teselkin | bd57dee | 2020-09-23 13:05:59 +0300 | [diff] [blame] | 1173 | |
| 1174 | /** |
| 1175 | * withTempDir runs a block of code inside a new temporary directory. |
| 1176 | * This temp dir will be removed when finished. |
| 1177 | * @param: closure Closure - code block to be executed in a tmp directory |
| 1178 | * |
| 1179 | * Example: |
| 1180 | * |
| 1181 | * withTempDir { |
| 1182 | * sh "pwd" |
| 1183 | * } |
| 1184 | * |
| 1185 | **/ |
| 1186 | void withTempDir(Closure closure) { |
| 1187 | dir(pwd(tmp: true)) { |
| 1188 | try { |
| 1189 | closure() |
| 1190 | } finally { |
| 1191 | deleteDir() |
| 1192 | } |
| 1193 | } |
| 1194 | } |
Alexandr Lovtsov | 9c1c93a | 2021-02-23 14:54:37 +0300 | [diff] [blame^] | 1195 | |
| 1196 | /** |
| 1197 | * Save metadata about results in yaml formatted file |
| 1198 | * @param success (boolean) answer the question "was it success or not?" |
| 1199 | * @param code (string) some generalized code to determine error |
| 1200 | * @param msg (string) user-friendly message about what's happend (error?) |
| 1201 | * @param extraMeta (map) additional data can be added to resulted yaml file trhoug this map |
| 1202 | * @param dstFile (string) name of yaml file to store the data |
| 1203 | */ |
| 1204 | def saveMetaResult(Boolean success, String code, String msg, Map extraMeta = [:], String dstFile = 'result.yaml') { |
| 1205 | Map result = extraMeta.clone() |
| 1206 | result.putAll([ |
| 1207 | 'success': success, |
| 1208 | 'code': code, |
| 1209 | 'message': msg, |
| 1210 | ]) |
| 1211 | writeYaml file: dstFile, data: result, overwrite: true |
| 1212 | archiveArtifacts artifacts: dstFile |
| 1213 | } |