blob: 2bd24ea708f81ccf1f8a2d401c4d8a8c285cdfa6 [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 Dmitriev5d8a1532019-07-30 16:39:27 +030055 * @param global_variables Map that keeps the artifact URLs and used 'env' objects:
56 * {'PARAM1_NAME': <param1 value>, 'PARAM2_NAME': 'http://.../artifacts/param2_value', ...}
Dennis Dmitrieve09e0292019-07-30 16:39:27 +030057 * @param propagate Boolean. If false: allows to collect artifacts after job is finished, even with FAILURE status
58 * If true: immediatelly fails the pipeline. DO NOT USE 'true' if you want to collect artifacts
59 * for 'finally' steps
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +030060 */
Dennis Dmitrieve09e0292019-07-30 16:39:27 +030061def runJob(job_name, job_parameters, global_variables, Boolean propagate = false) {
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +030062 def parameters = []
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +030063 def http = new com.mirantis.mk.Http()
Dennis Dmitrievce470932019-09-18 18:31:11 +030064 def engine = new groovy.text.GStringTemplateEngine()
65 def template
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +030066 def base = [:]
67 base["url"] = ''
68 def variable_content
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +030069
70 // Collect required parameters from 'global_variables' or 'env'
71 for (param in job_parameters) {
Dennis Dmitrievce470932019-09-18 18:31:11 +030072 if (param.value.containsKey('use_variable')) {
73 if (!global_variables[param.value.use_variable]) {
74 global_variables[param.value.use_variable] = env[param.value.use_variable] ?: ''
75 }
76 parameters.add([$class: "${param.value.type}", name: "${param.key}", value: global_variables[param.value.use_variable]])
77 println "${param.key}: <${param.value.type}> ${global_variables[param.value.use_variable]}"
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +030078 } else if (param.value.containsKey('get_variable_from_url')) {
79 if (!global_variables[param.value.get_variable_from_url]) {
80 global_variables[param.value.get_variable_from_url] = env[param.value.get_variable_from_url] ?: ''
81 }
Andrew Baraniuke0aef1e2019-10-16 14:50:10 +030082 if (global_variables[param.value.get_variable_from_url]) {
Dennis Dmitriev37828362019-11-11 18:06:49 +020083 variable_content = http.restGet(base, global_variables[param.value.get_variable_from_url]).trim()
Andrew Baraniuke0aef1e2019-10-16 14:50:10 +030084 parameters.add([$class: "${param.value.type}", name: "${param.key}", value: variable_content])
85 println "${param.key}: <${param.value.type}> ${variable_content}"
86 } else {
87 println "${param.key} is empty, skipping get_variable_from_url"
88 }
Dennis Dmitrievce470932019-09-18 18:31:11 +030089 } else if (param.value.containsKey('use_template')) {
90 template = engine.createTemplate(param.value.use_template).make(global_variables)
91 parameters.add([$class: "${param.value.type}", name: "${param.key}", value: template.toString()])
92 println "${param.key}: <${param.value.type}>\n${template.toString()}"
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +030093 }
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +030094 }
95
96 // Build the job
Dennis Dmitrieve09e0292019-07-30 16:39:27 +030097 def job_info = build job: "${job_name}", parameters: parameters, propagate: propagate
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +030098 return job_info
99}
100
azvyagintsev061179d2021-05-05 16:52:18 +0300101def runOrGetJob(job_name, job_parameters, global_variables, propagate, String fullTaskName = '') {
102 /**
103 * Run job directly or try to find already executed build
104 * Flow, in case CI_JOBS_OVERRIDES passed:
105 *
106 *
107 * CI_JOBS_OVERRIDES = text in yaml|json format
108 * CI_JOBS_OVERRIDES = 'kaas-testing-core-release-artifact' : 3505
109 * 'reindex-testing-core-release-index-with-rc' : 2822
110 * 'si-test-release-sanity-check-prepare-configuration': 1877
111 */
112 common = new com.mirantis.mk.Common()
113 def jobsOverrides = readYaml(text: env.CI_JOBS_OVERRIDES ?: '---') ?: [:]
114 // get id of overriding job
115 def jobOverrideID = jobsOverrides.getOrDefault(fullTaskName, '')
116
117 if (fullTaskName in jobsOverrides.keySet()) {
118 common.warningMsg("Overriding: ${fullTaskName}/${job_name} <<< ${jobOverrideID}")
119 common.infoMsg("For debug pin use:\n'${fullTaskName}' : ${jobOverrideID}")
120 return Jenkins.instance.getItemByFullName(job_name,
121 hudson.model.Job.class).getBuildByNumber(jobOverrideID.toInteger())
122 } else {
123 return runJob(job_name, job_parameters, global_variables, propagate)
124 }
125}
126
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300127/**
128 * Store URLs of the specified artifacts to the global_variables
129 *
130 * @param build_url URL of the completed job
131 * @param step_artifacts Map that contains artifact names in the job, and variable names
132 * where the URLs to that atrifacts should be stored, for example:
133 * {'ARTIFACT1': 'logs.tar.gz', 'ARTIFACT2': 'test_report.xml', ...}
134 * @param global_variables Map that will keep the artifact URLs. Variable 'ARTIFACT1', for example,
135 * be used in next job parameters: {'ARTIFACT1_URL':{ 'use_variable': 'ARTIFACT1', ...}}
136 *
137 * If the artifact with the specified name not found, the parameter ARTIFACT1_URL
138 * will be empty.
139 *
140 */
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300141def storeArtifacts(build_url, step_artifacts, global_variables, job_name, build_num) {
142 def common = new com.mirantis.mk.Common()
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300143 def http = new com.mirantis.mk.Http()
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300144 def baseJenkins = [:]
145 def baseArtifactory = [:]
146 build_url = build_url.replaceAll(~/\/+$/, "")
147 artifactory_url = "https://artifactory.mcp.mirantis.net/api/storage/si-local/jenkins-job-artifacts"
148 baseArtifactory["url"] = artifactory_url + "/${job_name}/${build_num}"
149
150 baseJenkins["url"] = build_url
151 def job_config = http.restGet(baseJenkins, "/api/json/")
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300152 def job_artifacts = job_config['artifacts']
153 for (artifact in step_artifacts) {
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300154 try {
155 artifactoryResp = http.restGet(baseArtifactory, "/${artifact.value}")
156 global_variables[artifact.key] = artifactoryResp.downloadUri
157 println "Artifact URL ${artifactoryResp.downloadUri} stored to ${artifact.key}"
158 continue
159 } catch (Exception e) {
160 common.warningMsg("Can't find an artifact in ${artifactory_url}/${job_name}/${build_num}/${artifact.value} error code ${e.message}")
161 }
162
163 job_artifact = job_artifacts.findAll { item -> artifact.value == item['fileName'] || artifact.value == item['relativePath'] }
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300164 if (job_artifact.size() == 1) {
165 // Store artifact URL
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300166 def artifact_url = "${build_url}/artifact/${job_artifact[0]['relativePath']}"
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300167 global_variables[artifact.key] = artifact_url
168 println "Artifact URL ${artifact_url} stored to ${artifact.key}"
169 } else if (job_artifact.size() > 1) {
170 // Error: too many artifacts with the same name, fail the job
171 error "Multiple artifacts ${artifact.value} for ${artifact.key} found in the build results ${build_url}, expected one:\n${job_artifact}"
172 } else {
173 // Warning: no artifact with expected name
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300174 println "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 +0300175 global_variables[artifact.key] = ''
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300176 }
177 }
178}
179
AndrewB8505a7f2020-06-05 13:42:08 +0300180/**
181 * Update workflow job build description
182 *
183 * @param jobs_data Map with all job names and result statuses, to showing it in description
184 */
185def updateDescription(jobs_data) {
186 table = ''
187 child_jobs_description = '<strong>Descriptions from jobs:</strong><br>'
188 table_template_start = "<div><table style='border: solid 1px;'><tr><th>Job:</th><th>Status:</th></tr>"
189 table_template_end = "</table></div>"
190
191 for (jobdata in jobs_data) {
192 // Grey background for 'finally' jobs in list
193 if (jobdata['type'] == 'finally') {
194 trstyle = "<tr style='background: #DDDDDD;'>"
195 } else {
196 trstyle = "<tr>"
197 }
198
199 // 'description' instead of job name if it exists
azvyagintsev75390d92021-04-12 14:20:11 +0300200 if (jobdata['desc'].toString() != "") {
azvyagintsev061179d2021-05-05 16:52:18 +0300201 display_name = "'${jobdata['desc']}': ${jobdata['build_id']}"
AndrewB8505a7f2020-06-05 13:42:08 +0300202 } else {
azvyagintsev061179d2021-05-05 16:52:18 +0300203 display_name = "'${jobdata['name']}': ${jobdata['build_id']}"
AndrewB8505a7f2020-06-05 13:42:08 +0300204 }
205
206 // Attach url for already builded jobs
azvyagintsev75390d92021-04-12 14:20:11 +0300207 if (jobdata['build_url'] != "0") {
AndrewB8505a7f2020-06-05 13:42:08 +0300208 build_url = "<a href=${jobdata['build_url']}>$display_name</a>"
209 } else {
210 build_url = display_name
211 }
212
213 // Styling the status of job result
azvyagintsev75390d92021-04-12 14:20:11 +0300214 switch (jobdata['status'].toString()) {
AndrewB8505a7f2020-06-05 13:42:08 +0300215 case "SUCCESS":
216 status_style = "<td style='color: green;'><img src='/images/16x16/blue.png' alt='SUCCESS'>"
217 break
218 case "UNSTABLE":
219 status_style = "<td style='color: #FF5733;'><img src='/images/16x16/yellow.png' alt='UNSTABLE'>"
220 break
221 case "ABORTED":
222 status_style = "<td style='color: red;'><img src='/images/16x16/aborted.png' alt='ABORTED'>"
223 break
224 case "NOT_BUILT":
225 status_style = "<td style='color: red;'><img src='/images/16x16/aborted.png' alt='NOT_BUILT'>"
226 break
227 case "FAILURE":
228 status_style = "<td style='color: red;'><img src='/images/16x16/red.png' alt='FAILURE'>"
229 break
230 default:
231 status_style = "<td>-"
232 }
233
234 // Collect table
235 table += "$trstyle<td>$build_url</td>$status_style</td></tr>"
236
237 // Collecting descriptions of builded child jobs
238 if (jobdata['child_desc'] != "") {
239 child_jobs_description += "<b><small><a href=${jobdata['build_url']}>- ${jobdata['name']} (${jobdata['status']}):</a></small></b><br>"
240 child_jobs_description += "<small>${jobdata['child_desc']}</small><br>"
241 }
242 }
243 currentBuild.description = table_template_start + table + table_template_end + child_jobs_description
244}
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300245
246/**
247 * Run the workflow or final steps one by one
248 *
249 * @param steps List of steps (Jenkins jobs) to execute
250 * @param global_variables Map where the collected artifact URLs and 'env' objects are stored
251 * @param failed_jobs Map with failed job names and result statuses, to report it later
AndrewB8505a7f2020-06-05 13:42:08 +0300252 * @param jobs_data Map with all job names and result statuses, to showing it in description
253 * @param step_id Counter for matching step ID with cell ID in description table
Dennis Dmitrieve09e0292019-07-30 16:39:27 +0300254 * @param propagate Boolean. If false: allows to collect artifacts after job is finished, even with FAILURE status
255 * If true: immediatelly fails the pipeline. DO NOT USE 'true' with runScenario().
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300256 */
AndrewB8505a7f2020-06-05 13:42:08 +0300257def runSteps(steps, global_variables, failed_jobs, jobs_data, step_id, Boolean propagate = false) {
258 // Show expected jobs list in description
259 updateDescription(jobs_data)
260
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300261 for (step in steps) {
262 stage("Running job ${step['job']}") {
AndrewB8505a7f2020-06-05 13:42:08 +0300263 def engine = new groovy.text.GStringTemplateEngine()
azvyagintsev061179d2021-05-05 16:52:18 +0300264 String desc = step['description'] ?: ''
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300265 def job_name = step['job']
Dennis Dmitriev5f014d82020-04-29 00:00:34 +0300266 def job_parameters = [:]
Dennis Dmitriev334eecd2020-04-30 14:32:45 +0300267 def step_parameters = step['parameters'] ?: [:]
Dennis Dmitriev5f014d82020-04-29 00:00:34 +0300268 if (step['inherit_parent_params'] ?: false) {
269 // add parameters from the current job for the child job
270 job_parameters << getJobDefaultParameters(env.JOB_NAME)
271 }
272 // add parameters from the workflow for the child job
Dennis Dmitriev334eecd2020-04-30 14:32:45 +0300273 job_parameters << step_parameters
Dennis Dmitriev5f014d82020-04-29 00:00:34 +0300274
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300275 // Collect job parameters and run the job
azvyagintsev061179d2021-05-05 16:52:18 +0300276 // WARN(alexz): desc must not contain invalid chars for yaml
277 def job_info = runOrGetJob(job_name, job_parameters, global_variables, propagate, desc)
278 def job_result = job_info.getResult().toString()
279 def build_url = job_info.getAbsoluteUrl().toString()
280 def build_description = job_info.getDescription().toString()
281 def build_id = job_info.getId().toString()
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300282
AndrewB8505a7f2020-06-05 13:42:08 +0300283 // Update jobs_data for updating description
284 jobs_data[step_id]['build_url'] = build_url
azvyagintsev061179d2021-05-05 16:52:18 +0300285 jobs_data[step_id]['build_id'] = build_id
AndrewB8505a7f2020-06-05 13:42:08 +0300286 jobs_data[step_id]['status'] = job_result
287 jobs_data[step_id]['desc'] = engine.createTemplate(desc).make(global_variables)
288 if (build_description) {
289 jobs_data[step_id]['child_desc'] = build_description
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300290 }
291
AndrewB8505a7f2020-06-05 13:42:08 +0300292 updateDescription(jobs_data)
293
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300294 // Store links to the resulting artifacts into 'global_variables'
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300295 storeArtifacts(build_url, step['artifacts'], global_variables, job_name, build_id)
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300296
Mykyta Karpina3d775e2020-04-24 14:45:17 +0300297 // Check job result, in case of SUCCESS, move to next step.
Mykyta Karpin0bd8bc62020-04-29 12:27:14 +0300298 // 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 +0200299 // In other cases check flag ignore_failed, if true ignore any statuses and keep going additionally
300 // if skip_results is not set or set to false fail entrie workflow, otherwise succed.
azvyagintsev75390d92021-04-12 14:20:11 +0300301 if (job_result != 'SUCCESS') {
Mykyta Karpina3d775e2020-04-24 14:45:17 +0300302 def ignoreStepResult = false
azvyagintsev75390d92021-04-12 14:20:11 +0300303 switch (job_result) {
304 // In cases when job was waiting too long in queue or internal job logic allows to skip building,
305 // 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 +0300306 case "NOT_BUILT":
307 ignoreStepResult = step['ignore_not_built'] ?: false
308 break;
309 default:
310 ignoreStepResult = step['ignore_failed'] ?: false
Vasyl Saienkoe72b9942021-03-04 10:54:49 +0200311 if (ignoreStepResult && !step['skip_results'] ?: false) {
312 failed_jobs[build_url] = job_result
313 }
Mykyta Karpina3d775e2020-04-24 14:45:17 +0300314 }
315 if (!ignoreStepResult) {
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300316 currentBuild.result = job_result
317 error "Job ${build_url} finished with result: ${job_result}"
Mykyta Karpina3d775e2020-04-24 14:45:17 +0300318 } // if (!ignoreStepResult)
319 } // if (job_result != 'SUCCESS')
320 println "Job ${build_url} finished with result: ${job_result}"
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300321 } // stage ("Running job ${step['job']}")
azvyagintsev75390d92021-04-12 14:20:11 +0300322 // Jump to next ID for updating next job data in description table
323 step_id++
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300324 } // for (step in scenario['workflow'])
325}
326
327/**
328 * Run the workflow scenario
329 *
330 * @param scenario: Map with scenario steps.
331
332 * There are two keys in the scenario:
333 * workflow: contains steps to run deploy and test jobs
334 * finally: contains steps to run report and cleanup jobs
335 *
336 * Scenario execution example:
337 *
338 * scenario_yaml = """\
339 * workflow:
340 * - job: deploy-kaas
341 * ignore_failed: false
AndrewB8505a7f2020-06-05 13:42:08 +0300342 * description: "Management cluster ${KAAS_VERSION}"
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300343 * parameters:
344 * KAAS_VERSION:
345 * type: StringParameterValue
346 * use_variable: KAAS_VERSION
347 * artifacts:
348 * KUBECONFIG_ARTIFACT: artifacts/management_kubeconfig
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +0300349 * DEPLOYED_KAAS_VERSION: artifacts/management_version
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300350 *
Dennis Dmitriev5f014d82020-04-29 00:00:34 +0300351 * - job: create-child
352 * inherit_parent_params: true
353 * ignore_failed: false
354 * parameters:
355 * KUBECONFIG_ARTIFACT_URL:
356 * type: StringParameterValue
357 * use_variable: KUBECONFIG_ARTIFACT
358 * KAAS_VERSION:
359 * type: StringParameterValue
360 * get_variable_from_url: DEPLOYED_KAAS_VERSION
361 *
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300362 * - job: test-kaas-ui
Mykyta Karpina3d775e2020-04-24 14:45:17 +0300363 * ignore_not_built: false
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300364 * parameters:
365 * KUBECONFIG_ARTIFACT_URL:
366 * type: StringParameterValue
367 * use_variable: KUBECONFIG_ARTIFACT
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +0300368 * KAAS_VERSION:
369 * type: StringParameterValue
370 * get_variable_from_url: DEPLOYED_KAAS_VERSION
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300371 * artifacts:
372 * REPORT_SI_KAAS_UI: artifacts/test_kaas_ui_result.xml
373 *
374 * finally:
375 * - job: testrail-report
376 * ignore_failed: true
377 * parameters:
Dennis Dmitrievce470932019-09-18 18:31:11 +0300378 * KAAS_VERSION:
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300379 * type: StringParameterValue
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +0300380 * get_variable_from_url: DEPLOYED_KAAS_VERSION
Dennis Dmitrievce470932019-09-18 18:31:11 +0300381 * REPORTS_LIST:
382 * type: TextParameterValue
383 * use_template: |
384 * REPORT_SI_KAAS_UI: \$REPORT_SI_KAAS_UI
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300385 * """
386 *
387 * runScenario(scenario)
388 *
Dennis Dmitriev5f014d82020-04-29 00:00:34 +0300389 * Scenario workflow keys:
390 *
391 * job: string. Jenkins job name
392 * 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 +0200393 * 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 +0300394 * 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
395 * inherit_parent_params: bool. if true, provide all parameters from the parent job to the child job as defaults
396 * parameters: dict. parameters name and type to inherit from parent to child job, or from artifact to child job
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300397 */
398
vnaumov5a6eb8a2020-03-31 11:16:54 +0200399def runScenario(scenario, slackReportChannel = '') {
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300400
Dennis Dmitriev79f3a2d2019-08-09 16:06:00 +0300401 // Clear description before adding new messages
402 currentBuild.description = ''
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300403 // Collect the parameters for the jobs here
404 global_variables = [:]
405 // List of failed jobs to show at the end
406 failed_jobs = [:]
AndrewB8505a7f2020-06-05 13:42:08 +0300407 // Jobs data to use for wf job build description
408 def jobs_data = []
409 // Counter for matching step ID with cell ID in description table
410 step_id = 0
411
412 // Generate expected list jobs for description
413 list_id = 0
414 for (step in scenario['workflow']) {
azvyagintsev75390d92021-04-12 14:20:11 +0300415 if (step['description'] != null && step['description'].toString() != "") {
AndrewB8505a7f2020-06-05 13:42:08 +0300416 display_name = step['description']
417 } else {
418 display_name = step['job']
419 }
azvyagintsev061179d2021-05-05 16:52:18 +0300420 jobs_data.add([list_id : "$list_id",
421 type : "workflow",
422 name : "$display_name",
423 build_url : "0",
424 build_id : "-",
425 status : "-",
426 desc : "",
427 child_desc: ""])
AndrewB8505a7f2020-06-05 13:42:08 +0300428 list_id += 1
429 }
430 finally_step_id = list_id
431 for (step in scenario['finally']) {
azvyagintsev75390d92021-04-12 14:20:11 +0300432 if (step['description'] != null && step['description'].toString() != "") {
AndrewB8505a7f2020-06-05 13:42:08 +0300433 display_name = step['description']
434 } else {
435 display_name = step['job']
436 }
azvyagintsev061179d2021-05-05 16:52:18 +0300437 jobs_data.add([list_id : "$list_id",
438 type : "finally",
439 name : "$display_name",
440 build_url : "0",
441 build_id : "-",
442 status : "-",
443 desc : "",
444 child_desc: ""])
AndrewB8505a7f2020-06-05 13:42:08 +0300445 list_id += 1
446 }
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300447
448 try {
449 // Run the 'workflow' jobs
AndrewB8505a7f2020-06-05 13:42:08 +0300450 runSteps(scenario['workflow'], global_variables, failed_jobs, jobs_data, step_id)
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300451 } catch (InterruptedException x) {
452 error "The job was aborted"
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300453 } catch (e) {
454 error("Build failed: " + e.toString())
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300455 } finally {
AndrewB8505a7f2020-06-05 13:42:08 +0300456 // Switching to 'finally' step index
457 step_id = finally_step_id
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300458 // Run the 'finally' jobs
AndrewB8505a7f2020-06-05 13:42:08 +0300459 runSteps(scenario['finally'], global_variables, failed_jobs, jobs_data, step_id)
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300460
461 if (failed_jobs) {
sgudz9ac09d22020-01-22 14:31:30 +0200462 statuses = []
463 failed_jobs.each {
sgudz74c8cdd2020-01-23 14:26:32 +0200464 statuses += it.value
azvyagintsev75390d92021-04-12 14:20:11 +0300465 }
sgudz9ac09d22020-01-22 14:31:30 +0200466 if (statuses.contains('FAILURE')) {
467 currentBuild.result = 'FAILURE'
azvyagintsev75390d92021-04-12 14:20:11 +0300468 } else if (statuses.contains('UNSTABLE')) {
sgudz9ac09d22020-01-22 14:31:30 +0200469 currentBuild.result = 'UNSTABLE'
azvyagintsev75390d92021-04-12 14:20:11 +0300470 } else {
sgudz9ac09d22020-01-22 14:31:30 +0200471 currentBuild.result = 'FAILURE'
472 }
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300473 println "Failed jobs: ${failed_jobs}"
vnaumov68cba272020-05-20 11:24:02 +0200474 } else {
475 currentBuild.result = 'SUCCESS'
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300476 }
vnaumov5a6eb8a2020-03-31 11:16:54 +0200477
478 if (slackReportChannel) {
479 def slack = new com.mirantis.mcp.SlackNotification()
480 slack.jobResultNotification(currentBuild.result, slackReportChannel, '', null, '', 'slack_webhook_url')
481 }
sgudz9ac09d22020-01-22 14:31:30 +0200482 } // finally
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300483}