blob: 93d673be08c8bf7bc9b5ef5962d33a8012b1397f [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 = []
azvyagintsev353b8762022-01-14 12:30:43 +020066 common = new com.mirantis.mk.Common()
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +030067 def http = new com.mirantis.mk.Http()
Dennis Dmitrievce470932019-09-18 18:31:11 +030068 def engine = new groovy.text.GStringTemplateEngine()
69 def template
Dennis Dmitriev6c355be2021-11-09 14:06:56 +020070 def yamls_from_urls = [:]
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +030071 def base = [:]
72 base["url"] = ''
73 def variable_content
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +030074
75 // Collect required parameters from 'global_variables' or 'env'
76 for (param in job_parameters) {
Dennis Dmitrievce470932019-09-18 18:31:11 +030077 if (param.value.containsKey('use_variable')) {
78 if (!global_variables[param.value.use_variable]) {
79 global_variables[param.value.use_variable] = env[param.value.use_variable] ?: ''
80 }
81 parameters.add([$class: "${param.value.type}", name: "${param.key}", value: global_variables[param.value.use_variable]])
azvyagintsev353b8762022-01-14 12:30:43 +020082 common.infoMsg("${param.key}: <${param.value.type}> ${global_variables[param.value.use_variable]}")
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +030083 } else if (param.value.containsKey('get_variable_from_url')) {
84 if (!global_variables[param.value.get_variable_from_url]) {
85 global_variables[param.value.get_variable_from_url] = env[param.value.get_variable_from_url] ?: ''
86 }
Andrew Baraniuke0aef1e2019-10-16 14:50:10 +030087 if (global_variables[param.value.get_variable_from_url]) {
Dennis Dmitriev37828362019-11-11 18:06:49 +020088 variable_content = http.restGet(base, global_variables[param.value.get_variable_from_url]).trim()
Andrew Baraniuke0aef1e2019-10-16 14:50:10 +030089 parameters.add([$class: "${param.value.type}", name: "${param.key}", value: variable_content])
azvyagintsev353b8762022-01-14 12:30:43 +020090 common.infoMsg("${param.key}: <${param.value.type}> ${variable_content}")
Andrew Baraniuke0aef1e2019-10-16 14:50:10 +030091 } else {
azvyagintsev353b8762022-01-14 12:30:43 +020092 common.warningMsg("${param.key} is empty, skipping get_variable_from_url")
Andrew Baraniuke0aef1e2019-10-16 14:50:10 +030093 }
Dennis Dmitriev6c355be2021-11-09 14:06:56 +020094 } else if (param.value.containsKey('get_variable_from_yaml')) {
95 if (param.value.get_variable_from_yaml.containsKey('yaml_url') && param.value.get_variable_from_yaml.containsKey('yaml_key')) {
96 // YAML url is stored in an environment or a global variable (like 'SI_CONFIG_ARTIFACT')
97 yaml_url_var = param.value.get_variable_from_yaml.yaml_url
98 if (!global_variables[yaml_url_var]) {
99 global_variables[yaml_url_var] = env[yaml_url_var] ?: ''
100 }
101 yaml_url = global_variables[yaml_url_var] // Real YAML URL
azvyagintsev353b8762022-01-14 12:30:43 +0200102 yaml_key = param.value.get_variable_from_yaml.yaml_key
103 // Key to get the data from YAML, to interpolate in the groovy, for example:
104 // <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 +0200105 if (yaml_url) {
106 if (!yamls_from_urls[yaml_url]) {
azvyagintsev353b8762022-01-14 12:30:43 +0200107 common.infoMsg("Reading YAML from ${yaml_url} for ${param.key}")
Dennis Dmitriev6c355be2021-11-09 14:06:56 +0200108 yaml_content = http.restGet(base, yaml_url)
109 yamls_from_urls[yaml_url] = readYaml text: yaml_content
110 }
azvyagintsev353b8762022-01-14 12:30:43 +0200111 common.infoMsg("Getting key ${yaml_key} from YAML ${yaml_url} for ${param.key}")
Dennis Dmitriev6c355be2021-11-09 14:06:56 +0200112 template_variables = [
azvyagintsev353b8762022-01-14 12:30:43 +0200113 'yaml_data': yamls_from_urls[yaml_url]
Dennis Dmitriev6c355be2021-11-09 14:06:56 +0200114 ]
115 request = "\${yaml_data${yaml_key}}"
Dennis Dmitriev450cf732021-11-11 14:59:17 +0200116
117 // Catch errors related to wrong key or index in the list or map objects
118 // For wrong key in map or wrong index in list, groovy returns <null> object,
119 // but it can be catched only after the string interpolation <template.toString()>,
120 // so we should catch the string 'null' instead of object <null>.
121 try {
122 template = engine.createTemplate(request).make(template_variables)
123 result = template.toString()
124 if (result == 'null') {
125 error "No such key or index, got 'null'"
126 }
127 } catch (e) {
128 error("Failed to get the key ${yaml_key} from YAML ${yaml_url}: " + e.toString())
129 }
130
131 parameters.add([$class: "${param.value.type}", name: "${param.key}", value: result])
azvyagintsev353b8762022-01-14 12:30:43 +0200132 common.infoMsg("${param.key}: <${param.value.type}>\n${result}")
Dennis Dmitriev6c355be2021-11-09 14:06:56 +0200133 } else {
azvyagintsev353b8762022-01-14 12:30:43 +0200134 common.warningMsg("'yaml_url' in ${param.key} is empty, skipping get_variable_from_yaml")
Dennis Dmitriev6c355be2021-11-09 14:06:56 +0200135 }
136 } else {
azvyagintsev353b8762022-01-14 12:30:43 +0200137 common.warningMsg("${param.key} missing 'yaml_url'/'yaml_key' parameters, skipping get_variable_from_yaml")
Dennis Dmitriev6c355be2021-11-09 14:06:56 +0200138 }
Dennis Dmitrievce470932019-09-18 18:31:11 +0300139 } else if (param.value.containsKey('use_template')) {
140 template = engine.createTemplate(param.value.use_template).make(global_variables)
141 parameters.add([$class: "${param.value.type}", name: "${param.key}", value: template.toString()])
azvyagintsev353b8762022-01-14 12:30:43 +0200142 common.infoMsg("${param.key}: <${param.value.type}>\n${template.toString()}")
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300143 }
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300144 }
145
146 // Build the job
Dennis Dmitrieve09e0292019-07-30 16:39:27 +0300147 def job_info = build job: "${job_name}", parameters: parameters, propagate: propagate
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300148 return job_info
149}
150
azvyagintsev061179d2021-05-05 16:52:18 +0300151def runOrGetJob(job_name, job_parameters, global_variables, propagate, String fullTaskName = '') {
152 /**
153 * Run job directly or try to find already executed build
154 * Flow, in case CI_JOBS_OVERRIDES passed:
155 *
156 *
157 * CI_JOBS_OVERRIDES = text in yaml|json format
158 * CI_JOBS_OVERRIDES = 'kaas-testing-core-release-artifact' : 3505
159 * 'reindex-testing-core-release-index-with-rc' : 2822
160 * 'si-test-release-sanity-check-prepare-configuration': 1877
161 */
162 common = new com.mirantis.mk.Common()
163 def jobsOverrides = readYaml(text: env.CI_JOBS_OVERRIDES ?: '---') ?: [:]
164 // get id of overriding job
165 def jobOverrideID = jobsOverrides.getOrDefault(fullTaskName, '')
azvyagintsev061179d2021-05-05 16:52:18 +0300166 if (fullTaskName in jobsOverrides.keySet()) {
167 common.warningMsg("Overriding: ${fullTaskName}/${job_name} <<< ${jobOverrideID}")
168 common.infoMsg("For debug pin use:\n'${fullTaskName}' : ${jobOverrideID}")
169 return Jenkins.instance.getItemByFullName(job_name,
azvyagintsev353b8762022-01-14 12:30:43 +0200170 hudson.model.Job.class).getBuildByNumber(jobOverrideID.toInteger())
azvyagintsev061179d2021-05-05 16:52:18 +0300171 } else {
172 return runJob(job_name, job_parameters, global_variables, propagate)
173 }
174}
175
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300176/**
177 * Store URLs of the specified artifacts to the global_variables
178 *
179 * @param build_url URL of the completed job
180 * @param step_artifacts Map that contains artifact names in the job, and variable names
181 * where the URLs to that atrifacts should be stored, for example:
182 * {'ARTIFACT1': 'logs.tar.gz', 'ARTIFACT2': 'test_report.xml', ...}
183 * @param global_variables Map that will keep the artifact URLs. Variable 'ARTIFACT1', for example,
184 * be used in next job parameters: {'ARTIFACT1_URL':{ 'use_variable': 'ARTIFACT1', ...}}
185 *
186 * If the artifact with the specified name not found, the parameter ARTIFACT1_URL
187 * will be empty.
188 *
189 */
Aleksey Zvyagintsev25ed4a52021-05-12 14:35:03 +0000190def storeArtifacts(build_url, step_artifacts, global_variables, job_name, build_num, artifactory_url = '') {
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300191 def common = new com.mirantis.mk.Common()
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300192 def http = new com.mirantis.mk.Http()
Aleksey Zvyagintsev25ed4a52021-05-12 14:35:03 +0000193 if (!artifactory_url) {
194 artifactory_url = 'https://artifactory.mcp.mirantis.net/api/storage/si-local/jenkins-job-artifacts'
195 }
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300196 def baseJenkins = [:]
197 def baseArtifactory = [:]
198 build_url = build_url.replaceAll(~/\/+$/, "")
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300199 baseArtifactory["url"] = artifactory_url + "/${job_name}/${build_num}"
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300200 baseJenkins["url"] = build_url
201 def job_config = http.restGet(baseJenkins, "/api/json/")
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300202 def job_artifacts = job_config['artifacts']
203 for (artifact in step_artifacts) {
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300204 try {
205 artifactoryResp = http.restGet(baseArtifactory, "/${artifact.value}")
206 global_variables[artifact.key] = artifactoryResp.downloadUri
207 println "Artifact URL ${artifactoryResp.downloadUri} stored to ${artifact.key}"
208 continue
209 } catch (Exception e) {
210 common.warningMsg("Can't find an artifact in ${artifactory_url}/${job_name}/${build_num}/${artifact.value} error code ${e.message}")
211 }
212
213 job_artifact = job_artifacts.findAll { item -> artifact.value == item['fileName'] || artifact.value == item['relativePath'] }
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300214 if (job_artifact.size() == 1) {
215 // Store artifact URL
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300216 def artifact_url = "${build_url}/artifact/${job_artifact[0]['relativePath']}"
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300217 global_variables[artifact.key] = artifact_url
218 println "Artifact URL ${artifact_url} stored to ${artifact.key}"
219 } else if (job_artifact.size() > 1) {
220 // Error: too many artifacts with the same name, fail the job
221 error "Multiple artifacts ${artifact.value} for ${artifact.key} found in the build results ${build_url}, expected one:\n${job_artifact}"
222 } else {
223 // Warning: no artifact with expected name
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300224 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 +0300225 global_variables[artifact.key] = ''
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300226 }
227 }
228}
229
AndrewB8505a7f2020-06-05 13:42:08 +0300230/**
231 * Update workflow job build description
232 *
233 * @param jobs_data Map with all job names and result statuses, to showing it in description
234 */
235def updateDescription(jobs_data) {
236 table = ''
237 child_jobs_description = '<strong>Descriptions from jobs:</strong><br>'
238 table_template_start = "<div><table style='border: solid 1px;'><tr><th>Job:</th><th>Status:</th></tr>"
239 table_template_end = "</table></div>"
240
241 for (jobdata in jobs_data) {
242 // Grey background for 'finally' jobs in list
243 if (jobdata['type'] == 'finally') {
244 trstyle = "<tr style='background: #DDDDDD;'>"
245 } else {
246 trstyle = "<tr>"
247 }
248
249 // 'description' instead of job name if it exists
azvyagintsev75390d92021-04-12 14:20:11 +0300250 if (jobdata['desc'].toString() != "") {
azvyagintsev061179d2021-05-05 16:52:18 +0300251 display_name = "'${jobdata['desc']}': ${jobdata['build_id']}"
AndrewB8505a7f2020-06-05 13:42:08 +0300252 } else {
azvyagintsev061179d2021-05-05 16:52:18 +0300253 display_name = "'${jobdata['name']}': ${jobdata['build_id']}"
AndrewB8505a7f2020-06-05 13:42:08 +0300254 }
255
256 // Attach url for already builded jobs
azvyagintsev75390d92021-04-12 14:20:11 +0300257 if (jobdata['build_url'] != "0") {
AndrewB8505a7f2020-06-05 13:42:08 +0300258 build_url = "<a href=${jobdata['build_url']}>$display_name</a>"
259 } else {
260 build_url = display_name
261 }
262
263 // Styling the status of job result
azvyagintsev75390d92021-04-12 14:20:11 +0300264 switch (jobdata['status'].toString()) {
AndrewB8505a7f2020-06-05 13:42:08 +0300265 case "SUCCESS":
266 status_style = "<td style='color: green;'><img src='/images/16x16/blue.png' alt='SUCCESS'>"
267 break
268 case "UNSTABLE":
269 status_style = "<td style='color: #FF5733;'><img src='/images/16x16/yellow.png' alt='UNSTABLE'>"
270 break
271 case "ABORTED":
272 status_style = "<td style='color: red;'><img src='/images/16x16/aborted.png' alt='ABORTED'>"
273 break
274 case "NOT_BUILT":
275 status_style = "<td style='color: red;'><img src='/images/16x16/aborted.png' alt='NOT_BUILT'>"
276 break
277 case "FAILURE":
278 status_style = "<td style='color: red;'><img src='/images/16x16/red.png' alt='FAILURE'>"
279 break
280 default:
281 status_style = "<td>-"
282 }
283
284 // Collect table
285 table += "$trstyle<td>$build_url</td>$status_style</td></tr>"
286
287 // Collecting descriptions of builded child jobs
288 if (jobdata['child_desc'] != "") {
289 child_jobs_description += "<b><small><a href=${jobdata['build_url']}>- ${jobdata['name']} (${jobdata['status']}):</a></small></b><br>"
290 child_jobs_description += "<small>${jobdata['child_desc']}</small><br>"
291 }
292 }
293 currentBuild.description = table_template_start + table + table_template_end + child_jobs_description
294}
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300295
296/**
297 * Run the workflow or final steps one by one
298 *
299 * @param steps List of steps (Jenkins jobs) to execute
300 * @param global_variables Map where the collected artifact URLs and 'env' objects are stored
301 * @param failed_jobs Map with failed job names and result statuses, to report it later
AndrewB8505a7f2020-06-05 13:42:08 +0300302 * @param jobs_data Map with all job names and result statuses, to showing it in description
303 * @param step_id Counter for matching step ID with cell ID in description table
Dennis Dmitrieve09e0292019-07-30 16:39:27 +0300304 * @param propagate Boolean. If false: allows to collect artifacts after job is finished, even with FAILURE status
305 * If true: immediatelly fails the pipeline. DO NOT USE 'true' with runScenario().
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300306 */
Aleksey Zvyagintsev25ed4a52021-05-12 14:35:03 +0000307def runSteps(steps, global_variables, failed_jobs, jobs_data, step_id, Boolean propagate = false, artifactoryBaseUrl = '') {
azvyagintsevb673f392021-05-19 15:31:48 +0300308 common = new com.mirantis.mk.Common()
AndrewB8505a7f2020-06-05 13:42:08 +0300309 // Show expected jobs list in description
310 updateDescription(jobs_data)
311
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300312 for (step in steps) {
313 stage("Running job ${step['job']}") {
AndrewB8505a7f2020-06-05 13:42:08 +0300314 def engine = new groovy.text.GStringTemplateEngine()
azvyagintsev061179d2021-05-05 16:52:18 +0300315 String desc = step['description'] ?: ''
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300316 def job_name = step['job']
Dennis Dmitriev5f014d82020-04-29 00:00:34 +0300317 def job_parameters = [:]
Dennis Dmitriev334eecd2020-04-30 14:32:45 +0300318 def step_parameters = step['parameters'] ?: [:]
Dennis Dmitriev5f014d82020-04-29 00:00:34 +0300319 if (step['inherit_parent_params'] ?: false) {
320 // add parameters from the current job for the child job
321 job_parameters << getJobDefaultParameters(env.JOB_NAME)
322 }
323 // add parameters from the workflow for the child job
Dennis Dmitriev334eecd2020-04-30 14:32:45 +0300324 job_parameters << step_parameters
azvyagintsev353b8762022-01-14 12:30:43 +0200325 def wfPauseStepBeforeRun = (step['wf_pause_step_before_run'] ?: false).toBoolean()
326 def wfPauseStepTimeout = (step['wf_pause_step_timeout'] ?: 10).toInteger()
327 def wfPauseStepSlackReportChannel = step['wf_pause_step_slack_report_channel'] ?: ''
Dennis Dmitriev5f014d82020-04-29 00:00:34 +0300328
azvyagintsev353b8762022-01-14 12:30:43 +0200329 if (wfPauseStepBeforeRun) {
330 // Try-catch construction will allow to continue Steps, if timeout reached
331 try {
332 if (wfPauseStepSlackReportChannel) {
333 def slack = new com.mirantis.mcp.SlackNotification()
334 slack.jobResultNotification('wf_pause_step_before_run', wfPauseStepSlackReportChannel, env.JOB_NAME, null, env.BUILD_URL, 'slack_webhook_url')
335 }
336 timeout(time: wfPauseStepTimeout, unit: 'MINUTES') {
337 input("Workflow pause requested before run: ${job_name}/${desc}\n" +
338 "Timeout set to ${wfPauseStepTimeout}.\n" +
339 "Do you want to proceed workflow?")
340 }
341 } catch (err) { // timeout reached or input false
342 def user = err.getCauses()[0].getUser()
343 if (user.toString() != 'SYSTEM') { // SYSTEM means timeout.
344 error("Aborted after workFlow pause by: [${user}]")
345 } else {
346 common.infoMsg("Timeout finished, continue..")
347 }
348 }
349 }
azvyagintsevb673f392021-05-19 15:31:48 +0300350 common.infoMsg("Attempt to run: ${job_name}/${desc}")
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300351 // Collect job parameters and run the job
azvyagintsev061179d2021-05-05 16:52:18 +0300352 // WARN(alexz): desc must not contain invalid chars for yaml
353 def job_info = runOrGetJob(job_name, job_parameters, global_variables, propagate, desc)
354 def job_result = job_info.getResult().toString()
355 def build_url = job_info.getAbsoluteUrl().toString()
356 def build_description = job_info.getDescription().toString()
357 def build_id = job_info.getId().toString()
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300358
AndrewB8505a7f2020-06-05 13:42:08 +0300359 // Update jobs_data for updating description
360 jobs_data[step_id]['build_url'] = build_url
azvyagintsev061179d2021-05-05 16:52:18 +0300361 jobs_data[step_id]['build_id'] = build_id
AndrewB8505a7f2020-06-05 13:42:08 +0300362 jobs_data[step_id]['status'] = job_result
363 jobs_data[step_id]['desc'] = engine.createTemplate(desc).make(global_variables)
364 if (build_description) {
365 jobs_data[step_id]['child_desc'] = build_description
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300366 }
367
AndrewB8505a7f2020-06-05 13:42:08 +0300368 updateDescription(jobs_data)
369
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300370 // Store links to the resulting artifacts into 'global_variables'
Aleksey Zvyagintsev25ed4a52021-05-12 14:35:03 +0000371 storeArtifacts(build_url, step['artifacts'], global_variables, job_name, build_id, artifactoryBaseUrl)
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300372
Mykyta Karpina3d775e2020-04-24 14:45:17 +0300373 // Check job result, in case of SUCCESS, move to next step.
Mykyta Karpin0bd8bc62020-04-29 12:27:14 +0300374 // 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 +0200375 // In other cases check flag ignore_failed, if true ignore any statuses and keep going additionally
376 // if skip_results is not set or set to false fail entrie workflow, otherwise succed.
azvyagintsev75390d92021-04-12 14:20:11 +0300377 if (job_result != 'SUCCESS') {
Mykyta Karpina3d775e2020-04-24 14:45:17 +0300378 def ignoreStepResult = false
azvyagintsev75390d92021-04-12 14:20:11 +0300379 switch (job_result) {
380 // In cases when job was waiting too long in queue or internal job logic allows to skip building,
381 // 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 +0300382 case "NOT_BUILT":
383 ignoreStepResult = step['ignore_not_built'] ?: false
384 break;
385 default:
386 ignoreStepResult = step['ignore_failed'] ?: false
Vasyl Saienkoe72b9942021-03-04 10:54:49 +0200387 if (ignoreStepResult && !step['skip_results'] ?: false) {
388 failed_jobs[build_url] = job_result
389 }
Mykyta Karpina3d775e2020-04-24 14:45:17 +0300390 }
391 if (!ignoreStepResult) {
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300392 currentBuild.result = job_result
393 error "Job ${build_url} finished with result: ${job_result}"
Mykyta Karpina3d775e2020-04-24 14:45:17 +0300394 } // if (!ignoreStepResult)
395 } // if (job_result != 'SUCCESS')
azvyagintsev353b8762022-01-14 12:30:43 +0200396 common.infoMsg("Job ${build_url} finished with result: ${job_result}")
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300397 } // stage ("Running job ${step['job']}")
azvyagintsev75390d92021-04-12 14:20:11 +0300398 // Jump to next ID for updating next job data in description table
399 step_id++
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300400 } // for (step in scenario['workflow'])
401}
402
403/**
404 * Run the workflow scenario
405 *
406 * @param scenario: Map with scenario steps.
407
408 * There are two keys in the scenario:
409 * workflow: contains steps to run deploy and test jobs
410 * finally: contains steps to run report and cleanup jobs
411 *
412 * Scenario execution example:
413 *
414 * scenario_yaml = """\
415 * workflow:
416 * - job: deploy-kaas
417 * ignore_failed: false
AndrewB8505a7f2020-06-05 13:42:08 +0300418 * description: "Management cluster ${KAAS_VERSION}"
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300419 * parameters:
420 * KAAS_VERSION:
421 * type: StringParameterValue
422 * use_variable: KAAS_VERSION
423 * artifacts:
424 * KUBECONFIG_ARTIFACT: artifacts/management_kubeconfig
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +0300425 * DEPLOYED_KAAS_VERSION: artifacts/management_version
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300426 *
Dennis Dmitriev5f014d82020-04-29 00:00:34 +0300427 * - job: create-child
428 * inherit_parent_params: true
429 * ignore_failed: false
430 * parameters:
431 * KUBECONFIG_ARTIFACT_URL:
432 * type: StringParameterValue
433 * use_variable: KUBECONFIG_ARTIFACT
434 * KAAS_VERSION:
435 * type: StringParameterValue
436 * get_variable_from_url: DEPLOYED_KAAS_VERSION
Dennis Dmitriev6c355be2021-11-09 14:06:56 +0200437 * RELEASE_NAME:
438 * type: StringParameterValue
439 * get_variable_from_yaml:
440 * yaml_url: SI_CONFIG_ARTIFACT
441 * yaml_key: .clusters[0].release_name
Dennis Dmitriev5f014d82020-04-29 00:00:34 +0300442 *
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300443 * - job: test-kaas-ui
Mykyta Karpina3d775e2020-04-24 14:45:17 +0300444 * ignore_not_built: false
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300445 * parameters:
446 * KUBECONFIG_ARTIFACT_URL:
447 * type: StringParameterValue
448 * use_variable: KUBECONFIG_ARTIFACT
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +0300449 * KAAS_VERSION:
450 * type: StringParameterValue
451 * get_variable_from_url: DEPLOYED_KAAS_VERSION
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300452 * artifacts:
453 * REPORT_SI_KAAS_UI: artifacts/test_kaas_ui_result.xml
454 *
455 * finally:
456 * - job: testrail-report
457 * ignore_failed: true
458 * parameters:
Dennis Dmitrievce470932019-09-18 18:31:11 +0300459 * KAAS_VERSION:
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300460 * type: StringParameterValue
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +0300461 * get_variable_from_url: DEPLOYED_KAAS_VERSION
Dennis Dmitrievce470932019-09-18 18:31:11 +0300462 * REPORTS_LIST:
463 * type: TextParameterValue
464 * use_template: |
465 * REPORT_SI_KAAS_UI: \$REPORT_SI_KAAS_UI
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300466 * """
467 *
468 * runScenario(scenario)
469 *
Dennis Dmitriev5f014d82020-04-29 00:00:34 +0300470 * Scenario workflow keys:
471 *
472 * job: string. Jenkins job name
473 * 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 +0200474 * 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 +0300475 * 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
476 * inherit_parent_params: bool. if true, provide all parameters from the parent job to the child job as defaults
477 * 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 +0200478 * wf_pause_step_before_run: bool. Interactive pause exact step before run.
479 * wf_pause_step_slack_report_channel: If step paused, send message about it in slack.
480 * wf_pause_step_timeout: timeout im minutes to wait for manual unpause.
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300481 */
482
Aleksey Zvyagintsev25ed4a52021-05-12 14:35:03 +0000483def runScenario(scenario, slackReportChannel = '', artifactoryBaseUrl = '') {
Dennis Dmitriev79f3a2d2019-08-09 16:06:00 +0300484 // Clear description before adding new messages
485 currentBuild.description = ''
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300486 // Collect the parameters for the jobs here
487 global_variables = [:]
488 // List of failed jobs to show at the end
489 failed_jobs = [:]
AndrewB8505a7f2020-06-05 13:42:08 +0300490 // Jobs data to use for wf job build description
491 def jobs_data = []
492 // Counter for matching step ID with cell ID in description table
493 step_id = 0
494
495 // Generate expected list jobs for description
496 list_id = 0
497 for (step in scenario['workflow']) {
azvyagintsev75390d92021-04-12 14:20:11 +0300498 if (step['description'] != null && step['description'].toString() != "") {
AndrewB8505a7f2020-06-05 13:42:08 +0300499 display_name = step['description']
500 } else {
501 display_name = step['job']
502 }
azvyagintsev061179d2021-05-05 16:52:18 +0300503 jobs_data.add([list_id : "$list_id",
504 type : "workflow",
505 name : "$display_name",
506 build_url : "0",
507 build_id : "-",
508 status : "-",
509 desc : "",
510 child_desc: ""])
AndrewB8505a7f2020-06-05 13:42:08 +0300511 list_id += 1
512 }
513 finally_step_id = list_id
514 for (step in scenario['finally']) {
azvyagintsev75390d92021-04-12 14:20:11 +0300515 if (step['description'] != null && step['description'].toString() != "") {
AndrewB8505a7f2020-06-05 13:42:08 +0300516 display_name = step['description']
517 } else {
518 display_name = step['job']
519 }
azvyagintsev061179d2021-05-05 16:52:18 +0300520 jobs_data.add([list_id : "$list_id",
521 type : "finally",
522 name : "$display_name",
523 build_url : "0",
524 build_id : "-",
525 status : "-",
526 desc : "",
527 child_desc: ""])
AndrewB8505a7f2020-06-05 13:42:08 +0300528 list_id += 1
529 }
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300530
531 try {
532 // Run the 'workflow' jobs
Aleksey Zvyagintsev25ed4a52021-05-12 14:35:03 +0000533 runSteps(scenario['workflow'], global_variables, failed_jobs, jobs_data, step_id, false, artifactoryBaseUrl)
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300534 } catch (InterruptedException x) {
535 error "The job was aborted"
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300536 } catch (e) {
537 error("Build failed: " + e.toString())
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300538 } finally {
AndrewB8505a7f2020-06-05 13:42:08 +0300539 // Switching to 'finally' step index
540 step_id = finally_step_id
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300541 // Run the 'finally' jobs
Aleksey Zvyagintsev25ed4a52021-05-12 14:35:03 +0000542 runSteps(scenario['finally'], global_variables, failed_jobs, jobs_data, step_id, false, artifactoryBaseUrl)
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300543
544 if (failed_jobs) {
sgudz9ac09d22020-01-22 14:31:30 +0200545 statuses = []
546 failed_jobs.each {
sgudz74c8cdd2020-01-23 14:26:32 +0200547 statuses += it.value
azvyagintsev75390d92021-04-12 14:20:11 +0300548 }
sgudz9ac09d22020-01-22 14:31:30 +0200549 if (statuses.contains('FAILURE')) {
550 currentBuild.result = 'FAILURE'
azvyagintsev75390d92021-04-12 14:20:11 +0300551 } else if (statuses.contains('UNSTABLE')) {
sgudz9ac09d22020-01-22 14:31:30 +0200552 currentBuild.result = 'UNSTABLE'
azvyagintsev75390d92021-04-12 14:20:11 +0300553 } else {
sgudz9ac09d22020-01-22 14:31:30 +0200554 currentBuild.result = 'FAILURE'
555 }
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300556 println "Failed jobs: ${failed_jobs}"
vnaumov68cba272020-05-20 11:24:02 +0200557 } else {
558 currentBuild.result = 'SUCCESS'
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300559 }
vnaumov5a6eb8a2020-03-31 11:16:54 +0200560
561 if (slackReportChannel) {
562 def slack = new com.mirantis.mcp.SlackNotification()
563 slack.jobResultNotification(currentBuild.result, slackReportChannel, '', null, '', 'slack_webhook_url')
564 }
sgudz9ac09d22020-01-22 14:31:30 +0200565 } // finally
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300566}