blob: e6c50a7cf8074fd350838f96f0228e8c9e244b0e [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 = []
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +030066 def http = new com.mirantis.mk.Http()
Dennis Dmitrievce470932019-09-18 18:31:11 +030067 def engine = new groovy.text.GStringTemplateEngine()
68 def template
Dennis Dmitriev6c355be2021-11-09 14:06:56 +020069 def yamls_from_urls = [:]
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +030070 def base = [:]
71 base["url"] = ''
72 def variable_content
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +030073
74 // Collect required parameters from 'global_variables' or 'env'
75 for (param in job_parameters) {
Dennis Dmitrievce470932019-09-18 18:31:11 +030076 if (param.value.containsKey('use_variable')) {
77 if (!global_variables[param.value.use_variable]) {
78 global_variables[param.value.use_variable] = env[param.value.use_variable] ?: ''
79 }
80 parameters.add([$class: "${param.value.type}", name: "${param.key}", value: global_variables[param.value.use_variable]])
81 println "${param.key}: <${param.value.type}> ${global_variables[param.value.use_variable]}"
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +030082 } else if (param.value.containsKey('get_variable_from_url')) {
83 if (!global_variables[param.value.get_variable_from_url]) {
84 global_variables[param.value.get_variable_from_url] = env[param.value.get_variable_from_url] ?: ''
85 }
Andrew Baraniuke0aef1e2019-10-16 14:50:10 +030086 if (global_variables[param.value.get_variable_from_url]) {
Dennis Dmitriev37828362019-11-11 18:06:49 +020087 variable_content = http.restGet(base, global_variables[param.value.get_variable_from_url]).trim()
Andrew Baraniuke0aef1e2019-10-16 14:50:10 +030088 parameters.add([$class: "${param.value.type}", name: "${param.key}", value: variable_content])
89 println "${param.key}: <${param.value.type}> ${variable_content}"
90 } else {
91 println "${param.key} is empty, skipping get_variable_from_url"
92 }
Dennis Dmitriev6c355be2021-11-09 14:06:56 +020093 } else if (param.value.containsKey('get_variable_from_yaml')) {
94 if (param.value.get_variable_from_yaml.containsKey('yaml_url') && param.value.get_variable_from_yaml.containsKey('yaml_key')) {
95 // YAML url is stored in an environment or a global variable (like 'SI_CONFIG_ARTIFACT')
96 yaml_url_var = param.value.get_variable_from_yaml.yaml_url
97 if (!global_variables[yaml_url_var]) {
98 global_variables[yaml_url_var] = env[yaml_url_var] ?: ''
99 }
100 yaml_url = global_variables[yaml_url_var] // Real YAML URL
101 yaml_key = param.value.get_variable_from_yaml.yaml_key // Key to get the data from YAML, to interpolate in the groovy, for example:
102 // <yaml_map_variable>.key.to.the[0].required.data , where yaml_key = '.key.to.the[0].required.data'
103 if (yaml_url) {
104 if (!yamls_from_urls[yaml_url]) {
105 println "Reading YAML from ${yaml_url} for ${param.key}"
106 yaml_content = http.restGet(base, yaml_url)
107 yamls_from_urls[yaml_url] = readYaml text: yaml_content
108 }
109 println "Getting key ${yaml_key} from YAML ${yaml_url} for ${param.key}"
110 template_variables = [
111 'yaml_data': yamls_from_urls[yaml_url]
112 ]
113 request = "\${yaml_data${yaml_key}}"
Dennis Dmitriev450cf732021-11-11 14:59:17 +0200114
115 // Catch errors related to wrong key or index in the list or map objects
116 // For wrong key in map or wrong index in list, groovy returns <null> object,
117 // but it can be catched only after the string interpolation <template.toString()>,
118 // so we should catch the string 'null' instead of object <null>.
119 try {
120 template = engine.createTemplate(request).make(template_variables)
121 result = template.toString()
122 if (result == 'null') {
123 error "No such key or index, got 'null'"
124 }
125 } catch (e) {
126 error("Failed to get the key ${yaml_key} from YAML ${yaml_url}: " + e.toString())
127 }
128
129 parameters.add([$class: "${param.value.type}", name: "${param.key}", value: result])
130 println "${param.key}: <${param.value.type}>\n${result}"
Dennis Dmitriev6c355be2021-11-09 14:06:56 +0200131 } else {
132 println "'yaml_url' in ${param.key} is empty, skipping get_variable_from_yaml"
133 }
134 } else {
135 println "${param.key} missing 'yaml_url'/'yaml_key' parameters, skipping get_variable_from_yaml"
136 }
Dennis Dmitrievce470932019-09-18 18:31:11 +0300137 } else if (param.value.containsKey('use_template')) {
138 template = engine.createTemplate(param.value.use_template).make(global_variables)
139 parameters.add([$class: "${param.value.type}", name: "${param.key}", value: template.toString()])
140 println "${param.key}: <${param.value.type}>\n${template.toString()}"
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300141 }
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300142 }
143
144 // Build the job
Dennis Dmitrieve09e0292019-07-30 16:39:27 +0300145 def job_info = build job: "${job_name}", parameters: parameters, propagate: propagate
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300146 return job_info
147}
148
azvyagintsev061179d2021-05-05 16:52:18 +0300149def runOrGetJob(job_name, job_parameters, global_variables, propagate, String fullTaskName = '') {
150 /**
151 * Run job directly or try to find already executed build
152 * Flow, in case CI_JOBS_OVERRIDES passed:
153 *
154 *
155 * CI_JOBS_OVERRIDES = text in yaml|json format
156 * CI_JOBS_OVERRIDES = 'kaas-testing-core-release-artifact' : 3505
157 * 'reindex-testing-core-release-index-with-rc' : 2822
158 * 'si-test-release-sanity-check-prepare-configuration': 1877
159 */
160 common = new com.mirantis.mk.Common()
161 def jobsOverrides = readYaml(text: env.CI_JOBS_OVERRIDES ?: '---') ?: [:]
162 // get id of overriding job
163 def jobOverrideID = jobsOverrides.getOrDefault(fullTaskName, '')
164
165 if (fullTaskName in jobsOverrides.keySet()) {
166 common.warningMsg("Overriding: ${fullTaskName}/${job_name} <<< ${jobOverrideID}")
167 common.infoMsg("For debug pin use:\n'${fullTaskName}' : ${jobOverrideID}")
168 return Jenkins.instance.getItemByFullName(job_name,
169 hudson.model.Job.class).getBuildByNumber(jobOverrideID.toInteger())
170 } else {
171 return runJob(job_name, job_parameters, global_variables, propagate)
172 }
173}
174
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300175/**
176 * Store URLs of the specified artifacts to the global_variables
177 *
178 * @param build_url URL of the completed job
179 * @param step_artifacts Map that contains artifact names in the job, and variable names
180 * where the URLs to that atrifacts should be stored, for example:
181 * {'ARTIFACT1': 'logs.tar.gz', 'ARTIFACT2': 'test_report.xml', ...}
182 * @param global_variables Map that will keep the artifact URLs. Variable 'ARTIFACT1', for example,
183 * be used in next job parameters: {'ARTIFACT1_URL':{ 'use_variable': 'ARTIFACT1', ...}}
184 *
185 * If the artifact with the specified name not found, the parameter ARTIFACT1_URL
186 * will be empty.
187 *
188 */
Aleksey Zvyagintsev25ed4a52021-05-12 14:35:03 +0000189def storeArtifacts(build_url, step_artifacts, global_variables, job_name, build_num, artifactory_url = '') {
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300190 def common = new com.mirantis.mk.Common()
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300191 def http = new com.mirantis.mk.Http()
Aleksey Zvyagintsev25ed4a52021-05-12 14:35:03 +0000192 if (!artifactory_url) {
193 artifactory_url = 'https://artifactory.mcp.mirantis.net/api/storage/si-local/jenkins-job-artifacts'
194 }
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300195 def baseJenkins = [:]
196 def baseArtifactory = [:]
197 build_url = build_url.replaceAll(~/\/+$/, "")
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300198 baseArtifactory["url"] = artifactory_url + "/${job_name}/${build_num}"
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300199 baseJenkins["url"] = build_url
200 def job_config = http.restGet(baseJenkins, "/api/json/")
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300201 def job_artifacts = job_config['artifacts']
202 for (artifact in step_artifacts) {
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300203 try {
204 artifactoryResp = http.restGet(baseArtifactory, "/${artifact.value}")
205 global_variables[artifact.key] = artifactoryResp.downloadUri
206 println "Artifact URL ${artifactoryResp.downloadUri} stored to ${artifact.key}"
207 continue
208 } catch (Exception e) {
209 common.warningMsg("Can't find an artifact in ${artifactory_url}/${job_name}/${build_num}/${artifact.value} error code ${e.message}")
210 }
211
212 job_artifact = job_artifacts.findAll { item -> artifact.value == item['fileName'] || artifact.value == item['relativePath'] }
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300213 if (job_artifact.size() == 1) {
214 // Store artifact URL
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300215 def artifact_url = "${build_url}/artifact/${job_artifact[0]['relativePath']}"
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300216 global_variables[artifact.key] = artifact_url
217 println "Artifact URL ${artifact_url} stored to ${artifact.key}"
218 } else if (job_artifact.size() > 1) {
219 // Error: too many artifacts with the same name, fail the job
220 error "Multiple artifacts ${artifact.value} for ${artifact.key} found in the build results ${build_url}, expected one:\n${job_artifact}"
221 } else {
222 // Warning: no artifact with expected name
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300223 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 +0300224 global_variables[artifact.key] = ''
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300225 }
226 }
227}
228
AndrewB8505a7f2020-06-05 13:42:08 +0300229/**
230 * Update workflow job build description
231 *
232 * @param jobs_data Map with all job names and result statuses, to showing it in description
233 */
234def updateDescription(jobs_data) {
235 table = ''
236 child_jobs_description = '<strong>Descriptions from jobs:</strong><br>'
237 table_template_start = "<div><table style='border: solid 1px;'><tr><th>Job:</th><th>Status:</th></tr>"
238 table_template_end = "</table></div>"
239
240 for (jobdata in jobs_data) {
241 // Grey background for 'finally' jobs in list
242 if (jobdata['type'] == 'finally') {
243 trstyle = "<tr style='background: #DDDDDD;'>"
244 } else {
245 trstyle = "<tr>"
246 }
247
248 // 'description' instead of job name if it exists
azvyagintsev75390d92021-04-12 14:20:11 +0300249 if (jobdata['desc'].toString() != "") {
azvyagintsev061179d2021-05-05 16:52:18 +0300250 display_name = "'${jobdata['desc']}': ${jobdata['build_id']}"
AndrewB8505a7f2020-06-05 13:42:08 +0300251 } else {
azvyagintsev061179d2021-05-05 16:52:18 +0300252 display_name = "'${jobdata['name']}': ${jobdata['build_id']}"
AndrewB8505a7f2020-06-05 13:42:08 +0300253 }
254
255 // Attach url for already builded jobs
azvyagintsev75390d92021-04-12 14:20:11 +0300256 if (jobdata['build_url'] != "0") {
AndrewB8505a7f2020-06-05 13:42:08 +0300257 build_url = "<a href=${jobdata['build_url']}>$display_name</a>"
258 } else {
259 build_url = display_name
260 }
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
284 table += "$trstyle<td>$build_url</td>$status_style</td></tr>"
285
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>"
289 child_jobs_description += "<small>${jobdata['child_desc']}</small><br>"
290 }
291 }
292 currentBuild.description = table_template_start + table + table_template_end + child_jobs_description
293}
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300294
295/**
296 * Run the workflow or final steps one by one
297 *
298 * @param steps List of steps (Jenkins jobs) to execute
299 * @param global_variables Map where the collected artifact URLs and 'env' objects are stored
300 * @param failed_jobs Map with failed job names and result statuses, to report it later
AndrewB8505a7f2020-06-05 13:42:08 +0300301 * @param jobs_data Map with all job names and result statuses, to showing it in description
302 * @param step_id Counter for matching step ID with cell ID in description table
Dennis Dmitrieve09e0292019-07-30 16:39:27 +0300303 * @param propagate Boolean. If false: allows to collect artifacts after job is finished, even with FAILURE status
304 * If true: immediatelly fails the pipeline. DO NOT USE 'true' with runScenario().
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300305 */
Aleksey Zvyagintsev25ed4a52021-05-12 14:35:03 +0000306def runSteps(steps, global_variables, failed_jobs, jobs_data, step_id, Boolean propagate = false, artifactoryBaseUrl = '') {
azvyagintsevb673f392021-05-19 15:31:48 +0300307 common = new com.mirantis.mk.Common()
AndrewB8505a7f2020-06-05 13:42:08 +0300308 // Show expected jobs list in description
309 updateDescription(jobs_data)
310
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300311 for (step in steps) {
312 stage("Running job ${step['job']}") {
AndrewB8505a7f2020-06-05 13:42:08 +0300313 def engine = new groovy.text.GStringTemplateEngine()
azvyagintsev061179d2021-05-05 16:52:18 +0300314 String desc = step['description'] ?: ''
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300315 def job_name = step['job']
Dennis Dmitriev5f014d82020-04-29 00:00:34 +0300316 def job_parameters = [:]
Dennis Dmitriev334eecd2020-04-30 14:32:45 +0300317 def step_parameters = step['parameters'] ?: [:]
Dennis Dmitriev5f014d82020-04-29 00:00:34 +0300318 if (step['inherit_parent_params'] ?: false) {
319 // add parameters from the current job for the child job
320 job_parameters << getJobDefaultParameters(env.JOB_NAME)
321 }
322 // add parameters from the workflow for the child job
Dennis Dmitriev334eecd2020-04-30 14:32:45 +0300323 job_parameters << step_parameters
Dennis Dmitriev5f014d82020-04-29 00:00:34 +0300324
azvyagintsevb673f392021-05-19 15:31:48 +0300325 common.infoMsg("Attempt to run: ${job_name}/${desc}")
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300326 // Collect job parameters and run the job
azvyagintsev061179d2021-05-05 16:52:18 +0300327 // WARN(alexz): desc must not contain invalid chars for yaml
328 def job_info = runOrGetJob(job_name, job_parameters, global_variables, propagate, desc)
329 def job_result = job_info.getResult().toString()
330 def build_url = job_info.getAbsoluteUrl().toString()
331 def build_description = job_info.getDescription().toString()
332 def build_id = job_info.getId().toString()
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300333
AndrewB8505a7f2020-06-05 13:42:08 +0300334 // Update jobs_data for updating description
335 jobs_data[step_id]['build_url'] = build_url
azvyagintsev061179d2021-05-05 16:52:18 +0300336 jobs_data[step_id]['build_id'] = build_id
AndrewB8505a7f2020-06-05 13:42:08 +0300337 jobs_data[step_id]['status'] = job_result
338 jobs_data[step_id]['desc'] = engine.createTemplate(desc).make(global_variables)
339 if (build_description) {
340 jobs_data[step_id]['child_desc'] = build_description
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300341 }
342
AndrewB8505a7f2020-06-05 13:42:08 +0300343 updateDescription(jobs_data)
344
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300345 // Store links to the resulting artifacts into 'global_variables'
Aleksey Zvyagintsev25ed4a52021-05-12 14:35:03 +0000346 storeArtifacts(build_url, step['artifacts'], global_variables, job_name, build_id, artifactoryBaseUrl)
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300347
Mykyta Karpina3d775e2020-04-24 14:45:17 +0300348 // Check job result, in case of SUCCESS, move to next step.
Mykyta Karpin0bd8bc62020-04-29 12:27:14 +0300349 // 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 +0200350 // In other cases check flag ignore_failed, if true ignore any statuses and keep going additionally
351 // if skip_results is not set or set to false fail entrie workflow, otherwise succed.
azvyagintsev75390d92021-04-12 14:20:11 +0300352 if (job_result != 'SUCCESS') {
Mykyta Karpina3d775e2020-04-24 14:45:17 +0300353 def ignoreStepResult = false
azvyagintsev75390d92021-04-12 14:20:11 +0300354 switch (job_result) {
355 // In cases when job was waiting too long in queue or internal job logic allows to skip building,
356 // 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 +0300357 case "NOT_BUILT":
358 ignoreStepResult = step['ignore_not_built'] ?: false
359 break;
360 default:
361 ignoreStepResult = step['ignore_failed'] ?: false
Vasyl Saienkoe72b9942021-03-04 10:54:49 +0200362 if (ignoreStepResult && !step['skip_results'] ?: false) {
363 failed_jobs[build_url] = job_result
364 }
Mykyta Karpina3d775e2020-04-24 14:45:17 +0300365 }
366 if (!ignoreStepResult) {
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300367 currentBuild.result = job_result
368 error "Job ${build_url} finished with result: ${job_result}"
Mykyta Karpina3d775e2020-04-24 14:45:17 +0300369 } // if (!ignoreStepResult)
370 } // if (job_result != 'SUCCESS')
371 println "Job ${build_url} finished with result: ${job_result}"
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300372 } // stage ("Running job ${step['job']}")
azvyagintsev75390d92021-04-12 14:20:11 +0300373 // Jump to next ID for updating next job data in description table
374 step_id++
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300375 } // for (step in scenario['workflow'])
376}
377
378/**
379 * Run the workflow scenario
380 *
381 * @param scenario: Map with scenario steps.
382
383 * There are two keys in the scenario:
384 * workflow: contains steps to run deploy and test jobs
385 * finally: contains steps to run report and cleanup jobs
386 *
387 * Scenario execution example:
388 *
389 * scenario_yaml = """\
390 * workflow:
391 * - job: deploy-kaas
392 * ignore_failed: false
AndrewB8505a7f2020-06-05 13:42:08 +0300393 * description: "Management cluster ${KAAS_VERSION}"
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300394 * parameters:
395 * KAAS_VERSION:
396 * type: StringParameterValue
397 * use_variable: KAAS_VERSION
398 * artifacts:
399 * KUBECONFIG_ARTIFACT: artifacts/management_kubeconfig
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +0300400 * DEPLOYED_KAAS_VERSION: artifacts/management_version
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300401 *
Dennis Dmitriev5f014d82020-04-29 00:00:34 +0300402 * - job: create-child
403 * inherit_parent_params: true
404 * ignore_failed: false
405 * parameters:
406 * KUBECONFIG_ARTIFACT_URL:
407 * type: StringParameterValue
408 * use_variable: KUBECONFIG_ARTIFACT
409 * KAAS_VERSION:
410 * type: StringParameterValue
411 * get_variable_from_url: DEPLOYED_KAAS_VERSION
Dennis Dmitriev6c355be2021-11-09 14:06:56 +0200412 * RELEASE_NAME:
413 * type: StringParameterValue
414 * get_variable_from_yaml:
415 * yaml_url: SI_CONFIG_ARTIFACT
416 * yaml_key: .clusters[0].release_name
Dennis Dmitriev5f014d82020-04-29 00:00:34 +0300417 *
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300418 * - job: test-kaas-ui
Mykyta Karpina3d775e2020-04-24 14:45:17 +0300419 * ignore_not_built: false
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300420 * parameters:
421 * KUBECONFIG_ARTIFACT_URL:
422 * type: StringParameterValue
423 * use_variable: KUBECONFIG_ARTIFACT
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +0300424 * KAAS_VERSION:
425 * type: StringParameterValue
426 * get_variable_from_url: DEPLOYED_KAAS_VERSION
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300427 * artifacts:
428 * REPORT_SI_KAAS_UI: artifacts/test_kaas_ui_result.xml
429 *
430 * finally:
431 * - job: testrail-report
432 * ignore_failed: true
433 * parameters:
Dennis Dmitrievce470932019-09-18 18:31:11 +0300434 * KAAS_VERSION:
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300435 * type: StringParameterValue
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +0300436 * get_variable_from_url: DEPLOYED_KAAS_VERSION
Dennis Dmitrievce470932019-09-18 18:31:11 +0300437 * REPORTS_LIST:
438 * type: TextParameterValue
439 * use_template: |
440 * REPORT_SI_KAAS_UI: \$REPORT_SI_KAAS_UI
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300441 * """
442 *
443 * runScenario(scenario)
444 *
Dennis Dmitriev5f014d82020-04-29 00:00:34 +0300445 * Scenario workflow keys:
446 *
447 * job: string. Jenkins job name
448 * 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 +0200449 * 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 +0300450 * 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
451 * inherit_parent_params: bool. if true, provide all parameters from the parent job to the child job as defaults
452 * 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 +0300453 */
454
Aleksey Zvyagintsev25ed4a52021-05-12 14:35:03 +0000455def runScenario(scenario, slackReportChannel = '', artifactoryBaseUrl = '') {
Dennis Dmitriev79f3a2d2019-08-09 16:06:00 +0300456 // Clear description before adding new messages
457 currentBuild.description = ''
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300458 // Collect the parameters for the jobs here
459 global_variables = [:]
460 // List of failed jobs to show at the end
461 failed_jobs = [:]
AndrewB8505a7f2020-06-05 13:42:08 +0300462 // Jobs data to use for wf job build description
463 def jobs_data = []
464 // Counter for matching step ID with cell ID in description table
465 step_id = 0
466
467 // Generate expected list jobs for description
468 list_id = 0
469 for (step in scenario['workflow']) {
azvyagintsev75390d92021-04-12 14:20:11 +0300470 if (step['description'] != null && step['description'].toString() != "") {
AndrewB8505a7f2020-06-05 13:42:08 +0300471 display_name = step['description']
472 } else {
473 display_name = step['job']
474 }
azvyagintsev061179d2021-05-05 16:52:18 +0300475 jobs_data.add([list_id : "$list_id",
476 type : "workflow",
477 name : "$display_name",
478 build_url : "0",
479 build_id : "-",
480 status : "-",
481 desc : "",
482 child_desc: ""])
AndrewB8505a7f2020-06-05 13:42:08 +0300483 list_id += 1
484 }
485 finally_step_id = list_id
486 for (step in scenario['finally']) {
azvyagintsev75390d92021-04-12 14:20:11 +0300487 if (step['description'] != null && step['description'].toString() != "") {
AndrewB8505a7f2020-06-05 13:42:08 +0300488 display_name = step['description']
489 } else {
490 display_name = step['job']
491 }
azvyagintsev061179d2021-05-05 16:52:18 +0300492 jobs_data.add([list_id : "$list_id",
493 type : "finally",
494 name : "$display_name",
495 build_url : "0",
496 build_id : "-",
497 status : "-",
498 desc : "",
499 child_desc: ""])
AndrewB8505a7f2020-06-05 13:42:08 +0300500 list_id += 1
501 }
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300502
503 try {
504 // Run the 'workflow' jobs
Aleksey Zvyagintsev25ed4a52021-05-12 14:35:03 +0000505 runSteps(scenario['workflow'], global_variables, failed_jobs, jobs_data, step_id, false, artifactoryBaseUrl)
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300506 } catch (InterruptedException x) {
507 error "The job was aborted"
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300508 } catch (e) {
509 error("Build failed: " + e.toString())
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300510 } finally {
AndrewB8505a7f2020-06-05 13:42:08 +0300511 // Switching to 'finally' step index
512 step_id = finally_step_id
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300513 // Run the 'finally' jobs
Aleksey Zvyagintsev25ed4a52021-05-12 14:35:03 +0000514 runSteps(scenario['finally'], global_variables, failed_jobs, jobs_data, step_id, false, artifactoryBaseUrl)
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300515
516 if (failed_jobs) {
sgudz9ac09d22020-01-22 14:31:30 +0200517 statuses = []
518 failed_jobs.each {
sgudz74c8cdd2020-01-23 14:26:32 +0200519 statuses += it.value
azvyagintsev75390d92021-04-12 14:20:11 +0300520 }
sgudz9ac09d22020-01-22 14:31:30 +0200521 if (statuses.contains('FAILURE')) {
522 currentBuild.result = 'FAILURE'
azvyagintsev75390d92021-04-12 14:20:11 +0300523 } else if (statuses.contains('UNSTABLE')) {
sgudz9ac09d22020-01-22 14:31:30 +0200524 currentBuild.result = 'UNSTABLE'
azvyagintsev75390d92021-04-12 14:20:11 +0300525 } else {
sgudz9ac09d22020-01-22 14:31:30 +0200526 currentBuild.result = 'FAILURE'
527 }
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300528 println "Failed jobs: ${failed_jobs}"
vnaumov68cba272020-05-20 11:24:02 +0200529 } else {
530 currentBuild.result = 'SUCCESS'
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300531 }
vnaumov5a6eb8a2020-03-31 11:16:54 +0200532
533 if (slackReportChannel) {
534 def slack = new com.mirantis.mcp.SlackNotification()
535 slack.jobResultNotification(currentBuild.result, slackReportChannel, '', null, '', 'slack_webhook_url')
536 }
sgudz9ac09d22020-01-22 14:31:30 +0200537 } // finally
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300538}