blob: b5760dae65f53e2571da9722d790e7d5a7df18ba [file] [log] [blame]
Jakub Josef79ecec32017-02-17 14:36:28 +01001package com.mirantis.mk
Jakub Josef6d8082b2017-08-09 12:40:50 +02002
Jakub Josefb41c8d52017-03-24 13:52:24 +01003import static groovy.json.JsonOutput.prettyPrint
4import static groovy.json.JsonOutput.toJson
Jakub Josef6d8082b2017-08-09 12:40:50 +02005
Jakub Josefbceaa322017-06-13 18:28:27 +02006import com.cloudbees.groovy.cps.NonCPS
Jakub Josefb7ab8472017-04-05 14:56:53 +02007import groovy.json.JsonSlurperClassic
azvyagintsev6bda9422018-08-20 11:57:05 +03008
Jakub Josef79ecec32017-02-17 14:36:28 +01009/**
10 *
11 * Common functions
12 *
13 */
14
15/**
16 * Generate current timestamp
17 *
azvyagintsev6bda9422018-08-20 11:57:05 +030018 * @param format Defaults to yyyyMMddHHmmss
Jakub Josef79ecec32017-02-17 14:36:28 +010019 */
azvyagintsev6bda9422018-08-20 11:57:05 +030020def getDatetime(format = "yyyyMMddHHmmss") {
Jakub Josef79ecec32017-02-17 14:36:28 +010021 def now = new Date();
22 return now.format(format, TimeZone.getTimeZone('UTC'));
23}
24
25/**
Jakub Josef79ecec32017-02-17 14:36:28 +010026 * Return workspace.
27 * Currently implemented by calling pwd so it won't return relevant result in
28 * dir context
29 */
azvyagintsev6bda9422018-08-20 11:57:05 +030030def getWorkspace(includeBuildNum = false) {
Jakub Josef79ecec32017-02-17 14:36:28 +010031 def workspace = sh script: 'pwd', returnStdout: true
32 workspace = workspace.trim()
azvyagintsev6bda9422018-08-20 11:57:05 +030033 if (includeBuildNum) {
34 if (!workspace.endsWith("/")) {
35 workspace += "/"
36 }
37 workspace += env.BUILD_NUMBER
Jakub Josefa661b8c2018-01-17 14:51:25 +010038 }
Jakub Josef79ecec32017-02-17 14:36:28 +010039 return workspace
40}
41
42/**
Filip Pytloun81c864d2017-03-21 15:19:30 +010043 * Get UID of jenkins user.
44 * Must be run from context of node
45 */
46def getJenkinsUid() {
azvyagintsev6bda9422018-08-20 11:57:05 +030047 return sh(
Filip Pytloun81c864d2017-03-21 15:19:30 +010048 script: 'id -u',
49 returnStdout: true
50 ).trim()
51}
52
53/**
54 * Get GID of jenkins user.
55 * Must be run from context of node
56 */
57def getJenkinsGid() {
azvyagintsev6bda9422018-08-20 11:57:05 +030058 return sh(
Filip Pytloun81c864d2017-03-21 15:19:30 +010059 script: 'id -g',
60 returnStdout: true
61 ).trim()
62}
63
64/**
Jakub Josefc8074db2018-01-30 13:33:20 +010065 * Returns Jenkins user uid and gid in one list (in that order)
66 * Must be run from context of node
67 */
azvyagintsev6bda9422018-08-20 11:57:05 +030068def getJenkinsUserIds() {
Jakub Josefc8074db2018-01-30 13:33:20 +010069 return sh(script: "id -u && id -g", returnStdout: true).tokenize("\n")
70}
71
72/**
Alexander Evseevbc1fea42017-12-13 10:03:03 +010073 *
74 * Find credentials by ID
75 *
azvyagintsev6bda9422018-08-20 11:57:05 +030076 * @param credsId Credentials ID
77 * @param credsType Credentials type (optional)
Alexander Evseevbc1fea42017-12-13 10:03:03 +010078 *
79 */
80def getCredentialsById(String credsId, String credsType = 'any') {
81 def credClasses = [ // ordered by class name
azvyagintsev6bda9422018-08-20 11:57:05 +030082 sshKey : com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey.class,
83 cert : com.cloudbees.plugins.credentials.common.CertificateCredentials.class,
84 password : com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials.class,
85 any : com.cloudbees.plugins.credentials.impl.BaseStandardCredentials.class,
86 dockerCert: org.jenkinsci.plugins.docker.commons.credentials.DockerServerCredentials.class,
87 file : org.jenkinsci.plugins.plaincredentials.FileCredentials.class,
88 string : org.jenkinsci.plugins.plaincredentials.StringCredentials.class,
Alexander Evseevbc1fea42017-12-13 10:03:03 +010089 ]
90 return com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
91 credClasses[credsType],
92 jenkins.model.Jenkins.instance
azvyagintsev6bda9422018-08-20 11:57:05 +030093 ).findAll { cred -> cred.id == credsId }[0]
Alexander Evseevbc1fea42017-12-13 10:03:03 +010094}
95
96/**
Jakub Josef79ecec32017-02-17 14:36:28 +010097 * Get credentials from store
98 *
azvyagintsev6bda9422018-08-20 11:57:05 +030099 * @param id Credentials name
Jakub Josef79ecec32017-02-17 14:36:28 +0100100 */
Jakub Josef3d9d9ab2017-03-14 15:09:03 +0100101def getCredentials(id, cred_type = "username_password") {
Alexander Evseevbc1fea42017-12-13 10:03:03 +0100102 warningMsg('You are using obsolete function. Please switch to use `getCredentialsById()`')
Jakub Josef79ecec32017-02-17 14:36:28 +0100103
Alexander Evseevbc1fea42017-12-13 10:03:03 +0100104 type_map = [
105 username_password: 'password',
azvyagintsev6bda9422018-08-20 11:57:05 +0300106 key : 'sshKey',
Alexander Evseevbc1fea42017-12-13 10:03:03 +0100107 ]
Jakub Josef79ecec32017-02-17 14:36:28 +0100108
Alexander Evseevbc1fea42017-12-13 10:03:03 +0100109 return getCredentialsById(id, type_map[cred_type])
Jakub Josef79ecec32017-02-17 14:36:28 +0100110}
111
112/**
113 * Abort build, wait for some time and ensure we will terminate
114 */
115def abortBuild() {
116 currentBuild.build().doStop()
117 sleep(180)
118 // just to be sure we will terminate
119 throw new InterruptedException()
120}
121
122/**
Jakub Josefbceaa322017-06-13 18:28:27 +0200123 * Print pretty-printed string representation of given item
124 * @param item item to be pretty-printed (list, map, whatever)
125 */
azvyagintsev6bda9422018-08-20 11:57:05 +0300126def prettyPrint(item) {
Jakub Josefbceaa322017-06-13 18:28:27 +0200127 println prettify(item)
128}
129
130/**
Jakub Josefb41c8d52017-03-24 13:52:24 +0100131 * Return pretty-printed string representation of given item
132 * @param item item to be pretty-printed (list, map, whatever)
133 * @return pretty-printed string
134 */
azvyagintsev6bda9422018-08-20 11:57:05 +0300135def prettify(item) {
Jakub Josefbceaa322017-06-13 18:28:27 +0200136 return groovy.json.JsonOutput.prettyPrint(toJson(item)).replace('\\n', System.getProperty('line.separator'))
Jakub Josefb41c8d52017-03-24 13:52:24 +0100137}
138
139/**
Jakub Josef79ecec32017-02-17 14:36:28 +0100140 * Print informational message
141 *
142 * @param msg
143 * @param color Colorful output or not
144 */
145def infoMsg(msg, color = true) {
146 printMsg(msg, "cyan")
147}
148
149/**
150 * Print error message
151 *
152 * @param msg
153 * @param color Colorful output or not
154 */
155def errorMsg(msg, color = true) {
156 printMsg(msg, "red")
157}
158
159/**
160 * Print success message
161 *
162 * @param msg
163 * @param color Colorful output or not
164 */
165def successMsg(msg, color = true) {
166 printMsg(msg, "green")
167}
168
169/**
170 * Print warning message
171 *
172 * @param msg
173 * @param color Colorful output or not
174 */
175def warningMsg(msg, color = true) {
Jakub Josef0e7bd632017-03-16 16:25:05 +0100176 printMsg(msg, "yellow")
Jakub Josef79ecec32017-02-17 14:36:28 +0100177}
178
179/**
Jakub Josef952ae0b2017-03-14 19:04:21 +0100180 * Print debug message, this message will show only if DEBUG global variable is present
181 * @param msg
182 * @param color Colorful output or not
183 */
azvyagintsev6bda9422018-08-20 11:57:05 +0300184def debugMsg(msg, color = true) {
Jakub Josef9a836ac2017-04-24 12:26:02 +0200185 // if debug property exists on env, debug is enabled
azvyagintsev6bda9422018-08-20 11:57:05 +0300186 if (env.getEnvironment().containsKey('DEBUG') && env['DEBUG'] == "true") {
Jakub Josef74b34692017-03-15 12:10:57 +0100187 printMsg("[DEBUG] ${msg}", "red")
Jakub Josef952ae0b2017-03-14 19:04:21 +0100188 }
189}
190
azvyagintsevf6e77912018-09-07 15:41:09 +0300191def getColorizedString(msg, color) {
192 def colorMap = [
193 'red' : '\u001B[31m',
194 'black' : '\u001B[30m',
195 'green' : '\u001B[32m',
196 'yellow': '\u001B[33m',
197 'blue' : '\u001B[34m',
198 'purple': '\u001B[35m',
199 'cyan' : '\u001B[36m',
200 'white' : '\u001B[37m',
201 'reset' : '\u001B[0m'
202 ]
Vasyl Saienko00ef98b2018-09-05 10:34:32 +0300203
azvyagintsevf6e77912018-09-07 15:41:09 +0300204 return "${colorMap[color]}${msg}${colorMap.reset}"
Vasyl Saienko00ef98b2018-09-05 10:34:32 +0300205}
206
Jakub Josef952ae0b2017-03-14 19:04:21 +0100207/**
Jakub Josef79ecec32017-02-17 14:36:28 +0100208 * Print message
209 *
azvyagintsev6bda9422018-08-20 11:57:05 +0300210 * @param msg Message to be printed
Vasyl Saienko00ef98b2018-09-05 10:34:32 +0300211 * @param color Color to use for output
Jakub Josef79ecec32017-02-17 14:36:28 +0100212 */
Vasyl Saienko00ef98b2018-09-05 10:34:32 +0300213def printMsg(msg, color) {
214 print getColorizedString(msg, color)
Jakub Josef79ecec32017-02-17 14:36:28 +0100215}
216
217/**
218 * Traverse directory structure and return list of files
219 *
220 * @param path Path to search
221 * @param type Type of files to search (groovy.io.FileType.FILES)
222 */
223@NonCPS
azvyagintsev6bda9422018-08-20 11:57:05 +0300224def getFiles(path, type = groovy.io.FileType.FILES) {
Jakub Josef79ecec32017-02-17 14:36:28 +0100225 files = []
226 new File(path).eachFile(type) {
227 files[] = it
228 }
229 return files
230}
231
232/**
233 * Helper method to convert map into form of list of [key,value] to avoid
234 * unserializable exceptions
235 *
236 * @param m Map
237 */
238@NonCPS
239def entries(m) {
azvyagintsev6bda9422018-08-20 11:57:05 +0300240 m.collect { k, v -> [k, v] }
Jakub Josef79ecec32017-02-17 14:36:28 +0100241}
242
243/**
244 * Opposite of build-in parallel, run map of steps in serial
245 *
Jakub Josef7fb8bbd2017-05-15 16:02:44 +0200246 * @param steps Map of String<name>: CPSClosure2<step> (or list of closures)
Jakub Josef79ecec32017-02-17 14:36:28 +0100247 */
248def serial(steps) {
249 stepsArray = entries(steps)
azvyagintsev6bda9422018-08-20 11:57:05 +0300250 for (i = 0; i < stepsArray.size; i++) {
Jakub Josefd31de302017-05-15 13:59:18 +0200251 def step = stepsArray[i]
Jakub Josef7fb8bbd2017-05-15 16:02:44 +0200252 def dummySteps = [:]
253 def stepKey
azvyagintsev6bda9422018-08-20 11:57:05 +0300254 if (step[1] instanceof List || step[1] instanceof Map) {
255 for (j = 0; j < step[1].size(); j++) {
256 if (step[1] instanceof List) {
Jakub Josef7fb8bbd2017-05-15 16:02:44 +0200257 stepKey = j
azvyagintsev6bda9422018-08-20 11:57:05 +0300258 } else if (step[1] instanceof Map) {
Jakub Josef7fb8bbd2017-05-15 16:02:44 +0200259 stepKey = step[1].keySet()[j]
260 }
azvyagintsev6bda9422018-08-20 11:57:05 +0300261 dummySteps.put("step-${step[0]}-${stepKey}", step[1][stepKey])
Jakub Josefd31de302017-05-15 13:59:18 +0200262 }
azvyagintsev6bda9422018-08-20 11:57:05 +0300263 } else {
Jakub Josefd31de302017-05-15 13:59:18 +0200264 dummySteps.put(step[0], step[1])
265 }
Jakub Josef79ecec32017-02-17 14:36:28 +0100266 parallel dummySteps
267 }
268}
269
270/**
Jakub Josef7fb8bbd2017-05-15 16:02:44 +0200271 * Partition given list to list of small lists
272 * @param inputList input list
273 * @param partitionSize (partition size, optional, default 5)
274 */
azvyagintsev6bda9422018-08-20 11:57:05 +0300275def partitionList(inputList, partitionSize = 5) {
276 List<List<String>> partitions = new ArrayList<>();
277 for (int i = 0; i < inputList.size(); i += partitionSize) {
278 partitions.add(new ArrayList<String>(inputList.subList(i, Math.min(i + partitionSize, inputList.size()))));
279 }
280 return partitions
Jakub Josef7fb8bbd2017-05-15 16:02:44 +0200281}
282
283/**
Jakub Josef79ecec32017-02-17 14:36:28 +0100284 * Get password credentials from store
285 *
azvyagintsev6bda9422018-08-20 11:57:05 +0300286 * @param id Credentials name
Jakub Josef79ecec32017-02-17 14:36:28 +0100287 */
288def getPasswordCredentials(id) {
Alexander Evseevbc1fea42017-12-13 10:03:03 +0100289 return getCredentialsById(id, 'password')
Jakub Josef79ecec32017-02-17 14:36:28 +0100290}
291
292/**
293 * Get SSH credentials from store
294 *
azvyagintsev6bda9422018-08-20 11:57:05 +0300295 * @param id Credentials name
Jakub Josef79ecec32017-02-17 14:36:28 +0100296 */
297def getSshCredentials(id) {
Alexander Evseevbc1fea42017-12-13 10:03:03 +0100298 return getCredentialsById(id, 'sshKey')
Jakub Josef79ecec32017-02-17 14:36:28 +0100299}
Jakub Josef79ecec32017-02-17 14:36:28 +0100300
301/**
302 * Tests Jenkins instance for existence of plugin with given name
303 * @param pluginName plugin short name to test
304 * @return boolean result
305 */
306@NonCPS
azvyagintsev6bda9422018-08-20 11:57:05 +0300307def jenkinsHasPlugin(pluginName) {
308 return Jenkins.instance.pluginManager.plugins.collect { p -> p.shortName }.contains(pluginName)
Jakub Josef79ecec32017-02-17 14:36:28 +0100309}
310
311@NonCPS
312def _needNotification(notificatedTypes, buildStatus, jobName) {
azvyagintsev6bda9422018-08-20 11:57:05 +0300313 if (notificatedTypes && notificatedTypes.contains("onchange")) {
314 if (jobName) {
Jakub Josef79ecec32017-02-17 14:36:28 +0100315 def job = Jenkins.instance.getItem(jobName)
316 def numbuilds = job.builds.size()
azvyagintsev6bda9422018-08-20 11:57:05 +0300317 if (numbuilds > 0) {
Jakub Josef79ecec32017-02-17 14:36:28 +0100318 //actual build is first for some reasons, so last finished build is second
319 def lastBuild = job.builds[1]
azvyagintsev6bda9422018-08-20 11:57:05 +0300320 if (lastBuild) {
321 if (lastBuild.result.toString().toLowerCase().equals(buildStatus)) {
Jakub Josef79ecec32017-02-17 14:36:28 +0100322 println("Build status didn't changed since last build, not sending notifications")
323 return false;
324 }
325 }
326 }
327 }
azvyagintsev6bda9422018-08-20 11:57:05 +0300328 } else if (!notificatedTypes.contains(buildStatus)) {
Jakub Josef79ecec32017-02-17 14:36:28 +0100329 return false;
330 }
331 return true;
332}
333
334/**
335 * Send notification to all enabled notifications services
336 * @param buildStatus message type (success, warning, error), null means SUCCESSFUL
337 * @param msgText message text
338 * @param enabledNotifications list of enabled notification types, types: slack, hipchat, email, default empty
339 * @param notificatedTypes types of notifications will be sent, default onchange - notificate if current build result not equal last result;
340 * otherwise use - ["success","unstable","failed"]
341 * @param jobName optional job name param, if empty env.JOB_NAME will be used
Jakub Josefd0571152017-07-17 14:11:39 +0200342 * @param buildNumber build number param, if empty env.BUILD_NUM will be used
343 * @param buildUrl build url param, if empty env.BUILD_URL will be used
Jakub Josef79ecec32017-02-17 14:36:28 +0100344 * @param mailFrom mail FROM param, if empty "jenkins" will be used, it's mandatory for sending email notifications
Jakub Josefd0571152017-07-17 14:11:39 +0200345 * @param mailTo mail TO param, it's mandatory for sending email notifications, this option enable mail notification
Jakub Josef79ecec32017-02-17 14:36:28 +0100346 */
azvyagintsev6bda9422018-08-20 11:57:05 +0300347def sendNotification(buildStatus, msgText = "", enabledNotifications = [], notificatedTypes = ["onchange"], jobName = null, buildNumber = null, buildUrl = null, mailFrom = "jenkins", mailTo = null) {
Jakub Josef79ecec32017-02-17 14:36:28 +0100348 // Default values
349 def colorName = 'blue'
350 def colorCode = '#0000FF'
351 def buildStatusParam = buildStatus != null && buildStatus != "" ? buildStatus : "SUCCESS"
352 def jobNameParam = jobName != null && jobName != "" ? jobName : env.JOB_NAME
353 def buildNumberParam = buildNumber != null && buildNumber != "" ? buildNumber : env.BUILD_NUMBER
354 def buildUrlParam = buildUrl != null && buildUrl != "" ? buildUrl : env.BUILD_URL
355 def subject = "${buildStatusParam}: Job '${jobNameParam} [${buildNumberParam}]'"
356 def summary = "${subject} (${buildUrlParam})"
357
azvyagintsev6bda9422018-08-20 11:57:05 +0300358 if (msgText != null && msgText != "") {
359 summary += "\n${msgText}"
Jakub Josef79ecec32017-02-17 14:36:28 +0100360 }
azvyagintsev6bda9422018-08-20 11:57:05 +0300361 if (buildStatusParam.toLowerCase().equals("success")) {
Jakub Josef79ecec32017-02-17 14:36:28 +0100362 colorCode = "#00FF00"
363 colorName = "green"
azvyagintsev6bda9422018-08-20 11:57:05 +0300364 } else if (buildStatusParam.toLowerCase().equals("unstable")) {
Jakub Josef79ecec32017-02-17 14:36:28 +0100365 colorCode = "#FFFF00"
366 colorName = "yellow"
azvyagintsev6bda9422018-08-20 11:57:05 +0300367 } else if (buildStatusParam.toLowerCase().equals("failure")) {
Jakub Josef79ecec32017-02-17 14:36:28 +0100368 colorCode = "#FF0000"
369 colorName = "red"
370 }
azvyagintsev6bda9422018-08-20 11:57:05 +0300371 if (_needNotification(notificatedTypes, buildStatusParam.toLowerCase(), jobNameParam)) {
372 if (enabledNotifications.contains("slack") && jenkinsHasPlugin("slack")) {
373 try {
Jakub Josef79ecec32017-02-17 14:36:28 +0100374 slackSend color: colorCode, message: summary
azvyagintsev6bda9422018-08-20 11:57:05 +0300375 } catch (Exception e) {
Jakub Josef79ecec32017-02-17 14:36:28 +0100376 println("Calling slack plugin failed")
377 e.printStackTrace()
378 }
379 }
azvyagintsev6bda9422018-08-20 11:57:05 +0300380 if (enabledNotifications.contains("hipchat") && jenkinsHasPlugin("hipchat")) {
381 try {
Jakub Josef79ecec32017-02-17 14:36:28 +0100382 hipchatSend color: colorName.toUpperCase(), message: summary
azvyagintsev6bda9422018-08-20 11:57:05 +0300383 } catch (Exception e) {
Jakub Josef79ecec32017-02-17 14:36:28 +0100384 println("Calling hipchat plugin failed")
385 e.printStackTrace()
386 }
387 }
azvyagintsev6bda9422018-08-20 11:57:05 +0300388 if (enabledNotifications.contains("email") && mailTo != null && mailTo != "" && mailFrom != null && mailFrom != "") {
389 try {
Jakub Josef79ecec32017-02-17 14:36:28 +0100390 mail body: summary, from: mailFrom, subject: subject, to: mailTo
azvyagintsev6bda9422018-08-20 11:57:05 +0300391 } catch (Exception e) {
Jakub Josef79ecec32017-02-17 14:36:28 +0100392 println("Sending mail plugin failed")
393 e.printStackTrace()
394 }
395 }
396 }
Filip Pytloun49d66302017-03-06 10:26:22 +0100397}
chnyda4e5ac792017-03-14 15:24:18 +0100398
399/**
400 * Execute linux command and catch nth element
401 * @param cmd command to execute
402 * @param index index to retrieve
403 * @return index-th element
404 */
405
azvyagintsev6bda9422018-08-20 11:57:05 +0300406def cutOrDie(cmd, index) {
chnyda4e5ac792017-03-14 15:24:18 +0100407 def common = new com.mirantis.mk.Common()
408 def output
409 try {
azvyagintsev6bda9422018-08-20 11:57:05 +0300410 output = sh(script: cmd, returnStdout: true)
411 def result = output.tokenize(" ")[index]
412 return result;
chnyda4e5ac792017-03-14 15:24:18 +0100413 } catch (Exception e) {
azvyagintsev6bda9422018-08-20 11:57:05 +0300414 common.errorMsg("Failed to execute cmd: ${cmd}\n output: ${output}")
chnyda4e5ac792017-03-14 15:24:18 +0100415 }
Filip Pytloun81c864d2017-03-21 15:19:30 +0100416}
Tomáš Kukrál767dd732017-03-23 10:38:59 +0100417
418/**
419 * Check variable contains keyword
420 * @param variable keywork is searched (contains) here
421 * @param keyword string to look for
422 * @return True if variable contains keyword (case insensitive), False if do not contains or any of input isn't a string
423 */
424
425def checkContains(variable, keyword) {
azvyagintsev6bda9422018-08-20 11:57:05 +0300426 if (env.getEnvironment().containsKey(variable)) {
Jakub Josef7a8dea22017-03-23 19:51:32 +0100427 return env[variable] && env[variable].toLowerCase().contains(keyword.toLowerCase())
Tomáš Kukrál767dd732017-03-23 10:38:59 +0100428 } else {
Tomáš Kukrálc76c1e02017-03-23 19:06:59 +0100429 return false
Tomáš Kukrál767dd732017-03-23 10:38:59 +0100430 }
431}
Jakub Josefa877db52017-04-05 14:22:30 +0200432
433/**
434 * Parse JSON string to hashmap
435 * @param jsonString input JSON string
436 * @return created hashmap
437 */
azvyagintsev6bda9422018-08-20 11:57:05 +0300438def parseJSON(jsonString) {
439 def m = [:]
440 def lazyMap = new JsonSlurperClassic().parseText(jsonString)
441 m.putAll(lazyMap)
442 return m
Jakub Josefa877db52017-04-05 14:22:30 +0200443}
Jakub Josefed239cd2017-05-09 15:27:33 +0200444
445/**
Vasyl Saienko79d6f3b2018-10-19 09:13:46 +0300446 *
447 * Deep merge of Map items. Merges variable number of maps in to onto.
448 * Using the following rules:
449 * - Lists are appended
450 * - Maps are updated
451 * - other object types are replaced.
452 *
453 *
454 * @param onto Map object to merge in
455 * @param overrides Map objects to merge to onto
456*/
457def mergeMaps(Map onto, Map... overrides){
458 if (!overrides){
459 return onto
460 }
461 else if (overrides.length == 1) {
462 overrides[0]?.each { k, v ->
463 if (v in Map && onto[k] in Map){
464 mergeMaps((Map) onto[k], (Map) v)
465 } else if (v in List) {
466 onto[k] += v
467 } else {
468 onto[k] = v
469 }
470 }
471 return onto
472 }
473 return overrides.inject(onto, { acc, override -> mergeMaps(acc, override ?: [:]) })
474}
475
476/**
Jakub Josefed239cd2017-05-09 15:27:33 +0200477 * Test pipeline input parameter existence and validity (not null and not empty string)
478 * @param paramName input parameter name (usually uppercase)
azvyagintsevc8ecdfd2018-09-11 12:47:15 +0300479 */
azvyagintsev6bda9422018-08-20 11:57:05 +0300480def validInputParam(paramName) {
azvyagintsevc8ecdfd2018-09-11 12:47:15 +0300481 if (paramName instanceof java.lang.String) {
482 return env.getEnvironment().containsKey(paramName) && env[paramName] != null && env[paramName] != ""
483 }
484 return false
Tomáš Kukráld34fe872017-06-13 10:50:50 +0200485}
486
487/**
488 * Take list of hashmaps and count number of hashmaps with parameter equals eq
489 * @param lm list of hashmaps
490 * @param param define parameter of hashmap to read and compare
491 * @param eq desired value of hashmap parameter
492 * @return count of hashmaps meeting defined condition
493 */
494
495@NonCPS
496def countHashMapEquals(lm, param, eq) {
azvyagintsev6bda9422018-08-20 11:57:05 +0300497 return lm.stream().filter { i -> i[param].equals(eq) }.collect(java.util.stream.Collectors.counting())
Tomáš Kukráld34fe872017-06-13 10:50:50 +0200498}
Vasyl Saienkofb055b12017-11-23 18:15:23 +0200499
500/**
501 * Execute shell command and return stdout, stderr and status
502 *
503 * @param cmd Command to execute
504 * @return map with stdout, stderr, status keys
505 */
506
507def shCmdStatus(cmd) {
azvyagintsev386e94e2019-06-13 13:39:04 +0300508 // Set +x , to hide odd messages about temp file manipulations
Vasyl Saienkofb055b12017-11-23 18:15:23 +0200509 def res = [:]
azvyagintsev386e94e2019-06-13 13:39:04 +0300510 def stderr = sh(script: 'set +x ; mktemp', returnStdout: true).trim()
511 def stdout = sh(script: 'set +x ; mktemp', returnStdout: true).trim()
Vasyl Saienkofb055b12017-11-23 18:15:23 +0200512
513 try {
azvyagintsev6bda9422018-08-20 11:57:05 +0300514 def status = sh(script: "${cmd} 1>${stdout} 2>${stderr}", returnStatus: true)
azvyagintsev386e94e2019-06-13 13:39:04 +0300515 res['stderr'] = sh(script: "set +x; cat ${stderr}", returnStdout: true).trim()
516 res['stdout'] = sh(script: "set +x; cat ${stdout}", returnStdout: true).trim()
Vasyl Saienkofb055b12017-11-23 18:15:23 +0200517 res['status'] = status
518 } finally {
azvyagintsev386e94e2019-06-13 13:39:04 +0300519 sh(script: "set +x; rm ${stderr}")
520 sh(script: "set +x; rm ${stdout}")
Vasyl Saienkofb055b12017-11-23 18:15:23 +0200521 }
522
523 return res
524}
Richard Felkl66a242d2018-01-25 15:27:15 +0100525
Richard Felkl66a242d2018-01-25 15:27:15 +0100526/**
527 * Retry commands passed to body
528 *
Martin Polreich331f2b62019-02-08 10:16:52 +0100529 * Don't use common.retry method for retrying salt.enforceState method. Use retries parameter
530 * built-in the salt.enforceState method instead to ensure correct functionality.
531 *
Richard Felkl66a242d2018-01-25 15:27:15 +0100532 * @param times Number of retries
Jakub Josef61463c72018-02-13 16:10:56 +0100533 * @param delay Delay between retries (in seconds)
Richard Felkl66a242d2018-01-25 15:27:15 +0100534 * @param body Commands to be in retry block
535 * @return calling commands in body
azvyagintsev6bda9422018-08-20 11:57:05 +0300536 * @example retry ( 3 , 5 ) { function body }* retry{ function body }
Richard Felkl66a242d2018-01-25 15:27:15 +0100537 */
538
539def retry(int times = 5, int delay = 0, Closure body) {
540 int retries = 0
azvyagintsev6bda9422018-08-20 11:57:05 +0300541 while (retries++ < times) {
Richard Felkl66a242d2018-01-25 15:27:15 +0100542 try {
543 return body.call()
azvyagintsev6bda9422018-08-20 11:57:05 +0300544 } catch (e) {
Denis Egorenko900a3af2019-01-14 12:54:56 +0400545 errorMsg(e.toString())
Richard Felkl66a242d2018-01-25 15:27:15 +0100546 sleep(delay)
547 }
548 }
Richard Felkl66a242d2018-01-25 15:27:15 +0100549 throw new Exception("Failed after $times retries")
550}
Dmitry Pyzhov0d0d8522018-05-15 22:37:37 +0300551
Dmitry Pyzhov0d0d8522018-05-15 22:37:37 +0300552/**
553 * Wait for user input with timeout
554 *
555 * @param timeoutInSeconds Timeout
556 * @param options Options for input widget
557 */
azvyagintsev6bda9422018-08-20 11:57:05 +0300558def waitForInputThenPass(timeoutInSeconds, options = [message: 'Ready to go?']) {
559 def userInput = true
560 try {
561 timeout(time: timeoutInSeconds, unit: 'SECONDS') {
562 userInput = input options
563 }
564 } catch (err) { // timeout reached or input false
565 def user = err.getCauses()[0].getUser()
566 if ('SYSTEM' == user.toString()) { // SYSTEM means timeout.
567 println("Timeout, proceeding")
568 } else {
569 userInput = false
570 println("Aborted by: [${user}]")
571 throw err
572 }
Dmitry Pyzhov0d0d8522018-05-15 22:37:37 +0300573 }
azvyagintsev6bda9422018-08-20 11:57:05 +0300574 return userInput
Dmitry Pyzhov0d0d8522018-05-15 22:37:37 +0300575}
Oleksii Grudev9e1d97a2018-06-29 16:04:30 +0300576
577/**
578 * Function receives Map variable as input and sorts it
579 * by values ascending. Returns sorted Map
580 * @param _map Map variable
581 */
582@NonCPS
583def SortMapByValueAsc(_map) {
azvyagintsev6bda9422018-08-20 11:57:05 +0300584 def sortedMap = _map.sort { it.value }
Oleksii Grudev9e1d97a2018-06-29 16:04:30 +0300585 return sortedMap
586}
azvyagintsev99d35842018-08-17 20:26:34 +0300587
588/**
589 * Compare 'old' and 'new' dir's recursively
590 * @param diffData =' Only in new/XXX/infra: secrets.yml
591 Files old/XXX/init.yml and new/XXX/init.yml differ
592 Only in old/XXX/infra: secrets11.yml '
593 *
594 * @return
595 * - new:
596 - XXX/secrets.yml
597 - diff:
598 - XXX/init.yml
599 - removed:
600 - XXX/secrets11.yml
601
602 */
603def diffCheckMultidir(diffData) {
azvyagintsevab5637b2018-08-20 18:18:15 +0300604 common = new com.mirantis.mk.Common()
605 // Some global constants. Don't change\move them!
606 keyNew = 'new'
607 keyRemoved = 'removed'
608 keyDiff = 'diff'
609 def output = [
610 new : [],
611 removed: [],
612 diff : [],
613 ]
614 String pathSep = '/'
615 diffData.each { line ->
616 def job_file = ''
617 def job_type = ''
618 if (line.startsWith('Files old/')) {
619 job_file = new File(line.replace('Files old/', '').tokenize()[0])
620 job_type = keyDiff
621 } else if (line.startsWith('Only in new/')) {
622 // get clean normalized filepath, under new/
623 job_file = new File(line.replace('Only in new/', '').replace(': ', pathSep)).toString()
624 job_type = keyNew
625 } else if (line.startsWith('Only in old/')) {
626 // get clean normalized filepath, under old/
627 job_file = new File(line.replace('Only in old/', '').replace(': ', pathSep)).toString()
628 job_type = keyRemoved
629 } else {
630 common.warningMsg("Not parsed diff line: ${line}!")
631 }
632 if (job_file != '') {
633 output[job_type].push(job_file)
634 }
azvyagintsev99d35842018-08-17 20:26:34 +0300635 }
azvyagintsevab5637b2018-08-20 18:18:15 +0300636 return output
azvyagintsev99d35842018-08-17 20:26:34 +0300637}
638
639/**
640 * Compare 2 folder, file by file
641 * Structure should be:
642 * ${compRoot}/
643 └── diff - diff results will be save here
644 ├── new - input folder with data
645 ├── old - input folder with data
646 ├── pillar.diff - globall diff will be saved here
647 * b_url - usual env.BUILD_URL, to be add into description
azvyagintsev3bbcafe2018-08-20 19:36:16 +0300648 * grepOpts - General grep cmdline; Could be used to pass some magic
649 * regexp into after-diff listing file(pillar.diff)
650 * Example: '-Ev infra/secrets.yml'
azvyagintsev99d35842018-08-17 20:26:34 +0300651 * return - html-based string
652 * TODO: allow to specify subdir for results?
azvyagintsev99d35842018-08-17 20:26:34 +0300653 **/
Denis Egorenko4551f372018-09-11 16:36:13 +0400654
azvyagintsev3bbcafe2018-08-20 19:36:16 +0300655def comparePillars(compRoot, b_url, grepOpts) {
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000656
azvyagintsevab5637b2018-08-20 18:18:15 +0300657 // Some global constants. Don't change\move them!
658 keyNew = 'new'
659 keyRemoved = 'removed'
660 keyDiff = 'diff'
661 def diff_status = 0
662 // FIXME
663 httpWS = b_url + '/artifact/'
664 dir(compRoot) {
azvyagintsev3bbcafe2018-08-20 19:36:16 +0300665 // If diff empty - exit 0
666 diff_status = sh(script: 'diff -q -r old/ new/ > pillar.diff',
azvyagintsevab5637b2018-08-20 18:18:15 +0300667 returnStatus: true,
668 )
azvyagintsev24d49652018-08-21 19:33:51 +0300669 }
azvyagintsevc0fe1442018-08-21 20:01:34 +0300670 // Unfortunately, diff not able to work with dir-based regexp
671 if (diff_status == 1 && grepOpts) {
672 dir(compRoot) {
673 grep_status = sh(script: """
azvyagintsev3bbcafe2018-08-20 19:36:16 +0300674 cp -v pillar.diff pillar_orig.diff
675 grep ${grepOpts} pillar_orig.diff > pillar.diff
676 """,
azvyagintsevc0fe1442018-08-21 20:01:34 +0300677 returnStatus: true
678 )
azvyagintsevf6e77912018-09-07 15:41:09 +0300679 if (grep_status == 1) {
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000680 warningMsg("Grep regexp ${grepOpts} removed all diff!")
azvyagintsevc0fe1442018-08-21 20:01:34 +0300681 diff_status = 0
azvyagintsevb99f87c2018-08-21 19:43:59 +0300682 }
azvyagintsev3bbcafe2018-08-20 19:36:16 +0300683 }
azvyagintsevc0fe1442018-08-21 20:01:34 +0300684 }
685 // Set job description
Denis Egorenko4551f372018-09-11 16:36:13 +0400686 description = ''
azvyagintsevc0fe1442018-08-21 20:01:34 +0300687 if (diff_status == 1) {
azvyagintsevab5637b2018-08-20 18:18:15 +0300688 // Analyse output file and prepare array with results
689 String data_ = readFile file: "${compRoot}/pillar.diff"
690 def diff_list = diffCheckMultidir(data_.split("\\r?\\n"))
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000691 infoMsg(diff_list)
azvyagintsevab5637b2018-08-20 18:18:15 +0300692 dir(compRoot) {
693 if (diff_list[keyDiff].size() > 0) {
694 if (!fileExists('diff')) {
695 sh('mkdir -p diff')
696 }
697 description += '<b>CHANGED</b><ul>'
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000698 infoMsg('Changed items:')
Denis Egorenko4551f372018-09-11 16:36:13 +0400699 def stepsForParallel = [:]
700 stepsForParallel.failFast = true
701 diff_list[keyDiff].each {
702 stepsForParallel.put("Differ for:${it}",
703 {
704 // We don't want to handle sub-dirs structure. So, simply make diff 'flat'
705 def item_f = it.toString().replace('/', '_')
706 description += "<li><a href=\"${httpWS}/diff/${item_f}/*view*/\">${it}</a></li>"
707 // Generate diff file
708 def diff_exit_code = sh([
709 script : "diff -U 50 old/${it} new/${it} > diff/${item_f}",
710 returnStdout: false,
711 returnStatus: true,
712 ])
713 // catch normal errors, diff should always return 1
714 if (diff_exit_code != 1) {
715 error 'Error with diff file generation'
716 }
717 })
azvyagintsevab5637b2018-08-20 18:18:15 +0300718 }
Denis Egorenko4551f372018-09-11 16:36:13 +0400719
720 parallel stepsForParallel
azvyagintsevab5637b2018-08-20 18:18:15 +0300721 }
722 if (diff_list[keyNew].size() > 0) {
723 description += '<b>ADDED</b><ul>'
724 for (item in diff_list[keyNew]) {
725 description += "<li><a href=\"${httpWS}/new/${item}/*view*/\">${item}</a></li>"
726 }
727 }
728 if (diff_list[keyRemoved].size() > 0) {
729 description += '<b>DELETED</b><ul>'
730 for (item in diff_list[keyRemoved]) {
731 description += "<li><a href=\"${httpWS}/old/${item}/*view*/\">${item}</a></li>"
732 }
733 }
Denis Egorenko62120962019-03-15 11:24:32 +0400734 def cwd = sh(script: 'basename $(pwd)', returnStdout: true).trim()
735 sh "tar -cf old_${cwd}.tar.gz old/ && rm -rf old/"
736 sh "tar -cf new_${cwd}.tar.gz new/ && rm -rf new/"
azvyagintsevab5637b2018-08-20 18:18:15 +0300737 }
azvyagintsev99d35842018-08-17 20:26:34 +0300738 }
azvyagintsevab5637b2018-08-20 18:18:15 +0300739
740 if (description != '') {
741 dir(compRoot) {
742 archiveArtifacts([
743 artifacts : '**',
744 allowEmptyArchive: true,
745 ])
746 }
747 return description.toString()
748 } else {
azvyagintseva57c82a2018-09-20 12:17:24 +0300749 return '<b>No job changes</b>'
azvyagintsevab5637b2018-08-20 18:18:15 +0300750 }
azvyagintsev99d35842018-08-17 20:26:34 +0300751}
azvyagintsevab5637b2018-08-20 18:18:15 +0300752
753/**
754 * Simple function, to get basename from string.
755 * line - path-string
756 * remove_ext - string, optionl. Drop file extenstion.
757 **/
758def GetBaseName(line, remove_ext) {
759 filename = line.toString().split('/').last()
760 if (remove_ext && filename.endsWith(remove_ext.toString())) {
761 filename = filename.take(filename.lastIndexOf(remove_ext.toString()))
762 }
763 return filename
Vasyl Saienko00ef98b2018-09-05 10:34:32 +0300764}
Vasyl Saienko723cbbc2018-09-05 11:08:52 +0300765
766/**
azvyagintsevf6e77912018-09-07 15:41:09 +0300767 * Return colored string of specific stage in stageMap
768 *
769 * @param stageMap LinkedHashMap object.
770 * @param stageName The name of current stage we are going to execute.
771 * @param color Text color
772 * */
773def getColoredStageView(stageMap, stageName, color) {
774 def stage = stageMap[stageName]
775 def banner = []
776 def currentStageIndex = new ArrayList<String>(stageMap.keySet()).indexOf(stageName)
777 def numberOfStages = stageMap.keySet().size() - 1
Vasyl Saienko723cbbc2018-09-05 11:08:52 +0300778
Vasyl Saienko723cbbc2018-09-05 11:08:52 +0300779 banner.add(getColorizedString(
azvyagintsevf6e77912018-09-07 15:41:09 +0300780 "=========== Stage ${currentStageIndex}/${numberOfStages}: ${stageName} ===========", color))
781 for (stage_item in stage.keySet()) {
782 banner.add(getColorizedString(
783 "${stage_item}: ${stage[stage_item]}", color))
Vasyl Saienko723cbbc2018-09-05 11:08:52 +0300784 }
azvyagintsevf6e77912018-09-07 15:41:09 +0300785 banner.add('\n')
786
787 return banner
788}
789
790/**
791 * Pring stageMap to console with specified color
792 *
793 * @param stageMap LinkedHashMap object with stages information.
794 * @param currentStage The name of current stage we are going to execute.
795 *
796 * */
797def printCurrentStage(stageMap, currentStage) {
798 print getColoredStageView(stageMap, currentStage, "cyan").join('\n')
799}
800
801/**
802 * Pring stageMap to console with specified color
803 *
804 * @param stageMap LinkedHashMap object.
805 * @param baseColor Text color (default white)
806 * */
807def printStageMap(stageMap, baseColor = "white") {
808 def banner = []
809 def index = 0
810 for (stage_name in stageMap.keySet()) {
811 banner.addAll(getColoredStageView(stageMap, stage_name, baseColor))
812 }
813 print banner.join('\n')
814}
815
816/**
817 * Wrap provided code in stage, and do interactive retires if needed.
818 *
819 * @param stageMap LinkedHashMap object with stages information.
820 * @param currentStage The name of current stage we are going to execute.
821 * @param target Target host to execute stage on.
822 * @param interactive Boolean flag to specify if interaction with user is enabled.
823 * @param body Command to be in stage block.
824 * */
825def stageWrapper(stageMap, currentStage, target, interactive = true, Closure body) {
826 def common = new com.mirantis.mk.Common()
827 def banner = []
828
829 printCurrentStage(stageMap, currentStage)
830
831 stage(currentStage) {
Vasyl Saienkobc6debb2018-09-10 14:08:09 +0300832 if (interactive){
azvyagintsevf6e77912018-09-07 15:41:09 +0300833 input message: getColorizedString("We are going to execute stage \'${currentStage}\' on the following target ${target}.\nPlease review stage information above.", "yellow")
Vasyl Saienkobc6debb2018-09-10 14:08:09 +0300834 }
835 try {
Vasyl Saienkobc6debb2018-09-10 14:08:09 +0300836 stageMap[currentStage]['Status'] = "SUCCESS"
Victor Ryzhenkin49d67812019-01-09 15:28:21 +0400837 return body.call()
Vasyl Saienkobc6debb2018-09-10 14:08:09 +0300838 } catch (Exception err) {
839 def msg = "Stage ${currentStage} failed with the following exception:\n${err}"
840 print getColorizedString(msg, "yellow")
841 common.errorMsg(err)
842 if (interactive) {
843 input message: getColorizedString("Please make sure problem is fixed to proceed with retry. Ready to proceed?", "yellow")
844 stageMap[currentStage]['Status'] = "RETRYING"
845 stageWrapper(stageMap, currentStage, target, interactive, body)
846 } else {
847 error(msg)
azvyagintsevf6e77912018-09-07 15:41:09 +0300848 }
Vasyl Saienkobc6debb2018-09-10 14:08:09 +0300849 }
azvyagintsevf6e77912018-09-07 15:41:09 +0300850 }
851}
852
853/**
854 * Ugly transition solution for internal tests.
855 * 1) Check input => transform to static result, based on runtime and input
856 * 2) Check remote-binary repo for exact resource
azvyagintsevf6fce3d2018-12-28 15:30:33 +0200857 * Return: changes each linux_system_* cto false, in case broken url in some of them
858 */
azvyagintsevf6e77912018-09-07 15:41:09 +0300859
860def checkRemoteBinary(LinkedHashMap config, List extraScmExtensions = []) {
861 def common = new com.mirantis.mk.Common()
azvyagintsevf6fce3d2018-12-28 15:30:33 +0200862 def res = [:]
azvyagintsevf6e77912018-09-07 15:41:09 +0300863 res['MirrorRoot'] = config.get('globalMirrorRoot', env["BIN_MIRROR_ROOT"] ? env["BIN_MIRROR_ROOT"] : "http://mirror.mirantis.com/")
864 // Reclass-like format's. To make life eazy!
azvyagintsev603d95b2018-11-09 15:37:10 +0200865 res['mcp_version'] = config.get('mcp_version', env["BIN_APT_MCP_VERSION"] ? env["BIN_APT_MCP_VERSION"] : 'nightly')
azvyagintsevf6fce3d2018-12-28 15:30:33 +0200866 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']}/")
867 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/")
868 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/")
azvyagintsevf6e77912018-09-07 15:41:09 +0300869
870 if (config.get('verify', true)) {
azvyagintsevf6fce3d2018-12-28 15:30:33 +0200871 res.each { key, val ->
872 if (key.toString().startsWith('linux_system_repo')) {
873 def MirrorRootStatus = sh(script: "wget --auth-no-challenge --spider ${val} 2>/dev/null", returnStatus: true)
874 if (MirrorRootStatus != 0) {
875 common.warningMsg("Resource: '${key}' at '${val}' not exist!")
876 res[key] = false
877 }
878 }
azvyagintsevf6e77912018-09-07 15:41:09 +0300879 }
880 }
881 return res
Vasyl Saienko723cbbc2018-09-05 11:08:52 +0300882}
Denis Egorenkoeded0d42018-09-26 13:25:49 +0400883
884/**
885 * Workaround to update env properties, like GERRIT_* vars,
886 * which should be passed from upstream job to downstream.
887 * Will not fail entire job in case any issues.
888 * @param envVar - EnvActionImpl env job
889 * @param extraVars - Multiline YAML text with extra vars
890 */
891def mergeEnv(envVar, extraVars) {
Denis Egorenko6d3cc232018-09-27 17:42:58 +0400892 def common = new com.mirantis.mk.Common()
Denis Egorenkoeded0d42018-09-26 13:25:49 +0400893 try {
894 def extraParams = readYaml text: extraVars
895 for(String key in extraParams.keySet()) {
896 envVar[key] = extraParams[key]
897 common.warningMsg("Parameter ${key} is updated from EXTRA vars.")
898 }
899 } catch (Exception e) {
900 common.errorMsg("Can't update env parameteres, because: ${e.toString()}")
901 }
902}
Denis Egorenko599bd632018-09-28 15:24:37 +0400903
904/**
905 * Wrapper around parallel pipeline function
906 * with ability to restrict number of parallel threads
907 * running simultaneously
908 *
909 * @param branches - Map with Clousers to be executed
910 * @param maxParallelJob - Integer number of parallel threads allowed
911 * to run simultaneously
912 */
913def runParallel(branches, maxParallelJob = 10) {
914 def runningSteps = 0
915 branches.each { branchName, branchBody ->
916 if (branchBody instanceof Closure) {
917 branches[branchName] = {
918 while (!(runningSteps < maxParallelJob)) {
919 continue
920 }
921 runningSteps += 1
922 branchBody.call()
923 runningSteps -= 1
924 }
925 }
926 }
927 if (branches) {
928 parallel branches
929 }
930}
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000931
932/**
933 * Ugly processing basic funcs with /etc/apt
Denis Egorenko5cea1412018-10-18 16:40:11 +0400934 * @param repoConfig YAML text or Map
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000935 * Example :
Denis Egorenko5cea1412018-10-18 16:40:11 +0400936 repoConfig = '''
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000937 ---
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000938 aprConfD: |-
Denis Egorenkoe02a1b22018-10-19 17:47:53 +0400939 APT::Get::AllowUnauthenticated 'true';
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000940 repo:
Denis Egorenkoe02a1b22018-10-19 17:47:53 +0400941 mcp_saltstack:
942 source: "deb [arch=amd64] http://mirror.mirantis.com/nightly/saltstack-2017.7/xenial xenial main"
943 pin:
944 - package: "libsodium18"
945 pin: "release o=SaltStack"
946 priority: 50
947 - package: "*"
948 pin: "release o=SaltStack"
949 priority: "1100"
950 repo_key: "http://mirror.mirantis.com/public.gpg"
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000951 '''
952 *
953 */
954
Denis Egorenko5cea1412018-10-18 16:40:11 +0400955def debianExtraRepos(repoConfig) {
956 def config = null
957 if (repoConfig instanceof Map) {
958 config = repoConfig
959 } else {
960 config = readYaml text: repoConfig
961 }
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000962 if (config.get('repo', false)) {
963 for (String repo in config['repo'].keySet()) {
Denis Egorenko395aa212018-10-11 15:11:28 +0400964 source = config['repo'][repo]['source']
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000965 warningMsg("Write ${source} > /etc/apt/sources.list.d/${repo}.list")
966 sh("echo '${source}' > /etc/apt/sources.list.d/${repo}.list")
Denis Egorenko395aa212018-10-11 15:11:28 +0400967 if (config['repo'][repo].containsKey('repo_key')) {
968 key = config['repo'][repo]['repo_key']
969 sh("wget -O - '${key}' | apt-key add -")
970 }
Denis Egorenkoe02a1b22018-10-19 17:47:53 +0400971 if (config['repo'][repo]['pin']) {
972 def repoPins = []
973 for (Map pin in config['repo'][repo]['pin']) {
974 repoPins.add("Package: ${pin['package']}")
975 repoPins.add("Pin: ${pin['pin']}")
976 repoPins.add("Pin-Priority: ${pin['priority']}")
Denis Egorenko1c93d122018-11-02 12:14:05 +0400977 // additional empty line between pins
978 repoPins.add('\n')
Denis Egorenkoe02a1b22018-10-19 17:47:53 +0400979 }
980 if (repoPins) {
981 repoPins.add(0, "### Extra ${repo} repo pin start ###")
982 repoPins.add("### Extra ${repo} repo pin end ###")
983 repoPinning = repoPins.join('\n')
984 warningMsg("Adding pinning \n${repoPinning}\n => /etc/apt/preferences.d/${repo}")
985 sh("echo '${repoPinning}' > /etc/apt/preferences.d/${repo}")
986 }
987 }
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000988 }
989 }
990 if (config.get('aprConfD', false)) {
991 for (String pref in config['aprConfD'].tokenize('\n')) {
992 warningMsg("Adding ${pref} => /etc/apt/apt.conf.d/99setupAndTestNode")
993 sh("echo '${pref}' >> /etc/apt/apt.conf.d/99setupAndTestNode")
994 }
995 sh('cat /etc/apt/apt.conf.d/99setupAndTestNode')
996 }
997}
Denis Egorenkoeaf78db2019-02-06 17:01:38 +0400998
999/**
1000 * Parse date from string
1001 * @param String date - date to parse
1002 * @param String format - date format in provided date string value
1003 *
1004 * return new Date() object
1005 */
1006Date parseDate(String date, String format) {
1007 return Date.parse(format, date)
1008}