blob: 03a43a6d9bacd8b432c446ca42fc60ab844f6fe4 [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()
322 slack.jobResultNotification('wf_pause_step_before_run',
323 wfPauseStepSlackReportChannel,
324 env.JOB_NAME, null,
325 env.BUILD_URL, 'slack_webhook_url')
326 }
327 timeout(time: wfPauseStepTimeout, unit: 'MINUTES') {
328 input("Workflow pause requested before run: ${jobName}/${jobDescription}\n" +
329 "Timeout set to ${wfPauseStepTimeout}.\n" +
330 "Do you want to proceed workflow?")
331 }
332 } catch (err) { // timeout reached or input false
333 def user = err.getCauses()[0].getUser()
334 if (user.toString() != 'SYSTEM') { // SYSTEM means timeout.
335 error("Aborted after workFlow pause by: [${user}]")
336 } else {
337 common.infoMsg("Timeout finished, continue..")
338 }
339 }
340 }
341 common.infoMsg("Attempt to run: ${jobName}/${jobDescription}")
342 // Collect job parameters and run the job
343 // WARN(alexz): desc must not contain invalid chars for yaml
344 def jobResult = runOrGetJob(jobName, jobParameters,
345 global_variables, propagate, jobDescription)
346 def buildDuration = jobResult.durationString ?: '-'
347 if (buildDuration.toString() == null) {
348 buildDuration = '-'
349 }
350 def jobSummary = [
351 job_result : jobResult.getResult().toString(),
352 build_url : jobResult.getAbsoluteUrl().toString(),
353 build_id : jobResult.getId().toString(),
354 buildDuration : buildDuration,
355 desc : engine.createTemplate(jobDescription).make(global_variables),
356 ]
357 def _buildDescription = jobResult.getDescription().toString()
358 if(_buildDescription){
359 jobSummary['build_description'] = _buildDescription
360 }
361 // Store links to the resulting artifacts into 'global_variables'
362 storeArtifacts(jobSummary['build_url'], step['artifacts'],
363 global_variables, jobName, jobSummary['build_id'], artifactoryBaseUrl)
364 return jobSummary
365 }
366}
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300367/**
368 * Run the workflow or final steps one by one
369 *
370 * @param steps List of steps (Jenkins jobs) to execute
371 * @param global_variables Map where the collected artifact URLs and 'env' objects are stored
372 * @param failed_jobs Map with failed job names and result statuses, to report it later
AndrewB8505a7f2020-06-05 13:42:08 +0300373 * @param jobs_data Map with all job names and result statuses, to showing it in description
374 * @param step_id Counter for matching step ID with cell ID in description table
Dennis Dmitrieve09e0292019-07-30 16:39:27 +0300375 * @param propagate Boolean. If false: allows to collect artifacts after job is finished, even with FAILURE status
376 * If true: immediatelly fails the pipeline. DO NOT USE 'true' with runScenario().
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300377 */
Aleksey Zvyagintsev25ed4a52021-05-12 14:35:03 +0000378def runSteps(steps, global_variables, failed_jobs, jobs_data, step_id, Boolean propagate = false, artifactoryBaseUrl = '') {
azvyagintsevb673f392021-05-19 15:31:48 +0300379 common = new com.mirantis.mk.Common()
AndrewB8505a7f2020-06-05 13:42:08 +0300380 // Show expected jobs list in description
381 updateDescription(jobs_data)
382
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300383 for (step in steps) {
azvyagintsev0d978152022-01-27 14:01:33 +0200384 stage("Preparing for run job ${step['job']}") {
385 def job_summary = runStep(global_variables, step, propagate, artifactoryBaseUrl).call()
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300386
AndrewB8505a7f2020-06-05 13:42:08 +0300387 // Update jobs_data for updating description
azvyagintsev0d978152022-01-27 14:01:33 +0200388 jobs_data[step_id]['build_url'] = job_summary['build_url']
389 jobs_data[step_id]['build_id'] = job_summary['build_id']
390 jobs_data[step_id]['status'] = job_summary['job_result']
391 jobs_data[step_id]['duration'] = job_summary['buildDuration']
392 jobs_data[step_id]['desc'] = job_summary['desc']
393 if (job_summary['build_description']) {
394 jobs_data[step_id]['child_desc'] = job_summary['build_description']
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300395 }
AndrewB8505a7f2020-06-05 13:42:08 +0300396 updateDescription(jobs_data)
azvyagintsev0d978152022-01-27 14:01:33 +0200397 def job_result = job_summary['job_result']
398 def build_url = job_summary['build_url']
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300399
Mykyta Karpina3d775e2020-04-24 14:45:17 +0300400 // Check job result, in case of SUCCESS, move to next step.
Mykyta Karpin0bd8bc62020-04-29 12:27:14 +0300401 // 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 +0200402 // In other cases check flag ignore_failed, if true ignore any statuses and keep going additionally
403 // if skip_results is not set or set to false fail entrie workflow, otherwise succed.
azvyagintsev75390d92021-04-12 14:20:11 +0300404 if (job_result != 'SUCCESS') {
Mykyta Karpina3d775e2020-04-24 14:45:17 +0300405 def ignoreStepResult = false
azvyagintsev75390d92021-04-12 14:20:11 +0300406 switch (job_result) {
407 // In cases when job was waiting too long in queue or internal job logic allows to skip building,
408 // 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 +0300409 case "NOT_BUILT":
410 ignoreStepResult = step['ignore_not_built'] ?: false
411 break;
Dmitry Tyzhnenkoa1412702022-02-14 21:23:09 +0200412 case "UNSTABLE":
Dmitry Tyzhnenkobafca282022-02-17 17:49:54 +0200413 ignoreStepResult = step['ignore_unstable'] ?: (step['ignore_failed'] ?: false)
Dmitry Tyzhnenkoa1412702022-02-14 21:23:09 +0200414 break;
Mykyta Karpina3d775e2020-04-24 14:45:17 +0300415 default:
416 ignoreStepResult = step['ignore_failed'] ?: false
Vasyl Saienkoe72b9942021-03-04 10:54:49 +0200417 if (ignoreStepResult && !step['skip_results'] ?: false) {
418 failed_jobs[build_url] = job_result
419 }
Mykyta Karpina3d775e2020-04-24 14:45:17 +0300420 }
421 if (!ignoreStepResult) {
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300422 currentBuild.result = job_result
423 error "Job ${build_url} finished with result: ${job_result}"
azvyagintsev0d978152022-01-27 14:01:33 +0200424 }
425 }
azvyagintsev353b8762022-01-14 12:30:43 +0200426 common.infoMsg("Job ${build_url} finished with result: ${job_result}")
azvyagintsev0d978152022-01-27 14:01:33 +0200427 }
azvyagintsev75390d92021-04-12 14:20:11 +0300428 // Jump to next ID for updating next job data in description table
429 step_id++
azvyagintsev0d978152022-01-27 14:01:33 +0200430 }
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300431}
432
433/**
434 * Run the workflow scenario
435 *
436 * @param scenario: Map with scenario steps.
437
438 * There are two keys in the scenario:
439 * workflow: contains steps to run deploy and test jobs
440 * finally: contains steps to run report and cleanup jobs
441 *
442 * Scenario execution example:
443 *
444 * scenario_yaml = """\
445 * workflow:
446 * - job: deploy-kaas
447 * ignore_failed: false
AndrewB8505a7f2020-06-05 13:42:08 +0300448 * description: "Management cluster ${KAAS_VERSION}"
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300449 * parameters:
450 * KAAS_VERSION:
451 * type: StringParameterValue
452 * use_variable: KAAS_VERSION
453 * artifacts:
454 * KUBECONFIG_ARTIFACT: artifacts/management_kubeconfig
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +0300455 * DEPLOYED_KAAS_VERSION: artifacts/management_version
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300456 *
Dennis Dmitriev5f014d82020-04-29 00:00:34 +0300457 * - job: create-child
458 * inherit_parent_params: true
459 * ignore_failed: false
460 * parameters:
461 * KUBECONFIG_ARTIFACT_URL:
462 * type: StringParameterValue
463 * use_variable: KUBECONFIG_ARTIFACT
464 * KAAS_VERSION:
465 * type: StringParameterValue
466 * get_variable_from_url: DEPLOYED_KAAS_VERSION
Dennis Dmitriev6c355be2021-11-09 14:06:56 +0200467 * RELEASE_NAME:
468 * type: StringParameterValue
469 * get_variable_from_yaml:
470 * yaml_url: SI_CONFIG_ARTIFACT
471 * yaml_key: .clusters[0].release_name
Dennis Dmitriev5f014d82020-04-29 00:00:34 +0300472 *
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300473 * - job: test-kaas-ui
Mykyta Karpina3d775e2020-04-24 14:45:17 +0300474 * ignore_not_built: false
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300475 * parameters:
476 * KUBECONFIG_ARTIFACT_URL:
477 * type: StringParameterValue
478 * use_variable: KUBECONFIG_ARTIFACT
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +0300479 * KAAS_VERSION:
480 * type: StringParameterValue
481 * get_variable_from_url: DEPLOYED_KAAS_VERSION
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300482 * artifacts:
483 * REPORT_SI_KAAS_UI: artifacts/test_kaas_ui_result.xml
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300484 * finally:
485 * - job: testrail-report
486 * ignore_failed: true
487 * parameters:
Dennis Dmitrievce470932019-09-18 18:31:11 +0300488 * KAAS_VERSION:
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300489 * type: StringParameterValue
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +0300490 * get_variable_from_url: DEPLOYED_KAAS_VERSION
Dennis Dmitrievce470932019-09-18 18:31:11 +0300491 * REPORTS_LIST:
492 * type: TextParameterValue
493 * use_template: |
494 * REPORT_SI_KAAS_UI: \$REPORT_SI_KAAS_UI
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300495 * """
496 *
497 * runScenario(scenario)
498 *
Dennis Dmitriev5f014d82020-04-29 00:00:34 +0300499 * Scenario workflow keys:
500 *
501 * job: string. Jenkins job name
502 * 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 +0200503 * 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 +0300504 * 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
505 * inherit_parent_params: bool. if true, provide all parameters from the parent job to the child job as defaults
506 * 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 +0200507 * wf_pause_step_before_run: bool. Interactive pause exact step before run.
508 * wf_pause_step_slack_report_channel: If step paused, send message about it in slack.
509 * wf_pause_step_timeout: timeout im minutes to wait for manual unpause.
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300510 */
511
Aleksey Zvyagintsev25ed4a52021-05-12 14:35:03 +0000512def runScenario(scenario, slackReportChannel = '', artifactoryBaseUrl = '') {
Dennis Dmitriev79f3a2d2019-08-09 16:06:00 +0300513 // Clear description before adding new messages
514 currentBuild.description = ''
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300515 // Collect the parameters for the jobs here
azvyagintsev0d978152022-01-27 14:01:33 +0200516 def global_variables = [:]
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300517 // List of failed jobs to show at the end
azvyagintsev0d978152022-01-27 14:01:33 +0200518 def failed_jobs = [:]
AndrewB8505a7f2020-06-05 13:42:08 +0300519 // Jobs data to use for wf job build description
520 def jobs_data = []
521 // Counter for matching step ID with cell ID in description table
azvyagintsev0d978152022-01-27 14:01:33 +0200522 def step_id = 0
AndrewB8505a7f2020-06-05 13:42:08 +0300523
524 // Generate expected list jobs for description
azvyagintsev0d978152022-01-27 14:01:33 +0200525 def list_id = 0
AndrewB8505a7f2020-06-05 13:42:08 +0300526 for (step in scenario['workflow']) {
azvyagintsev0d978152022-01-27 14:01:33 +0200527 def display_name = step['job']
azvyagintsev75390d92021-04-12 14:20:11 +0300528 if (step['description'] != null && step['description'].toString() != "") {
AndrewB8505a7f2020-06-05 13:42:08 +0300529 display_name = step['description']
AndrewB8505a7f2020-06-05 13:42:08 +0300530 }
azvyagintsev061179d2021-05-05 16:52:18 +0300531 jobs_data.add([list_id : "$list_id",
532 type : "workflow",
533 name : "$display_name",
534 build_url : "0",
535 build_id : "-",
536 status : "-",
537 desc : "",
azvyagintsev2eeaa562022-01-27 12:03:40 +0200538 child_desc: "",
539 duration : '-'])
AndrewB8505a7f2020-06-05 13:42:08 +0300540 list_id += 1
541 }
azvyagintsev0d978152022-01-27 14:01:33 +0200542
543 def finally_step_id = list_id
AndrewB8505a7f2020-06-05 13:42:08 +0300544 for (step in scenario['finally']) {
azvyagintsev0d978152022-01-27 14:01:33 +0200545 def display_name = step['job']
azvyagintsev75390d92021-04-12 14:20:11 +0300546 if (step['description'] != null && step['description'].toString() != "") {
AndrewB8505a7f2020-06-05 13:42:08 +0300547 display_name = step['description']
AndrewB8505a7f2020-06-05 13:42:08 +0300548 }
azvyagintsev061179d2021-05-05 16:52:18 +0300549 jobs_data.add([list_id : "$list_id",
550 type : "finally",
551 name : "$display_name",
552 build_url : "0",
553 build_id : "-",
554 status : "-",
555 desc : "",
azvyagintsev2eeaa562022-01-27 12:03:40 +0200556 child_desc: "",
557 duration : '-'])
AndrewB8505a7f2020-06-05 13:42:08 +0300558 list_id += 1
559 }
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300560
561 try {
562 // Run the 'workflow' jobs
Aleksey Zvyagintsev25ed4a52021-05-12 14:35:03 +0000563 runSteps(scenario['workflow'], global_variables, failed_jobs, jobs_data, step_id, false, artifactoryBaseUrl)
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300564 } catch (InterruptedException x) {
565 error "The job was aborted"
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300566 } catch (e) {
567 error("Build failed: " + e.toString())
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300568 } finally {
AndrewB8505a7f2020-06-05 13:42:08 +0300569 // Switching to 'finally' step index
570 step_id = finally_step_id
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300571 // Run the 'finally' jobs
Aleksey Zvyagintsev25ed4a52021-05-12 14:35:03 +0000572 runSteps(scenario['finally'], global_variables, failed_jobs, jobs_data, step_id, false, artifactoryBaseUrl)
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300573
574 if (failed_jobs) {
azvyagintsev0d978152022-01-27 14:01:33 +0200575 def statuses = []
sgudz9ac09d22020-01-22 14:31:30 +0200576 failed_jobs.each {
sgudz74c8cdd2020-01-23 14:26:32 +0200577 statuses += it.value
azvyagintsev75390d92021-04-12 14:20:11 +0300578 }
sgudz9ac09d22020-01-22 14:31:30 +0200579 if (statuses.contains('FAILURE')) {
580 currentBuild.result = 'FAILURE'
azvyagintsev75390d92021-04-12 14:20:11 +0300581 } else if (statuses.contains('UNSTABLE')) {
sgudz9ac09d22020-01-22 14:31:30 +0200582 currentBuild.result = 'UNSTABLE'
azvyagintsev75390d92021-04-12 14:20:11 +0300583 } else {
sgudz9ac09d22020-01-22 14:31:30 +0200584 currentBuild.result = 'FAILURE'
585 }
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300586 println "Failed jobs: ${failed_jobs}"
vnaumov68cba272020-05-20 11:24:02 +0200587 } else {
588 currentBuild.result = 'SUCCESS'
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300589 }
vnaumov5a6eb8a2020-03-31 11:16:54 +0200590
591 if (slackReportChannel) {
592 def slack = new com.mirantis.mcp.SlackNotification()
593 slack.jobResultNotification(currentBuild.result, slackReportChannel, '', null, '', 'slack_webhook_url')
594 }
sgudz9ac09d22020-01-22 14:31:30 +0200595 } // finally
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300596}