blob: abb13ee6038c216a943a5804d1d94f17c1c70373 [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 Dmitriev38a45cd2023-02-27 14:22:13 +020020 * Print 'global_variables' accumulated during workflow execution, including
21 * collected artifacts.
22 * Output is prepared in format that can be copy-pasted into groovy code
23 * to replay the workflow using the already created artifacts.
24 *
25 * @param global_variables Map that keeps the artifact URLs and used 'env' objects:
26 * {'PARAM1_NAME': <param1 value>, 'PARAM2_NAME': 'http://.../artifacts/param2_value', ...}
27 */
28def printVariables(global_variables) {
29 def message = "// Collected global_variables during the workflow:\n"
30 for (variable in global_variables) {
31 message += "env.${variable.key}=\"${variable.value}\"\n"
32 }
33 common.warningMsg(message)
34}
35
36/**
Dennis Dmitriev5f014d82020-04-29 00:00:34 +030037 * Get Jenkins parameter names, values and types from jobName
38 * @param jobName job name
39 * @return Map with parameter names as keys and the following map as values:
40 * [
41 * <str name1>: [type: <str cls1>, use_variable: <str name1>, defaultValue: <cls value1>],
42 * <str name2>: [type: <str cls2>, use_variable: <str name2>, defaultValue: <cls value2>],
43 * ]
44 */
45def getJobDefaultParameters(jobName) {
46 def jenkinsUtils = new com.mirantis.mk.JenkinsUtils()
47 def item = jenkinsUtils.getJobByName(env.JOB_NAME)
48 def parameters = [:]
49 def prop = item.getProperty(ParametersDefinitionProperty.class)
azvyagintsev75390d92021-04-12 14:20:11 +030050 if (prop != null) {
51 for (param in prop.getParameterDefinitions()) {
Dennis Dmitriev5f014d82020-04-29 00:00:34 +030052 def defaultParam = param.getDefaultParameterValue()
53 def cls = defaultParam.getClass().getName()
54 def value = defaultParam.getValue()
55 def name = defaultParam.getName()
56 parameters[name] = [type: cls, use_variable: name, defaultValue: value]
57 }
58 }
59 return parameters
60}
61
62/**
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +030063 * Run a Jenkins job using the collected parameters
64 *
65 * @param job_name Name of the running job
66 * @param job_parameters Map that declares which values from global_variables should be used, in the following format:
67 * {'PARAM_NAME': {'type': <job parameter $class name>, 'use_variable': <a key from global_variables>}, ...}
Dennis Dmitrievce470932019-09-18 18:31:11 +030068 * or
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +030069 * {'PARAM_NAME': {'type': <job parameter $class name>, 'get_variable_from_url': <a key from global_variables which contains URL with required content>}, ...}
70 * or
Dennis Dmitrievce470932019-09-18 18:31:11 +030071 * {'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 +020072 * or
73 * {'PARAM_NAME': {'type': <job parameter $class name>, 'get_variable_from_yaml': {'yaml_url': <URL with YAML content>,
74 * 'yaml_key': <a groovy-interpolating path to the key in the YAML, starting from dot '.'> } }, ...}
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +030075 * @param global_variables Map that keeps the artifact URLs and used 'env' objects:
76 * {'PARAM1_NAME': <param1 value>, 'PARAM2_NAME': 'http://.../artifacts/param2_value', ...}
Dennis Dmitrieve09e0292019-07-30 16:39:27 +030077 * @param propagate Boolean. If false: allows to collect artifacts after job is finished, even with FAILURE status
78 * If true: immediatelly fails the pipeline. DO NOT USE 'true' if you want to collect artifacts
79 * for 'finally' steps
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +030080 */
Dennis Dmitrieve09e0292019-07-30 16:39:27 +030081def runJob(job_name, job_parameters, global_variables, Boolean propagate = false) {
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +030082 def parameters = []
azvyagintsev0d978152022-01-27 14:01:33 +020083 def common = new com.mirantis.mk.Common()
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +030084 def http = new com.mirantis.mk.Http()
Dennis Dmitrievce470932019-09-18 18:31:11 +030085 def engine = new groovy.text.GStringTemplateEngine()
86 def template
Dennis Dmitriev6c355be2021-11-09 14:06:56 +020087 def yamls_from_urls = [:]
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +030088 def base = [:]
89 base["url"] = ''
90 def variable_content
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +030091
92 // Collect required parameters from 'global_variables' or 'env'
93 for (param in job_parameters) {
Dennis Dmitrievce470932019-09-18 18:31:11 +030094 if (param.value.containsKey('use_variable')) {
95 if (!global_variables[param.value.use_variable]) {
96 global_variables[param.value.use_variable] = env[param.value.use_variable] ?: ''
97 }
98 parameters.add([$class: "${param.value.type}", name: "${param.key}", value: global_variables[param.value.use_variable]])
azvyagintsev353b8762022-01-14 12:30:43 +020099 common.infoMsg("${param.key}: <${param.value.type}> ${global_variables[param.value.use_variable]}")
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +0300100 } else if (param.value.containsKey('get_variable_from_url')) {
101 if (!global_variables[param.value.get_variable_from_url]) {
102 global_variables[param.value.get_variable_from_url] = env[param.value.get_variable_from_url] ?: ''
103 }
Andrew Baraniuke0aef1e2019-10-16 14:50:10 +0300104 if (global_variables[param.value.get_variable_from_url]) {
Dennis Dmitriev37828362019-11-11 18:06:49 +0200105 variable_content = http.restGet(base, global_variables[param.value.get_variable_from_url]).trim()
Andrew Baraniuke0aef1e2019-10-16 14:50:10 +0300106 parameters.add([$class: "${param.value.type}", name: "${param.key}", value: variable_content])
azvyagintsev353b8762022-01-14 12:30:43 +0200107 common.infoMsg("${param.key}: <${param.value.type}> ${variable_content}")
Andrew Baraniuke0aef1e2019-10-16 14:50:10 +0300108 } else {
azvyagintsev353b8762022-01-14 12:30:43 +0200109 common.warningMsg("${param.key} is empty, skipping get_variable_from_url")
Andrew Baraniuke0aef1e2019-10-16 14:50:10 +0300110 }
Dennis Dmitriev6c355be2021-11-09 14:06:56 +0200111 } else if (param.value.containsKey('get_variable_from_yaml')) {
112 if (param.value.get_variable_from_yaml.containsKey('yaml_url') && param.value.get_variable_from_yaml.containsKey('yaml_key')) {
113 // YAML url is stored in an environment or a global variable (like 'SI_CONFIG_ARTIFACT')
azvyagintsev0d978152022-01-27 14:01:33 +0200114 def yaml_url_var = param.value.get_variable_from_yaml.yaml_url
Dennis Dmitriev6c355be2021-11-09 14:06:56 +0200115 if (!global_variables[yaml_url_var]) {
116 global_variables[yaml_url_var] = env[yaml_url_var] ?: ''
117 }
118 yaml_url = global_variables[yaml_url_var] // Real YAML URL
azvyagintsev353b8762022-01-14 12:30:43 +0200119 yaml_key = param.value.get_variable_from_yaml.yaml_key
120 // Key to get the data from YAML, to interpolate in the groovy, for example:
121 // <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 +0200122 if (yaml_url) {
123 if (!yamls_from_urls[yaml_url]) {
azvyagintsev353b8762022-01-14 12:30:43 +0200124 common.infoMsg("Reading YAML from ${yaml_url} for ${param.key}")
Dennis Dmitriev6c355be2021-11-09 14:06:56 +0200125 yaml_content = http.restGet(base, yaml_url)
126 yamls_from_urls[yaml_url] = readYaml text: yaml_content
127 }
azvyagintsev353b8762022-01-14 12:30:43 +0200128 common.infoMsg("Getting key ${yaml_key} from YAML ${yaml_url} for ${param.key}")
Dennis Dmitriev6c355be2021-11-09 14:06:56 +0200129 template_variables = [
azvyagintsev353b8762022-01-14 12:30:43 +0200130 'yaml_data': yamls_from_urls[yaml_url]
Dennis Dmitriev6c355be2021-11-09 14:06:56 +0200131 ]
132 request = "\${yaml_data${yaml_key}}"
Dennis Dmitriev5e076712022-02-08 15:05:21 +0200133 def result
Dennis Dmitriev450cf732021-11-11 14:59:17 +0200134 // Catch errors related to wrong key or index in the list or map objects
135 // For wrong key in map or wrong index in list, groovy returns <null> object,
136 // but it can be catched only after the string interpolation <template.toString()>,
137 // so we should catch the string 'null' instead of object <null>.
138 try {
139 template = engine.createTemplate(request).make(template_variables)
Dennis Dmitriev5e076712022-02-08 15:05:21 +0200140 result = template.toString()
Dennis Dmitriev450cf732021-11-11 14:59:17 +0200141 if (result == 'null') {
142 error "No such key or index, got 'null'"
143 }
144 } catch (e) {
145 error("Failed to get the key ${yaml_key} from YAML ${yaml_url}: " + e.toString())
146 }
147
148 parameters.add([$class: "${param.value.type}", name: "${param.key}", value: result])
azvyagintsev353b8762022-01-14 12:30:43 +0200149 common.infoMsg("${param.key}: <${param.value.type}>\n${result}")
Dennis Dmitriev6c355be2021-11-09 14:06:56 +0200150 } else {
azvyagintsev353b8762022-01-14 12:30:43 +0200151 common.warningMsg("'yaml_url' in ${param.key} is empty, skipping get_variable_from_yaml")
Dennis Dmitriev6c355be2021-11-09 14:06:56 +0200152 }
153 } else {
azvyagintsev353b8762022-01-14 12:30:43 +0200154 common.warningMsg("${param.key} missing 'yaml_url'/'yaml_key' parameters, skipping get_variable_from_yaml")
Dennis Dmitriev6c355be2021-11-09 14:06:56 +0200155 }
Dennis Dmitrievce470932019-09-18 18:31:11 +0300156 } else if (param.value.containsKey('use_template')) {
157 template = engine.createTemplate(param.value.use_template).make(global_variables)
158 parameters.add([$class: "${param.value.type}", name: "${param.key}", value: template.toString()])
azvyagintsev353b8762022-01-14 12:30:43 +0200159 common.infoMsg("${param.key}: <${param.value.type}>\n${template.toString()}")
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300160 }
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300161 }
162
163 // Build the job
Dennis Dmitrieve09e0292019-07-30 16:39:27 +0300164 def job_info = build job: "${job_name}", parameters: parameters, propagate: propagate
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300165 return job_info
166}
167
azvyagintsev061179d2021-05-05 16:52:18 +0300168def runOrGetJob(job_name, job_parameters, global_variables, propagate, String fullTaskName = '') {
169 /**
170 * Run job directly or try to find already executed build
171 * Flow, in case CI_JOBS_OVERRIDES passed:
172 *
173 *
174 * CI_JOBS_OVERRIDES = text in yaml|json format
175 * CI_JOBS_OVERRIDES = 'kaas-testing-core-release-artifact' : 3505
176 * 'reindex-testing-core-release-index-with-rc' : 2822
177 * 'si-test-release-sanity-check-prepare-configuration': 1877
178 */
179 common = new com.mirantis.mk.Common()
180 def jobsOverrides = readYaml(text: env.CI_JOBS_OVERRIDES ?: '---') ?: [:]
181 // get id of overriding job
182 def jobOverrideID = jobsOverrides.getOrDefault(fullTaskName, '')
azvyagintsev061179d2021-05-05 16:52:18 +0300183 if (fullTaskName in jobsOverrides.keySet()) {
184 common.warningMsg("Overriding: ${fullTaskName}/${job_name} <<< ${jobOverrideID}")
185 common.infoMsg("For debug pin use:\n'${fullTaskName}' : ${jobOverrideID}")
186 return Jenkins.instance.getItemByFullName(job_name,
azvyagintsev353b8762022-01-14 12:30:43 +0200187 hudson.model.Job.class).getBuildByNumber(jobOverrideID.toInteger())
azvyagintsev061179d2021-05-05 16:52:18 +0300188 } else {
189 return runJob(job_name, job_parameters, global_variables, propagate)
190 }
191}
192
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300193/**
194 * Store URLs of the specified artifacts to the global_variables
195 *
196 * @param build_url URL of the completed job
197 * @param step_artifacts Map that contains artifact names in the job, and variable names
198 * where the URLs to that atrifacts should be stored, for example:
199 * {'ARTIFACT1': 'logs.tar.gz', 'ARTIFACT2': 'test_report.xml', ...}
200 * @param global_variables Map that will keep the artifact URLs. Variable 'ARTIFACT1', for example,
201 * be used in next job parameters: {'ARTIFACT1_URL':{ 'use_variable': 'ARTIFACT1', ...}}
202 *
203 * If the artifact with the specified name not found, the parameter ARTIFACT1_URL
204 * will be empty.
205 *
206 */
Aleksey Zvyagintsev25ed4a52021-05-12 14:35:03 +0000207def storeArtifacts(build_url, step_artifacts, global_variables, job_name, build_num, artifactory_url = '') {
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300208 def common = new com.mirantis.mk.Common()
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300209 def http = new com.mirantis.mk.Http()
Aleksey Zvyagintsev25ed4a52021-05-12 14:35:03 +0000210 if (!artifactory_url) {
211 artifactory_url = 'https://artifactory.mcp.mirantis.net/api/storage/si-local/jenkins-job-artifacts'
212 }
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300213 def baseJenkins = [:]
214 def baseArtifactory = [:]
215 build_url = build_url.replaceAll(~/\/+$/, "")
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300216 baseArtifactory["url"] = artifactory_url + "/${job_name}/${build_num}"
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300217 baseJenkins["url"] = build_url
218 def job_config = http.restGet(baseJenkins, "/api/json/")
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300219 def job_artifacts = job_config['artifacts']
azvyagintsev0d978152022-01-27 14:01:33 +0200220 common.infoMsg("Attempt to storeArtifacts for: ${job_name}/${build_num}")
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300221 for (artifact in step_artifacts) {
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300222 try {
azvyagintsev0d978152022-01-27 14:01:33 +0200223 def artifactoryResp = http.restGet(baseArtifactory, "/${artifact.value}")
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300224 global_variables[artifact.key] = artifactoryResp.downloadUri
azvyagintsev0d978152022-01-27 14:01:33 +0200225 common.infoMsg("Artifact URL ${artifactoryResp.downloadUri} stored to ${artifact.key}")
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300226 continue
227 } catch (Exception e) {
azvyagintsev0d978152022-01-27 14:01:33 +0200228 common.warningMsg("Can't find an artifact in ${artifactory_url}/${job_name}/${build_num}/${artifact.value} to store in ${artifact.key}\n" +
229 "error code ${e.message}")
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300230 }
231
azvyagintsev0d978152022-01-27 14:01:33 +0200232 def job_artifact = job_artifacts.findAll { item -> artifact.value == item['fileName'] || artifact.value == item['relativePath'] }
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300233 if (job_artifact.size() == 1) {
234 // Store artifact URL
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300235 def artifact_url = "${build_url}/artifact/${job_artifact[0]['relativePath']}"
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300236 global_variables[artifact.key] = artifact_url
azvyagintsev0d978152022-01-27 14:01:33 +0200237 common.infoMsg("Artifact URL ${artifact_url} stored to ${artifact.key}")
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300238 } else if (job_artifact.size() > 1) {
239 // Error: too many artifacts with the same name, fail the job
240 error "Multiple artifacts ${artifact.value} for ${artifact.key} found in the build results ${build_url}, expected one:\n${job_artifact}"
241 } else {
242 // Warning: no artifact with expected name
azvyagintsev0d978152022-01-27 14:01:33 +0200243 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 +0300244 global_variables[artifact.key] = ''
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300245 }
246 }
247}
248
AndrewB8505a7f2020-06-05 13:42:08 +0300249/**
250 * Update workflow job build description
251 *
252 * @param jobs_data Map with all job names and result statuses, to showing it in description
253 */
254def updateDescription(jobs_data) {
azvyagintsev0d978152022-01-27 14:01:33 +0200255 def common = new com.mirantis.mk.Common()
256 def table = ''
257 def child_jobs_description = '<strong>Descriptions from jobs:</strong><br>'
258 def table_template_start = "<div><table style='border: solid 1px;'><tr><th>Job:</th><th>Duration:</th><th>Status:</th></tr>"
259 def table_template_end = "</table></div>"
AndrewB8505a7f2020-06-05 13:42:08 +0300260
261 for (jobdata in jobs_data) {
azvyagintsev0d978152022-01-27 14:01:33 +0200262 def trstyle = "<tr>"
AndrewB8505a7f2020-06-05 13:42:08 +0300263 // Grey background for 'finally' jobs in list
264 if (jobdata['type'] == 'finally') {
265 trstyle = "<tr style='background: #DDDDDD;'>"
AndrewB8505a7f2020-06-05 13:42:08 +0300266 }
AndrewB8505a7f2020-06-05 13:42:08 +0300267 // 'description' instead of job name if it exists
azvyagintsev0d978152022-01-27 14:01:33 +0200268 def display_name = "'${jobdata['name']}': ${jobdata['build_id']}"
azvyagintsev75390d92021-04-12 14:20:11 +0300269 if (jobdata['desc'].toString() != "") {
azvyagintsev061179d2021-05-05 16:52:18 +0300270 display_name = "'${jobdata['desc']}': ${jobdata['build_id']}"
AndrewB8505a7f2020-06-05 13:42:08 +0300271 }
272
azvyagintsev2eeaa562022-01-27 12:03:40 +0200273 // Attach url for already built jobs
azvyagintsev0d978152022-01-27 14:01:33 +0200274 def build_url = display_name
azvyagintsev75390d92021-04-12 14:20:11 +0300275 if (jobdata['build_url'] != "0") {
AndrewB8505a7f2020-06-05 13:42:08 +0300276 build_url = "<a href=${jobdata['build_url']}>$display_name</a>"
AndrewB8505a7f2020-06-05 13:42:08 +0300277 }
278
279 // Styling the status of job result
azvyagintsev75390d92021-04-12 14:20:11 +0300280 switch (jobdata['status'].toString()) {
AndrewB8505a7f2020-06-05 13:42:08 +0300281 case "SUCCESS":
282 status_style = "<td style='color: green;'><img src='/images/16x16/blue.png' alt='SUCCESS'>"
283 break
284 case "UNSTABLE":
285 status_style = "<td style='color: #FF5733;'><img src='/images/16x16/yellow.png' alt='UNSTABLE'>"
286 break
287 case "ABORTED":
288 status_style = "<td style='color: red;'><img src='/images/16x16/aborted.png' alt='ABORTED'>"
289 break
290 case "NOT_BUILT":
291 status_style = "<td style='color: red;'><img src='/images/16x16/aborted.png' alt='NOT_BUILT'>"
292 break
293 case "FAILURE":
294 status_style = "<td style='color: red;'><img src='/images/16x16/red.png' alt='FAILURE'>"
295 break
296 default:
297 status_style = "<td>-"
298 }
299
300 // Collect table
azvyagintsev2eeaa562022-01-27 12:03:40 +0200301 table += "$trstyle<td>$build_url</td><td>${jobdata['duration']}</td>$status_style</td></tr>"
AndrewB8505a7f2020-06-05 13:42:08 +0300302
303 // Collecting descriptions of builded child jobs
304 if (jobdata['child_desc'] != "") {
305 child_jobs_description += "<b><small><a href=${jobdata['build_url']}>- ${jobdata['name']} (${jobdata['status']}):</a></small></b><br>"
azvyagintsev0d978152022-01-27 14:01:33 +0200306 // remove "null" message-result from description, but leave XXX:JOBRESULT in description
307 if (jobdata['child_desc'] != "null") {
308 child_jobs_description += "<small>${jobdata['child_desc']}</small><br>"
309 }
AndrewB8505a7f2020-06-05 13:42:08 +0300310 }
311 }
312 currentBuild.description = table_template_start + table + table_template_end + child_jobs_description
313}
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300314
azvyagintsev0d978152022-01-27 14:01:33 +0200315def runStep(global_variables, step, Boolean propagate = false, artifactoryBaseUrl = '') {
316 return {
317 def common = new com.mirantis.mk.Common()
318 def engine = new groovy.text.GStringTemplateEngine()
319
320 String jobDescription = step['description'] ?: ''
321 def jobName = step['job']
322 def jobParameters = [:]
323 def stepParameters = step['parameters'] ?: [:]
324 if (step['inherit_parent_params'] ?: false) {
325 // add parameters from the current job for the child job
326 jobParameters << getJobDefaultParameters(env.JOB_NAME)
327 }
328 // add parameters from the workflow for the child job
329 jobParameters << stepParameters
330 def wfPauseStepBeforeRun = (step['wf_pause_step_before_run'] ?: false).toBoolean()
331 def wfPauseStepTimeout = (step['wf_pause_step_timeout'] ?: 10).toInteger()
332 def wfPauseStepSlackReportChannel = step['wf_pause_step_slack_report_channel'] ?: ''
333
334 if (wfPauseStepBeforeRun) {
335 // Try-catch construction will allow to continue Steps, if timeout reached
336 try {
337 if (wfPauseStepSlackReportChannel) {
338 def slack = new com.mirantis.mcp.SlackNotification()
azvyagintsevda22aa82022-06-10 15:46:55 +0300339 wfPauseStepSlackReportChannel.split(',').each {
340 slack.jobResultNotification('wf_pause_step_before_run',
341 it.toString(),
342 env.JOB_NAME, null,
343 env.BUILD_URL, 'slack_webhook_url')
344 }
azvyagintsev0d978152022-01-27 14:01:33 +0200345 }
346 timeout(time: wfPauseStepTimeout, unit: 'MINUTES') {
347 input("Workflow pause requested before run: ${jobName}/${jobDescription}\n" +
348 "Timeout set to ${wfPauseStepTimeout}.\n" +
349 "Do you want to proceed workflow?")
350 }
351 } catch (err) { // timeout reached or input false
352 def user = err.getCauses()[0].getUser()
353 if (user.toString() != 'SYSTEM') { // SYSTEM means timeout.
354 error("Aborted after workFlow pause by: [${user}]")
355 } else {
356 common.infoMsg("Timeout finished, continue..")
357 }
358 }
359 }
360 common.infoMsg("Attempt to run: ${jobName}/${jobDescription}")
361 // Collect job parameters and run the job
362 // WARN(alexz): desc must not contain invalid chars for yaml
363 def jobResult = runOrGetJob(jobName, jobParameters,
364 global_variables, propagate, jobDescription)
365 def buildDuration = jobResult.durationString ?: '-'
366 if (buildDuration.toString() == null) {
367 buildDuration = '-'
368 }
369 def jobSummary = [
370 job_result : jobResult.getResult().toString(),
371 build_url : jobResult.getAbsoluteUrl().toString(),
372 build_id : jobResult.getId().toString(),
373 buildDuration : buildDuration,
374 desc : engine.createTemplate(jobDescription).make(global_variables),
375 ]
376 def _buildDescription = jobResult.getDescription().toString()
377 if(_buildDescription){
378 jobSummary['build_description'] = _buildDescription
379 }
380 // Store links to the resulting artifacts into 'global_variables'
381 storeArtifacts(jobSummary['build_url'], step['artifacts'],
382 global_variables, jobName, jobSummary['build_id'], artifactoryBaseUrl)
383 return jobSummary
384 }
385}
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300386/**
387 * Run the workflow or final steps one by one
388 *
389 * @param steps List of steps (Jenkins jobs) to execute
390 * @param global_variables Map where the collected artifact URLs and 'env' objects are stored
391 * @param failed_jobs Map with failed job names and result statuses, to report it later
AndrewB8505a7f2020-06-05 13:42:08 +0300392 * @param jobs_data Map with all job names and result statuses, to showing it in description
393 * @param step_id Counter for matching step ID with cell ID in description table
Dennis Dmitrieve09e0292019-07-30 16:39:27 +0300394 * @param propagate Boolean. If false: allows to collect artifacts after job is finished, even with FAILURE status
395 * If true: immediatelly fails the pipeline. DO NOT USE 'true' with runScenario().
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300396 */
Aleksey Zvyagintsev25ed4a52021-05-12 14:35:03 +0000397def runSteps(steps, global_variables, failed_jobs, jobs_data, step_id, Boolean propagate = false, artifactoryBaseUrl = '') {
azvyagintsevb673f392021-05-19 15:31:48 +0300398 common = new com.mirantis.mk.Common()
AndrewB8505a7f2020-06-05 13:42:08 +0300399 // Show expected jobs list in description
400 updateDescription(jobs_data)
401
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300402 for (step in steps) {
azvyagintsev0d978152022-01-27 14:01:33 +0200403 stage("Preparing for run job ${step['job']}") {
404 def job_summary = runStep(global_variables, step, propagate, artifactoryBaseUrl).call()
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300405
AndrewB8505a7f2020-06-05 13:42:08 +0300406 // Update jobs_data for updating description
azvyagintsev0d978152022-01-27 14:01:33 +0200407 jobs_data[step_id]['build_url'] = job_summary['build_url']
408 jobs_data[step_id]['build_id'] = job_summary['build_id']
409 jobs_data[step_id]['status'] = job_summary['job_result']
410 jobs_data[step_id]['duration'] = job_summary['buildDuration']
411 jobs_data[step_id]['desc'] = job_summary['desc']
412 if (job_summary['build_description']) {
413 jobs_data[step_id]['child_desc'] = job_summary['build_description']
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300414 }
AndrewB8505a7f2020-06-05 13:42:08 +0300415 updateDescription(jobs_data)
azvyagintsev0d978152022-01-27 14:01:33 +0200416 def job_result = job_summary['job_result']
417 def build_url = job_summary['build_url']
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300418
Mykyta Karpina3d775e2020-04-24 14:45:17 +0300419 // Check job result, in case of SUCCESS, move to next step.
Mykyta Karpin0bd8bc62020-04-29 12:27:14 +0300420 // 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 +0200421 // In other cases check flag ignore_failed, if true ignore any statuses and keep going additionally
422 // if skip_results is not set or set to false fail entrie workflow, otherwise succed.
azvyagintsev75390d92021-04-12 14:20:11 +0300423 if (job_result != 'SUCCESS') {
Mykyta Karpina3d775e2020-04-24 14:45:17 +0300424 def ignoreStepResult = false
azvyagintsev75390d92021-04-12 14:20:11 +0300425 switch (job_result) {
426 // In cases when job was waiting too long in queue or internal job logic allows to skip building,
427 // 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 +0300428 case "NOT_BUILT":
429 ignoreStepResult = step['ignore_not_built'] ?: false
430 break;
Dmitry Tyzhnenkoa1412702022-02-14 21:23:09 +0200431 case "UNSTABLE":
Dmitry Tyzhnenkobafca282022-02-17 17:49:54 +0200432 ignoreStepResult = step['ignore_unstable'] ?: (step['ignore_failed'] ?: false)
Dmitry Tyzhnenkoa1412702022-02-14 21:23:09 +0200433 break;
Mykyta Karpina3d775e2020-04-24 14:45:17 +0300434 default:
435 ignoreStepResult = step['ignore_failed'] ?: false
Vasyl Saienkoe72b9942021-03-04 10:54:49 +0200436 if (ignoreStepResult && !step['skip_results'] ?: false) {
437 failed_jobs[build_url] = job_result
438 }
Mykyta Karpina3d775e2020-04-24 14:45:17 +0300439 }
440 if (!ignoreStepResult) {
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300441 currentBuild.result = job_result
442 error "Job ${build_url} finished with result: ${job_result}"
azvyagintsev0d978152022-01-27 14:01:33 +0200443 }
444 }
azvyagintsev353b8762022-01-14 12:30:43 +0200445 common.infoMsg("Job ${build_url} finished with result: ${job_result}")
azvyagintsev0d978152022-01-27 14:01:33 +0200446 }
azvyagintsev75390d92021-04-12 14:20:11 +0300447 // Jump to next ID for updating next job data in description table
448 step_id++
azvyagintsev0d978152022-01-27 14:01:33 +0200449 }
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300450}
451
452/**
453 * Run the workflow scenario
454 *
455 * @param scenario: Map with scenario steps.
456
457 * There are two keys in the scenario:
458 * workflow: contains steps to run deploy and test jobs
459 * finally: contains steps to run report and cleanup jobs
460 *
461 * Scenario execution example:
462 *
463 * scenario_yaml = """\
464 * workflow:
465 * - job: deploy-kaas
466 * ignore_failed: false
AndrewB8505a7f2020-06-05 13:42:08 +0300467 * description: "Management cluster ${KAAS_VERSION}"
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300468 * parameters:
469 * KAAS_VERSION:
470 * type: StringParameterValue
471 * use_variable: KAAS_VERSION
472 * artifacts:
473 * KUBECONFIG_ARTIFACT: artifacts/management_kubeconfig
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +0300474 * DEPLOYED_KAAS_VERSION: artifacts/management_version
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300475 *
Dennis Dmitriev5f014d82020-04-29 00:00:34 +0300476 * - job: create-child
477 * inherit_parent_params: true
478 * ignore_failed: false
479 * parameters:
480 * KUBECONFIG_ARTIFACT_URL:
481 * type: StringParameterValue
482 * use_variable: KUBECONFIG_ARTIFACT
483 * KAAS_VERSION:
484 * type: StringParameterValue
485 * get_variable_from_url: DEPLOYED_KAAS_VERSION
Dennis Dmitriev6c355be2021-11-09 14:06:56 +0200486 * RELEASE_NAME:
487 * type: StringParameterValue
488 * get_variable_from_yaml:
489 * yaml_url: SI_CONFIG_ARTIFACT
490 * yaml_key: .clusters[0].release_name
Dennis Dmitriev5f014d82020-04-29 00:00:34 +0300491 *
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300492 * - job: test-kaas-ui
Mykyta Karpina3d775e2020-04-24 14:45:17 +0300493 * ignore_not_built: false
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300494 * parameters:
495 * KUBECONFIG_ARTIFACT_URL:
496 * type: StringParameterValue
497 * use_variable: KUBECONFIG_ARTIFACT
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +0300498 * KAAS_VERSION:
499 * type: StringParameterValue
500 * get_variable_from_url: DEPLOYED_KAAS_VERSION
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300501 * artifacts:
502 * REPORT_SI_KAAS_UI: artifacts/test_kaas_ui_result.xml
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300503 * finally:
504 * - job: testrail-report
505 * ignore_failed: true
506 * parameters:
Dennis Dmitrievce470932019-09-18 18:31:11 +0300507 * KAAS_VERSION:
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300508 * type: StringParameterValue
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +0300509 * get_variable_from_url: DEPLOYED_KAAS_VERSION
Dennis Dmitrievce470932019-09-18 18:31:11 +0300510 * REPORTS_LIST:
511 * type: TextParameterValue
512 * use_template: |
513 * REPORT_SI_KAAS_UI: \$REPORT_SI_KAAS_UI
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300514 * """
515 *
516 * runScenario(scenario)
517 *
Dennis Dmitriev5f014d82020-04-29 00:00:34 +0300518 * Scenario workflow keys:
519 *
520 * job: string. Jenkins job name
521 * 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 +0200522 * 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 +0300523 * 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
524 * inherit_parent_params: bool. if true, provide all parameters from the parent job to the child job as defaults
525 * 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 +0200526 * wf_pause_step_before_run: bool. Interactive pause exact step before run.
527 * wf_pause_step_slack_report_channel: If step paused, send message about it in slack.
528 * wf_pause_step_timeout: timeout im minutes to wait for manual unpause.
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300529 */
530
Dennis Dmitriev38a45cd2023-02-27 14:22:13 +0200531def runScenario(scenario, slackReportChannel = '', artifactoryBaseUrl = '', Boolean logGlobalVariables = false) {
Dennis Dmitriev79f3a2d2019-08-09 16:06:00 +0300532 // Clear description before adding new messages
533 currentBuild.description = ''
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300534 // Collect the parameters for the jobs here
azvyagintsev0d978152022-01-27 14:01:33 +0200535 def global_variables = [:]
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300536 // List of failed jobs to show at the end
azvyagintsev0d978152022-01-27 14:01:33 +0200537 def failed_jobs = [:]
AndrewB8505a7f2020-06-05 13:42:08 +0300538 // Jobs data to use for wf job build description
539 def jobs_data = []
540 // Counter for matching step ID with cell ID in description table
azvyagintsev0d978152022-01-27 14:01:33 +0200541 def step_id = 0
AndrewB8505a7f2020-06-05 13:42:08 +0300542
543 // Generate expected list jobs for description
azvyagintsev0d978152022-01-27 14:01:33 +0200544 def list_id = 0
AndrewB8505a7f2020-06-05 13:42:08 +0300545 for (step in scenario['workflow']) {
azvyagintsev0d978152022-01-27 14:01:33 +0200546 def display_name = step['job']
azvyagintsev75390d92021-04-12 14:20:11 +0300547 if (step['description'] != null && step['description'].toString() != "") {
AndrewB8505a7f2020-06-05 13:42:08 +0300548 display_name = step['description']
AndrewB8505a7f2020-06-05 13:42:08 +0300549 }
azvyagintsev061179d2021-05-05 16:52:18 +0300550 jobs_data.add([list_id : "$list_id",
551 type : "workflow",
552 name : "$display_name",
553 build_url : "0",
554 build_id : "-",
555 status : "-",
556 desc : "",
azvyagintsev2eeaa562022-01-27 12:03:40 +0200557 child_desc: "",
558 duration : '-'])
AndrewB8505a7f2020-06-05 13:42:08 +0300559 list_id += 1
560 }
azvyagintsev0d978152022-01-27 14:01:33 +0200561
Sergey Lalov702384d2022-11-10 12:10:23 +0400562 def pause_step_id = list_id
563 for (step in scenario['pause']) {
564 def display_name = step['job']
565 if (step['description'] != null && step['description'].toString() != "") {
566 display_name = step['description']
567 }
568 jobs_data.add([list_id : "$list_id",
569 type : "pause",
570 name : "$display_name",
571 build_url : "0",
572 build_id : "-",
573 status : "-",
574 desc : "",
575 child_desc: "",
576 duration : '-'])
577 list_id += 1
578 }
579
azvyagintsev0d978152022-01-27 14:01:33 +0200580 def finally_step_id = list_id
AndrewB8505a7f2020-06-05 13:42:08 +0300581 for (step in scenario['finally']) {
azvyagintsev0d978152022-01-27 14:01:33 +0200582 def display_name = step['job']
azvyagintsev75390d92021-04-12 14:20:11 +0300583 if (step['description'] != null && step['description'].toString() != "") {
AndrewB8505a7f2020-06-05 13:42:08 +0300584 display_name = step['description']
AndrewB8505a7f2020-06-05 13:42:08 +0300585 }
azvyagintsev061179d2021-05-05 16:52:18 +0300586 jobs_data.add([list_id : "$list_id",
587 type : "finally",
588 name : "$display_name",
589 build_url : "0",
590 build_id : "-",
591 status : "-",
592 desc : "",
azvyagintsev2eeaa562022-01-27 12:03:40 +0200593 child_desc: "",
594 duration : '-'])
AndrewB8505a7f2020-06-05 13:42:08 +0300595 list_id += 1
596 }
Sergey Lalov702384d2022-11-10 12:10:23 +0400597 def job_failed_flag = false
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300598 try {
599 // Run the 'workflow' jobs
Aleksey Zvyagintsev25ed4a52021-05-12 14:35:03 +0000600 runSteps(scenario['workflow'], global_variables, failed_jobs, jobs_data, step_id, false, artifactoryBaseUrl)
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300601 } catch (InterruptedException x) {
Sergey Lalov702384d2022-11-10 12:10:23 +0400602 job_failed_flag = true
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300603 error "The job was aborted"
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300604 } catch (e) {
Sergey Lalov702384d2022-11-10 12:10:23 +0400605 job_failed_flag = true
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300606 error("Build failed: " + e.toString())
Sergey Lalov702384d2022-11-10 12:10:23 +0400607
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300608 } finally {
Dennis Dmitriev38a45cd2023-02-27 14:22:13 +0200609 // Log global_variables
610 if (logGlobalVariables) {
611 printVariables(global_variables)
612 }
613
Sergey Lalov702384d2022-11-10 12:10:23 +0400614 flag_pause_variable = (env.PAUSE_FOR_DEBUG) != null
615 // Run the 'finally' or 'pause' jobs
Sergey Lalov6e9400c2022-11-17 12:59:31 +0400616 common.infoMsg(failed_jobs)
617 if (flag_pause_variable && (PAUSE_FOR_DEBUG && (job_failed_flag || failed_jobs))) {
Sergey Lalov702384d2022-11-10 12:10:23 +0400618 // Switching to 'pause' step index
619 common.infoMsg("FINALLY BLOCK - PAUSE")
620 step_id = pause_step_id
621 runSteps(scenario['pause'], global_variables, failed_jobs, jobs_data, step_id, false, artifactoryBaseUrl)
622
623 }
624 // Switching to 'finally' step index
625 common.infoMsg("FINALLY BLOCK - CLEAR")
AndrewB8505a7f2020-06-05 13:42:08 +0300626 step_id = finally_step_id
Aleksey Zvyagintsev25ed4a52021-05-12 14:35:03 +0000627 runSteps(scenario['finally'], global_variables, failed_jobs, jobs_data, step_id, false, artifactoryBaseUrl)
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300628
629 if (failed_jobs) {
azvyagintsev0d978152022-01-27 14:01:33 +0200630 def statuses = []
sgudz9ac09d22020-01-22 14:31:30 +0200631 failed_jobs.each {
sgudz74c8cdd2020-01-23 14:26:32 +0200632 statuses += it.value
azvyagintsev75390d92021-04-12 14:20:11 +0300633 }
sgudz9ac09d22020-01-22 14:31:30 +0200634 if (statuses.contains('FAILURE')) {
635 currentBuild.result = 'FAILURE'
azvyagintsev75390d92021-04-12 14:20:11 +0300636 } else if (statuses.contains('UNSTABLE')) {
sgudz9ac09d22020-01-22 14:31:30 +0200637 currentBuild.result = 'UNSTABLE'
azvyagintsev75390d92021-04-12 14:20:11 +0300638 } else {
sgudz9ac09d22020-01-22 14:31:30 +0200639 currentBuild.result = 'FAILURE'
640 }
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300641 println "Failed jobs: ${failed_jobs}"
vnaumov68cba272020-05-20 11:24:02 +0200642 } else {
643 currentBuild.result = 'SUCCESS'
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300644 }
vnaumov5a6eb8a2020-03-31 11:16:54 +0200645
646 if (slackReportChannel) {
647 def slack = new com.mirantis.mcp.SlackNotification()
648 slack.jobResultNotification(currentBuild.result, slackReportChannel, '', null, '', 'slack_webhook_url')
649 }
sgudz9ac09d22020-01-22 14:31:30 +0200650 } // finally
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300651}