blob: 93ef859d64c5b7618250687ce524970af3fa4971 [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}}"
114 template = engine.createTemplate(request).make(template_variables)
115 parameters.add([$class: "${param.value.type}", name: "${param.key}", value: template.toString()])
116 println "${param.key}: <${param.value.type}>\n${template.toString()}"
117 } else {
118 println "'yaml_url' in ${param.key} is empty, skipping get_variable_from_yaml"
119 }
120 } else {
121 println "${param.key} missing 'yaml_url'/'yaml_key' parameters, skipping get_variable_from_yaml"
122 }
Dennis Dmitrievce470932019-09-18 18:31:11 +0300123 } else if (param.value.containsKey('use_template')) {
124 template = engine.createTemplate(param.value.use_template).make(global_variables)
125 parameters.add([$class: "${param.value.type}", name: "${param.key}", value: template.toString()])
126 println "${param.key}: <${param.value.type}>\n${template.toString()}"
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300127 }
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300128 }
129
130 // Build the job
Dennis Dmitrieve09e0292019-07-30 16:39:27 +0300131 def job_info = build job: "${job_name}", parameters: parameters, propagate: propagate
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300132 return job_info
133}
134
azvyagintsev061179d2021-05-05 16:52:18 +0300135def runOrGetJob(job_name, job_parameters, global_variables, propagate, String fullTaskName = '') {
136 /**
137 * Run job directly or try to find already executed build
138 * Flow, in case CI_JOBS_OVERRIDES passed:
139 *
140 *
141 * CI_JOBS_OVERRIDES = text in yaml|json format
142 * CI_JOBS_OVERRIDES = 'kaas-testing-core-release-artifact' : 3505
143 * 'reindex-testing-core-release-index-with-rc' : 2822
144 * 'si-test-release-sanity-check-prepare-configuration': 1877
145 */
146 common = new com.mirantis.mk.Common()
147 def jobsOverrides = readYaml(text: env.CI_JOBS_OVERRIDES ?: '---') ?: [:]
148 // get id of overriding job
149 def jobOverrideID = jobsOverrides.getOrDefault(fullTaskName, '')
150
151 if (fullTaskName in jobsOverrides.keySet()) {
152 common.warningMsg("Overriding: ${fullTaskName}/${job_name} <<< ${jobOverrideID}")
153 common.infoMsg("For debug pin use:\n'${fullTaskName}' : ${jobOverrideID}")
154 return Jenkins.instance.getItemByFullName(job_name,
155 hudson.model.Job.class).getBuildByNumber(jobOverrideID.toInteger())
156 } else {
157 return runJob(job_name, job_parameters, global_variables, propagate)
158 }
159}
160
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300161/**
162 * Store URLs of the specified artifacts to the global_variables
163 *
164 * @param build_url URL of the completed job
165 * @param step_artifacts Map that contains artifact names in the job, and variable names
166 * where the URLs to that atrifacts should be stored, for example:
167 * {'ARTIFACT1': 'logs.tar.gz', 'ARTIFACT2': 'test_report.xml', ...}
168 * @param global_variables Map that will keep the artifact URLs. Variable 'ARTIFACT1', for example,
169 * be used in next job parameters: {'ARTIFACT1_URL':{ 'use_variable': 'ARTIFACT1', ...}}
170 *
171 * If the artifact with the specified name not found, the parameter ARTIFACT1_URL
172 * will be empty.
173 *
174 */
Aleksey Zvyagintsev25ed4a52021-05-12 14:35:03 +0000175def storeArtifacts(build_url, step_artifacts, global_variables, job_name, build_num, artifactory_url = '') {
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300176 def common = new com.mirantis.mk.Common()
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300177 def http = new com.mirantis.mk.Http()
Aleksey Zvyagintsev25ed4a52021-05-12 14:35:03 +0000178 if (!artifactory_url) {
179 artifactory_url = 'https://artifactory.mcp.mirantis.net/api/storage/si-local/jenkins-job-artifacts'
180 }
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300181 def baseJenkins = [:]
182 def baseArtifactory = [:]
183 build_url = build_url.replaceAll(~/\/+$/, "")
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300184 baseArtifactory["url"] = artifactory_url + "/${job_name}/${build_num}"
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300185 baseJenkins["url"] = build_url
186 def job_config = http.restGet(baseJenkins, "/api/json/")
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300187 def job_artifacts = job_config['artifacts']
188 for (artifact in step_artifacts) {
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300189 try {
190 artifactoryResp = http.restGet(baseArtifactory, "/${artifact.value}")
191 global_variables[artifact.key] = artifactoryResp.downloadUri
192 println "Artifact URL ${artifactoryResp.downloadUri} stored to ${artifact.key}"
193 continue
194 } catch (Exception e) {
195 common.warningMsg("Can't find an artifact in ${artifactory_url}/${job_name}/${build_num}/${artifact.value} error code ${e.message}")
196 }
197
198 job_artifact = job_artifacts.findAll { item -> artifact.value == item['fileName'] || artifact.value == item['relativePath'] }
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300199 if (job_artifact.size() == 1) {
200 // Store artifact URL
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300201 def artifact_url = "${build_url}/artifact/${job_artifact[0]['relativePath']}"
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300202 global_variables[artifact.key] = artifact_url
203 println "Artifact URL ${artifact_url} stored to ${artifact.key}"
204 } else if (job_artifact.size() > 1) {
205 // Error: too many artifacts with the same name, fail the job
206 error "Multiple artifacts ${artifact.value} for ${artifact.key} found in the build results ${build_url}, expected one:\n${job_artifact}"
207 } else {
208 // Warning: no artifact with expected name
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300209 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 +0300210 global_variables[artifact.key] = ''
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300211 }
212 }
213}
214
AndrewB8505a7f2020-06-05 13:42:08 +0300215/**
216 * Update workflow job build description
217 *
218 * @param jobs_data Map with all job names and result statuses, to showing it in description
219 */
220def updateDescription(jobs_data) {
221 table = ''
222 child_jobs_description = '<strong>Descriptions from jobs:</strong><br>'
223 table_template_start = "<div><table style='border: solid 1px;'><tr><th>Job:</th><th>Status:</th></tr>"
224 table_template_end = "</table></div>"
225
226 for (jobdata in jobs_data) {
227 // Grey background for 'finally' jobs in list
228 if (jobdata['type'] == 'finally') {
229 trstyle = "<tr style='background: #DDDDDD;'>"
230 } else {
231 trstyle = "<tr>"
232 }
233
234 // 'description' instead of job name if it exists
azvyagintsev75390d92021-04-12 14:20:11 +0300235 if (jobdata['desc'].toString() != "") {
azvyagintsev061179d2021-05-05 16:52:18 +0300236 display_name = "'${jobdata['desc']}': ${jobdata['build_id']}"
AndrewB8505a7f2020-06-05 13:42:08 +0300237 } else {
azvyagintsev061179d2021-05-05 16:52:18 +0300238 display_name = "'${jobdata['name']}': ${jobdata['build_id']}"
AndrewB8505a7f2020-06-05 13:42:08 +0300239 }
240
241 // Attach url for already builded jobs
azvyagintsev75390d92021-04-12 14:20:11 +0300242 if (jobdata['build_url'] != "0") {
AndrewB8505a7f2020-06-05 13:42:08 +0300243 build_url = "<a href=${jobdata['build_url']}>$display_name</a>"
244 } else {
245 build_url = display_name
246 }
247
248 // Styling the status of job result
azvyagintsev75390d92021-04-12 14:20:11 +0300249 switch (jobdata['status'].toString()) {
AndrewB8505a7f2020-06-05 13:42:08 +0300250 case "SUCCESS":
251 status_style = "<td style='color: green;'><img src='/images/16x16/blue.png' alt='SUCCESS'>"
252 break
253 case "UNSTABLE":
254 status_style = "<td style='color: #FF5733;'><img src='/images/16x16/yellow.png' alt='UNSTABLE'>"
255 break
256 case "ABORTED":
257 status_style = "<td style='color: red;'><img src='/images/16x16/aborted.png' alt='ABORTED'>"
258 break
259 case "NOT_BUILT":
260 status_style = "<td style='color: red;'><img src='/images/16x16/aborted.png' alt='NOT_BUILT'>"
261 break
262 case "FAILURE":
263 status_style = "<td style='color: red;'><img src='/images/16x16/red.png' alt='FAILURE'>"
264 break
265 default:
266 status_style = "<td>-"
267 }
268
269 // Collect table
270 table += "$trstyle<td>$build_url</td>$status_style</td></tr>"
271
272 // Collecting descriptions of builded child jobs
273 if (jobdata['child_desc'] != "") {
274 child_jobs_description += "<b><small><a href=${jobdata['build_url']}>- ${jobdata['name']} (${jobdata['status']}):</a></small></b><br>"
275 child_jobs_description += "<small>${jobdata['child_desc']}</small><br>"
276 }
277 }
278 currentBuild.description = table_template_start + table + table_template_end + child_jobs_description
279}
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300280
281/**
282 * Run the workflow or final steps one by one
283 *
284 * @param steps List of steps (Jenkins jobs) to execute
285 * @param global_variables Map where the collected artifact URLs and 'env' objects are stored
286 * @param failed_jobs Map with failed job names and result statuses, to report it later
AndrewB8505a7f2020-06-05 13:42:08 +0300287 * @param jobs_data Map with all job names and result statuses, to showing it in description
288 * @param step_id Counter for matching step ID with cell ID in description table
Dennis Dmitrieve09e0292019-07-30 16:39:27 +0300289 * @param propagate Boolean. If false: allows to collect artifacts after job is finished, even with FAILURE status
290 * If true: immediatelly fails the pipeline. DO NOT USE 'true' with runScenario().
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300291 */
Aleksey Zvyagintsev25ed4a52021-05-12 14:35:03 +0000292def runSteps(steps, global_variables, failed_jobs, jobs_data, step_id, Boolean propagate = false, artifactoryBaseUrl = '') {
azvyagintsevb673f392021-05-19 15:31:48 +0300293 common = new com.mirantis.mk.Common()
AndrewB8505a7f2020-06-05 13:42:08 +0300294 // Show expected jobs list in description
295 updateDescription(jobs_data)
296
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300297 for (step in steps) {
298 stage("Running job ${step['job']}") {
AndrewB8505a7f2020-06-05 13:42:08 +0300299 def engine = new groovy.text.GStringTemplateEngine()
azvyagintsev061179d2021-05-05 16:52:18 +0300300 String desc = step['description'] ?: ''
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300301 def job_name = step['job']
Dennis Dmitriev5f014d82020-04-29 00:00:34 +0300302 def job_parameters = [:]
Dennis Dmitriev334eecd2020-04-30 14:32:45 +0300303 def step_parameters = step['parameters'] ?: [:]
Dennis Dmitriev5f014d82020-04-29 00:00:34 +0300304 if (step['inherit_parent_params'] ?: false) {
305 // add parameters from the current job for the child job
306 job_parameters << getJobDefaultParameters(env.JOB_NAME)
307 }
308 // add parameters from the workflow for the child job
Dennis Dmitriev334eecd2020-04-30 14:32:45 +0300309 job_parameters << step_parameters
Dennis Dmitriev5f014d82020-04-29 00:00:34 +0300310
azvyagintsevb673f392021-05-19 15:31:48 +0300311 common.infoMsg("Attempt to run: ${job_name}/${desc}")
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300312 // Collect job parameters and run the job
azvyagintsev061179d2021-05-05 16:52:18 +0300313 // WARN(alexz): desc must not contain invalid chars for yaml
314 def job_info = runOrGetJob(job_name, job_parameters, global_variables, propagate, desc)
315 def job_result = job_info.getResult().toString()
316 def build_url = job_info.getAbsoluteUrl().toString()
317 def build_description = job_info.getDescription().toString()
318 def build_id = job_info.getId().toString()
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300319
AndrewB8505a7f2020-06-05 13:42:08 +0300320 // Update jobs_data for updating description
321 jobs_data[step_id]['build_url'] = build_url
azvyagintsev061179d2021-05-05 16:52:18 +0300322 jobs_data[step_id]['build_id'] = build_id
AndrewB8505a7f2020-06-05 13:42:08 +0300323 jobs_data[step_id]['status'] = job_result
324 jobs_data[step_id]['desc'] = engine.createTemplate(desc).make(global_variables)
325 if (build_description) {
326 jobs_data[step_id]['child_desc'] = build_description
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300327 }
328
AndrewB8505a7f2020-06-05 13:42:08 +0300329 updateDescription(jobs_data)
330
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300331 // Store links to the resulting artifacts into 'global_variables'
Aleksey Zvyagintsev25ed4a52021-05-12 14:35:03 +0000332 storeArtifacts(build_url, step['artifacts'], global_variables, job_name, build_id, artifactoryBaseUrl)
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300333
Mykyta Karpina3d775e2020-04-24 14:45:17 +0300334 // Check job result, in case of SUCCESS, move to next step.
Mykyta Karpin0bd8bc62020-04-29 12:27:14 +0300335 // 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 +0200336 // In other cases check flag ignore_failed, if true ignore any statuses and keep going additionally
337 // if skip_results is not set or set to false fail entrie workflow, otherwise succed.
azvyagintsev75390d92021-04-12 14:20:11 +0300338 if (job_result != 'SUCCESS') {
Mykyta Karpina3d775e2020-04-24 14:45:17 +0300339 def ignoreStepResult = false
azvyagintsev75390d92021-04-12 14:20:11 +0300340 switch (job_result) {
341 // In cases when job was waiting too long in queue or internal job logic allows to skip building,
342 // 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 +0300343 case "NOT_BUILT":
344 ignoreStepResult = step['ignore_not_built'] ?: false
345 break;
346 default:
347 ignoreStepResult = step['ignore_failed'] ?: false
Vasyl Saienkoe72b9942021-03-04 10:54:49 +0200348 if (ignoreStepResult && !step['skip_results'] ?: false) {
349 failed_jobs[build_url] = job_result
350 }
Mykyta Karpina3d775e2020-04-24 14:45:17 +0300351 }
352 if (!ignoreStepResult) {
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300353 currentBuild.result = job_result
354 error "Job ${build_url} finished with result: ${job_result}"
Mykyta Karpina3d775e2020-04-24 14:45:17 +0300355 } // if (!ignoreStepResult)
356 } // if (job_result != 'SUCCESS')
357 println "Job ${build_url} finished with result: ${job_result}"
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300358 } // stage ("Running job ${step['job']}")
azvyagintsev75390d92021-04-12 14:20:11 +0300359 // Jump to next ID for updating next job data in description table
360 step_id++
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300361 } // for (step in scenario['workflow'])
362}
363
364/**
365 * Run the workflow scenario
366 *
367 * @param scenario: Map with scenario steps.
368
369 * There are two keys in the scenario:
370 * workflow: contains steps to run deploy and test jobs
371 * finally: contains steps to run report and cleanup jobs
372 *
373 * Scenario execution example:
374 *
375 * scenario_yaml = """\
376 * workflow:
377 * - job: deploy-kaas
378 * ignore_failed: false
AndrewB8505a7f2020-06-05 13:42:08 +0300379 * description: "Management cluster ${KAAS_VERSION}"
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300380 * parameters:
381 * KAAS_VERSION:
382 * type: StringParameterValue
383 * use_variable: KAAS_VERSION
384 * artifacts:
385 * KUBECONFIG_ARTIFACT: artifacts/management_kubeconfig
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +0300386 * DEPLOYED_KAAS_VERSION: artifacts/management_version
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300387 *
Dennis Dmitriev5f014d82020-04-29 00:00:34 +0300388 * - job: create-child
389 * inherit_parent_params: true
390 * ignore_failed: false
391 * parameters:
392 * KUBECONFIG_ARTIFACT_URL:
393 * type: StringParameterValue
394 * use_variable: KUBECONFIG_ARTIFACT
395 * KAAS_VERSION:
396 * type: StringParameterValue
397 * get_variable_from_url: DEPLOYED_KAAS_VERSION
Dennis Dmitriev6c355be2021-11-09 14:06:56 +0200398 * RELEASE_NAME:
399 * type: StringParameterValue
400 * get_variable_from_yaml:
401 * yaml_url: SI_CONFIG_ARTIFACT
402 * yaml_key: .clusters[0].release_name
Dennis Dmitriev5f014d82020-04-29 00:00:34 +0300403 *
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300404 * - job: test-kaas-ui
Mykyta Karpina3d775e2020-04-24 14:45:17 +0300405 * ignore_not_built: false
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300406 * parameters:
407 * KUBECONFIG_ARTIFACT_URL:
408 * type: StringParameterValue
409 * use_variable: KUBECONFIG_ARTIFACT
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +0300410 * KAAS_VERSION:
411 * type: StringParameterValue
412 * get_variable_from_url: DEPLOYED_KAAS_VERSION
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300413 * artifacts:
414 * REPORT_SI_KAAS_UI: artifacts/test_kaas_ui_result.xml
415 *
416 * finally:
417 * - job: testrail-report
418 * ignore_failed: true
419 * parameters:
Dennis Dmitrievce470932019-09-18 18:31:11 +0300420 * KAAS_VERSION:
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300421 * type: StringParameterValue
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +0300422 * get_variable_from_url: DEPLOYED_KAAS_VERSION
Dennis Dmitrievce470932019-09-18 18:31:11 +0300423 * REPORTS_LIST:
424 * type: TextParameterValue
425 * use_template: |
426 * REPORT_SI_KAAS_UI: \$REPORT_SI_KAAS_UI
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300427 * """
428 *
429 * runScenario(scenario)
430 *
Dennis Dmitriev5f014d82020-04-29 00:00:34 +0300431 * Scenario workflow keys:
432 *
433 * job: string. Jenkins job name
434 * 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 +0200435 * 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 +0300436 * 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
437 * inherit_parent_params: bool. if true, provide all parameters from the parent job to the child job as defaults
438 * 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 +0300439 */
440
Aleksey Zvyagintsev25ed4a52021-05-12 14:35:03 +0000441def runScenario(scenario, slackReportChannel = '', artifactoryBaseUrl = '') {
Dennis Dmitriev79f3a2d2019-08-09 16:06:00 +0300442 // Clear description before adding new messages
443 currentBuild.description = ''
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300444 // Collect the parameters for the jobs here
445 global_variables = [:]
446 // List of failed jobs to show at the end
447 failed_jobs = [:]
AndrewB8505a7f2020-06-05 13:42:08 +0300448 // Jobs data to use for wf job build description
449 def jobs_data = []
450 // Counter for matching step ID with cell ID in description table
451 step_id = 0
452
453 // Generate expected list jobs for description
454 list_id = 0
455 for (step in scenario['workflow']) {
azvyagintsev75390d92021-04-12 14:20:11 +0300456 if (step['description'] != null && step['description'].toString() != "") {
AndrewB8505a7f2020-06-05 13:42:08 +0300457 display_name = step['description']
458 } else {
459 display_name = step['job']
460 }
azvyagintsev061179d2021-05-05 16:52:18 +0300461 jobs_data.add([list_id : "$list_id",
462 type : "workflow",
463 name : "$display_name",
464 build_url : "0",
465 build_id : "-",
466 status : "-",
467 desc : "",
468 child_desc: ""])
AndrewB8505a7f2020-06-05 13:42:08 +0300469 list_id += 1
470 }
471 finally_step_id = list_id
472 for (step in scenario['finally']) {
azvyagintsev75390d92021-04-12 14:20:11 +0300473 if (step['description'] != null && step['description'].toString() != "") {
AndrewB8505a7f2020-06-05 13:42:08 +0300474 display_name = step['description']
475 } else {
476 display_name = step['job']
477 }
azvyagintsev061179d2021-05-05 16:52:18 +0300478 jobs_data.add([list_id : "$list_id",
479 type : "finally",
480 name : "$display_name",
481 build_url : "0",
482 build_id : "-",
483 status : "-",
484 desc : "",
485 child_desc: ""])
AndrewB8505a7f2020-06-05 13:42:08 +0300486 list_id += 1
487 }
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300488
489 try {
490 // Run the 'workflow' jobs
Aleksey Zvyagintsev25ed4a52021-05-12 14:35:03 +0000491 runSteps(scenario['workflow'], global_variables, failed_jobs, jobs_data, step_id, false, artifactoryBaseUrl)
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300492 } catch (InterruptedException x) {
493 error "The job was aborted"
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300494 } catch (e) {
495 error("Build failed: " + e.toString())
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300496 } finally {
AndrewB8505a7f2020-06-05 13:42:08 +0300497 // Switching to 'finally' step index
498 step_id = finally_step_id
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300499 // Run the 'finally' jobs
Aleksey Zvyagintsev25ed4a52021-05-12 14:35:03 +0000500 runSteps(scenario['finally'], global_variables, failed_jobs, jobs_data, step_id, false, artifactoryBaseUrl)
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300501
502 if (failed_jobs) {
sgudz9ac09d22020-01-22 14:31:30 +0200503 statuses = []
504 failed_jobs.each {
sgudz74c8cdd2020-01-23 14:26:32 +0200505 statuses += it.value
azvyagintsev75390d92021-04-12 14:20:11 +0300506 }
sgudz9ac09d22020-01-22 14:31:30 +0200507 if (statuses.contains('FAILURE')) {
508 currentBuild.result = 'FAILURE'
azvyagintsev75390d92021-04-12 14:20:11 +0300509 } else if (statuses.contains('UNSTABLE')) {
sgudz9ac09d22020-01-22 14:31:30 +0200510 currentBuild.result = 'UNSTABLE'
azvyagintsev75390d92021-04-12 14:20:11 +0300511 } else {
sgudz9ac09d22020-01-22 14:31:30 +0200512 currentBuild.result = 'FAILURE'
513 }
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300514 println "Failed jobs: ${failed_jobs}"
vnaumov68cba272020-05-20 11:24:02 +0200515 } else {
516 currentBuild.result = 'SUCCESS'
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300517 }
vnaumov5a6eb8a2020-03-31 11:16:54 +0200518
519 if (slackReportChannel) {
520 def slack = new com.mirantis.mcp.SlackNotification()
521 slack.jobResultNotification(currentBuild.result, slackReportChannel, '', null, '', 'slack_webhook_url')
522 }
sgudz9ac09d22020-01-22 14:31:30 +0200523 } // finally
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300524}