blob: f2313372fa1f2726145c5d317301fb265d60f0e1 [file] [log] [blame]
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001package com.mirantis.mk
2
3/**
4 *
5 * Run a simple workflow
6 *
7 * Function runScenario() executes a sequence of jobs, like
8 * - Parameters for the jobs are taken from the 'env' object
9 * - URLs of artifacts from completed jobs may be passed
10 * as parameters to the next jobs.
11 *
12 * No constants, environment specific logic or other conditional dependencies.
13 * All the logic should be placed in the workflow jobs, and perform necessary
14 * actions depending on the job parameters.
15 * The runScenario() function only provides the
16 *
17 */
18
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +030019/**
Dennis Dmitriev5f014d82020-04-29 00:00:34 +030020 * Get Jenkins parameter names, values and types from jobName
21 * @param jobName job name
22 * @return Map with parameter names as keys and the following map as values:
23 * [
24 * <str name1>: [type: <str cls1>, use_variable: <str name1>, defaultValue: <cls value1>],
25 * <str name2>: [type: <str cls2>, use_variable: <str name2>, defaultValue: <cls value2>],
26 * ]
27 */
28def getJobDefaultParameters(jobName) {
29 def jenkinsUtils = new com.mirantis.mk.JenkinsUtils()
30 def item = jenkinsUtils.getJobByName(env.JOB_NAME)
31 def parameters = [:]
32 def prop = item.getProperty(ParametersDefinitionProperty.class)
azvyagintsev75390d92021-04-12 14:20:11 +030033 if (prop != null) {
34 for (param in prop.getParameterDefinitions()) {
Dennis Dmitriev5f014d82020-04-29 00:00:34 +030035 def defaultParam = param.getDefaultParameterValue()
36 def cls = defaultParam.getClass().getName()
37 def value = defaultParam.getValue()
38 def name = defaultParam.getName()
39 parameters[name] = [type: cls, use_variable: name, defaultValue: value]
40 }
41 }
42 return parameters
43}
44
45/**
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +030046 * Run a Jenkins job using the collected parameters
47 *
48 * @param job_name Name of the running job
49 * @param job_parameters Map that declares which values from global_variables should be used, in the following format:
50 * {'PARAM_NAME': {'type': <job parameter $class name>, 'use_variable': <a key from global_variables>}, ...}
Dennis Dmitrievce470932019-09-18 18:31:11 +030051 * or
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +030052 * {'PARAM_NAME': {'type': <job parameter $class name>, 'get_variable_from_url': <a key from global_variables which contains URL with required content>}, ...}
53 * or
Dennis Dmitrievce470932019-09-18 18:31:11 +030054 * {'PARAM_NAME': {'type': <job parameter $class name>, 'use_template': <a GString multiline template with variables from global_variables>}, ...}
Dennis Dmitriev6c355be2021-11-09 14:06:56 +020055 * or
56 * {'PARAM_NAME': {'type': <job parameter $class name>, 'get_variable_from_yaml': {'yaml_url': <URL with YAML content>,
57 * 'yaml_key': <a groovy-interpolating path to the key in the YAML, starting from dot '.'> } }, ...}
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +030058 * @param global_variables Map that keeps the artifact URLs and used 'env' objects:
59 * {'PARAM1_NAME': <param1 value>, 'PARAM2_NAME': 'http://.../artifacts/param2_value', ...}
Dennis Dmitrieve09e0292019-07-30 16:39:27 +030060 * @param propagate Boolean. If false: allows to collect artifacts after job is finished, even with FAILURE status
61 * If true: immediatelly fails the pipeline. DO NOT USE 'true' if you want to collect artifacts
62 * for 'finally' steps
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +030063 */
Dennis Dmitrieve09e0292019-07-30 16:39:27 +030064def runJob(job_name, job_parameters, global_variables, Boolean propagate = false) {
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +030065 def parameters = []
azvyagintsev0d978152022-01-27 14:01:33 +020066 def common = new com.mirantis.mk.Common()
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +030067 def http = new com.mirantis.mk.Http()
Dennis Dmitrievce470932019-09-18 18:31:11 +030068 def engine = new groovy.text.GStringTemplateEngine()
69 def template
Dennis Dmitriev6c355be2021-11-09 14:06:56 +020070 def yamls_from_urls = [:]
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +030071 def base = [:]
72 base["url"] = ''
73 def variable_content
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +030074
75 // Collect required parameters from 'global_variables' or 'env'
76 for (param in job_parameters) {
Dennis Dmitrievce470932019-09-18 18:31:11 +030077 if (param.value.containsKey('use_variable')) {
78 if (!global_variables[param.value.use_variable]) {
79 global_variables[param.value.use_variable] = env[param.value.use_variable] ?: ''
80 }
81 parameters.add([$class: "${param.value.type}", name: "${param.key}", value: global_variables[param.value.use_variable]])
azvyagintsev353b8762022-01-14 12:30:43 +020082 common.infoMsg("${param.key}: <${param.value.type}> ${global_variables[param.value.use_variable]}")
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +030083 } else if (param.value.containsKey('get_variable_from_url')) {
84 if (!global_variables[param.value.get_variable_from_url]) {
85 global_variables[param.value.get_variable_from_url] = env[param.value.get_variable_from_url] ?: ''
86 }
Andrew Baraniuke0aef1e2019-10-16 14:50:10 +030087 if (global_variables[param.value.get_variable_from_url]) {
Dennis Dmitriev37828362019-11-11 18:06:49 +020088 variable_content = http.restGet(base, global_variables[param.value.get_variable_from_url]).trim()
Andrew Baraniuke0aef1e2019-10-16 14:50:10 +030089 parameters.add([$class: "${param.value.type}", name: "${param.key}", value: variable_content])
azvyagintsev353b8762022-01-14 12:30:43 +020090 common.infoMsg("${param.key}: <${param.value.type}> ${variable_content}")
Andrew Baraniuke0aef1e2019-10-16 14:50:10 +030091 } else {
azvyagintsev353b8762022-01-14 12:30:43 +020092 common.warningMsg("${param.key} is empty, skipping get_variable_from_url")
Andrew Baraniuke0aef1e2019-10-16 14:50:10 +030093 }
Dennis Dmitriev6c355be2021-11-09 14:06:56 +020094 } else if (param.value.containsKey('get_variable_from_yaml')) {
95 if (param.value.get_variable_from_yaml.containsKey('yaml_url') && param.value.get_variable_from_yaml.containsKey('yaml_key')) {
96 // YAML url is stored in an environment or a global variable (like 'SI_CONFIG_ARTIFACT')
azvyagintsev0d978152022-01-27 14:01:33 +020097 def yaml_url_var = param.value.get_variable_from_yaml.yaml_url
Dennis Dmitriev6c355be2021-11-09 14:06:56 +020098 if (!global_variables[yaml_url_var]) {
99 global_variables[yaml_url_var] = env[yaml_url_var] ?: ''
100 }
101 yaml_url = global_variables[yaml_url_var] // Real YAML URL
azvyagintsev353b8762022-01-14 12:30:43 +0200102 yaml_key = param.value.get_variable_from_yaml.yaml_key
103 // Key to get the data from YAML, to interpolate in the groovy, for example:
104 // <yaml_map_variable>.key.to.the[0].required.data , where yaml_key = '.key.to.the[0].required.data'
Dennis Dmitriev6c355be2021-11-09 14:06:56 +0200105 if (yaml_url) {
106 if (!yamls_from_urls[yaml_url]) {
azvyagintsev353b8762022-01-14 12:30:43 +0200107 common.infoMsg("Reading YAML from ${yaml_url} for ${param.key}")
Dennis Dmitriev6c355be2021-11-09 14:06:56 +0200108 yaml_content = http.restGet(base, yaml_url)
109 yamls_from_urls[yaml_url] = readYaml text: yaml_content
110 }
azvyagintsev353b8762022-01-14 12:30:43 +0200111 common.infoMsg("Getting key ${yaml_key} from YAML ${yaml_url} for ${param.key}")
Dennis Dmitriev6c355be2021-11-09 14:06:56 +0200112 template_variables = [
azvyagintsev353b8762022-01-14 12:30:43 +0200113 'yaml_data': yamls_from_urls[yaml_url]
Dennis Dmitriev6c355be2021-11-09 14:06:56 +0200114 ]
115 request = "\${yaml_data${yaml_key}}"
Dennis Dmitriev5e076712022-02-08 15:05:21 +0200116 def result
Dennis Dmitriev450cf732021-11-11 14:59:17 +0200117 // Catch errors related to wrong key or index in the list or map objects
118 // For wrong key in map or wrong index in list, groovy returns <null> object,
119 // but it can be catched only after the string interpolation <template.toString()>,
120 // so we should catch the string 'null' instead of object <null>.
121 try {
122 template = engine.createTemplate(request).make(template_variables)
Dennis Dmitriev5e076712022-02-08 15:05:21 +0200123 result = template.toString()
Dennis Dmitriev450cf732021-11-11 14:59:17 +0200124 if (result == 'null') {
125 error "No such key or index, got 'null'"
126 }
127 } catch (e) {
128 error("Failed to get the key ${yaml_key} from YAML ${yaml_url}: " + e.toString())
129 }
130
131 parameters.add([$class: "${param.value.type}", name: "${param.key}", value: result])
azvyagintsev353b8762022-01-14 12:30:43 +0200132 common.infoMsg("${param.key}: <${param.value.type}>\n${result}")
Dennis Dmitriev6c355be2021-11-09 14:06:56 +0200133 } else {
azvyagintsev353b8762022-01-14 12:30:43 +0200134 common.warningMsg("'yaml_url' in ${param.key} is empty, skipping get_variable_from_yaml")
Dennis Dmitriev6c355be2021-11-09 14:06:56 +0200135 }
136 } else {
azvyagintsev353b8762022-01-14 12:30:43 +0200137 common.warningMsg("${param.key} missing 'yaml_url'/'yaml_key' parameters, skipping get_variable_from_yaml")
Dennis Dmitriev6c355be2021-11-09 14:06:56 +0200138 }
Dennis Dmitrievce470932019-09-18 18:31:11 +0300139 } else if (param.value.containsKey('use_template')) {
140 template = engine.createTemplate(param.value.use_template).make(global_variables)
141 parameters.add([$class: "${param.value.type}", name: "${param.key}", value: template.toString()])
azvyagintsev353b8762022-01-14 12:30:43 +0200142 common.infoMsg("${param.key}: <${param.value.type}>\n${template.toString()}")
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300143 }
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300144 }
145
146 // Build the job
Dennis Dmitrieve09e0292019-07-30 16:39:27 +0300147 def job_info = build job: "${job_name}", parameters: parameters, propagate: propagate
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300148 return job_info
149}
150
azvyagintsev061179d2021-05-05 16:52:18 +0300151def runOrGetJob(job_name, job_parameters, global_variables, propagate, String fullTaskName = '') {
152 /**
153 * Run job directly or try to find already executed build
154 * Flow, in case CI_JOBS_OVERRIDES passed:
155 *
156 *
157 * CI_JOBS_OVERRIDES = text in yaml|json format
158 * CI_JOBS_OVERRIDES = 'kaas-testing-core-release-artifact' : 3505
159 * 'reindex-testing-core-release-index-with-rc' : 2822
160 * 'si-test-release-sanity-check-prepare-configuration': 1877
161 */
162 common = new com.mirantis.mk.Common()
163 def jobsOverrides = readYaml(text: env.CI_JOBS_OVERRIDES ?: '---') ?: [:]
164 // get id of overriding job
165 def jobOverrideID = jobsOverrides.getOrDefault(fullTaskName, '')
azvyagintsev061179d2021-05-05 16:52:18 +0300166 if (fullTaskName in jobsOverrides.keySet()) {
167 common.warningMsg("Overriding: ${fullTaskName}/${job_name} <<< ${jobOverrideID}")
168 common.infoMsg("For debug pin use:\n'${fullTaskName}' : ${jobOverrideID}")
169 return Jenkins.instance.getItemByFullName(job_name,
azvyagintsev353b8762022-01-14 12:30:43 +0200170 hudson.model.Job.class).getBuildByNumber(jobOverrideID.toInteger())
azvyagintsev061179d2021-05-05 16:52:18 +0300171 } else {
172 return runJob(job_name, job_parameters, global_variables, propagate)
173 }
174}
175
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300176/**
177 * Store URLs of the specified artifacts to the global_variables
178 *
179 * @param build_url URL of the completed job
180 * @param step_artifacts Map that contains artifact names in the job, and variable names
181 * where the URLs to that atrifacts should be stored, for example:
182 * {'ARTIFACT1': 'logs.tar.gz', 'ARTIFACT2': 'test_report.xml', ...}
183 * @param global_variables Map that will keep the artifact URLs. Variable 'ARTIFACT1', for example,
184 * be used in next job parameters: {'ARTIFACT1_URL':{ 'use_variable': 'ARTIFACT1', ...}}
185 *
186 * If the artifact with the specified name not found, the parameter ARTIFACT1_URL
187 * will be empty.
188 *
189 */
Aleksey Zvyagintsev25ed4a52021-05-12 14:35:03 +0000190def storeArtifacts(build_url, step_artifacts, global_variables, job_name, build_num, artifactory_url = '') {
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300191 def common = new com.mirantis.mk.Common()
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300192 def http = new com.mirantis.mk.Http()
Aleksey Zvyagintsev25ed4a52021-05-12 14:35:03 +0000193 if (!artifactory_url) {
194 artifactory_url = 'https://artifactory.mcp.mirantis.net/api/storage/si-local/jenkins-job-artifacts'
195 }
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300196 def baseJenkins = [:]
197 def baseArtifactory = [:]
198 build_url = build_url.replaceAll(~/\/+$/, "")
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300199 baseArtifactory["url"] = artifactory_url + "/${job_name}/${build_num}"
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300200 baseJenkins["url"] = build_url
201 def job_config = http.restGet(baseJenkins, "/api/json/")
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300202 def job_artifacts = job_config['artifacts']
azvyagintsev0d978152022-01-27 14:01:33 +0200203 common.infoMsg("Attempt to storeArtifacts for: ${job_name}/${build_num}")
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300204 for (artifact in step_artifacts) {
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300205 try {
azvyagintsev0d978152022-01-27 14:01:33 +0200206 def artifactoryResp = http.restGet(baseArtifactory, "/${artifact.value}")
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300207 global_variables[artifact.key] = artifactoryResp.downloadUri
azvyagintsev0d978152022-01-27 14:01:33 +0200208 common.infoMsg("Artifact URL ${artifactoryResp.downloadUri} stored to ${artifact.key}")
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300209 continue
210 } catch (Exception e) {
azvyagintsev0d978152022-01-27 14:01:33 +0200211 common.warningMsg("Can't find an artifact in ${artifactory_url}/${job_name}/${build_num}/${artifact.value} to store in ${artifact.key}\n" +
212 "error code ${e.message}")
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300213 }
214
azvyagintsev0d978152022-01-27 14:01:33 +0200215 def job_artifact = job_artifacts.findAll { item -> artifact.value == item['fileName'] || artifact.value == item['relativePath'] }
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300216 if (job_artifact.size() == 1) {
217 // Store artifact URL
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300218 def artifact_url = "${build_url}/artifact/${job_artifact[0]['relativePath']}"
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300219 global_variables[artifact.key] = artifact_url
azvyagintsev0d978152022-01-27 14:01:33 +0200220 common.infoMsg("Artifact URL ${artifact_url} stored to ${artifact.key}")
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300221 } else if (job_artifact.size() > 1) {
222 // Error: too many artifacts with the same name, fail the job
223 error "Multiple artifacts ${artifact.value} for ${artifact.key} found in the build results ${build_url}, expected one:\n${job_artifact}"
224 } else {
225 // Warning: no artifact with expected name
azvyagintsev0d978152022-01-27 14:01:33 +0200226 common.warningMsg("Artifact ${artifact.value} for ${artifact.key} not found in the build results ${build_url} and in the artifactory ${artifactory_url}/${job_name}/${build_num}/, found the following artifacts in Jenkins:\n${job_artifacts}")
Andrew Baraniuke0aef1e2019-10-16 14:50:10 +0300227 global_variables[artifact.key] = ''
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300228 }
229 }
230}
231
AndrewB8505a7f2020-06-05 13:42:08 +0300232/**
233 * Update workflow job build description
234 *
235 * @param jobs_data Map with all job names and result statuses, to showing it in description
236 */
237def updateDescription(jobs_data) {
azvyagintsev0d978152022-01-27 14:01:33 +0200238 def common = new com.mirantis.mk.Common()
239 def table = ''
240 def child_jobs_description = '<strong>Descriptions from jobs:</strong><br>'
241 def table_template_start = "<div><table style='border: solid 1px;'><tr><th>Job:</th><th>Duration:</th><th>Status:</th></tr>"
242 def table_template_end = "</table></div>"
AndrewB8505a7f2020-06-05 13:42:08 +0300243
244 for (jobdata in jobs_data) {
azvyagintsev0d978152022-01-27 14:01:33 +0200245 def trstyle = "<tr>"
AndrewB8505a7f2020-06-05 13:42:08 +0300246 // Grey background for 'finally' jobs in list
247 if (jobdata['type'] == 'finally') {
248 trstyle = "<tr style='background: #DDDDDD;'>"
AndrewB8505a7f2020-06-05 13:42:08 +0300249 }
AndrewB8505a7f2020-06-05 13:42:08 +0300250 // 'description' instead of job name if it exists
azvyagintsev0d978152022-01-27 14:01:33 +0200251 def display_name = "'${jobdata['name']}': ${jobdata['build_id']}"
azvyagintsev75390d92021-04-12 14:20:11 +0300252 if (jobdata['desc'].toString() != "") {
azvyagintsev061179d2021-05-05 16:52:18 +0300253 display_name = "'${jobdata['desc']}': ${jobdata['build_id']}"
AndrewB8505a7f2020-06-05 13:42:08 +0300254 }
255
azvyagintsev2eeaa562022-01-27 12:03:40 +0200256 // Attach url for already built jobs
azvyagintsev0d978152022-01-27 14:01:33 +0200257 def build_url = display_name
azvyagintsev75390d92021-04-12 14:20:11 +0300258 if (jobdata['build_url'] != "0") {
AndrewB8505a7f2020-06-05 13:42:08 +0300259 build_url = "<a href=${jobdata['build_url']}>$display_name</a>"
AndrewB8505a7f2020-06-05 13:42:08 +0300260 }
261
262 // Styling the status of job result
azvyagintsev75390d92021-04-12 14:20:11 +0300263 switch (jobdata['status'].toString()) {
AndrewB8505a7f2020-06-05 13:42:08 +0300264 case "SUCCESS":
265 status_style = "<td style='color: green;'><img src='/images/16x16/blue.png' alt='SUCCESS'>"
266 break
267 case "UNSTABLE":
268 status_style = "<td style='color: #FF5733;'><img src='/images/16x16/yellow.png' alt='UNSTABLE'>"
269 break
270 case "ABORTED":
271 status_style = "<td style='color: red;'><img src='/images/16x16/aborted.png' alt='ABORTED'>"
272 break
273 case "NOT_BUILT":
274 status_style = "<td style='color: red;'><img src='/images/16x16/aborted.png' alt='NOT_BUILT'>"
275 break
276 case "FAILURE":
277 status_style = "<td style='color: red;'><img src='/images/16x16/red.png' alt='FAILURE'>"
278 break
279 default:
280 status_style = "<td>-"
281 }
282
283 // Collect table
azvyagintsev2eeaa562022-01-27 12:03:40 +0200284 table += "$trstyle<td>$build_url</td><td>${jobdata['duration']}</td>$status_style</td></tr>"
AndrewB8505a7f2020-06-05 13:42:08 +0300285
286 // Collecting descriptions of builded child jobs
287 if (jobdata['child_desc'] != "") {
288 child_jobs_description += "<b><small><a href=${jobdata['build_url']}>- ${jobdata['name']} (${jobdata['status']}):</a></small></b><br>"
azvyagintsev0d978152022-01-27 14:01:33 +0200289 // remove "null" message-result from description, but leave XXX:JOBRESULT in description
290 if (jobdata['child_desc'] != "null") {
291 child_jobs_description += "<small>${jobdata['child_desc']}</small><br>"
292 }
AndrewB8505a7f2020-06-05 13:42:08 +0300293 }
294 }
295 currentBuild.description = table_template_start + table + table_template_end + child_jobs_description
296}
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300297
azvyagintsev0d978152022-01-27 14:01:33 +0200298def runStep(global_variables, step, Boolean propagate = false, artifactoryBaseUrl = '') {
299 return {
300 def common = new com.mirantis.mk.Common()
301 def engine = new groovy.text.GStringTemplateEngine()
302
303 String jobDescription = step['description'] ?: ''
304 def jobName = step['job']
305 def jobParameters = [:]
306 def stepParameters = step['parameters'] ?: [:]
307 if (step['inherit_parent_params'] ?: false) {
308 // add parameters from the current job for the child job
309 jobParameters << getJobDefaultParameters(env.JOB_NAME)
310 }
311 // add parameters from the workflow for the child job
312 jobParameters << stepParameters
313 def wfPauseStepBeforeRun = (step['wf_pause_step_before_run'] ?: false).toBoolean()
314 def wfPauseStepTimeout = (step['wf_pause_step_timeout'] ?: 10).toInteger()
315 def wfPauseStepSlackReportChannel = step['wf_pause_step_slack_report_channel'] ?: ''
316
317 if (wfPauseStepBeforeRun) {
318 // Try-catch construction will allow to continue Steps, if timeout reached
319 try {
320 if (wfPauseStepSlackReportChannel) {
321 def slack = new com.mirantis.mcp.SlackNotification()
azvyagintsevda22aa82022-06-10 15:46:55 +0300322 wfPauseStepSlackReportChannel.split(',').each {
323 slack.jobResultNotification('wf_pause_step_before_run',
324 it.toString(),
325 env.JOB_NAME, null,
326 env.BUILD_URL, 'slack_webhook_url')
327 }
azvyagintsev0d978152022-01-27 14:01:33 +0200328 }
329 timeout(time: wfPauseStepTimeout, unit: 'MINUTES') {
330 input("Workflow pause requested before run: ${jobName}/${jobDescription}\n" +
331 "Timeout set to ${wfPauseStepTimeout}.\n" +
332 "Do you want to proceed workflow?")
333 }
334 } catch (err) { // timeout reached or input false
335 def user = err.getCauses()[0].getUser()
336 if (user.toString() != 'SYSTEM') { // SYSTEM means timeout.
337 error("Aborted after workFlow pause by: [${user}]")
338 } else {
339 common.infoMsg("Timeout finished, continue..")
340 }
341 }
342 }
343 common.infoMsg("Attempt to run: ${jobName}/${jobDescription}")
344 // Collect job parameters and run the job
345 // WARN(alexz): desc must not contain invalid chars for yaml
346 def jobResult = runOrGetJob(jobName, jobParameters,
347 global_variables, propagate, jobDescription)
348 def buildDuration = jobResult.durationString ?: '-'
349 if (buildDuration.toString() == null) {
350 buildDuration = '-'
351 }
352 def jobSummary = [
353 job_result : jobResult.getResult().toString(),
354 build_url : jobResult.getAbsoluteUrl().toString(),
355 build_id : jobResult.getId().toString(),
356 buildDuration : buildDuration,
357 desc : engine.createTemplate(jobDescription).make(global_variables),
358 ]
359 def _buildDescription = jobResult.getDescription().toString()
360 if(_buildDescription){
361 jobSummary['build_description'] = _buildDescription
362 }
363 // Store links to the resulting artifacts into 'global_variables'
364 storeArtifacts(jobSummary['build_url'], step['artifacts'],
365 global_variables, jobName, jobSummary['build_id'], artifactoryBaseUrl)
366 return jobSummary
367 }
368}
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300369/**
370 * Run the workflow or final steps one by one
371 *
372 * @param steps List of steps (Jenkins jobs) to execute
373 * @param global_variables Map where the collected artifact URLs and 'env' objects are stored
374 * @param failed_jobs Map with failed job names and result statuses, to report it later
AndrewB8505a7f2020-06-05 13:42:08 +0300375 * @param jobs_data Map with all job names and result statuses, to showing it in description
376 * @param step_id Counter for matching step ID with cell ID in description table
Dennis Dmitrieve09e0292019-07-30 16:39:27 +0300377 * @param propagate Boolean. If false: allows to collect artifacts after job is finished, even with FAILURE status
378 * If true: immediatelly fails the pipeline. DO NOT USE 'true' with runScenario().
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300379 */
Aleksey Zvyagintsev25ed4a52021-05-12 14:35:03 +0000380def runSteps(steps, global_variables, failed_jobs, jobs_data, step_id, Boolean propagate = false, artifactoryBaseUrl = '') {
azvyagintsevb673f392021-05-19 15:31:48 +0300381 common = new com.mirantis.mk.Common()
AndrewB8505a7f2020-06-05 13:42:08 +0300382 // Show expected jobs list in description
383 updateDescription(jobs_data)
384
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300385 for (step in steps) {
azvyagintsev0d978152022-01-27 14:01:33 +0200386 stage("Preparing for run job ${step['job']}") {
387 def job_summary = runStep(global_variables, step, propagate, artifactoryBaseUrl).call()
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300388
AndrewB8505a7f2020-06-05 13:42:08 +0300389 // Update jobs_data for updating description
azvyagintsev0d978152022-01-27 14:01:33 +0200390 jobs_data[step_id]['build_url'] = job_summary['build_url']
391 jobs_data[step_id]['build_id'] = job_summary['build_id']
392 jobs_data[step_id]['status'] = job_summary['job_result']
393 jobs_data[step_id]['duration'] = job_summary['buildDuration']
394 jobs_data[step_id]['desc'] = job_summary['desc']
395 if (job_summary['build_description']) {
396 jobs_data[step_id]['child_desc'] = job_summary['build_description']
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300397 }
AndrewB8505a7f2020-06-05 13:42:08 +0300398 updateDescription(jobs_data)
azvyagintsev0d978152022-01-27 14:01:33 +0200399 def job_result = job_summary['job_result']
400 def build_url = job_summary['build_url']
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300401
Mykyta Karpina3d775e2020-04-24 14:45:17 +0300402 // Check job result, in case of SUCCESS, move to next step.
Mykyta Karpin0bd8bc62020-04-29 12:27:14 +0300403 // In case job has status NOT_BUILT, fail the build or keep going depending on 'ignore_not_built' flag
Vasyl Saienkoe72b9942021-03-04 10:54:49 +0200404 // In other cases check flag ignore_failed, if true ignore any statuses and keep going additionally
405 // if skip_results is not set or set to false fail entrie workflow, otherwise succed.
azvyagintsev75390d92021-04-12 14:20:11 +0300406 if (job_result != 'SUCCESS') {
Mykyta Karpina3d775e2020-04-24 14:45:17 +0300407 def ignoreStepResult = false
azvyagintsev75390d92021-04-12 14:20:11 +0300408 switch (job_result) {
409 // In cases when job was waiting too long in queue or internal job logic allows to skip building,
410 // job may have NOT_BUILT status. In that case ignore_not_built flag can be used not to fail scenario.
Mykyta Karpina3d775e2020-04-24 14:45:17 +0300411 case "NOT_BUILT":
412 ignoreStepResult = step['ignore_not_built'] ?: false
413 break;
Dmitry Tyzhnenkoa1412702022-02-14 21:23:09 +0200414 case "UNSTABLE":
Dmitry Tyzhnenkobafca282022-02-17 17:49:54 +0200415 ignoreStepResult = step['ignore_unstable'] ?: (step['ignore_failed'] ?: false)
Dmitry Tyzhnenkoa1412702022-02-14 21:23:09 +0200416 break;
Mykyta Karpina3d775e2020-04-24 14:45:17 +0300417 default:
418 ignoreStepResult = step['ignore_failed'] ?: false
Vasyl Saienkoe72b9942021-03-04 10:54:49 +0200419 if (ignoreStepResult && !step['skip_results'] ?: false) {
420 failed_jobs[build_url] = job_result
421 }
Mykyta Karpina3d775e2020-04-24 14:45:17 +0300422 }
423 if (!ignoreStepResult) {
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300424 currentBuild.result = job_result
425 error "Job ${build_url} finished with result: ${job_result}"
azvyagintsev0d978152022-01-27 14:01:33 +0200426 }
427 }
azvyagintsev353b8762022-01-14 12:30:43 +0200428 common.infoMsg("Job ${build_url} finished with result: ${job_result}")
azvyagintsev0d978152022-01-27 14:01:33 +0200429 }
azvyagintsev75390d92021-04-12 14:20:11 +0300430 // Jump to next ID for updating next job data in description table
431 step_id++
azvyagintsev0d978152022-01-27 14:01:33 +0200432 }
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300433}
434
435/**
436 * Run the workflow scenario
437 *
438 * @param scenario: Map with scenario steps.
439
440 * There are two keys in the scenario:
441 * workflow: contains steps to run deploy and test jobs
442 * finally: contains steps to run report and cleanup jobs
443 *
444 * Scenario execution example:
445 *
446 * scenario_yaml = """\
447 * workflow:
448 * - job: deploy-kaas
449 * ignore_failed: false
AndrewB8505a7f2020-06-05 13:42:08 +0300450 * description: "Management cluster ${KAAS_VERSION}"
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300451 * parameters:
452 * KAAS_VERSION:
453 * type: StringParameterValue
454 * use_variable: KAAS_VERSION
455 * artifacts:
456 * KUBECONFIG_ARTIFACT: artifacts/management_kubeconfig
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +0300457 * DEPLOYED_KAAS_VERSION: artifacts/management_version
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300458 *
Dennis Dmitriev5f014d82020-04-29 00:00:34 +0300459 * - job: create-child
460 * inherit_parent_params: true
461 * ignore_failed: false
462 * parameters:
463 * KUBECONFIG_ARTIFACT_URL:
464 * type: StringParameterValue
465 * use_variable: KUBECONFIG_ARTIFACT
466 * KAAS_VERSION:
467 * type: StringParameterValue
468 * get_variable_from_url: DEPLOYED_KAAS_VERSION
Dennis Dmitriev6c355be2021-11-09 14:06:56 +0200469 * RELEASE_NAME:
470 * type: StringParameterValue
471 * get_variable_from_yaml:
472 * yaml_url: SI_CONFIG_ARTIFACT
473 * yaml_key: .clusters[0].release_name
Dennis Dmitriev5f014d82020-04-29 00:00:34 +0300474 *
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300475 * - job: test-kaas-ui
Mykyta Karpina3d775e2020-04-24 14:45:17 +0300476 * ignore_not_built: false
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300477 * parameters:
478 * KUBECONFIG_ARTIFACT_URL:
479 * type: StringParameterValue
480 * use_variable: KUBECONFIG_ARTIFACT
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +0300481 * KAAS_VERSION:
482 * type: StringParameterValue
483 * get_variable_from_url: DEPLOYED_KAAS_VERSION
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300484 * artifacts:
485 * REPORT_SI_KAAS_UI: artifacts/test_kaas_ui_result.xml
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300486 * finally:
487 * - job: testrail-report
488 * ignore_failed: true
489 * parameters:
Dennis Dmitrievce470932019-09-18 18:31:11 +0300490 * KAAS_VERSION:
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300491 * type: StringParameterValue
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +0300492 * get_variable_from_url: DEPLOYED_KAAS_VERSION
Dennis Dmitrievce470932019-09-18 18:31:11 +0300493 * REPORTS_LIST:
494 * type: TextParameterValue
495 * use_template: |
496 * REPORT_SI_KAAS_UI: \$REPORT_SI_KAAS_UI
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300497 * """
498 *
499 * runScenario(scenario)
500 *
Dennis Dmitriev5f014d82020-04-29 00:00:34 +0300501 * Scenario workflow keys:
502 *
503 * job: string. Jenkins job name
504 * ignore_failed: bool. if true, keep running the workflow jobs if the job is failed, but fail the workflow at finish
Vasyl Saienkoe72b9942021-03-04 10:54:49 +0200505 * skip_results: bool. if true, keep running the workflow jobs if the job is failed, but do not fail the workflow at finish. Makes sense only when ignore_failed is set.
Dennis Dmitriev5f014d82020-04-29 00:00:34 +0300506 * ignore_not_built: bool. if true, keep running the workflow jobs if the job set own status to NOT_BUILT, do not fail the workflow at finish for such jobs
507 * inherit_parent_params: bool. if true, provide all parameters from the parent job to the child job as defaults
508 * parameters: dict. parameters name and type to inherit from parent to child job, or from artifact to child job
azvyagintsevb3cd2a72022-01-17 23:41:34 +0200509 * wf_pause_step_before_run: bool. Interactive pause exact step before run.
510 * wf_pause_step_slack_report_channel: If step paused, send message about it in slack.
511 * wf_pause_step_timeout: timeout im minutes to wait for manual unpause.
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300512 */
513
Aleksey Zvyagintsev25ed4a52021-05-12 14:35:03 +0000514def runScenario(scenario, slackReportChannel = '', artifactoryBaseUrl = '') {
Dennis Dmitriev79f3a2d2019-08-09 16:06:00 +0300515 // Clear description before adding new messages
516 currentBuild.description = ''
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300517 // Collect the parameters for the jobs here
azvyagintsev0d978152022-01-27 14:01:33 +0200518 def global_variables = [:]
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300519 // List of failed jobs to show at the end
azvyagintsev0d978152022-01-27 14:01:33 +0200520 def failed_jobs = [:]
AndrewB8505a7f2020-06-05 13:42:08 +0300521 // Jobs data to use for wf job build description
522 def jobs_data = []
523 // Counter for matching step ID with cell ID in description table
azvyagintsev0d978152022-01-27 14:01:33 +0200524 def step_id = 0
AndrewB8505a7f2020-06-05 13:42:08 +0300525
526 // Generate expected list jobs for description
azvyagintsev0d978152022-01-27 14:01:33 +0200527 def list_id = 0
AndrewB8505a7f2020-06-05 13:42:08 +0300528 for (step in scenario['workflow']) {
azvyagintsev0d978152022-01-27 14:01:33 +0200529 def display_name = step['job']
azvyagintsev75390d92021-04-12 14:20:11 +0300530 if (step['description'] != null && step['description'].toString() != "") {
AndrewB8505a7f2020-06-05 13:42:08 +0300531 display_name = step['description']
AndrewB8505a7f2020-06-05 13:42:08 +0300532 }
azvyagintsev061179d2021-05-05 16:52:18 +0300533 jobs_data.add([list_id : "$list_id",
534 type : "workflow",
535 name : "$display_name",
536 build_url : "0",
537 build_id : "-",
538 status : "-",
539 desc : "",
azvyagintsev2eeaa562022-01-27 12:03:40 +0200540 child_desc: "",
541 duration : '-'])
AndrewB8505a7f2020-06-05 13:42:08 +0300542 list_id += 1
543 }
azvyagintsev0d978152022-01-27 14:01:33 +0200544
Sergey Lalov702384d2022-11-10 12:10:23 +0400545 def pause_step_id = list_id
546 for (step in scenario['pause']) {
547 def display_name = step['job']
548 if (step['description'] != null && step['description'].toString() != "") {
549 display_name = step['description']
550 }
551 jobs_data.add([list_id : "$list_id",
552 type : "pause",
553 name : "$display_name",
554 build_url : "0",
555 build_id : "-",
556 status : "-",
557 desc : "",
558 child_desc: "",
559 duration : '-'])
560 list_id += 1
561 }
562
azvyagintsev0d978152022-01-27 14:01:33 +0200563 def finally_step_id = list_id
AndrewB8505a7f2020-06-05 13:42:08 +0300564 for (step in scenario['finally']) {
azvyagintsev0d978152022-01-27 14:01:33 +0200565 def display_name = step['job']
azvyagintsev75390d92021-04-12 14:20:11 +0300566 if (step['description'] != null && step['description'].toString() != "") {
AndrewB8505a7f2020-06-05 13:42:08 +0300567 display_name = step['description']
AndrewB8505a7f2020-06-05 13:42:08 +0300568 }
azvyagintsev061179d2021-05-05 16:52:18 +0300569 jobs_data.add([list_id : "$list_id",
570 type : "finally",
571 name : "$display_name",
572 build_url : "0",
573 build_id : "-",
574 status : "-",
575 desc : "",
azvyagintsev2eeaa562022-01-27 12:03:40 +0200576 child_desc: "",
577 duration : '-'])
AndrewB8505a7f2020-06-05 13:42:08 +0300578 list_id += 1
579 }
Sergey Lalov702384d2022-11-10 12:10:23 +0400580 def job_failed_flag = false
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300581 try {
582 // Run the 'workflow' jobs
Aleksey Zvyagintsev25ed4a52021-05-12 14:35:03 +0000583 runSteps(scenario['workflow'], global_variables, failed_jobs, jobs_data, step_id, false, artifactoryBaseUrl)
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300584 } catch (InterruptedException x) {
Sergey Lalov702384d2022-11-10 12:10:23 +0400585 job_failed_flag = true
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300586 error "The job was aborted"
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300587 } catch (e) {
Sergey Lalov702384d2022-11-10 12:10:23 +0400588 job_failed_flag = true
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300589 error("Build failed: " + e.toString())
Sergey Lalov702384d2022-11-10 12:10:23 +0400590
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300591 } finally {
Sergey Lalov702384d2022-11-10 12:10:23 +0400592 flag_pause_variable = (env.PAUSE_FOR_DEBUG) != null
593 // Run the 'finally' or 'pause' jobs
Sergey Lalov6e9400c2022-11-17 12:59:31 +0400594 common.infoMsg(failed_jobs)
595 if (flag_pause_variable && (PAUSE_FOR_DEBUG && (job_failed_flag || failed_jobs))) {
Sergey Lalov702384d2022-11-10 12:10:23 +0400596 // Switching to 'pause' step index
597 common.infoMsg("FINALLY BLOCK - PAUSE")
598 step_id = pause_step_id
599 runSteps(scenario['pause'], global_variables, failed_jobs, jobs_data, step_id, false, artifactoryBaseUrl)
600
601 }
602 // Switching to 'finally' step index
603 common.infoMsg("FINALLY BLOCK - CLEAR")
AndrewB8505a7f2020-06-05 13:42:08 +0300604 step_id = finally_step_id
Aleksey Zvyagintsev25ed4a52021-05-12 14:35:03 +0000605 runSteps(scenario['finally'], global_variables, failed_jobs, jobs_data, step_id, false, artifactoryBaseUrl)
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300606
607 if (failed_jobs) {
azvyagintsev0d978152022-01-27 14:01:33 +0200608 def statuses = []
sgudz9ac09d22020-01-22 14:31:30 +0200609 failed_jobs.each {
sgudz74c8cdd2020-01-23 14:26:32 +0200610 statuses += it.value
azvyagintsev75390d92021-04-12 14:20:11 +0300611 }
sgudz9ac09d22020-01-22 14:31:30 +0200612 if (statuses.contains('FAILURE')) {
613 currentBuild.result = 'FAILURE'
azvyagintsev75390d92021-04-12 14:20:11 +0300614 } else if (statuses.contains('UNSTABLE')) {
sgudz9ac09d22020-01-22 14:31:30 +0200615 currentBuild.result = 'UNSTABLE'
azvyagintsev75390d92021-04-12 14:20:11 +0300616 } else {
sgudz9ac09d22020-01-22 14:31:30 +0200617 currentBuild.result = 'FAILURE'
618 }
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300619 println "Failed jobs: ${failed_jobs}"
vnaumov68cba272020-05-20 11:24:02 +0200620 } else {
621 currentBuild.result = 'SUCCESS'
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300622 }
vnaumov5a6eb8a2020-03-31 11:16:54 +0200623
624 if (slackReportChannel) {
625 def slack = new com.mirantis.mcp.SlackNotification()
626 slack.jobResultNotification(currentBuild.result, slackReportChannel, '', null, '', 'slack_webhook_url')
627 }
sgudz9ac09d22020-01-22 14:31:30 +0200628 } // finally
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300629}