blob: 01725f208293253954f04d3e14010fb7933704d2 [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) {
Dennis Dmitrievc6751012023-07-03 20:45:46 +030031 message += "env.${variable.key}=\"\"\"${variable.value}\"\"\"\n"
Dennis Dmitriev38a45cd2023-02-27 14:22:13 +020032 }
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 *
Andrii Baraniukcf4c2fa2023-04-18 13:53:32 +0300196 * @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', ...}}
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300202 *
Andrii Baraniukcf4c2fa2023-04-18 13:53:32 +0300203 * If the artifact with the specified name not found, the parameter ARTIFACT1_URL
204 * will be empty.
205 * @param artifactory_server Artifactory server ID defined in Jenkins config
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300206 *
207 */
Andrii Baraniukcf4c2fa2023-04-18 13:53:32 +0300208def storeArtifacts(build_url, step_artifacts, global_variables, job_name, build_num, artifactory_url = '', artifactory_server = '') {
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300209 def common = new com.mirantis.mk.Common()
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300210 def http = new com.mirantis.mk.Http()
Andrii Baraniukcf4c2fa2023-04-18 13:53:32 +0300211 def artifactory = new com.mirantis.mcp.MCPArtifactory()
212 if(!artifactory_url && !artifactory_server) {
213 artifactory_url = 'https://artifactory.mcp.mirantis.net/artifactory/api/storage/si-local/jenkins-job-artifacts'
214 } else if (!artifactory_url && artifactory_server) {
215 artifactory_url = artifactory.getArtifactoryServer(artifactory_server).getUrl() + '/artifactory/api/storage/si-local/jenkins-job-artifacts'
Aleksey Zvyagintsev25ed4a52021-05-12 14:35:03 +0000216 }
Andrii Baraniukcf4c2fa2023-04-18 13:53:32 +0300217
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300218 def baseJenkins = [:]
219 def baseArtifactory = [:]
220 build_url = build_url.replaceAll(~/\/+$/, "")
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300221 baseArtifactory["url"] = artifactory_url + "/${job_name}/${build_num}"
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300222 baseJenkins["url"] = build_url
223 def job_config = http.restGet(baseJenkins, "/api/json/")
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300224 def job_artifacts = job_config['artifacts']
azvyagintsev0d978152022-01-27 14:01:33 +0200225 common.infoMsg("Attempt to storeArtifacts for: ${job_name}/${build_num}")
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300226 for (artifact in step_artifacts) {
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300227 try {
azvyagintsev0d978152022-01-27 14:01:33 +0200228 def artifactoryResp = http.restGet(baseArtifactory, "/${artifact.value}")
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300229 global_variables[artifact.key] = artifactoryResp.downloadUri
azvyagintsev0d978152022-01-27 14:01:33 +0200230 common.infoMsg("Artifact URL ${artifactoryResp.downloadUri} stored to ${artifact.key}")
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300231 continue
232 } catch (Exception e) {
azvyagintsev0d978152022-01-27 14:01:33 +0200233 common.warningMsg("Can't find an artifact in ${artifactory_url}/${job_name}/${build_num}/${artifact.value} to store in ${artifact.key}\n" +
234 "error code ${e.message}")
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300235 }
236
azvyagintsev0d978152022-01-27 14:01:33 +0200237 def job_artifact = job_artifacts.findAll { item -> artifact.value == item['fileName'] || artifact.value == item['relativePath'] }
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300238 if (job_artifact.size() == 1) {
239 // Store artifact URL
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300240 def artifact_url = "${build_url}/artifact/${job_artifact[0]['relativePath']}"
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300241 global_variables[artifact.key] = artifact_url
azvyagintsev0d978152022-01-27 14:01:33 +0200242 common.infoMsg("Artifact URL ${artifact_url} stored to ${artifact.key}")
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300243 } else if (job_artifact.size() > 1) {
244 // Error: too many artifacts with the same name, fail the job
245 error "Multiple artifacts ${artifact.value} for ${artifact.key} found in the build results ${build_url}, expected one:\n${job_artifact}"
246 } else {
247 // Warning: no artifact with expected name
azvyagintsev0d978152022-01-27 14:01:33 +0200248 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 +0300249 global_variables[artifact.key] = ''
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300250 }
251 }
252}
253
AndrewB8505a7f2020-06-05 13:42:08 +0300254/**
255 * Update workflow job build description
256 *
257 * @param jobs_data Map with all job names and result statuses, to showing it in description
258 */
259def updateDescription(jobs_data) {
azvyagintsev0d978152022-01-27 14:01:33 +0200260 def common = new com.mirantis.mk.Common()
261 def table = ''
262 def child_jobs_description = '<strong>Descriptions from jobs:</strong><br>'
263 def table_template_start = "<div><table style='border: solid 1px;'><tr><th>Job:</th><th>Duration:</th><th>Status:</th></tr>"
264 def table_template_end = "</table></div>"
AndrewB8505a7f2020-06-05 13:42:08 +0300265
266 for (jobdata in jobs_data) {
azvyagintsev0d978152022-01-27 14:01:33 +0200267 def trstyle = "<tr>"
AndrewB8505a7f2020-06-05 13:42:08 +0300268 // Grey background for 'finally' jobs in list
269 if (jobdata['type'] == 'finally') {
270 trstyle = "<tr style='background: #DDDDDD;'>"
AndrewB8505a7f2020-06-05 13:42:08 +0300271 }
AndrewB8505a7f2020-06-05 13:42:08 +0300272 // 'description' instead of job name if it exists
azvyagintsev0d978152022-01-27 14:01:33 +0200273 def display_name = "'${jobdata['name']}': ${jobdata['build_id']}"
azvyagintsev75390d92021-04-12 14:20:11 +0300274 if (jobdata['desc'].toString() != "") {
azvyagintsev061179d2021-05-05 16:52:18 +0300275 display_name = "'${jobdata['desc']}': ${jobdata['build_id']}"
AndrewB8505a7f2020-06-05 13:42:08 +0300276 }
277
azvyagintsev2eeaa562022-01-27 12:03:40 +0200278 // Attach url for already built jobs
azvyagintsev0d978152022-01-27 14:01:33 +0200279 def build_url = display_name
azvyagintsev75390d92021-04-12 14:20:11 +0300280 if (jobdata['build_url'] != "0") {
AndrewB8505a7f2020-06-05 13:42:08 +0300281 build_url = "<a href=${jobdata['build_url']}>$display_name</a>"
AndrewB8505a7f2020-06-05 13:42:08 +0300282 }
283
284 // Styling the status of job result
azvyagintsev75390d92021-04-12 14:20:11 +0300285 switch (jobdata['status'].toString()) {
AndrewB8505a7f2020-06-05 13:42:08 +0300286 case "SUCCESS":
287 status_style = "<td style='color: green;'><img src='/images/16x16/blue.png' alt='SUCCESS'>"
288 break
289 case "UNSTABLE":
290 status_style = "<td style='color: #FF5733;'><img src='/images/16x16/yellow.png' alt='UNSTABLE'>"
291 break
292 case "ABORTED":
293 status_style = "<td style='color: red;'><img src='/images/16x16/aborted.png' alt='ABORTED'>"
294 break
295 case "NOT_BUILT":
296 status_style = "<td style='color: red;'><img src='/images/16x16/aborted.png' alt='NOT_BUILT'>"
297 break
298 case "FAILURE":
299 status_style = "<td style='color: red;'><img src='/images/16x16/red.png' alt='FAILURE'>"
300 break
301 default:
302 status_style = "<td>-"
303 }
304
305 // Collect table
azvyagintsev2eeaa562022-01-27 12:03:40 +0200306 table += "$trstyle<td>$build_url</td><td>${jobdata['duration']}</td>$status_style</td></tr>"
AndrewB8505a7f2020-06-05 13:42:08 +0300307
308 // Collecting descriptions of builded child jobs
309 if (jobdata['child_desc'] != "") {
310 child_jobs_description += "<b><small><a href=${jobdata['build_url']}>- ${jobdata['name']} (${jobdata['status']}):</a></small></b><br>"
azvyagintsev0d978152022-01-27 14:01:33 +0200311 // remove "null" message-result from description, but leave XXX:JOBRESULT in description
312 if (jobdata['child_desc'] != "null") {
313 child_jobs_description += "<small>${jobdata['child_desc']}</small><br>"
314 }
AndrewB8505a7f2020-06-05 13:42:08 +0300315 }
316 }
317 currentBuild.description = table_template_start + table + table_template_end + child_jobs_description
318}
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300319
Andrii Baraniukcf4c2fa2023-04-18 13:53:32 +0300320def runStep(global_variables, step, Boolean propagate = false, artifactoryBaseUrl = '', artifactoryServer = '') {
azvyagintsev0d978152022-01-27 14:01:33 +0200321 return {
322 def common = new com.mirantis.mk.Common()
323 def engine = new groovy.text.GStringTemplateEngine()
324
325 String jobDescription = step['description'] ?: ''
326 def jobName = step['job']
327 def jobParameters = [:]
328 def stepParameters = step['parameters'] ?: [:]
329 if (step['inherit_parent_params'] ?: false) {
330 // add parameters from the current job for the child job
331 jobParameters << getJobDefaultParameters(env.JOB_NAME)
332 }
333 // add parameters from the workflow for the child job
334 jobParameters << stepParameters
335 def wfPauseStepBeforeRun = (step['wf_pause_step_before_run'] ?: false).toBoolean()
336 def wfPauseStepTimeout = (step['wf_pause_step_timeout'] ?: 10).toInteger()
337 def wfPauseStepSlackReportChannel = step['wf_pause_step_slack_report_channel'] ?: ''
338
339 if (wfPauseStepBeforeRun) {
340 // Try-catch construction will allow to continue Steps, if timeout reached
341 try {
342 if (wfPauseStepSlackReportChannel) {
343 def slack = new com.mirantis.mcp.SlackNotification()
azvyagintsevda22aa82022-06-10 15:46:55 +0300344 wfPauseStepSlackReportChannel.split(',').each {
345 slack.jobResultNotification('wf_pause_step_before_run',
346 it.toString(),
347 env.JOB_NAME, null,
348 env.BUILD_URL, 'slack_webhook_url')
349 }
azvyagintsev0d978152022-01-27 14:01:33 +0200350 }
351 timeout(time: wfPauseStepTimeout, unit: 'MINUTES') {
352 input("Workflow pause requested before run: ${jobName}/${jobDescription}\n" +
353 "Timeout set to ${wfPauseStepTimeout}.\n" +
354 "Do you want to proceed workflow?")
355 }
356 } catch (err) { // timeout reached or input false
357 def user = err.getCauses()[0].getUser()
358 if (user.toString() != 'SYSTEM') { // SYSTEM means timeout.
359 error("Aborted after workFlow pause by: [${user}]")
360 } else {
361 common.infoMsg("Timeout finished, continue..")
362 }
363 }
364 }
365 common.infoMsg("Attempt to run: ${jobName}/${jobDescription}")
366 // Collect job parameters and run the job
367 // WARN(alexz): desc must not contain invalid chars for yaml
368 def jobResult = runOrGetJob(jobName, jobParameters,
369 global_variables, propagate, jobDescription)
370 def buildDuration = jobResult.durationString ?: '-'
371 if (buildDuration.toString() == null) {
372 buildDuration = '-'
373 }
374 def jobSummary = [
375 job_result : jobResult.getResult().toString(),
376 build_url : jobResult.getAbsoluteUrl().toString(),
377 build_id : jobResult.getId().toString(),
378 buildDuration : buildDuration,
379 desc : engine.createTemplate(jobDescription).make(global_variables),
380 ]
381 def _buildDescription = jobResult.getDescription().toString()
382 if(_buildDescription){
383 jobSummary['build_description'] = _buildDescription
384 }
385 // Store links to the resulting artifacts into 'global_variables'
386 storeArtifacts(jobSummary['build_url'], step['artifacts'],
Andrii Baraniukcf4c2fa2023-04-18 13:53:32 +0300387 global_variables, jobName, jobSummary['build_id'], artifactoryBaseUrl, artifactoryServer)
azvyagintsev0d978152022-01-27 14:01:33 +0200388 return jobSummary
389 }
390}
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300391/**
392 * Run the workflow or final steps one by one
393 *
394 * @param steps List of steps (Jenkins jobs) to execute
395 * @param global_variables Map where the collected artifact URLs and 'env' objects are stored
396 * @param failed_jobs Map with failed job names and result statuses, to report it later
AndrewB8505a7f2020-06-05 13:42:08 +0300397 * @param jobs_data Map with all job names and result statuses, to showing it in description
398 * @param step_id Counter for matching step ID with cell ID in description table
Dennis Dmitrieve09e0292019-07-30 16:39:27 +0300399 * @param propagate Boolean. If false: allows to collect artifacts after job is finished, even with FAILURE status
400 * If true: immediatelly fails the pipeline. DO NOT USE 'true' with runScenario().
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300401 */
Andrii Baraniukcf4c2fa2023-04-18 13:53:32 +0300402def runSteps(steps, global_variables, failed_jobs, jobs_data, step_id, Boolean propagate = false, artifactoryBaseUrl = '', artifactoryServer = '') {
azvyagintsevb673f392021-05-19 15:31:48 +0300403 common = new com.mirantis.mk.Common()
AndrewB8505a7f2020-06-05 13:42:08 +0300404 // Show expected jobs list in description
405 updateDescription(jobs_data)
406
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300407 for (step in steps) {
azvyagintsev0d978152022-01-27 14:01:33 +0200408 stage("Preparing for run job ${step['job']}") {
Andrii Baraniukcf4c2fa2023-04-18 13:53:32 +0300409 def job_summary = runStep(global_variables, step, propagate, artifactoryBaseUrl, artifactoryServer).call()
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300410
AndrewB8505a7f2020-06-05 13:42:08 +0300411 // Update jobs_data for updating description
azvyagintsev0d978152022-01-27 14:01:33 +0200412 jobs_data[step_id]['build_url'] = job_summary['build_url']
413 jobs_data[step_id]['build_id'] = job_summary['build_id']
414 jobs_data[step_id]['status'] = job_summary['job_result']
415 jobs_data[step_id]['duration'] = job_summary['buildDuration']
416 jobs_data[step_id]['desc'] = job_summary['desc']
417 if (job_summary['build_description']) {
418 jobs_data[step_id]['child_desc'] = job_summary['build_description']
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300419 }
AndrewB8505a7f2020-06-05 13:42:08 +0300420 updateDescription(jobs_data)
azvyagintsev0d978152022-01-27 14:01:33 +0200421 def job_result = job_summary['job_result']
422 def build_url = job_summary['build_url']
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300423
Mykyta Karpina3d775e2020-04-24 14:45:17 +0300424 // Check job result, in case of SUCCESS, move to next step.
Mykyta Karpin0bd8bc62020-04-29 12:27:14 +0300425 // 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 +0200426 // In other cases check flag ignore_failed, if true ignore any statuses and keep going additionally
427 // if skip_results is not set or set to false fail entrie workflow, otherwise succed.
azvyagintsev75390d92021-04-12 14:20:11 +0300428 if (job_result != 'SUCCESS') {
Mykyta Karpina3d775e2020-04-24 14:45:17 +0300429 def ignoreStepResult = false
azvyagintsev75390d92021-04-12 14:20:11 +0300430 switch (job_result) {
431 // In cases when job was waiting too long in queue or internal job logic allows to skip building,
432 // 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 +0300433 case "NOT_BUILT":
434 ignoreStepResult = step['ignore_not_built'] ?: false
435 break;
Dmitry Tyzhnenkoa1412702022-02-14 21:23:09 +0200436 case "UNSTABLE":
Dmitry Tyzhnenkobafca282022-02-17 17:49:54 +0200437 ignoreStepResult = step['ignore_unstable'] ?: (step['ignore_failed'] ?: false)
Sergey Lalov3a2e7902023-07-27 01:19:02 +0400438 if (ignoreStepResult && !step['skip_results'] ?: false) {
439 failed_jobs[build_url] = job_result
440 }
Dmitry Tyzhnenkoa1412702022-02-14 21:23:09 +0200441 break;
Mykyta Karpina3d775e2020-04-24 14:45:17 +0300442 default:
443 ignoreStepResult = step['ignore_failed'] ?: false
Vasyl Saienkoe72b9942021-03-04 10:54:49 +0200444 if (ignoreStepResult && !step['skip_results'] ?: false) {
445 failed_jobs[build_url] = job_result
446 }
Mykyta Karpina3d775e2020-04-24 14:45:17 +0300447 }
448 if (!ignoreStepResult) {
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300449 currentBuild.result = job_result
450 error "Job ${build_url} finished with result: ${job_result}"
azvyagintsev0d978152022-01-27 14:01:33 +0200451 }
452 }
azvyagintsev353b8762022-01-14 12:30:43 +0200453 common.infoMsg("Job ${build_url} finished with result: ${job_result}")
azvyagintsev0d978152022-01-27 14:01:33 +0200454 }
azvyagintsev75390d92021-04-12 14:20:11 +0300455 // Jump to next ID for updating next job data in description table
456 step_id++
azvyagintsev0d978152022-01-27 14:01:33 +0200457 }
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300458}
459
460/**
461 * Run the workflow scenario
462 *
463 * @param scenario: Map with scenario steps.
464
465 * There are two keys in the scenario:
466 * workflow: contains steps to run deploy and test jobs
467 * finally: contains steps to run report and cleanup jobs
468 *
469 * Scenario execution example:
470 *
471 * scenario_yaml = """\
472 * workflow:
473 * - job: deploy-kaas
474 * ignore_failed: false
AndrewB8505a7f2020-06-05 13:42:08 +0300475 * description: "Management cluster ${KAAS_VERSION}"
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300476 * parameters:
477 * KAAS_VERSION:
478 * type: StringParameterValue
479 * use_variable: KAAS_VERSION
480 * artifacts:
481 * KUBECONFIG_ARTIFACT: artifacts/management_kubeconfig
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +0300482 * DEPLOYED_KAAS_VERSION: artifacts/management_version
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300483 *
Dennis Dmitriev5f014d82020-04-29 00:00:34 +0300484 * - job: create-child
485 * inherit_parent_params: true
486 * ignore_failed: false
487 * parameters:
488 * KUBECONFIG_ARTIFACT_URL:
489 * type: StringParameterValue
490 * use_variable: KUBECONFIG_ARTIFACT
491 * KAAS_VERSION:
492 * type: StringParameterValue
493 * get_variable_from_url: DEPLOYED_KAAS_VERSION
Dennis Dmitriev6c355be2021-11-09 14:06:56 +0200494 * RELEASE_NAME:
495 * type: StringParameterValue
496 * get_variable_from_yaml:
497 * yaml_url: SI_CONFIG_ARTIFACT
498 * yaml_key: .clusters[0].release_name
Dennis Dmitriev5f014d82020-04-29 00:00:34 +0300499 *
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300500 * - job: test-kaas-ui
Mykyta Karpina3d775e2020-04-24 14:45:17 +0300501 * ignore_not_built: false
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300502 * parameters:
503 * KUBECONFIG_ARTIFACT_URL:
504 * type: StringParameterValue
505 * use_variable: KUBECONFIG_ARTIFACT
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +0300506 * KAAS_VERSION:
507 * type: StringParameterValue
508 * get_variable_from_url: DEPLOYED_KAAS_VERSION
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300509 * artifacts:
510 * REPORT_SI_KAAS_UI: artifacts/test_kaas_ui_result.xml
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300511 * finally:
512 * - job: testrail-report
513 * ignore_failed: true
514 * parameters:
Dennis Dmitrievce470932019-09-18 18:31:11 +0300515 * KAAS_VERSION:
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300516 * type: StringParameterValue
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +0300517 * get_variable_from_url: DEPLOYED_KAAS_VERSION
Dennis Dmitrievce470932019-09-18 18:31:11 +0300518 * REPORTS_LIST:
519 * type: TextParameterValue
520 * use_template: |
521 * REPORT_SI_KAAS_UI: \$REPORT_SI_KAAS_UI
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300522 * """
523 *
524 * runScenario(scenario)
525 *
Dennis Dmitriev5f014d82020-04-29 00:00:34 +0300526 * Scenario workflow keys:
527 *
528 * job: string. Jenkins job name
529 * ignore_failed: bool. if true, keep running the workflow jobs if the job is failed, but fail the workflow at finish
Sergey Lalov3a2e7902023-07-27 01:19:02 +0400530 * ignore_unstable: bool. if true, keep running the workflow jobs if the job is unstable, but mark the workflow is unstable at finish
Vasyl Saienkoe72b9942021-03-04 10:54:49 +0200531 * 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 +0300532 * 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
533 * inherit_parent_params: bool. if true, provide all parameters from the parent job to the child job as defaults
534 * 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 +0200535 * wf_pause_step_before_run: bool. Interactive pause exact step before run.
536 * wf_pause_step_slack_report_channel: If step paused, send message about it in slack.
537 * wf_pause_step_timeout: timeout im minutes to wait for manual unpause.
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300538 */
539
Andrii Baraniukcf4c2fa2023-04-18 13:53:32 +0300540def runScenario(scenario, slackReportChannel = '', artifactoryBaseUrl = '', Boolean logGlobalVariables = false, artifactoryServer = '') {
Dennis Dmitriev79f3a2d2019-08-09 16:06:00 +0300541 // Clear description before adding new messages
542 currentBuild.description = ''
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300543 // Collect the parameters for the jobs here
azvyagintsev0d978152022-01-27 14:01:33 +0200544 def global_variables = [:]
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300545 // List of failed jobs to show at the end
azvyagintsev0d978152022-01-27 14:01:33 +0200546 def failed_jobs = [:]
AndrewB8505a7f2020-06-05 13:42:08 +0300547 // Jobs data to use for wf job build description
548 def jobs_data = []
549 // Counter for matching step ID with cell ID in description table
azvyagintsev0d978152022-01-27 14:01:33 +0200550 def step_id = 0
AndrewB8505a7f2020-06-05 13:42:08 +0300551
552 // Generate expected list jobs for description
azvyagintsev0d978152022-01-27 14:01:33 +0200553 def list_id = 0
AndrewB8505a7f2020-06-05 13:42:08 +0300554 for (step in scenario['workflow']) {
azvyagintsev0d978152022-01-27 14:01:33 +0200555 def display_name = step['job']
azvyagintsev75390d92021-04-12 14:20:11 +0300556 if (step['description'] != null && step['description'].toString() != "") {
AndrewB8505a7f2020-06-05 13:42:08 +0300557 display_name = step['description']
AndrewB8505a7f2020-06-05 13:42:08 +0300558 }
azvyagintsev061179d2021-05-05 16:52:18 +0300559 jobs_data.add([list_id : "$list_id",
560 type : "workflow",
561 name : "$display_name",
562 build_url : "0",
563 build_id : "-",
564 status : "-",
565 desc : "",
azvyagintsev2eeaa562022-01-27 12:03:40 +0200566 child_desc: "",
567 duration : '-'])
AndrewB8505a7f2020-06-05 13:42:08 +0300568 list_id += 1
569 }
azvyagintsev0d978152022-01-27 14:01:33 +0200570
Sergey Lalov702384d2022-11-10 12:10:23 +0400571 def pause_step_id = list_id
572 for (step in scenario['pause']) {
573 def display_name = step['job']
574 if (step['description'] != null && step['description'].toString() != "") {
575 display_name = step['description']
576 }
577 jobs_data.add([list_id : "$list_id",
578 type : "pause",
579 name : "$display_name",
580 build_url : "0",
581 build_id : "-",
582 status : "-",
583 desc : "",
584 child_desc: "",
585 duration : '-'])
586 list_id += 1
587 }
588
azvyagintsev0d978152022-01-27 14:01:33 +0200589 def finally_step_id = list_id
AndrewB8505a7f2020-06-05 13:42:08 +0300590 for (step in scenario['finally']) {
azvyagintsev0d978152022-01-27 14:01:33 +0200591 def display_name = step['job']
azvyagintsev75390d92021-04-12 14:20:11 +0300592 if (step['description'] != null && step['description'].toString() != "") {
AndrewB8505a7f2020-06-05 13:42:08 +0300593 display_name = step['description']
AndrewB8505a7f2020-06-05 13:42:08 +0300594 }
azvyagintsev061179d2021-05-05 16:52:18 +0300595 jobs_data.add([list_id : "$list_id",
596 type : "finally",
597 name : "$display_name",
598 build_url : "0",
599 build_id : "-",
600 status : "-",
601 desc : "",
azvyagintsev2eeaa562022-01-27 12:03:40 +0200602 child_desc: "",
603 duration : '-'])
AndrewB8505a7f2020-06-05 13:42:08 +0300604 list_id += 1
605 }
Sergey Lalov702384d2022-11-10 12:10:23 +0400606 def job_failed_flag = false
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300607 try {
608 // Run the 'workflow' jobs
Andrii Baraniukcf4c2fa2023-04-18 13:53:32 +0300609 runSteps(scenario['workflow'], global_variables, failed_jobs, jobs_data, step_id, false, artifactoryBaseUrl, artifactoryServer)
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300610 } catch (InterruptedException x) {
Sergey Lalov702384d2022-11-10 12:10:23 +0400611 job_failed_flag = true
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300612 error "The job was aborted"
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300613 } catch (e) {
Sergey Lalov702384d2022-11-10 12:10:23 +0400614 job_failed_flag = true
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300615 error("Build failed: " + e.toString())
Sergey Lalov702384d2022-11-10 12:10:23 +0400616
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300617 } finally {
Dennis Dmitriev38a45cd2023-02-27 14:22:13 +0200618 // Log global_variables
619 if (logGlobalVariables) {
620 printVariables(global_variables)
621 }
622
Sergey Lalov702384d2022-11-10 12:10:23 +0400623 flag_pause_variable = (env.PAUSE_FOR_DEBUG) != null
624 // Run the 'finally' or 'pause' jobs
Sergey Lalov6e9400c2022-11-17 12:59:31 +0400625 common.infoMsg(failed_jobs)
Sergey Lalov2d1cd9c2023-08-03 17:08:09 +0400626 // Run only if there are failed jobs in the scenario
627 if (flag_pause_variable && (PAUSE_FOR_DEBUG && job_failed_flag)) {
Sergey Lalov702384d2022-11-10 12:10:23 +0400628 // Switching to 'pause' step index
629 common.infoMsg("FINALLY BLOCK - PAUSE")
630 step_id = pause_step_id
Andrii Baraniukcf4c2fa2023-04-18 13:53:32 +0300631 runSteps(scenario['pause'], global_variables, failed_jobs, jobs_data, step_id, false, artifactoryBaseUrl, artifactoryServer)
Sergey Lalov702384d2022-11-10 12:10:23 +0400632
633 }
634 // Switching to 'finally' step index
635 common.infoMsg("FINALLY BLOCK - CLEAR")
AndrewB8505a7f2020-06-05 13:42:08 +0300636 step_id = finally_step_id
Andrii Baraniukcf4c2fa2023-04-18 13:53:32 +0300637 runSteps(scenario['finally'], global_variables, failed_jobs, jobs_data, step_id, false, artifactoryBaseUrl, artifactoryServer)
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300638
639 if (failed_jobs) {
azvyagintsev0d978152022-01-27 14:01:33 +0200640 def statuses = []
sgudz9ac09d22020-01-22 14:31:30 +0200641 failed_jobs.each {
sgudz74c8cdd2020-01-23 14:26:32 +0200642 statuses += it.value
azvyagintsev75390d92021-04-12 14:20:11 +0300643 }
sgudz9ac09d22020-01-22 14:31:30 +0200644 if (statuses.contains('FAILURE')) {
645 currentBuild.result = 'FAILURE'
Sergey Lalove5e0a842023-10-02 15:55:59 +0400646 } else if (statuses.contains('ABORTED')) {
647 currentBuild.result = 'ABORTED'
648 }
649 else if (statuses.contains('UNSTABLE')) {
sgudz9ac09d22020-01-22 14:31:30 +0200650 currentBuild.result = 'UNSTABLE'
azvyagintsev75390d92021-04-12 14:20:11 +0300651 } else {
sgudz9ac09d22020-01-22 14:31:30 +0200652 currentBuild.result = 'FAILURE'
653 }
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300654 println "Failed jobs: ${failed_jobs}"
vnaumov68cba272020-05-20 11:24:02 +0200655 } else {
656 currentBuild.result = 'SUCCESS'
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300657 }
vnaumov5a6eb8a2020-03-31 11:16:54 +0200658
Sergey Lalov3a2e7902023-07-27 01:19:02 +0400659 common.infoMsg("Workflow finished with result: ${currentBuild.result}")
660
vnaumov5a6eb8a2020-03-31 11:16:54 +0200661 if (slackReportChannel) {
662 def slack = new com.mirantis.mcp.SlackNotification()
663 slack.jobResultNotification(currentBuild.result, slackReportChannel, '', null, '', 'slack_webhook_url')
664 }
sgudz9ac09d22020-01-22 14:31:30 +0200665 } // finally
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300666}